diff --git a/telegram_inference_bot.py b/telegram_inference_bot.py index 9cb6bb0..8b0c929 100644 --- a/telegram_inference_bot.py +++ b/telegram_inference_bot.py @@ -4,6 +4,8 @@ import importlib import inspect import logging import asyncio +import subprocess +import requests from telegram import Update, __version__ as telegram_version, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, CallbackQueryHandler from openai import OpenAI @@ -38,8 +40,12 @@ logging.basicConfig(level=logging.WARNING, handlers=[ logging.FileHandler('logs/output.log', mode='a') ]) -# Set up Telegram bot -TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN') +# Set up Telegram bots +DAEMON_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN') +APPRENTICE_BOT_TOKEN = os.getenv('TELEGRAM_APPRENTICE_BOT_TOKEN') +GITHUB_REPO_OWNER = os.getenv('GITHUB_REPO_OWNER') +GITHUB_REPO_NAME = os.getenv('GITHUB_REPO_NAME') +GITHUB_ACCESS_TOKEN = os.getenv('GITHUB_ACCESS_TOKEN') # Load system prompt with open("prompts/developer_prompt.txt", "r") as file: @@ -272,22 +278,75 @@ async def abort_processing(update: Update, context: ContextTypes.DEFAULT_TYPE) - else: await query.edit_message_text(text="No active processing to abort.") +async def handover(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + if context.bot.token == DAEMON_BOT_TOKEN: + # Daemon bot initiating handover + apprentice_chat_id = os.getenv('APPRENTICE_CHAT_ID') + await context.bot.send_message(chat_id=apprentice_chat_id, text="Handover initiated. Taking control.") + await update.message.reply_text("Handover initiated. Apprentice bot is now in control.") + else: + await update.message.reply_text("Handover can only be initiated by the daemon bot.") + +async def update_apprentice(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + if context.bot.token == APPRENTICE_BOT_TOKEN: + try: + # Pull latest changes + subprocess.run(["git", "pull", "origin", "main"], check=True) + + # Restart the bot + os.execv(sys.executable, ['python'] + sys.argv) + except subprocess.CalledProcessError as e: + logging.error(f"Failed to pull latest changes: {e}") + await update.message.reply_text("Failed to update. Please check the logs.") + except Exception as e: + logging.error(f"Failed to restart the bot: {e}") + await update.message.reply_text("Failed to restart. Please check the logs.") + else: + await update.message.reply_text("Update can only be performed by the apprentice bot.") + +async def check_for_updates(context: ContextTypes.DEFAULT_TYPE) -> None: + url = f"https://api.github.com/repos/{GITHUB_REPO_OWNER}/{GITHUB_REPO_NAME}/pulls" + headers = {"Authorization": f"token {GITHUB_ACCESS_TOKEN}"} + response = requests.get(url, headers=headers) + + if response.status_code == 200: + pull_requests = response.json() + for pr in pull_requests: + if pr['state'] == 'closed' and pr['merged']: + # A pull request was merged, update the apprentice bot + await context.bot.send_message(chat_id=os.getenv('APPRENTICE_CHAT_ID'), text="A new update is available. Updating now...") + await update_apprentice(None, context) + break + def main() -> None: # Create the Application and pass it your bot's token - application = Application.builder().token(TELEGRAM_BOT_TOKEN).build() + daemon_app = Application.builder().token(DAEMON_BOT_TOKEN).build() + apprentice_app = Application.builder().token(APPRENTICE_BOT_TOKEN).build() - # Add handlers - application.add_handler(CommandHandler("start", start)) - application.add_handler(CommandHandler("clear", clear)) - application.add_handler(CommandHandler("switch", switch)) - application.add_handler(CommandHandler("toggle", switch_providers)) - application.add_handler(CommandHandler("status", status)) - application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) - application.add_handler(CallbackQueryHandler(abort_processing, pattern='^abort$')) + # Add handlers for both bots + for app in [daemon_app, apprentice_app]: + app.add_handler(CommandHandler("start", start)) + app.add_handler(CommandHandler("clear", clear)) + app.add_handler(CommandHandler("switch", switch)) + app.add_handler(CommandHandler("toggle", switch_providers)) + app.add_handler(CommandHandler("status", status)) + app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) + app.add_handler(CallbackQueryHandler(abort_processing, pattern='^abort$')) - # Start the Bot - logging.info("Bot is running...") - application.run_polling() + # Add handover command only to daemon bot + daemon_app.add_handler(CommandHandler("handover", handover)) + + # Add update command only to apprentice bot + apprentice_app.add_handler(CommandHandler("update", update_apprentice)) + + # Set up job queue to check for updates every 15 minutes + job_queue = apprentice_app.job_queue + job_queue.run_repeating(check_for_updates, interval=900, first=10) + + # Start both bots + logging.info("Bots are running...") + daemon_app.run_polling() + apprentice_app.run_polling() if __name__ == '__main__': main() \ No newline at end of file