From 1c0474312806a4f3315f704c955da7f96a9730a6 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Tue, 28 Mar 2017 16:49:58 +0200 Subject: [PATCH 1/3] 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 2/3] 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 From d742c268819a78bb6df98d010b89afe8ac357410 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Tue, 28 Mar 2017 22:48:53 +0200 Subject: [PATCH 3/3] Probably fixed #2 --- telegram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telegram.py b/telegram.py index d51b5085..b7569ed9 100644 --- a/telegram.py +++ b/telegram.py @@ -63,7 +63,7 @@ class Bot: self.updates.append(Update(update)) except NotImplementedError: pass - if len(data) > 0: + if len(self.updates) > 0: self.offset = self.updates[-1].update_id + 1 async def parse_update(self, update):