gggg / app.py
enotkrutoy's picture
Update app.py
03bb072 verified
raw
history blame
3.44 kB
import os
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
import requests
import json
HF_API_KEY = os.getenv("HF_API_KEY")
HF_API_URL = "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions"
# Обработчик стартовой команды
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Привет! Я бот, который отвечает на ваши вопросы. Напишите мне что-нибудь.")
# Обработчик сообщений
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_message = update.message.text
await update.message.reply_text("Думаю...")
# Формируем запрос к API Hugging Face
headers = {
"Authorization": f"Bearer {HF_API_KEY}",
"Content-Type": "application/json",
}
payl
HF_API_KEY = os.getenv("HF_API_KEY")
HF_API_URL = "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions"
# Обработчик стартовой команды
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Привет! Я бот, который отвечает на ваши вопросы. Напишите мне что-нибудь.")
# Обработчик сообщений
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_message = update.message.text
await update.message.reply_text("Думаю...")
# Формируем запрос к API Hugging Face
headers = {
"Authorization": f"Bearer {HF_API_KEY}",
"Content-Type": "application/json",
}
payload = {
"model": "Qwen/Qwen2.5-Coder-32B-Instruct",
"messages": [
{"role": "user", "content": user_message}
],
"temperature": 0.5,
"max_tokens": 2048,
"top_p": 0.7,
"stream": False,
}
try:
response = requests.post(HF_API_URL, headers=headers, data=json.dumps(payload))
response.raise_for_status()
data = response.json()
# Извлекаем текст из ответа модели
reply = ""
choices = data.get("choices", [])
if choices:
reply = choices[0].get("message", {}).get("content", "")
# Отправляем ответ пользователю
await update.message.reply_text(reply if reply else "К сожалению, я не смог ничего придумать.")
except requests.exceptions.RequestException as e:
await update.message.reply_text(f"Сетевая ошибка: {e}")
except json.JSONDecodeError as e:
await update.message.reply_text(f"Ошибка декодирования JSON: {e}")
except Exception as e:
await update.message.reply_text(f"Неизвестная ошибка: {e}")
# Запуск бота
if __name__ == "__main__":
TOKEN = "7518565019:AAFwsGHOMhicachCqq78t8j4MBMhDY9PIDQ"
app = ApplicationBuilder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
print("Бот запущен!")
app.run_polling()