From 6a75d760e0d1fe1d6d5aff18a5ec057027569df3 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 27 Feb 2017 23:52:47 +0100 Subject: [PATCH] Added /diario to the basic bot + other things --- basicbot.py | 19 +++++++++++++++---- telegram.py | 14 ++++++++++++-- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/basicbot.py b/basicbot.py index 7e589d05..679417d8 100644 --- a/basicbot.py +++ b/basicbot.py @@ -2,10 +2,21 @@ import asyncio loop = asyncio.get_event_loop() import telegram -b = telegram.Bot("ciao pizza") +b = telegram.Bot("hidden") -async def print_message(bot, update): - print(update.message.content) +async def diario(bot, update, arguments): + # Sì, ho copiato la funzione dal bot vecchio + if len(arguments) > 0: + entry = " ".join(arguments) + if entry.isprintable(): + entry = entry.replace("\n", " ") + time = update.message.date.timestamp() + # TODO: add better file handling + fdiario = open("diario.txt", "a") + fdiario.write(f"{int(time)}|{entry}\n") + fdiario.close() + del fdiario + await update.message.chat.send_message(bot, "Aggiunto al diario!") -b.commands["echo"] = print_message +b.commands["diario"] = diario b.run() \ No newline at end of file diff --git a/telegram.py b/telegram.py index 498f1af8..514c6fde 100644 --- a/telegram.py +++ b/telegram.py @@ -60,10 +60,15 @@ class Bot: # Add the chat to the chat list if update.message.chat not in self.chats: self.chats.append(update.message.chat) + else: + # Replace the chat object in the update with the correct one + update.message.chat = self.chats[self.chats.index(update.message.chat)] # Add the user to the chat chat = self.find_chat(update.message.chat.chat_id) if update.message.sent_from not in chat.users: chat.users.append(update.message.sent_from) + else: + update.message.sent_from = chat.users[chat.users.index(update.message.sent_from)] # Add / edit the message to the message list if not update.message.edited: chat.messages.append(update.message) @@ -77,9 +82,11 @@ class Bot: # Check if a command can be run # TODO: use message entities? if isinstance(update.message.content, str) and update.message.content.startswith("/"): - command = update.message.content.split(" ")[0].lstrip("/") + split_msg = update.message.content.split(" ") + command = split_msg[0].lstrip("/") if command in self.commands: - loop.create_task(self.commands[command](self, update)) + arguments = split_msg[1:] + loop.create_task(self.commands[command](bot=self, update=update, arguments=arguments)) # Update message status if a service message is received if isinstance(update.message.content, ServiceMessage): # New user in chat @@ -207,6 +214,9 @@ class Chat: if msg.msg_id == msg_id: return msg + async def send_message(self, bot, text, **params): + """Send a message in the chat through the bot object.""" + await bot.api_request("sendMessage", text=text, chat_id=self.chat_id, **params) class User: