From e61d675693df9307c82506ccb4272ddd23a0b655 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sun, 26 Mar 2017 12:02:59 +0200 Subject: [PATCH 01/20] fix error logs --- telegram.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/telegram.py b/telegram.py index 5a5a641c..fb9db66d 100644 --- a/telegram.py +++ b/telegram.py @@ -141,7 +141,8 @@ class Bot: async with session.request("GET", f"https://api.telegram.org/bot{token}/{endpoint}", params=params) as response: # Check for errors in the request if response.status != 200: - raise TelegramAPIError(f"Request returned {response.status} {response.reason}\n{response.text()}") + error = await response.text() + raise TelegramAPIError(f"Request returned {response.status} {response.reason}\n{error}") # Parse the json data as soon it's ready data = await response.json() # Check for errors in the response From 9b332e4a3bc67894ae9c4a55687ab76a096dc1dd Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sun, 26 Mar 2017 13:26:01 +0200 Subject: [PATCH 02/20] fix error logs --- telegram.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/telegram.py b/telegram.py index fb9db66d..ad778043 100644 --- a/telegram.py +++ b/telegram.py @@ -139,12 +139,13 @@ class Bot: # Send the request to the Telegram API token = self.token async with session.request("GET", f"https://api.telegram.org/bot{token}/{endpoint}", params=params) as response: - # Check for errors in the request - if response.status != 200: - error = await response.text() - raise TelegramAPIError(f"Request returned {response.status} {response.reason}\n{error}") # Parse the json data as soon it's ready data = await response.json() + # Check for errors in the request + if "description" in data: + error = data["description"] + if response.status != 200: + raise TelegramAPIError(f"Request returned {response.status} {response.reason}\n{}") # Check for errors in the response if not data["ok"]: error = data["description"] @@ -230,7 +231,11 @@ class Chat: # TODO: This could give problems if a class inherits Bot if not isinstance(bot, Bot): raise TypeError("bot is not an instance of Bot.") - await bot.api_request("sendMessage", text=text, chat_id=self.chat_id, **params) + # Catch TelegramAPI exceptions + try: + await bot.api_request("sendMessage", text=text, chat_id=self.chat_id, **params) + except TelegramAPIError as e: + print(f"[Telegram] sendMessage failed: {e.text}") class User: From e7694ffc57d0331684ebdf5a7de47523047734be Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sun, 26 Mar 2017 13:26:49 +0200 Subject: [PATCH 03/20] fix error logs --- telegram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telegram.py b/telegram.py index ad778043..60b7b03b 100644 --- a/telegram.py +++ b/telegram.py @@ -145,7 +145,7 @@ class Bot: if "description" in data: error = data["description"] if response.status != 200: - raise TelegramAPIError(f"Request returned {response.status} {response.reason}\n{}") + raise TelegramAPIError(f"Request returned {response.status} {response.reason}") # Check for errors in the response if not data["ok"]: error = data["description"] From a5b7e836c414c1514a1668244dd2e1afc9a62ebe Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sun, 26 Mar 2017 13:35:42 +0200 Subject: [PATCH 04/20] fix error logs --- telegram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telegram.py b/telegram.py index 60b7b03b..e2ac9cda 100644 --- a/telegram.py +++ b/telegram.py @@ -235,7 +235,7 @@ class Chat: try: await bot.api_request("sendMessage", text=text, chat_id=self.chat_id, **params) except TelegramAPIError as e: - print(f"[Telegram] sendMessage failed: {e.text}") + print(f"[Telegram] sendMessage failed: {e.args[0]}") class User: From c6f2fe1011bea62c556decf8dc9ce1572afc5837 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sun, 26 Mar 2017 13:52:07 +0200 Subject: [PATCH 05/20] Sistemato help --- grandbot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/grandbot.py b/grandbot.py index adec8658..181e9ceb 100644 --- a/grandbot.py +++ b/grandbot.py @@ -231,7 +231,7 @@ Sintassi: `/help [comando]`""" await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/help [comando]`", parse_mode="Markdown") else: if arguments[0] in b.commands: - await update.message.reply(bot, b.commands[arguments[0]].__doc__, parse_mode="Markdown") + await update.message.reply(bot, b.commands[arguments[0] + "_telegram"].__doc__, parse_mode="Markdown") else: await update.message.reply(bot, "⚠ Il comando specificato non esiste.") @@ -246,7 +246,7 @@ Sintassi: `!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__) + bot.send_message(message.channel, b.commands[arguments[0] + "_discord"].__doc__) else: bot.send_message(message.channel, "⚠ Il comando specificato non esiste.") From 8a6d9b1555ffc67130768d18ff358477e61ddba3 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sun, 26 Mar 2017 13:52:49 +0200 Subject: [PATCH 06/20] Sistemato diario --- grandbot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/grandbot.py b/grandbot.py index 181e9ceb..3cb171b4 100644 --- a/grandbot.py +++ b/grandbot.py @@ -125,7 +125,7 @@ Sintassi: `/leggi `""" await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/leggi `", parse_mode="Markdown") return # Open the file - file = open("diario.txt", "r") + file = open("diario.txt", "r", encoding="utf8") # Split the data in lines entries = file.read().split("\n") file.close() @@ -159,7 +159,7 @@ async def leggi_discord(bot, message, arguments): await bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`!leggi `") return # Open the file - file = open("diario.txt", "r") + file = open("diario.txt", "r", encoding="utf8") # Split the data in lines entries = file.read().split("\n") file.close() From 3548775b1855ab17154a4e9a25a371b95ddd6fa2 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sun, 26 Mar 2017 14:08:11 +0200 Subject: [PATCH 07/20] fixed syntax check for roll --- grandbot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/grandbot.py b/grandbot.py index 3cb171b4..218f2f6e 100644 --- a/grandbot.py +++ b/grandbot.py @@ -454,7 +454,7 @@ async def roll_telegram(bot, update, arguments): Sintassi: `/roll `""" # Check the command syntax - if len(arguments) != 0: + if len(arguments) != 1: await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/roll `", parse_mode="Markdown") return @@ -467,7 +467,7 @@ async def roll_discord(bot, message, arguments): Sintassi: `!roll `""" # Check the command syntax - if len(arguments) != 0: + if len(arguments) != 1: await bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`!roll `") return # Roll the dice! From 75887d5ab318d4a6eb82983fbe44da0314bdc6de Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sun, 26 Mar 2017 14:10:32 +0200 Subject: [PATCH 08/20] fixed randrange for roll --- grandbot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/grandbot.py b/grandbot.py index 218f2f6e..cab300bf 100644 --- a/grandbot.py +++ b/grandbot.py @@ -459,7 +459,7 @@ Sintassi: `/roll `""" parse_mode="Markdown") return # Roll the dice! - await update.message.reply(bot, f"*Numero generato:* {random.randrange(0, arguments[0]) + 1}") + await update.message.reply(bot, f"*Numero generato:* {random.randrange(0, int(arguments[0])) + 1}") async def roll_discord(bot, message, arguments): @@ -471,7 +471,7 @@ Sintassi: `!roll `""" 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}") + await bot.send_message(message.channel, f"*Numero generato:* {random.randrange(0, int(arguments[0])) + 1}") if __name__ == "__main__": From 3afcf8ce29983b65634cc7cec0805e2593763a54 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 27 Mar 2017 12:00:37 +0200 Subject: [PATCH 09/20] Added requirements file --- requirements.txt | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 requirements.txt diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..c01fd0c2 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +aiohttp +async_timeout +markovify +discord.py[voice] +sqlalchemy +bcrypt \ No newline at end of file From ef7c93068bcb97a39620ccec2ea1793f557c7edf Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 27 Mar 2017 12:03:29 +0200 Subject: [PATCH 10/20] Added travis file --- .travis.yml | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..c8e24c34 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,7 @@ +language: python +python: + - "3.6" +install: + - pip install -r requirements.txt +script: + - python python -m py_compile grandbot.py \ No newline at end of file From f452bcc468c20b2eda701cfd3302f49500f5d40c Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 27 Mar 2017 12:10:49 +0200 Subject: [PATCH 11/20] Whoops. --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index c8e24c34..72b09a0f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,4 +4,4 @@ python: install: - pip install -r requirements.txt script: - - python python -m py_compile grandbot.py \ No newline at end of file + - python3.6 -m py_compile grandbot.py \ No newline at end of file From f93bb25b3e12825f75f58786bdf1efa547a99c53 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 27 Mar 2017 12:21:59 +0200 Subject: [PATCH 12/20] Added travis badge --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 46eb6acb..ad271be2 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # Royal Bot the Third +[![Build Status](https://travis-ci.org/Steffo99/royal-bot-the-third.svg?branch=master)](https://travis-ci.org/Steffo99/royal-bot-the-third) + A _(not yet)_ modular multiservice bot written in **Python 3.6**! Development has just started, so it isn't ready yet for use. From d98b4e919cc1198973dfbe7df217fee0ec43d7c7 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 27 Mar 2017 12:45:22 +0200 Subject: [PATCH 13/20] Removed error catching in send_message --- telegram.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/telegram.py b/telegram.py index e2ac9cda..9b4e39a1 100644 --- a/telegram.py +++ b/telegram.py @@ -231,11 +231,7 @@ class Chat: # TODO: This could give problems if a class inherits Bot if not isinstance(bot, Bot): raise TypeError("bot is not an instance of Bot.") - # Catch TelegramAPI exceptions - try: - await bot.api_request("sendMessage", text=text, chat_id=self.chat_id, **params) - except TelegramAPIError as e: - print(f"[Telegram] sendMessage failed: {e.args[0]}") + await bot.api_request("sendMessage", text=text, chat_id=self.chat_id, **params) class User: From fb0d03ac513f61c508d1799dd7e667aa2c8e8f48 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 27 Mar 2017 12:48:41 +0200 Subject: [PATCH 14/20] Added set_chat_action --- telegram.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/telegram.py b/telegram.py index 9b4e39a1..930b0088 100644 --- a/telegram.py +++ b/telegram.py @@ -234,6 +234,28 @@ class Chat: await bot.api_request("sendMessage", text=text, chat_id=self.chat_id, **params) + async def set_chat_action(self, bot, action): + """Set a status for the chat. + +Valid actions are: +typing +upload_photo +record_video +upload_video +record_audio +upload_audio +upload_document +find_location""" + # TODO: This could give problems if a class inherits Bot + if not isinstance(bot, Bot): + raise TypeError("bot is not an instance of Bot.") + # Check if the action is valid + if action not in ["typing", "upload_photo", "record_video", "upload_video", "record_audio", "upload_audio", "upload_document", "find_location"]: + raise ValueError("Invalid action") + # Send the request + await bot.api_request("sendChatAction", chat_id=self.chat_id, action=action) + + class User: def __init__(self, user_dict): self.user_id = user_dict["id"] From e206173a36dd87dc5c7f1ea9e8152bd8d11710d5 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 27 Mar 2017 12:49:31 +0200 Subject: [PATCH 15/20] Changed starting db --- database.py | 25 +------------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/database.py b/database.py index 8815225a..913f52d3 100644 --- a/database.py +++ b/database.py @@ -90,30 +90,7 @@ def login(username, password, enable_exceptions=False): def init_royal_db(): - create_user("steffo", "uno", True) - create_user("adry", "due", True) - create_user("cate", "tre", True) - create_user("protoh", "quattro", True) - create_user("infopz", "cinque", True) - create_user("kappa", "sei", True) - create_user("manu", "sette", True) - create_user("frank", "otto", True) - create_user("paltri", "nove", True) - create_user("mestakes", "dieci", True) - create_user("tauei", "undici", True) - create_user("sensei", "dodici", True) - create_user("gattopardo", "tredici", True) - create_user("dima", "quattordici", True) - create_user("spaggia", "quindici", True) - create_user("igor", "sedici", True) - create_user("nemesis", "diciassette", True) - create_user("comiso", "diciotto", True) - create_user("fulz", "diciannove", True) - create_user("dailir", "venti", True) - create_user("fedececco", "ventuno", True) - create_user("albertwerk", "ventidue", True) - create_user("voltaggio", "ventitre", True) - create_user("doc", "ventiquattro", True) + create_user("test", "test", False) session = Session() # Generate the database if it's empty From b1349e2e008323be6b4528938b953f79563b6eb0 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 27 Mar 2017 12:52:02 +0200 Subject: [PATCH 16/20] Set typing chat action when a message is received --- grandbot.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/grandbot.py b/grandbot.py index cab300bf..5f4a886c 100644 --- a/grandbot.py +++ b/grandbot.py @@ -32,6 +32,8 @@ def currently_logged_in(thing): async def start_telegram(bot, update, arguments): + # Set status to typing + await update.message.chat.set_chat_action("typing") 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") @@ -47,6 +49,8 @@ async def diario_telegram(bot, update, arguments): Devi essere un Royal per poter eseguire questo comando. Sintassi: `/diario `""" + # Set status to typing + await update.message.chat.set_chat_action("typing") # Check if the user is logged in if not currently_logged_in(update): await update.message.reply(bot, "⚠ Non hai ancora eseguito l'accesso! Usa `/sync`.", parse_mode="Markdown") @@ -121,6 +125,8 @@ async def leggi_telegram(bot, update, arguments): 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 `""" + # Set status to typing + await update.message.chat.set_chat_action("typing") if len(arguments) == 0 or len(arguments) > 1: await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/leggi `", parse_mode="Markdown") return @@ -190,6 +196,8 @@ Puoi specificare con che parole (massimo 2) deve iniziare la frase generata. Se non vengono specificate, verrà scelta una parola a caso. Sintassi: `/markov [inizio]`""" + # Set status to typing + await update.message.chat.set_chat_action("typing") if len(arguments) > 2: await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/markov [inizio]`") file = open("diario.txt", "r", encoding="utf8") @@ -225,6 +233,8 @@ async def help_telegram(bot, update, arguments): """Visualizza la descrizione di un comando. Sintassi: `/help [comando]`""" + # Set status to typing + await update.message.chat.set_chat_action("typing") if len(arguments) == 0: await update.message.reply(bot, help.__doc__, parse_mode="Markdown") elif len(arguments) > 1: @@ -255,6 +265,8 @@ async def discord_telegram(bot, update, arguments): """Manda un messaggio a #chat di Discord. Sintassi: `/discord `""" + # Set status to typing + await update.message.chat.set_chat_action("typing") # Try to login logged_user = currently_logged_in(update) # Check if the user is logged in @@ -309,6 +321,8 @@ async def sync_telegram(bot, update, arguments): """Connetti il tuo account Telegram al Database Royal Games. Sintassi: `/sync `""" + # Set status to typing + await update.message.chat.set_chat_action("typing") if len(arguments) != 2: await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/sync `", parse_mode="Markdown") return @@ -355,6 +369,8 @@ async def changepassword_telegram(bot, update, arguments): """Cambia la tua password del Database Royal Games. Sintassi: `/changepassword `""" + # Set status to typing + await update.message.chat.set_chat_action("typing") if len(arguments) != 2: await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/changepassword `", parse_mode="Markdown") return @@ -373,6 +389,8 @@ async def cv_telegram(bot, update, arguments): """Visualizza lo stato attuale della chat vocale Discord. Sintassi: `/cv`""" + # Set status to typing + await update.message.chat.set_chat_action("typing") if len(arguments) != 0: await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/cv`", parse_mode="Markdown") return @@ -453,6 +471,8 @@ async def roll_telegram(bot, update, arguments): """Lancia un dado a N facce. Sintassi: `/roll `""" + # Set status to typing + await update.message.chat.set_chat_action("typing") # Check the command syntax if len(arguments) != 1: await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/roll `", From 11cdc3e6fe0419c23641e2af397ac83f0cae7d36 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 27 Mar 2017 12:55:37 +0200 Subject: [PATCH 17/20] oops! --- grandbot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/grandbot.py b/grandbot.py index 5f4a886c..b2d82e87 100644 --- a/grandbot.py +++ b/grandbot.py @@ -33,7 +33,7 @@ def currently_logged_in(thing): async def start_telegram(bot, update, arguments): # Set status to typing - await update.message.chat.set_chat_action("typing") + await update.message.chat.set_chat_action(bot, "typing") 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") From 3e4160f692033949809db4c7ac09a2a5f07f6a76 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 27 Mar 2017 12:57:06 +0200 Subject: [PATCH 18/20] oops!2 --- grandbot.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/grandbot.py b/grandbot.py index b2d82e87..1fe8ddf6 100644 --- a/grandbot.py +++ b/grandbot.py @@ -50,7 +50,7 @@ Devi essere un Royal per poter eseguire questo comando. Sintassi: `/diario `""" # Set status to typing - await update.message.chat.set_chat_action("typing") + await update.message.chat.set_chat_action(bot, "typing") # Check if the user is logged in if not currently_logged_in(update): await update.message.reply(bot, "⚠ Non hai ancora eseguito l'accesso! Usa `/sync`.", parse_mode="Markdown") @@ -126,7 +126,7 @@ Puoi visualizzare il diario [qui](https://royal.steffo.me/diario.htm), leggere u Sintassi: `/leggi `""" # Set status to typing - await update.message.chat.set_chat_action("typing") + await update.message.chat.set_chat_action(bot, "typing") if len(arguments) == 0 or len(arguments) > 1: await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/leggi `", parse_mode="Markdown") return @@ -197,7 +197,7 @@ Se non vengono specificate, verrà scelta una parola a caso. Sintassi: `/markov [inizio]`""" # Set status to typing - await update.message.chat.set_chat_action("typing") + await update.message.chat.set_chat_action(bot, "typing") if len(arguments) > 2: await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/markov [inizio]`") file = open("diario.txt", "r", encoding="utf8") @@ -234,7 +234,7 @@ async def help_telegram(bot, update, arguments): Sintassi: `/help [comando]`""" # Set status to typing - await update.message.chat.set_chat_action("typing") + await update.message.chat.set_chat_action(bot, "typing") if len(arguments) == 0: await update.message.reply(bot, help.__doc__, parse_mode="Markdown") elif len(arguments) > 1: @@ -266,7 +266,7 @@ async def discord_telegram(bot, update, arguments): Sintassi: `/discord `""" # Set status to typing - await update.message.chat.set_chat_action("typing") + await update.message.chat.set_chat_action(bot, "typing") # Try to login logged_user = currently_logged_in(update) # Check if the user is logged in @@ -322,7 +322,7 @@ async def sync_telegram(bot, update, arguments): Sintassi: `/sync `""" # Set status to typing - await update.message.chat.set_chat_action("typing") + await update.message.chat.set_chat_action(bot, "typing") if len(arguments) != 2: await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/sync `", parse_mode="Markdown") return @@ -370,7 +370,7 @@ async def changepassword_telegram(bot, update, arguments): Sintassi: `/changepassword `""" # Set status to typing - await update.message.chat.set_chat_action("typing") + await update.message.chat.set_chat_action(bot, "typing") if len(arguments) != 2: await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/changepassword `", parse_mode="Markdown") return @@ -390,7 +390,7 @@ async def cv_telegram(bot, update, arguments): Sintassi: `/cv`""" # Set status to typing - await update.message.chat.set_chat_action("typing") + await update.message.chat.set_chat_action(bot, "typing") if len(arguments) != 0: await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/cv`", parse_mode="Markdown") return @@ -472,7 +472,7 @@ async def roll_telegram(bot, update, arguments): Sintassi: `/roll `""" # Set status to typing - await update.message.chat.set_chat_action("typing") + await update.message.chat.set_chat_action(bot, "typing") # Check the command syntax if len(arguments) != 1: await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/roll `", From 1c0474312806a4f3315f704c955da7f96a9730a6 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Tue, 28 Mar 2017 16:49:58 +0200 Subject: [PATCH 19/20] Edited TelegramAPIError class --- telegram.py | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/telegram.py b/telegram.py index 930b0088..d51b5085 100644 --- a/telegram.py +++ b/telegram.py @@ -5,7 +5,11 @@ import datetime class TelegramAPIError(Exception): - pass + def __init__(self, code, description): + # Error code + self.code = code + # Error description + self.description = description class UpdateError(Exception): @@ -142,14 +146,8 @@ class Bot: # Parse the json data as soon it's ready data = await response.json() # Check for errors in the request - if "description" in data: - error = data["description"] - if response.status != 200: - raise TelegramAPIError(f"Request returned {response.status} {response.reason}") - # Check for errors in the response - if not data["ok"]: - error = data["description"] - raise TelegramAPIError(f"Response returned an error: {error}") + if response.status != 200 or not data["ok"]: + raise TelegramAPIError(data["error_code"], data["description"]) # Return a dictionary containing the data return data["result"] From 90f8add3910f752cbc98be66913acbef4959c202 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Tue, 28 Mar 2017 17:43:07 +0200 Subject: [PATCH 20/20] Database stuff --- database.py | 3 ++- grandbot.py | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 71 insertions(+), 4 deletions(-) diff --git a/database.py b/database.py index 913f52d3..56a82ec2 100644 --- a/database.py +++ b/database.py @@ -1,3 +1,4 @@ +import sqlalchemy.exc from sqlalchemy import create_engine, Column, Integer, String, Boolean from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base @@ -90,7 +91,7 @@ def login(username, password, enable_exceptions=False): def init_royal_db(): - create_user("test", "test", False) + create_user("test", "test", True) session = Session() # Generate the database if it's empty diff --git a/grandbot.py b/grandbot.py index 1fe8ddf6..9f92d868 100644 --- a/grandbot.py +++ b/grandbot.py @@ -158,9 +158,9 @@ Sintassi: `/leggi `""" 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 `. +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 `""" +Sintassi: `!leggi `""" if len(arguments) == 0 or len(arguments) > 1: await bot.send_message(message.channel, "⚠ Sintassi del comando non valida.\n`!leggi `") return @@ -479,7 +479,7 @@ Sintassi: `/roll `""" parse_mode="Markdown") return # Roll the dice! - await update.message.reply(bot, f"*Numero generato:* {random.randrange(0, int(arguments[0])) + 1}") + await update.message.reply(bot, f"*Numero generato:* {random.randrange(0, int(arguments[0])) + 1}", parse_mode="Markdown") async def roll_discord(bot, message, arguments): @@ -494,6 +494,70 @@ Sintassi: `!roll `""" await bot.send_message(message.channel, f"*Numero generato:* {random.randrange(0, int(arguments[0])) + 1}") +async def adduser_telegram(bot, update, arguments): + """Aggiungi un utente al database Royal Games! + +Devi essere un Royal per poter eseguire questo comando. + +Sintassi: `/adduser `""" + # Check if the user is logged in + if not currently_logged_in(update): + await update.message.reply(bot, "⚠ 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(update).royal: + await update.message.reply(bot, "⚠ Non sei autorizzato a eseguire questo comando.") + return + # Check the command syntax + if len(arguments) != 2: + await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/adduser `", parse_mode="Markdown") + return + # Try to create a new user + try: + database.create_user(arguments[0], arguments[1], False) + except database.sqlalchemy.exc.DBAPIError: + await update.message.reply(bot, "⚠ Qualcosa è andato storto nella creazione dell'utente. Per altre info, guarda i log del bot.") + raise + else: + await update.message.reply(bot, "✅ Creazione riuscita!") + + +async def toggleroyal_telegram(bot, update, arguments): + """Inverti lo stato di Royal di un utente. + +Devi essere un Royal per poter eseguire questo comando. + +Sintassi: `/toggleroyal `""" + # Check if the user is logged in + if not currently_logged_in(update): + await update.message.reply(bot, "⚠ 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(update).royal: + await update.message.reply(bot, "⚠ Non sei autorizzato a eseguire questo comando.") + return + # Check the command syntax + if len(arguments) != 1: + await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/toggleroyal `", parse_mode="Markdown") + return + # Create a new database session + session = database.Session() + # Find the user + user = session.query(database.User).filter_by(username=arguments[0]).first() + # Check if the user exists + if user is None: + await update.message.reply(bot, "⚠ L'utente specificato non esiste.") + return + # Toggle his Royal status + user.royal = not user.royal + # Save the change + session.commit() + # Answer on Telegram + if user.royal: + await update.message.reply(bot, f"✅ L'utente `{user.username}` ora è un Royal.", parse_mode="Markdown") + else: + await update.message.reply(bot, f"✅ L'utente `{user.username}` non è più un Royal.", parse_mode="Markdown") + if __name__ == "__main__": # Init Telegram bot commands b.commands["start"] = start_telegram @@ -506,6 +570,8 @@ if __name__ == "__main__": b.commands["markov"] = markov_telegram b.commands["cv"] = cv_telegram b.commands["roll"] = roll_telegram + b.commands["adduser"] = adduser_telegram + b.commands["toggleroyal"] = toggleroyal_telegram # Init Discord bot commands d.commands["sync"] = sync_discord d.commands["roll"] = roll_discord