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_NAME=your_repo_name
GITHUB_ACCESS_TOKEN=your_github_personal_access_token
# Chat IDs
DAEMON_CHAT_ID=your_daemon_chat_id
APPRENTICE_CHAT_ID=your_apprentice_chat_id
+20 -83
View File
@@ -3,10 +3,8 @@ import os
import importlib
import inspect
import logging
import sys
import subprocess
import requests
from telegram import Update, __version__ as telegram_version, InlineKeyboardButton, InlineKeyboardMarkup
import asyncio
from telegram import error as TelegramErrors, Update, __version__ as telegram_version, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, CallbackQueryHandler
from openai import OpenAI
from dotenv import load_dotenv
@@ -40,12 +38,8 @@ logging.basicConfig(level=logging.WARNING, handlers=[
logging.FileHandler('logs/output.log', mode='a')
])
# 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')
# Set up Telegram bot
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
# Load system prompt
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 = {}
if use_anthropic:
formatted_result = {"role": "user", "content":tool_use_results}
else:
formatted_result = {"role": "function", "name": function_name, "content": json.dumps(tool_use_results[0])}
formatted_result = {"role": "user", "content":tool_use_results}
messages.append(formatted_result)
@@ -187,11 +178,10 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
# Remove the status message
await context.bot.delete_message(chat_id=update.effective_chat.id, message_id=status_message.message_id)
del processing_status[user_id]
if use_anthropic:
try:
await update.message.reply_text(messages[-1]["content"][0].text)
else:
await update.message.reply_text(assistant_reply.content)
except TelegramErrors.BadRequest as e:
logging.error(f"An error occurred when trying to send a message in telegram: {str(e)}")
except Exception as e:
logging.error(f"An error occurred: {str(e)}")
@@ -278,75 +268,22 @@ 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
daemon_app = Application.builder().token(DAEMON_BOT_TOKEN).build()
apprentice_app = Application.builder().token(APPRENTICE_BOT_TOKEN).build()
application = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
# 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$'))
# 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 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()
# Start the Bot
logging.info("Bot is running...")
application.run_polling()
if __name__ == '__main__':
main()