/
aiintegrator
/
techsupp-bot
Обзор
Документация
Войти
/
aiintegrator
/
techsupp-bot
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
bot.py
75 строк
3 KB
zorin99W
Add missing Update import from telegram
13 дек 2025, 20:54
Не верифицирован
13 дек 2025, 20:54
9ce0232
Код
Авторство
О чём код?
#!/usr/bin/env python3 import os import logging from telegram import Update from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes from telegram.constants import ChatAction from openai import OpenAI logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(__name__) TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN') OPENROUTER_API_KEY = os.getenv('OPENROUTER_API_KEY') if not TELEGRAM_BOT_TOKEN: raise ValueError("TELEGRAM_BOT_TOKEN env var not set") if not OPENROUTER_API_KEY: raise ValueError("OPENROUTER_API_KEY env var not set") try: client = OpenAI( api_key=OPENROUTER_API_KEY, base_url="https://openrouter.io/api/v1" ) logger.info("OpenAI client initialized") except Exception as e: logger.error(f"Failed to initialize OpenAI client: {e}") raise def get_ai_response(user_message: str) -> str: try: response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": user_message}] ) return response.choices[0].message.content except Exception as e: logger.error(f"AI response error: {e}") return f"Sorry, I couldn't process that: {str(e)}" async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: logger.info(f"Start command from {update.effective_user.id}") await update.message.reply_text( "Привет! Это бот технической поддержки TechnoHome.\n" "Задайте вопрос - получите ответ!" ) async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: user_message = update.message.text user_id = update.effective_user.id logger.info(f"Message from {user_id}: {user_message}") try: await update.message.chat.send_action(ChatAction.TYPING) response = get_ai_response(user_message) await update.message.reply_text(response) except Exception as e: logger.error(f"Error handling message: {e}") await update.message.reply_text(f"Ошибка: {str(e)}") def main() -> None: logger.info("Starting Telegram bot...") app = Application.builder().token(TELEGRAM_BOT_TOKEN).build() app.add_handler(CommandHandler("start", start)) app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) logger.info("Bot started, polling...") app.run_polling(allowed_updates=Update.ALL_TYPES) if __name__ == '__main__': main()