From 067a7808b27fc84dd1eb4f18cf3f5c2b3e4b0880 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Fri, 24 Mar 2017 12:24:39 +0100 Subject: [PATCH 1/6] Renamed files and functions --- grandbot.py | 63 ++++++++++++++++++++--------- extra_discord.py => royaldiscord.py | 0 2 files changed, 45 insertions(+), 18 deletions(-) rename extra_discord.py => royaldiscord.py (100%) diff --git a/grandbot.py b/grandbot.py index 9c73bb6b..529c4203 100644 --- a/grandbot.py +++ b/grandbot.py @@ -4,7 +4,7 @@ import json import random import aiohttp import async_timeout -import extra_discord +import royaldiscord import markovify import database import royalbotconfig @@ -12,7 +12,7 @@ import telegram loop = asyncio.get_event_loop() b = telegram.Bot(royalbotconfig.telegram_token) -d = extra_discord.ExtraClient(royalbotconfig.discord_token) +d = royaldiscord.ExtraClient(royalbotconfig.discord_token) def currently_logged_in(update): @@ -22,7 +22,7 @@ def currently_logged_in(update): return user -async def start(bot, update, arguments): +async def start_telegram(bot, update, arguments): user = currently_logged_in(update) if user is None: await update.message.reply(bot, f"Ciao!\n_Non hai eseguito l'accesso al RYGdb._", parse_mode="Markdown") @@ -32,7 +32,7 @@ async def start(bot, update, arguments): await update.message.reply(bot, f"Ciao!\nHai eseguito l'accesso come `{user}`.\n\n*Account collegati:*\n{telegram_status} Telegram\n{discord_status} Discord", parse_mode="Markdown") -async def diario(bot, update, arguments): +async def diario_telegram(bot, update, arguments): """Aggiungi una frase al diario Royal Games. Devi essere un Royal per poter eseguire questo comando. @@ -69,7 +69,7 @@ Sintassi: `/diario `""" await update.message.reply(bot, "✅ Aggiunto al diario!") -async def leggi(bot, update, arguments): +async def leggi_telegram(bot, update, arguments): """Leggi una frase dal diario Royal Games. Puoi visualizzare il diario [qui](https://royal.steffo.me/diario.htm), leggere una frase casuale scrivendo `/leggi random` o leggere una frase specifica scrivendo `/leggi `. @@ -101,7 +101,7 @@ Sintassi: `/leggi `""" await update.message.reply(bot, f"Frase #{entry_number} | {date}\n{text}", parse_mode="Markdown") -async def markov(bot, update, arguments): +async def markov_telegram(bot, update, arguments): """Genera una frase del diario utilizzando le catene di Markov. Puoi specificare con che parole (massimo 2) deve iniziare la frase generata. @@ -139,7 +139,7 @@ Sintassi: `/markov [inizio]`""" await update.message.reply(bot, f"⚠ Il bot non è riuscito a generare una nuova frase.\nSe è la prima volta che vedi questo errore, riprova, altrimenti prova a cambiare configurazione.") -async def help_cmd(bot, update, arguments): +async def help_telegram(bot, update, arguments): """Visualizza la descrizione di un comando. Sintassi: `/help [comando]`""" @@ -154,7 +154,7 @@ Sintassi: `/help [comando]`""" await update.message.reply(bot, "⚠ Il comando specificato non esiste.") -async def discord(bot, update, arguments): +async def discord_telegram(bot, update, arguments): """Manda un messaggio a #chat di Discord. Sintassi: `/discord `""" @@ -254,7 +254,7 @@ Sintassi: `!sync `""" await bot.send_message(message.channel, "⚠ Username o password non validi.") -async def changepassword(bot, update, arguments): +async def changepassword_telegram(bot, update, arguments): """Cambia la tua password del Database Royal Games. Sintassi: `/changepassword `""" @@ -272,7 +272,7 @@ Sintassi: `/changepassword `""" await update.message.reply(bot, "⚠ Username o password non validi.", parse_mode="Markdown") -async def cv(bot, update, arguments): +async def cv_telegram(bot, update, arguments): """Visualizza lo stato attuale della chat vocale Discord. Sintassi: `/cv`""" @@ -352,19 +352,46 @@ Sintassi: `/cv`""" await update.message.reply(bot, to_send, parse_mode="Markdown", disable_web_page_preview=1) +async def roll_telegram(bot, update, arguments): + """Lancia un dado a N facce. + +Sintassi: `/roll `""" + # Check the command syntax + if len(arguments) != 0: + await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/roll `", + parse_mode="Markdown") + return + # Roll the dice! + await update.message.reply(bot, f"*Numero generato:* {random.randrange(0, arguments[0]) + 1}") + + +async def roll_discord(bot, message, arguments): + """Lancia un dado a N facce. + +Sintassi: `!roll `""" + # Check the command syntax + if len(arguments) != 0: + await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/roll `", + parse_mode="Markdown") + return + # Roll the dice! + await bot.send_message(message.channel, f"*Numero generato:* {random.randrange(0, arguments[0]) + 1}") + if __name__ == "__main__": # Init Telegram bot commands - b.commands["start"] = start - b.commands["leggi"] = leggi - b.commands["diario"] = diario - b.commands["discord"] = discord + b.commands["start"] = start_telegram + b.commands["leggi"] = leggi_telegram + b.commands["diario"] = diario_telegram + b.commands["discord"] = discord_telegram b.commands["sync"] = sync_telegram - b.commands["changepassword"] = changepassword - b.commands["help"] = help_cmd - b.commands["markov"] = markov - b.commands["cv"] = cv + b.commands["changepassword"] = changepassword_telegram + b.commands["help"] = help_telegram + b.commands["markov"] = markov_telegram + b.commands["cv"] = cv_telegram + b.commands["roll"] = roll_telegram # Init Discord bot commands d.commands["sync"] = sync_discord + d.commands["roll"] = roll_discord # Init Telegram bot loop.create_task(b.run()) print("Telegram bot start scheduled!") diff --git a/extra_discord.py b/royaldiscord.py similarity index 100% rename from extra_discord.py rename to royaldiscord.py From 38c56f8c1c1208a7f10d4c549f2f99a817e770f7 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Fri, 24 Mar 2017 12:27:54 +0100 Subject: [PATCH 2/6] Added discord !help command --- grandbot.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/grandbot.py b/grandbot.py index 529c4203..e8940389 100644 --- a/grandbot.py +++ b/grandbot.py @@ -154,6 +154,21 @@ Sintassi: `/help [comando]`""" await update.message.reply(bot, "⚠ Il comando specificato non esiste.") +async def help_discord(bot, message, arguments): + """Visualizza la descrizione di un comando. + +Sintassi: `!help [comando]`""" + if len(arguments) == 0: + bot.send_message(message.channel, help.__doc__) + elif len(arguments) > 1: + bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`/help [comando]`") + else: + if arguments[0] in b.commands: + bot.send_message(message.channel, b.commands[arguments[0]].__doc__) + else: + bot.send_message(message.channel, "⚠ Il comando specificato non esiste.") + + async def discord_telegram(bot, update, arguments): """Manda un messaggio a #chat di Discord. @@ -377,6 +392,7 @@ Sintassi: `!roll `""" # Roll the dice! await bot.send_message(message.channel, f"*Numero generato:* {random.randrange(0, arguments[0]) + 1}") + if __name__ == "__main__": # Init Telegram bot commands b.commands["start"] = start_telegram @@ -392,6 +408,7 @@ if __name__ == "__main__": # Init Discord bot commands d.commands["sync"] = sync_discord d.commands["roll"] = roll_discord + d.commands["help"] = help_discord # Init Telegram bot loop.create_task(b.run()) print("Telegram bot start scheduled!") From 81bd11e54a3e041568e2aaa758ff08750f82f599 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Fri, 24 Mar 2017 12:30:34 +0100 Subject: [PATCH 3/6] Added discord !leggi command --- grandbot.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/grandbot.py b/grandbot.py index e8940389..2b312a34 100644 --- a/grandbot.py +++ b/grandbot.py @@ -101,6 +101,38 @@ Sintassi: `/leggi `""" await update.message.reply(bot, f"Frase #{entry_number} | {date}\n{text}", parse_mode="Markdown") +async def leggi_discord(bot, message, arguments): + """Leggi una frase dal diario Royal Games. + + Puoi visualizzare il diario [qui](https://royal.steffo.me/diario.htm), leggere una frase casuale scrivendo `/leggi random` o leggere una frase specifica scrivendo `/leggi `. + + Sintassi: `!leggi `""" + if len(arguments) == 0 or len(arguments) > 1: + await bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`/leggi `") + return + # Open the file + file = open("diario.txt", "r") + # Split the data in lines + entries = file.read().split("\n") + file.close() + # Choose an entry + if arguments[0] == "random": + # either randomly... + entry_number = random.randrange(len(entries)) + else: + # ...or a specific one + entry_number = arguments[0] + # Split the timestamp from the text + entry = entries[entry_number].split("|", 1) + # Parse the timestamp + date = datetime.datetime.fromtimestamp(entry[0]).isoformat() + # Get the text + text = entry[1] + # Sanitize the text to prevent TelegramErrors + text = text.replace("_", "\_").replace("*", "\*").replace("`", "\`").replace("[", "\[") + await bot.send_message(message.channel, f"Frase #{entry_number} | {date}\n{text}") + + async def markov_telegram(bot, update, arguments): """Genera una frase del diario utilizzando le catene di Markov. @@ -409,6 +441,7 @@ if __name__ == "__main__": d.commands["sync"] = sync_discord d.commands["roll"] = roll_discord d.commands["help"] = help_discord + d.commands["leggi"] = leggi_discord # Init Telegram bot loop.create_task(b.run()) print("Telegram bot start scheduled!") From 9f595583350b8164da7a5b21f94aaa0daa519b18 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Fri, 24 Mar 2017 12:45:54 +0100 Subject: [PATCH 4/6] Added Discord !diario command Also, currently_logged_in now support discord messages --- grandbot.py | 54 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 4 deletions(-) diff --git a/grandbot.py b/grandbot.py index 2b312a34..4bbbbaec 100644 --- a/grandbot.py +++ b/grandbot.py @@ -15,10 +15,19 @@ b = telegram.Bot(royalbotconfig.telegram_token) d = royaldiscord.ExtraClient(royalbotconfig.discord_token) -def currently_logged_in(update): +def currently_logged_in(thing): """Trova l'utente connesso all'account di Telegram che ha mandato l'update.""" + # Create a new database session session = database.Session() - user = session.query(database.User).filter_by(telegram_id=update.message.sent_from.user_id).first() + # Check if thing is a Telegram update + if isinstance(thing, telegram.Update): + user = session.query(database.User).filter_by(telegram_id=thing.message.sent_from.user_id).first() + # Check if thing is a Discord message + elif isinstance(thing, royaldiscord.discord.Message): + user = session.query(database.User).filter_by(discord_id=thing.author.id).first() + # I don't know what thing is. + else: + raise TypeError("thing must be either a telegram.Update or a discord.Message") return user @@ -69,6 +78,43 @@ Sintassi: `/diario `""" await update.message.reply(bot, "✅ Aggiunto al diario!") +async def diario_discord(bot, message, arguments): + """Aggiungi una frase al diario Royal Games. + +Devi essere un Royal per poter eseguire questo comando. + +Sintassi: `!diario `""" + # Check if the user is logged in + if not currently_logged_in(message): + bot.send_message(message.channel, "⚠ Non hai ancora eseguito l'accesso! Usa `/sync`.", parse_mode="Markdown") + return + # Check if the currently logged in user is a Royal Games member + if not currently_logged_in(message).royal: + bot.send_message(message.channel, "⚠ Non sei autorizzato a eseguire questo comando.") + return + # Check the command syntax + if len(arguments) == 0: + bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`/diario `", parse_mode="Markdown") + return + # Check for non-ASCII characters + entry = " ".join(arguments) + if not entry.isprintable(): + bot.send_message(message.channel, "⚠ La frase che stai provando ad aggiungere contiene caratteri non ASCII, quindi non è stata aggiunta.\nToglili e riprova!") + return + # Remove endlines + entry = entry.replace("\n", " ") + # TODO: check if a end-of-file character can be sent on Discord + # Generate a timestamp + time = message.timestamp + # Write on the diario file + file = open("diario.txt", "a", encoding="utf8") + file.write(f"{int(time)}|{entry}\n") + file.close() + del file + # Answer on Telegram + bot.send_message(message.channel, "✅ Aggiunto al diario!") + + async def leggi_telegram(bot, update, arguments): """Leggi una frase dal diario Royal Games. @@ -418,8 +464,7 @@ async def roll_discord(bot, message, arguments): Sintassi: `!roll `""" # Check the command syntax if len(arguments) != 0: - await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/roll `", - parse_mode="Markdown") + await bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`/roll `", parse_mode="Markdown") return # Roll the dice! await bot.send_message(message.channel, f"*Numero generato:* {random.randrange(0, arguments[0]) + 1}") @@ -442,6 +487,7 @@ if __name__ == "__main__": d.commands["roll"] = roll_discord d.commands["help"] = help_discord d.commands["leggi"] = leggi_discord + d.commands["diario"] = diario_discord # Init Telegram bot loop.create_task(b.run()) print("Telegram bot start scheduled!") From c84ecfa6740eb2cec993ae625ce887eba248ba8a Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Fri, 24 Mar 2017 12:52:38 +0100 Subject: [PATCH 5/6] Some fixes --- grandbot.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/grandbot.py b/grandbot.py index 4bbbbaec..a63de24b 100644 --- a/grandbot.py +++ b/grandbot.py @@ -86,7 +86,7 @@ Devi essere un Royal per poter eseguire questo comando. Sintassi: `!diario `""" # Check if the user is logged in if not currently_logged_in(message): - bot.send_message(message.channel, "⚠ Non hai ancora eseguito l'accesso! Usa `/sync`.", parse_mode="Markdown") + bot.send_message(message.channel, "⚠ Non hai ancora eseguito l'accesso! Usa `!sync`.") return # Check if the currently logged in user is a Royal Games member if not currently_logged_in(message).royal: @@ -94,7 +94,7 @@ Sintassi: `!diario `""" return # Check the command syntax if len(arguments) == 0: - bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`/diario `", parse_mode="Markdown") + bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`!diario `") return # Check for non-ASCII characters entry = " ".join(arguments) @@ -154,7 +154,7 @@ async def leggi_discord(bot, message, arguments): Sintassi: `!leggi `""" if len(arguments) == 0 or len(arguments) > 1: - await bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`/leggi `") + await bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`!leggi `") return # Open the file file = open("diario.txt", "r") @@ -239,7 +239,7 @@ Sintassi: `!help [comando]`""" if len(arguments) == 0: bot.send_message(message.channel, help.__doc__) elif len(arguments) > 1: - bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`/help [comando]`") + bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`!help [comando]`") else: if arguments[0] in b.commands: bot.send_message(message.channel, b.commands[arguments[0]].__doc__) @@ -464,7 +464,7 @@ async def roll_discord(bot, message, arguments): Sintassi: `!roll `""" # Check the command syntax if len(arguments) != 0: - await bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`/roll `", parse_mode="Markdown") + await bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`!roll `") return # Roll the dice! await bot.send_message(message.channel, f"*Numero generato:* {random.randrange(0, arguments[0]) + 1}") From 404bda88f49c1dd9d9d251ecc9346b8e17a3cd47 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Fri, 24 Mar 2017 12:56:05 +0100 Subject: [PATCH 6/6] TODO --- grandbot.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/grandbot.py b/grandbot.py index a63de24b..adec8658 100644 --- a/grandbot.py +++ b/grandbot.py @@ -135,11 +135,13 @@ Sintassi: `/leggi `""" entry_number = random.randrange(len(entries)) else: # ...or a specific one - entry_number = arguments[0] + # TODO: check if the entry actually exists + # TODO: check if the first argument is a number + entry_number = int(arguments[0]) # Split the timestamp from the text entry = entries[entry_number].split("|", 1) # Parse the timestamp - date = datetime.datetime.fromtimestamp(entry[0]).isoformat() + date = datetime.datetime.fromtimestamp(int(entry[0])).isoformat() # Get the text text = entry[1] # Sanitize the text to prevent TelegramErrors @@ -167,11 +169,13 @@ async def leggi_discord(bot, message, arguments): entry_number = random.randrange(len(entries)) else: # ...or a specific one - entry_number = arguments[0] + # TODO: check if the entry actually exists + # TODO: check if the first argument is a number + entry_number = int(arguments[0]) # Split the timestamp from the text entry = entries[entry_number].split("|", 1) # Parse the timestamp - date = datetime.datetime.fromtimestamp(entry[0]).isoformat() + date = datetime.datetime.fromtimestamp(int(entry[0])).isoformat() # Get the text text = entry[1] # Sanitize the text to prevent TelegramErrors