/
Dima57
/
TelegramBot_with_Python
Обзор
Документация
Войти
/
Dima57
/
TelegramBot_with_Python
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
mybot.py
84 строки
4 KB
Dima57
Изменение файла myBot.py
29 янв 2026, 17:24
Верифицирован
29 янв 2026, 17:24
ee0cf17
Код
Авторство
О чём код?
import telebot import requests import json from telebot import types # ------------ Постоянные переменные ------------ Authorization_Key = 'MDE5YmU1ZTEtODVhZC03NWVhLWI1MGUtZmZmMmJlY2Q5ZjMxOmYwNmVjNGJiLTNlODktNDIwMC05ODMyLWIzYjE2OWE3NWFhNA==' Telegram_Token = '8514578310:AAHD_tZ1zmMJ6zWfKn7poNGCqOPvqoZdlpk' # ------------ Функциональная часть ------------ # 1. Функция, отвечающая за формирование Access-токена API GigaChat def get_access_token(authorization_key): url = "https://ngw.devices.sberbank.ru:9443/api/v2/oauth" payload={ 'scope': 'GIGACHAT_API_PERS' } headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'RqUID': '341d20fe-fced-4ab6-bcd7-015e70ac00ba', 'Authorization': f'Basic {authorization_key}' } response = requests.request("POST", url, headers=headers, data=payload, verify=False) access_token = response.json()['access_token'] return access_token # 2. Функция, отвечающая за формирование ответа на сообщение пользователя от GigaChat def get_chat_completion(access_token, user_message, conversation_history=None): url = "https://gigachat.devices.sberbank.ru/api/v1/chat/completions" if conversation_history is None: conversation_history = [] conversation_history.append({ "role": "user", "content": user_message }) payload = json.dumps({ "model": "GigaChat:latest", "messages": conversation_history, "temperature": 0.5, "top_p": 0.1, "n": 1, "stream": False, "max_tokens": 256, "repetition_penalty": 1, "update_interval": 0 }) headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': f'Bearer {access_token}' } response = requests.post(url, headers=headers, data=payload, verify=False) response_data = response.json() conversation_history.append({ "role": "assistant", "content": response_data['choices'][0]['message']['content'] }) return response_data['choices'][0]['message']['content'] # ------------ Бот ------------ bot = telebot.TeleBot(Telegram_Token) # ------------ REPLY-клавиатура -------------------- def create_keyboard(): keyboard= types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) button_history = types.KeyboardButton('История сообщений') button_clear = types.KeyboardButton('Удалить историю') button_help = types.KeyboardButton('Помощь') keyboard.add(button_history, button_clear, button_help) return keyboard # ------------ Приветственное сообщение ------------ @bot.message_handler(commands=['start']) def welcome_message(message): bot.send_photo(message.chat.id, photo=open('image/banner.webp','rb')) bot.reply_to(message, 'Вас приветствует интерактивный Giga-бот!\n\nЗдесь вы можете получить информацию на любую интересующую Вас тему.\nДостаточно ввести свой запрос и отправить его мне.') # ------------ Обработка сообщений ------------ @bot.message_handler(content_types=['text']) def answer_to_user(message): at = get_access_token(Authorization_Key) answer_to_user = get_chat_completion(at, message.text) bot.send_message(message.chat.id, answer_to_user, parse_mode='Markdown', reply_markup=create_keyboard()) # ------------ Запуск бота ------------ if __name__ == '__main__': print('Бот запущен...') bot.polling(none_stop=True)