Made it work again

This commit is contained in:
2024-08-18 18:00:22 -05:00
parent 3753fdd286
commit 817220a7be
2 changed files with 21 additions and 88 deletions
-4
View File
@@ -12,7 +12,3 @@ ANTHROPIC_API_KEY=your_anthropic_api_key_here
GITHUB_REPO_OWNER=your_github_username_or_organization GITHUB_REPO_OWNER=your_github_username_or_organization
GITHUB_REPO_NAME=your_repo_name GITHUB_REPO_NAME=your_repo_name
GITHUB_ACCESS_TOKEN=your_github_personal_access_token GITHUB_ACCESS_TOKEN=your_github_personal_access_token
# Chat IDs
DAEMON_CHAT_ID=your_daemon_chat_id
APPRENTICE_CHAT_ID=your_apprentice_chat_id
+19 -82
View File
@@ -3,10 +3,8 @@ import os
import importlib import importlib
import inspect import inspect
import logging import logging
import sys import asyncio
import subprocess from telegram import error as TelegramErrors, Update, __version__ as telegram_version, InlineKeyboardButton, InlineKeyboardMarkup
import requests
from telegram import Update, __version__ as telegram_version, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, CallbackQueryHandler from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, CallbackQueryHandler
from openai import OpenAI from openai import OpenAI
from dotenv import load_dotenv from dotenv import load_dotenv
@@ -40,12 +38,8 @@ logging.basicConfig(level=logging.WARNING, handlers=[
logging.FileHandler('logs/output.log', mode='a') logging.FileHandler('logs/output.log', mode='a')
]) ])
# Set up Telegram bots # Set up Telegram bot
DAEMON_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN') TELEGRAM_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 # Load system prompt
with open("prompts/developer_prompt.txt", "r") as file: with open("prompts/developer_prompt.txt", "r") as file:
@@ -147,10 +141,7 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
formatted_result = {} formatted_result = {}
if use_anthropic:
formatted_result = {"role": "user", "content":tool_use_results} formatted_result = {"role": "user", "content":tool_use_results}
else:
formatted_result = {"role": "function", "name": function_name, "content": json.dumps(tool_use_results[0])}
messages.append(formatted_result) messages.append(formatted_result)
@@ -187,11 +178,10 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
# Remove the status message # Remove the status message
await context.bot.delete_message(chat_id=update.effective_chat.id, message_id=status_message.message_id) await context.bot.delete_message(chat_id=update.effective_chat.id, message_id=status_message.message_id)
del processing_status[user_id] del processing_status[user_id]
try:
if use_anthropic:
await update.message.reply_text(messages[-1]["content"][0].text) await update.message.reply_text(messages[-1]["content"][0].text)
else: except TelegramErrors.BadRequest as e:
await update.message.reply_text(assistant_reply.content) logging.error(f"An error occurred when trying to send a message in telegram: {str(e)}")
except Exception as e: except Exception as e:
logging.error(f"An error occurred: {str(e)}") logging.error(f"An error occurred: {str(e)}")
@@ -278,75 +268,22 @@ async def abort_processing(update: Update, context: ContextTypes.DEFAULT_TYPE) -
else: else:
await query.edit_message_text(text="No active processing to abort.") 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: def main() -> None:
# Create the Application and pass it your bot's token # Create the Application and pass it your bot's token
daemon_app = Application.builder().token(DAEMON_BOT_TOKEN).build() application = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
apprentice_app = Application.builder().token(APPRENTICE_BOT_TOKEN).build()
# Add handlers for both bots # Add handlers
for app in [daemon_app, apprentice_app]: application.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("start", start)) application.add_handler(CommandHandler("clear", clear))
app.add_handler(CommandHandler("clear", clear)) application.add_handler(CommandHandler("switch", switch))
app.add_handler(CommandHandler("switch", switch)) application.add_handler(CommandHandler("toggle", switch_providers))
app.add_handler(CommandHandler("toggle", switch_providers)) application.add_handler(CommandHandler("status", status))
app.add_handler(CommandHandler("status", status)) application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) application.add_handler(CallbackQueryHandler(abort_processing, pattern='^abort$'))
app.add_handler(CallbackQueryHandler(abort_processing, pattern='^abort$'))
# Add handover command only to daemon bot # Start the Bot
daemon_app.add_handler(CommandHandler("handover", handover)) logging.info("Bot is running...")
application.run_polling()
# 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__': if __name__ == '__main__':
main() main()