Add Telegram bot support #23

Merged
Berack96 merged 23 commits from 6-telegram-interface into main 2025-10-13 10:49:46 +02:00
Showing only changes of commit e6e40f96f0 - Show all commits

View File

@@ -3,10 +3,9 @@ from enum import Enum
from typing import Any from typing import Any
from agno.utils.log import log_info # type: ignore from agno.utils.log import log_info # type: ignore
from telegram import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message, Update, User from telegram import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message, Update, User
from telegram.ext import Application, CommandHandler, ContextTypes, ConversationHandler, ExtBot, JobQueue, CallbackQueryHandler, MessageHandler, filters from telegram.constants import ChatAction
from app.models import AppModels from telegram.ext import Application, CallbackQueryHandler, CommandHandler, ContextTypes, ConversationHandler, ExtBot, JobQueue, MessageHandler, filters
from app.predictor import PredictorStyle from app.agents import AppModels, PredictorStyle
# Lo stato cambia in base al valore di ritorno delle funzioni async # Lo stato cambia in base al valore di ritorno delle funzioni async
# END state è già definito in telegram.ext.ConversationHandler # END state è già definito in telegram.ext.ConversationHandler
@@ -29,14 +28,11 @@ class ConfigsChat(Enum):
STRATEGY = "Strategy" STRATEGY = "Strategy"
class ConfigsRun: class ConfigsRun:
model_team: AppModels
model_output: AppModels
strategy: PredictorStyle
def __init__(self): def __init__(self):
self.model_team = BotFunctions.app_models[0] self.model_team = BotFunctions.app_models[0]
self.model_output = BotFunctions.app_models[0] self.model_output = BotFunctions.app_models[0]
self.strategy = PredictorStyle.CONSERVATIVE self.strategy = PredictorStyle.CONSERVATIVE
self.user_query = ""
@@ -95,8 +91,8 @@ class BotFunctions:
confs = BotFunctions.users_req.setdefault(user, ConfigsRun()) confs = BotFunctions.users_req.setdefault(user, ConfigsRun())
str_model_team = f"{ConfigsChat.MODEL_TEAM.value}: {confs.model_team.name}" str_model_team = f"{ConfigsChat.MODEL_TEAM.value}: {confs.model_team.name}"
str_model_output = f"{ConfigsChat.MODEL_OUTPUT.value}:\t\t {confs.model_output.name}" str_model_output = f"{ConfigsChat.MODEL_OUTPUT.value}: {confs.model_output.name}"
str_strategy = f"{ConfigsChat.STRATEGY.value}:\t\t {confs.strategy.name}" str_strategy = f"{ConfigsChat.STRATEGY.value}: {confs.strategy.name}"
msg, keyboard = ( msg, keyboard = (
"Please choose an option or write your query", "Please choose an option or write your query",
@@ -185,12 +181,14 @@ class BotFunctions:
@staticmethod @staticmethod
async def __start_team(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: async def __start_team(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
message, user = await BotFunctions.handle_message(update) message, user = await BotFunctions.handle_message(update)
msg2 = await message.reply_text("Elaborating your request...")
confs = BotFunctions.users_req[user] confs = BotFunctions.users_req[user]
log_info(f"@{user.username} started the team with [{confs.model_team}, {confs.model_output}, {confs.strategy}]") confs.user_query = message.text or ""
await BotFunctions.__run_team(confs, msg2) log_info(f"@{user.username} started the team with [{confs.model_team}, {confs.model_output}, {confs.strategy}]")
await BotFunctions.__run_team(update, confs)
log_info(f"@{user.username} team finished.")
return ConversationHandler.END return ConversationHandler.END
@staticmethod @staticmethod
@@ -203,16 +201,43 @@ class BotFunctions:
return ConversationHandler.END return ConversationHandler.END
@staticmethod @staticmethod
async def __run_team(confs: ConfigsRun, msg: Message) -> None: async def __run_team(update: Update, confs: ConfigsRun) -> None:
# TODO fare il run effettivo del team if not update.message: return
import asyncio
bot = update.get_bot()
msg_id = update.message.message_id - 1
chat_id = update.message.chat_id
configs = [
'Running with configurations: ',
f'Team: {confs.model_team.name}',
f'Output: {confs.model_output.name}',
f'Strategy: {confs.strategy.name}',
f'Query: "{confs.user_query}"'
]
full_message = f"""```\n{'\n'.join(configs)}\n```\n\n"""
msg = await bot.edit_message_text(chat_id=chat_id, message_id=msg_id, text=full_message, parse_mode='MarkdownV2')
if isinstance(msg, bool): return
# Remove user query and bot message
await bot.delete_message(chat_id=chat_id, message_id=update.message.id)
# TODO fare il run effettivo del team
# Simulate a long-running task # Simulate a long-running task
n_simulations = 3 n_simulations = 3
import asyncio
await bot.send_chat_action(chat_id=chat_id, action=ChatAction.TYPING)
for i in range(n_simulations): for i in range(n_simulations):
await msg.edit_text(f"Working... {i+1}/{n_simulations}") await msg.edit_text(f"{full_message}Working {i+1}/{n_simulations}", parse_mode='MarkdownV2')
await asyncio.sleep(2) await asyncio.sleep(2)
await msg.edit_text("Team work completed.") await msg.delete()
# attach report file to the message
import io
report_content = f"# Report\n\nThis is a sample report generated by the team."
document = io.BytesIO(report_content.encode('utf-8'))
await bot.send_document(chat_id=chat_id, document=document, filename="report.md", parse_mode='MarkdownV2', caption=full_message)