| | from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup |
| | from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, ContextTypes, filters, CallbackQueryHandler |
| | import google.generativeai as genai |
| | import os |
| |
|
| | |
| | os.environ["TELEGRAM_BOT_TOKEN"] = "8159814432:AAGPG5YC3vhzNif1oAZbeFaZ74vaGnvTnBM" |
| | os.environ["GEMINI_API_KEY"] = "AIzaSyDo0WsJFk7ibsvRIjXOM_v0WvD7QLrK0Qc" |
| |
|
| | TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") |
| | GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") |
| |
|
| | |
| | import logging |
| | logging.basicConfig(level=logging.INFO) |
| |
|
| | |
| | genai.configure(api_key=GEMINI_API_KEY) |
| | model = genai.GenerativeModel("gemini-1.5-flash-latest") |
| |
|
| | |
| | def get_menu(): |
| | return InlineKeyboardMarkup([ |
| | [InlineKeyboardButton("🧠 Задать вопрос", callback_data='ask')], |
| | [InlineKeyboardButton("🧩 Пример запроса", callback_data='example')], |
| | [InlineKeyboardButton("🧹 Очистить контекст", callback_data='clear')], |
| | ]) |
| |
|
| | |
| | async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): |
| | await update.message.reply_text("🤖 Выберите действие:", reply_markup=get_menu()) |
| |
|
| | |
| | async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE): |
| | query = update.callback_query |
| | await query.answer() |
| |
|
| | if query.data == 'ask': |
| | await query.edit_message_text("✍️ Напишите свой вопрос.") |
| | elif query.data == 'example': |
| | await query.edit_message_text("🧪 Пример: \"Объясни теорию относительности\"") |
| | elif query.data == 'clear': |
| | context.user_data['history'] = [] |
| | await query.edit_message_text("🧹 Контекст очищен.") |
| |
|
| | |
| | async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): |
| | user_input = update.message.text |
| |
|
| | if 'history' not in context.user_data: |
| | context.user_data['history'] = [] |
| |
|
| | history = context.user_data['history'] |
| | history.append({'role': 'user', 'parts': [user_input]}) |
| |
|
| | try: |
| | response = model.generate_content(user_input) |
| | reply_text = response.text |
| | history.append({'role': 'model', 'parts': [reply_text]}) |
| | except Exception as e: |
| | reply_text = f"⚠️ Ошибка: {str(e)}" |
| |
|
| | await update.message.reply_text(reply_text) |
| |
|
| | |
| | if __name__ == "__main__": |
| | application = ApplicationBuilder().token(TELEGRAM_BOT_TOKEN).build() |
| |
|
| | application.add_handler(CommandHandler("start", start)) |
| | application.add_handler(CallbackQueryHandler(button_handler)) |
| | application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) |
| |
|
| | print("✅ Бот успешно запущен...") |
| | application.run_polling() |