From 2b8b547e210c5465ed21af21bfc3f0e18df2caf1 Mon Sep 17 00:00:00 2001 From: Roberto Date: Fri, 16 Dec 2022 20:44:47 +0100 Subject: [PATCH 01/66] :construction: building trivial building trivial feature #75 --- modules/trivial.py | 62 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 modules/trivial.py diff --git a/modules/trivial.py b/modules/trivial.py new file mode 100644 index 0000000..b52dab6 --- /dev/null +++ b/modules/trivial.py @@ -0,0 +1,62 @@ +from utils.get_config import sendMessage,get_chat,get_id_msg +from pyrogram import Client,errors +import requests +import json + +global token + +categorie = {"General Knowledge" :9, + "Books" :10, + "Film" :11, + "Music" :12, + "Musical & Theatres" :13, + "Television" :14, + "Video Games" :15, + "Board Games" :16, + "Science & Nature" :17, + "Science & Computers" :18, + "Science & Mathematics" :19, + "Mythology" :20, + "Sports" :21, + "Geography" :22, + "History" :23, + "Politics" :24, + "Art" :25, + "Celebrities" :26, + "Animals" :27, + "Vehicles" :28, + "Comics" :29, + "Science & Gadgets" :30, + "Japanese Anime & Manga":31, + "Cartoon & Animations" :32} + + +""" + Chiamata per la creazione di un token che garantisce l'unicità delle domande fetchate da opentb.com + Il token ha una vita di 6 ore se inattivo ininterrottamente. + Una volta esaurito, va resettato e generato di nuovo. +""" +def create_token(): + global token + url = "https://opentdb.com/api_token.php?command=request" + resp = requests.get(url) + data = json.loads(resp.text) + if data["response_code"] == 0: + token = data["token"] + else: + return "__Errore durante la creazione token.__" + return token + +""" + Chiamata per il reset del token nel caso in cui sia stato esaurito completamente. +""" +def reset_token(): + global token + url = "https://opentb.com/api_token.php?command=reset&token=" + token + resp = requests.get(url) + data = json.loads(resp.text) + if data["response_code"] == 0: + token = data["token"] + else: + return "__Errore durante reset token.__" + return token From c78bd54f3faa6377f64f81a0e106c4403c4f8115 Mon Sep 17 00:00:00 2001 From: Roberto Date: Sat, 17 Dec 2022 16:28:35 +0100 Subject: [PATCH 02/66] :construction: building trivial Solving #75 --- modules/trivial.py | 69 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 3 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index b52dab6..0e1b777 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -1,9 +1,10 @@ from utils.get_config import sendMessage,get_chat,get_id_msg from pyrogram import Client,errors +from pyrogram.enums import PollType import requests import json +import random -global token categorie = {"General Knowledge" :9, "Books" :10, @@ -30,6 +31,21 @@ "Japanese Anime & Manga":31, "Cartoon & Animations" :32} +difficolta = {"Easy" :"easy", + "Medium" :"medium", + "Hard" :"hard"} + +tipo_domanda = {"tf" :"boolean", + "multi" :"multiple"} + +response_code = {0:"Ok", + 1:"No Results", + 2:"Invalid Parameter", + 3:"Token not found", + 4:"Token Empty"} + + +global token """ Chiamata per la creazione di un token che garantisce l'unicità delle domande fetchate da opentb.com @@ -44,7 +60,7 @@ def create_token(): if data["response_code"] == 0: token = data["token"] else: - return "__Errore durante la creazione token.__" + return response_code[data["response_code"]] return token """ @@ -58,5 +74,52 @@ def reset_token(): if data["response_code"] == 0: token = data["token"] else: - return "__Errore durante reset token.__" + return response_code[data["response_code"]] return token + + + + +@Client.on_message() +def send_question(query,client,message): + global token + #check token existence + try: + if token == None: + token = create_token() + except NameError: + token = create_token() + #check token is good + if token == "Token Empty": + token = reset_token() + elif len(token) < 17: + return sendMessage(client,message,token) + #build parameter for request + splitted = query.split("/") + try: + category= splitted[1] + splitted = splitted[0].split(" ") + question_type = splitted[0] + difficulty = splitted[1] + except IndexError: + return sendMessage(client,message,"__Errore formato trivial.__") + + #build api url + api_url = "https://opentdb.com/api.php?amount=1&category=" + str(categorie[category.title()]) + "&difficulty=" + difficolta[difficulty.title()] + "&type=" + tipo_domanda[question_type] + "&token=" + token + resp = requests.get(api_url) + data = json.loads(resp.text) + for item in data["results"]: + category = item["category"] + difficulty = item["difficulty"] + question = item["question"] + correct = item["correct_answer"] + incorrect = item["incorrect_answers"] + incorrect.append(correct) + random.shuffle(incorrect) + #prepare question and send + try: + client.send_poll(get_chat(message),question="Category: " + category.title() + "\nDifficulty: " + difficulty.title() + "\n" + question,options=incorrect,type=PollType.QUIZ,correct_option_id=incorrect.index(correct),open_period=40,is_anonymous=False,reply_to_message_id=get_id_msg(message)) + except errors.exceptions.bad_request_400.PollAnswersInvalid: + return sendMessage(client,message,"__Errore durante invio trivial__") + + From 09bc00b4563815d9c67f197f9fb03a228b885b5d Mon Sep 17 00:00:00 2001 From: Roberto Date: Sat, 17 Dec 2022 16:29:04 +0100 Subject: [PATCH 03/66] Add route --- utils/controller.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/utils/controller.py b/utils/controller.py index 7a799f0..0dd1b6a 100644 --- a/utils/controller.py +++ b/utils/controller.py @@ -11,6 +11,7 @@ import modules.urban import modules.tper import modules.viaggiatreno +import modules.trivial import utils.dbfunctions as udb import utils.sysfunctions as usys import utils.get_config as ugc @@ -35,6 +36,7 @@ '/mystat' : udb.show_stats, '/tper' : modules.tper.send_tper_stop, '/tpershop' : modules.tper.get_tper_edicola, + '/trivial' : modules.trivial.send_question, '/helprob' : usys.help} dictionary_admin = {'/getmessage' : usys.get_message, @@ -55,7 +57,7 @@ Questa funzione prende come argomento il match e la richiesta dal main e dirotta la richiesta sul file dedicato a quel comando """ def fetch_command(match,query,client,message): - udb.update_stats(ugc.get_id_user(message),match) + #udb.update_stats(ugc.get_id_user(message),match) dictionary[match](query,client,message) """ Analogamente a fetch_command ma per i comandi esclusivi degli utenti admin From 622c2b28e0d914440a6d2968abe75314f7fe12d1 Mon Sep 17 00:00:00 2001 From: Roberto Date: Mon, 19 Dec 2022 20:12:44 +0100 Subject: [PATCH 04/66] :construction: :recycle: refactor trivial Refactor a few lines for #75 --- modules/trivial.py | 46 +++++++++++++++++++++++++++++++-------------- utils/controller.py | 2 +- 2 files changed, 33 insertions(+), 15 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index 0e1b777..121b9e8 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -31,9 +31,6 @@ "Japanese Anime & Manga":31, "Cartoon & Animations" :32} -difficolta = {"Easy" :"easy", - "Medium" :"medium", - "Hard" :"hard"} tipo_domanda = {"tf" :"boolean", "multi" :"multiple"} @@ -77,9 +74,17 @@ def reset_token(): return response_code[data["response_code"]] return token +""" + funzione ausiliaria per settare la difficoltà randomicamente +""" +def set_difficulty(): + difficulty_list = ["easy","medium","hard"] + random.shuffle(difficulty_list) + return difficulty_list[0] - - +""" + Restituisce una domanda quiz tramite le api di opentdb.com +""" @Client.on_message() def send_question(query,client,message): global token @@ -95,17 +100,30 @@ def send_question(query,client,message): elif len(token) < 17: return sendMessage(client,message,token) #build parameter for request - splitted = query.split("/") - try: - category= splitted[1] - splitted = splitted[0].split(" ") - question_type = splitted[0] - difficulty = splitted[1] - except IndexError: - return sendMessage(client,message,"__Errore formato trivial.__") + if query == "/trivial": + #Build random options for the request + category_number = random.randint(9,32) + category_keys = list(categorie.keys()) + values = categorie.values() + + category = str({i for i in categorie if categorie[i] == category_number}).replace("{'","").replace("'}","") + + question_list = ["tf","multi"] + random.shuffle(question_list) + + question_type = question_list[0] + difficulty = set_difficulty() + else: + splitted = query.split(" ") + try: + category= splitted[1] + question_type = splitted[0] + difficulty = set_difficulty() + except IndexError: + return sendMessage(client,message,"__Errore formato trivial.__") #build api url - api_url = "https://opentdb.com/api.php?amount=1&category=" + str(categorie[category.title()]) + "&difficulty=" + difficolta[difficulty.title()] + "&type=" + tipo_domanda[question_type] + "&token=" + token + api_url = "https://opentdb.com/api.php?amount=1&category=" + str(categorie[category.title()]) + "&difficulty=" + difficulty + "&type=" + tipo_domanda[question_type] + "&token=" + token resp = requests.get(api_url) data = json.loads(resp.text) for item in data["results"]: diff --git a/utils/controller.py b/utils/controller.py index 0dd1b6a..58218cd 100644 --- a/utils/controller.py +++ b/utils/controller.py @@ -57,7 +57,7 @@ Questa funzione prende come argomento il match e la richiesta dal main e dirotta la richiesta sul file dedicato a quel comando """ def fetch_command(match,query,client,message): - #udb.update_stats(ugc.get_id_user(message),match) + udb.update_stats(ugc.get_id_user(message),match) dictionary[match](query,client,message) """ Analogamente a fetch_command ma per i comandi esclusivi degli utenti admin From b40f97c01eca83876715b235724f7d88229c80d7 Mon Sep 17 00:00:00 2001 From: Roberto Date: Mon, 19 Dec 2022 23:03:10 +0100 Subject: [PATCH 05/66] fix split --- modules/trivial.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/trivial.py b/modules/trivial.py index 121b9e8..09b9079 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -114,7 +114,7 @@ def send_question(query,client,message): question_type = question_list[0] difficulty = set_difficulty() else: - splitted = query.split(" ") + splitted = query.split("/") try: category= splitted[1] question_type = splitted[0] From c11a7e70778f46ccf598a163e6493f9d03b8bcf4 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 20 Dec 2022 11:50:50 +0100 Subject: [PATCH 06/66] :bug: another fix --- modules/trivial.py | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/trivial.py b/modules/trivial.py index 09b9079..fada6f2 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -126,6 +126,7 @@ def send_question(query,client,message): api_url = "https://opentdb.com/api.php?amount=1&category=" + str(categorie[category.title()]) + "&difficulty=" + difficulty + "&type=" + tipo_domanda[question_type] + "&token=" + token resp = requests.get(api_url) data = json.loads(resp.text) + incorrect = [] for item in data["results"]: category = item["category"] difficulty = item["difficulty"] From f8ec9a9e22158ce89685f0c3a900325204aa914f Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 20 Dec 2022 13:48:01 +0100 Subject: [PATCH 07/66] :bug: fix --- modules/trivial.py | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/trivial.py b/modules/trivial.py index fada6f2..57f7b18 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -127,6 +127,7 @@ def send_question(query,client,message): resp = requests.get(api_url) data = json.loads(resp.text) incorrect = [] + question = "" for item in data["results"]: category = item["category"] difficulty = item["difficulty"] From 4434cbba41e462efd6b812100cc792889c0edea4 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 20 Dec 2022 14:28:07 +0100 Subject: [PATCH 08/66] Adjust HTML codes Another improve for #75 --- modules/trivial.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/modules/trivial.py b/modules/trivial.py index 57f7b18..6b2c0a0 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -4,6 +4,7 @@ import requests import json import random +from bs4 import BeautifulSoup categorie = {"General Knowledge" :9, @@ -82,6 +83,17 @@ def set_difficulty(): random.shuffle(difficulty_list) return difficulty_list[0] + +""" + Conversione codifica HTML in testo +""" +def html2text(strings): + result = [] + for i in range(len(strings)): + zuppa = BeautifulSoup(strings[i]) + result.append(zuppa.get_text()) + return result + """ Restituisce una domanda quiz tramite le api di opentdb.com """ @@ -137,6 +149,9 @@ def send_question(query,client,message): incorrect.append(correct) random.shuffle(incorrect) #prepare question and send + zuppa = BeautifulSoup(question) + question = zuppa.get_text() + incorrect = html2text(incorrect) try: client.send_poll(get_chat(message),question="Category: " + category.title() + "\nDifficulty: " + difficulty.title() + "\n" + question,options=incorrect,type=PollType.QUIZ,correct_option_id=incorrect.index(correct),open_period=40,is_anonymous=False,reply_to_message_id=get_id_msg(message)) except errors.exceptions.bad_request_400.PollAnswersInvalid: From d31b46d60114f53ec9bbc6039d6d1fc5b5ca1671 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 20 Dec 2022 19:24:17 +0100 Subject: [PATCH 09/66] :recycle: refactor code Refactored some lines #75 --- modules/trivial.py | 47 +++++++++++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 17 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index 6b2c0a0..0b91406 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -75,6 +75,26 @@ def reset_token(): return response_code[data["response_code"]] return token + + +""" + Controlla se il token è in buono stato e quindi se non lo è lo resetta o lo crea se non esistente. +""" +def check_token(): + #check token existence + try: + if token == None: + token = create_token() + except NameError: + token = create_token() + #check token is good + if token == "Token Empty": + token = reset_token() + elif len(token) < 17: + return sendMessage(client,message,token) + return token + + """ funzione ausiliaria per settare la difficoltà randomicamente """ @@ -90,40 +110,33 @@ def set_difficulty(): def html2text(strings): result = [] for i in range(len(strings)): - zuppa = BeautifulSoup(strings[i]) + zuppa = BeautifulSoup(strings[i],features="lxml") result.append(zuppa.get_text()) return result + """ Restituisce una domanda quiz tramite le api di opentdb.com """ @Client.on_message() def send_question(query,client,message): + #check token global token - #check token existence - try: - if token == None: - token = create_token() - except NameError: - token = create_token() - #check token is good - if token == "Token Empty": - token = reset_token() - elif len(token) < 17: - return sendMessage(client,message,token) + token = check_token() + #build parameter for request if query == "/trivial": #Build random options for the request category_number = random.randint(9,32) category_keys = list(categorie.keys()) values = categorie.values() - + #list comprehension per recuperare la chiave del dizionario categoria a partire dal valore random creato category = str({i for i in categorie if categorie[i] == category_number}).replace("{'","").replace("'}","") - + #create question type in random mode question_list = ["tf","multi"] random.shuffle(question_list) - question_type = question_list[0] + #setting difficulty difficulty = set_difficulty() else: splitted = query.split("/") @@ -149,8 +162,8 @@ def send_question(query,client,message): incorrect.append(correct) random.shuffle(incorrect) #prepare question and send - zuppa = BeautifulSoup(question) - question = zuppa.get_text() + zuppa = BeautifulSoup(question,features="lxml") + question = zuppa.get_text() incorrect = html2text(incorrect) try: client.send_poll(get_chat(message),question="Category: " + category.title() + "\nDifficulty: " + difficulty.title() + "\n" + question,options=incorrect,type=PollType.QUIZ,correct_option_id=incorrect.index(correct),open_period=40,is_anonymous=False,reply_to_message_id=get_id_msg(message)) From 5d8b7a2870d851908ab232038bbec2c7fb555bb3 Mon Sep 17 00:00:00 2001 From: Roberto Date: Wed, 21 Dec 2022 22:57:43 +0100 Subject: [PATCH 10/66] Update help --- help.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/help.json b/help.json index c239775..1a06e4e 100644 --- a/help.json +++ b/help.json @@ -40,5 +40,5 @@ }, "openai":"**/ai 'input' ** => genera un testo in base all'input dato grazie alle api di OpenAI", "urban": "**/urban 'word' ** => restituisce la definizione di urban dictionary per la parola richiesta", - "default": "Cerca un comando in particolare come ad esempio:\n /helprob wiki\n__Comandi: wiki, lyrics, covid, vaccine, weather, urban, poll, reminder, tper, atm, treni e mappe.\n\ncomandi admin: **playlotto, getmessage, weathermap, weathersat, openai e pingrob.**\nVuoi usarli? Diventa un utente premium! Contatta @MasterCruelty__" + "default": "Cerca un comando in particolare come ad esempio:\n /helprob wiki\n__Comandi: wiki, lyrics, covid, vaccine, weather, urban, poll, reminder, tper, atm, treni, kart e mappe.\n\ncomandi admin: **playlotto, getmessage, weathermap, weathersat, openai e pingrob.**\nVuoi usarli? Diventa un utente premium! Contatta @MasterCruelty__" } From 91fed11e2e48c8a62504e2f013578cc9e55e3001 Mon Sep 17 00:00:00 2001 From: Roberto Date: Wed, 21 Dec 2022 23:12:20 +0100 Subject: [PATCH 11/66] Minor fix initialized variable to avoid exception --- modules/trivial.py | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/trivial.py b/modules/trivial.py index 0b91406..b0145cb 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -153,6 +153,7 @@ def send_question(query,client,message): data = json.loads(resp.text) incorrect = [] question = "" + correct = "" for item in data["results"]: category = item["category"] difficulty = item["difficulty"] From df7f7387f0ed593ac018414192cd23d8cadd47bf Mon Sep 17 00:00:00 2001 From: Roberto Date: Thu, 22 Dec 2022 18:31:50 +0100 Subject: [PATCH 12/66] Update help --- help.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/help.json b/help.json index 39324f3..cf5e978 100644 --- a/help.json +++ b/help.json @@ -17,7 +17,7 @@ "searchatm":"**/searchatm 'address'** => Restituisce tutte le fermate trovate con quell'indirizzo.\n__/searchatm via vigevano__\n" }, "tper":{ - "intro":"__Features disponibili per il trasporto pubblico di Bologna e Ferrara__\n", + "intro":"__Features disponibili per il trasporto pubblico in quasi tutta la Regione Emilia-Romagna.__\n", "tper_default":"**/tper 'stop_code'** => restituisce i dati relativi alla fermata inserita.\nSe ti serve solo una linea in particolare sulla fermata, aggiungi uno spazio e mettila.\n __Esempio: /tper 1234 30__\n**1234 è la fermta e 30 è la linea di cui voglio sapere gli orari.**\n\n", "tpershop": "**/tpershop 'stop_code'** => restituisce la rivendita più vicina alla fermata inserita.\n" }, From 2d7b238e3b655c8cfbfcb6aab908ccb09269d44d Mon Sep 17 00:00:00 2001 From: Roberto Date: Thu, 22 Dec 2022 19:22:15 +0100 Subject: [PATCH 13/66] :wrench: Add table Add table trivial for leaderboard #75 --- utils/dbtables.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/utils/dbtables.py b/utils/dbtables.py index 42fed10..2debe4c 100644 --- a/utils/dbtables.py +++ b/utils/dbtables.py @@ -21,11 +21,25 @@ class User(BaseModel): admin = BooleanField(default=False) superadmin = BooleanField(default=False) + +""" + command: comando lanciato + times: numero di volte che è stato lanciato +""" class Stats(BaseModel): id_user = ForeignKeyField(User) command = CharField() times = IntegerField(default = 0) +""" + category: categoria di domanda + points: numero di punti acquisiti +""" +class Trivial(BaseModel): + id_user = ForeignKeyField(User) + category = CharField() + points = IntegerField(default = 0) + class Group(BaseModel): id_group = IntegerField(unique = True) title = CharField() From 1837698b0cf40d59af0df2665da2484af78e076b Mon Sep 17 00:00:00 2001 From: Roberto Date: Thu, 22 Dec 2022 19:22:48 +0100 Subject: [PATCH 14/66] :wrench: Add functions Add a couple of functions to build the leaderboard feature #75 --- utils/dbfunctions.py | 49 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index 83907fd..7753fb1 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -43,6 +43,55 @@ def show_stats(utente,client,message): result += item.command + "__: Usato " + str(item.times) + " volte.__\n" return sendMessage(client,message,result) +""" + @params utente,punteggio,categoria + + Aggiorna il punteggio dell'utente sulla categoria +""" +def update_trivial_score(utente,punteggio,categoria): + query = (Trivial + .update({Trivial.points: Trivial.points + punteggio}) + .where((Trivial.id_user == utente) & + (Trivial.category == categoria))).execute() + if(query == 0): + score = Trivial(id_user = utente,category = categoria, points = punteggio) + score.save() + return + +""" + @params utente,client,message + + Restituisce le proprie statistiche sul gioco Trivial +""" +def personal_leaderboard(utente,client,message): + id_utente = get_id_user(message) + result = "Le tue statistiche su Trivial\n" + query = (Trivial + .select() + .join(User, on=(User.id_user == Trivial.id_user)) + .where(Trivial.id_user == id_utente) + .order_by(Trivial.points.desc())) + count = 0 + for item in query: + result += item.category + "__: " + str(item.points) + "punti.__\n" + count += item.points + result += "**Punteggio totale: " + str(count) + "**" + return sendMessage(client,message,result) + +""" + @params client,message + Classifica globale dei punti su Trivial +""" +def global_leaderboard(client,message): + query = (Trivial + .select(User.name,fn.SUM(Trivial.points)) + .join(User, on=(User.id_user == Trivial.id_user)) + .order_by(fn.SUM(Trivial.points))) + + result = "" + for item in query: + result += item.name + ": __" + str(item.points) + " punti.__" + return sendMEssage(client,message,result) """ questa funzione fa una select dalla tabella User e restituisce gli id di tutti gli utenti registratii dentro una lista di int From 336d5295cd9963f8f89df207275921f58fd02793 Mon Sep 17 00:00:00 2001 From: Roberto Date: Fri, 23 Dec 2022 12:44:06 +0100 Subject: [PATCH 15/66] :bug: Fix /piste Add a condition if there's a single track without postal code --- modules/pistekart.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/modules/pistekart.py b/modules/pistekart.py index 9e4ffc9..64bd72d 100644 --- a/modules/pistekart.py +++ b/modules/pistekart.py @@ -33,6 +33,8 @@ def get_piste_region(query,client,message): pista = "" else: pista += results[i] + "\n" + if result == "" and i == len(results)-1: + result = pista try: return sendMessage(client,message,result) From 1873311768fe173541d5b0c8f4ab0c8669f2d63e Mon Sep 17 00:00:00 2001 From: Roberto Date: Fri, 23 Dec 2022 13:44:20 +0100 Subject: [PATCH 16/66] handle exception --- modules/pistekart.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/modules/pistekart.py b/modules/pistekart.py index 64bd72d..3d1b37a 100644 --- a/modules/pistekart.py +++ b/modules/pistekart.py @@ -64,5 +64,8 @@ def get_info_pista(query,client,message): #invio messaggio con descrizione pista e foto tracciato sendMessage(client,message,"__" + info_track+ "__") - sendPhoto(client,message,img_url,"__Foto del tracciato__") + try: + sendPhoto(client,message,img_url,"__Foto del tracciato__") + except ValueError: + sendMessage(client,message,"__Foto del tracciato non disponibile__") From 8f1c822d64a50c7b54143991ddfa831c45c39073 Mon Sep 17 00:00:00 2001 From: Roberto Date: Fri, 23 Dec 2022 23:42:12 +0100 Subject: [PATCH 17/66] Change function name --- utils/dbfunctions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index 7753fb1..fb102e5 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -63,7 +63,7 @@ def update_trivial_score(utente,punteggio,categoria): Restituisce le proprie statistiche sul gioco Trivial """ -def personal_leaderboard(utente,client,message): +def personal_trivial_leaderboard(utente,client,message): id_utente = get_id_user(message) result = "Le tue statistiche su Trivial\n" query = (Trivial @@ -82,7 +82,7 @@ def personal_leaderboard(utente,client,message): @params client,message Classifica globale dei punti su Trivial """ -def global_leaderboard(client,message): +def global_trivial_leaderboard(client,message): query = (Trivial .select(User.name,fn.SUM(Trivial.points)) .join(User, on=(User.id_user == Trivial.id_user)) From 7d9ca5eca48b33c5da36d3c16a6c182d4225a80d Mon Sep 17 00:00:00 2001 From: Roberto Date: Fri, 23 Dec 2022 23:42:36 +0100 Subject: [PATCH 18/66] :construction: build add points --- modules/trivial.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/modules/trivial.py b/modules/trivial.py index b0145cb..1580137 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -1,6 +1,9 @@ from utils.get_config import sendMessage,get_chat,get_id_msg from pyrogram import Client,errors from pyrogram.enums import PollType +from pyrogram.handlers import PollHandler,RawUpdateHandler +from pyrogram.raw.functions.messages import GetPollResults +from pyrogram.raw.types import UpdateMessagePollVote import requests import json import random @@ -166,9 +169,22 @@ def send_question(query,client,message): zuppa = BeautifulSoup(question,features="lxml") question = zuppa.get_text() incorrect = html2text(incorrect) + + #aggiungo handler per ricevere aggiornamenti sul quiz in corso + #riga commentata per quanto in futuro sarà possibile ricevere update anche sui quiz + client.add_handler(PollHandler(callback=check_trivial_updates)) + #client.add_handler(RawUpdateHandler(callback=check_trivial_updates)) + try: - client.send_poll(get_chat(message),question="Category: " + category.title() + "\nDifficulty: " + difficulty.title() + "\n" + question,options=incorrect,type=PollType.QUIZ,correct_option_id=incorrect.index(correct),open_period=40,is_anonymous=False,reply_to_message_id=get_id_msg(message)) + msg = client.send_poll(get_chat(message),question="Category: " + category.title() + "\nDifficulty: " + difficulty.title() + "\n" + question,options=incorrect,type=PollType.QUIZ,correct_option_id=incorrect.index(correct),open_period=40,is_anonymous=False,reply_to_message_id=get_id_msg(message)) except errors.exceptions.bad_request_400.PollAnswersInvalid: return sendMessage(client,message,"__Errore durante invio trivial__") +@Client.on_raw_update() +def check_trivial_updates(client,update):#,users,chat): + print(update) + """if isinstance(update,UpdateMessagePollVote): + client.invoke(GetPollResults(peer = str(update.user_id),msg_id =update.poll_id)) + #print(update) + player = update.user_id""" From 69125db267da31e8bad1bdb218ae47609dfaae0b Mon Sep 17 00:00:00 2001 From: Roberto Date: Sat, 24 Dec 2022 17:19:09 +0100 Subject: [PATCH 19/66] :construction: trivial points Trying to get info about poll quiz to give points #75 --- modules/trivial.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index 1580137..267a284 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -2,12 +2,13 @@ from pyrogram import Client,errors from pyrogram.enums import PollType from pyrogram.handlers import PollHandler,RawUpdateHandler -from pyrogram.raw.functions.messages import GetPollResults +from pyrogram.raw.functions.messages import GetPollResults,GetPollVotes from pyrogram.raw.types import UpdateMessagePollVote import requests import json import random from bs4 import BeautifulSoup +import time categorie = {"General Knowledge" :9, @@ -172,19 +173,21 @@ def send_question(query,client,message): #aggiungo handler per ricevere aggiornamenti sul quiz in corso #riga commentata per quanto in futuro sarà possibile ricevere update anche sui quiz - client.add_handler(PollHandler(callback=check_trivial_updates)) - #client.add_handler(RawUpdateHandler(callback=check_trivial_updates)) + #client.add_handler(PollHandler(callback=check_trivial_updates)) + client.add_handler(RawUpdateHandler(callback=check_trivial_updates)) try: - msg = client.send_poll(get_chat(message),question="Category: " + category.title() + "\nDifficulty: " + difficulty.title() + "\n" + question,options=incorrect,type=PollType.QUIZ,correct_option_id=incorrect.index(correct),open_period=40,is_anonymous=False,reply_to_message_id=get_id_msg(message)) + msg = client.send_poll(get_chat(message),question="Category: " + category.title() + "\nDifficulty: " + difficulty.title() + "\n" + question,options=incorrect,type=PollType.QUIZ,correct_option_id=incorrect.index(correct),open_period=10,is_anonymous=False,reply_to_message_id=get_id_msg(message)) + #time.sleep(10) + print(GetPollResults(peer = get_chat(message),msg_id =msg.poll.id)) + results = client.invoke(GetPollVotes(peer = get_chat(message),limit=99,id=msg.poll.id,option=bytes(incorrect.index(correct)))) + print(results) + except errors.exceptions.bad_request_400.PollAnswersInvalid: return sendMessage(client,message,"__Errore durante invio trivial__") @Client.on_raw_update() -def check_trivial_updates(client,update):#,users,chat): +def check_trivial_updates(client,update,users,chat): print(update) - """if isinstance(update,UpdateMessagePollVote): - client.invoke(GetPollResults(peer = str(update.user_id),msg_id =update.poll_id)) - #print(update) - player = update.user_id""" + #if isinstance(update,UpdateMessagePollVote): From 6209af71ce2a05b5229bc458d24b68b85c16bfe4 Mon Sep 17 00:00:00 2001 From: Roberto Date: Mon, 26 Dec 2022 22:06:42 +0100 Subject: [PATCH 20/66] Create table --- utils/dbtables.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/dbtables.py b/utils/dbtables.py index 2debe4c..b858cb8 100644 --- a/utils/dbtables.py +++ b/utils/dbtables.py @@ -46,7 +46,7 @@ class Group(BaseModel): db.connect() -db.create_tables([User,Stats]) +db.create_tables([User,Stats,Trivial]) #Inizializzo il super admin da file di configurazione overlord = User(id_user = id_super_admin[0], name = id_super_admin[1], username = id_super_admin[2], admin = True, superadmin = True) From 3559ea538454a785005fa12326c8592b61b540a6 Mon Sep 17 00:00:00 2001 From: Roberto Date: Mon, 26 Dec 2022 22:33:49 +0100 Subject: [PATCH 21/66] Add routes --- utils/controller.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/utils/controller.py b/utils/controller.py index b024dcc..268fcf0 100644 --- a/utils/controller.py +++ b/utils/controller.py @@ -38,6 +38,8 @@ '/tper' : modules.tper.send_tper_stop, '/tpershop' : modules.tper.get_tper_edicola, '/trivial' : modules.trivial.send_question, + '/mytscore' : modules.trivial.get_personal_score, + '/globaltscore' : modules.trivial.get_global_score, '/infopista' : modules.pistekart.get_info_pista, '/piste' : modules.pistekart.get_piste_region, '/helprob' : usys.help} From 25d27461929de1d4e057ed9a246f5e31692afa54 Mon Sep 17 00:00:00 2001 From: Roberto Date: Mon, 26 Dec 2022 22:34:19 +0100 Subject: [PATCH 22/66] :bug: Fix query --- utils/dbfunctions.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index fb102e5..5702908 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -65,7 +65,7 @@ def update_trivial_score(utente,punteggio,categoria): """ def personal_trivial_leaderboard(utente,client,message): id_utente = get_id_user(message) - result = "Le tue statistiche su Trivial\n" + result = "Le tue statistiche su Trivial\n\n" query = (Trivial .select() .join(User, on=(User.id_user == Trivial.id_user)) @@ -73,7 +73,7 @@ def personal_trivial_leaderboard(utente,client,message): .order_by(Trivial.points.desc())) count = 0 for item in query: - result += item.category + "__: " + str(item.points) + "punti.__\n" + result += item.category + "__: " + str(item.points) + " punti.__\n" count += item.points result += "**Punteggio totale: " + str(count) + "**" return sendMessage(client,message,result) @@ -83,15 +83,16 @@ def personal_trivial_leaderboard(utente,client,message): Classifica globale dei punti su Trivial """ def global_trivial_leaderboard(client,message): - query = (Trivial - .select(User.name,fn.SUM(Trivial.points)) - .join(User, on=(User.id_user == Trivial.id_user)) - .order_by(fn.SUM(Trivial.points))) + query = (User + .select(User.name.alias('user'),fn.SUM(Trivial.points).alias('count')) + .join(Trivial, on=(User.id_user == Trivial.id_user)) + .order_by(fn.SUM(Trivial.points)) + .group_by(User.id_user)) result = "" for item in query: - result += item.name + ": __" + str(item.points) + " punti.__" - return sendMEssage(client,message,result) + result += item.user + ": __" + str(item.count) + " punti.__" + return sendMessage(client,message,result) """ questa funzione fa una select dalla tabella User e restituisce gli id di tutti gli utenti registratii dentro una lista di int From 6e80b85e6a43950ebff4fdc8c5cf1264c6594e01 Mon Sep 17 00:00:00 2001 From: Roberto Date: Mon, 26 Dec 2022 22:35:41 +0100 Subject: [PATCH 23/66] :wrench: points Adding global variables to keep info a bout poll ongoing because bots can't hold functions like GetPollResults --- modules/trivial.py | 55 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 9 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index 267a284..73781ea 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -1,14 +1,13 @@ -from utils.get_config import sendMessage,get_chat,get_id_msg +from utils.get_config import sendMessage,get_chat,get_id_msg,get_id_user +from utils.dbfunctions import personal_trivial_leaderboard,global_trivial_leaderboard,update_trivial_score from pyrogram import Client,errors from pyrogram.enums import PollType from pyrogram.handlers import PollHandler,RawUpdateHandler -from pyrogram.raw.functions.messages import GetPollResults,GetPollVotes from pyrogram.raw.types import UpdateMessagePollVote import requests import json import random from bs4 import BeautifulSoup -import time categorie = {"General Knowledge" :9, @@ -122,8 +121,17 @@ def html2text(strings): """ Restituisce una domanda quiz tramite le api di opentdb.com """ +global corretta +global difficolta_domanda +global versione_domanda +global categoria @Client.on_message() def send_question(query,client,message): + #variabili globali per tenere traccia di alcune informazioni per la fine del poll + global corretta + global difficolta_domanda + global versione_domanda + global categoria #check token global token token = check_token() @@ -175,19 +183,48 @@ def send_question(query,client,message): #riga commentata per quanto in futuro sarà possibile ricevere update anche sui quiz #client.add_handler(PollHandler(callback=check_trivial_updates)) client.add_handler(RawUpdateHandler(callback=check_trivial_updates)) + corretta = incorrect.index(correct) + versione_domanda = tipo_domanda[question_type] + difficolta_domanda = difficulty + categoria = category.title() try: msg = client.send_poll(get_chat(message),question="Category: " + category.title() + "\nDifficulty: " + difficulty.title() + "\n" + question,options=incorrect,type=PollType.QUIZ,correct_option_id=incorrect.index(correct),open_period=10,is_anonymous=False,reply_to_message_id=get_id_msg(message)) - #time.sleep(10) - print(GetPollResults(peer = get_chat(message),msg_id =msg.poll.id)) - results = client.invoke(GetPollVotes(peer = get_chat(message),limit=99,id=msg.poll.id,option=bytes(incorrect.index(correct)))) - print(results) except errors.exceptions.bad_request_400.PollAnswersInvalid: return sendMessage(client,message,"__Errore durante invio trivial__") + +punteggi = { 'Easy' : 1, + 'Medium': 2, + 'Hard' : 3} + +""" + Funzione che prende raw updates per ogni volta che un giocatore vota sul quiz, assegnando o meno il punteggio. +""" @Client.on_raw_update() def check_trivial_updates(client,update,users,chat): - print(update) - #if isinstance(update,UpdateMessagePollVote): + if isinstance(update,UpdateMessagePollVote): + data = update + player = data.user_id + chosen = data.options[0] + int_chosen = int.from_bytes(chosen,"big") + if corretta == int_chosen: + print(str(player) + " ha risposto correttamente") + if versione_domanda.title() == 'Boolean': + update_trivial_score(player,1,categoria) + else: + update_trivial_score(player,punteggi[difficolta_domanda.title()],categoria) + +""" + richiamo funzione per punteggi personali +""" +def get_personal_score(query,client,message): + return personal_trivial_leaderboard(get_id_user(message),client,message) + +""" + richiamo funzione per classifica globale +""" +def get_global_score(query,client,message): + return global_trivial_leaderboard(client,message) From aaa4a02a1793f74fe7a76184d9f48c92c3cfeedf Mon Sep 17 00:00:00 2001 From: Roberto Date: Mon, 26 Dec 2022 22:57:46 +0100 Subject: [PATCH 24/66] :bug: Fix query --- utils/dbfunctions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index 5702908..c8634d4 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -86,12 +86,12 @@ def global_trivial_leaderboard(client,message): query = (User .select(User.name.alias('user'),fn.SUM(Trivial.points).alias('count')) .join(Trivial, on=(User.id_user == Trivial.id_user)) - .order_by(fn.SUM(Trivial.points)) + .order_by(fn.SUM(Trivial.points).desc()) .group_by(User.id_user)) result = "" for item in query: - result += item.user + ": __" + str(item.count) + " punti.__" + result += item.user + ": __" + str(item.count) + " punti.__\n" return sendMessage(client,message,result) """ From acc200737829c2eca53464e54f30e79661518001 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 15:10:56 +0100 Subject: [PATCH 25/66] :wrench: Add waitTrivial table Modifying db #75 --- utils/dbtables.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/utils/dbtables.py b/utils/dbtables.py index b858cb8..7e43917 100644 --- a/utils/dbtables.py +++ b/utils/dbtables.py @@ -43,10 +43,21 @@ class Trivial(BaseModel): class Group(BaseModel): id_group = IntegerField(unique = True) title = CharField() + command = CharField() + +""" + valore booleano necessario per non avere due quiz attivi in contemporanea +""" +class waitTrivial(BaseModel): + value = BooleanField() db.connect() -db.create_tables([User,Stats,Trivial]) +db.create_tables([User,Stats,Trivial,waitTrivial]) + +#Inizializzo il wait trivial a False +wait_trivial = waitTrivial(value = False) +wait_trivial.save() #Inizializzo il super admin da file di configurazione overlord = User(id_user = id_super_admin[0], name = id_super_admin[1], username = id_super_admin[2], admin = True, superadmin = True) From 70ed8210176134c242df192d7b1533358c27e622 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 15:11:32 +0100 Subject: [PATCH 26/66] :wrench: Add db functions Add 3 functions to manage waitTrivial #75 --- utils/dbfunctions.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index c8634d4..9dd0b12 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -94,6 +94,36 @@ def global_trivial_leaderboard(client,message): result += item.user + ": __" + str(item.count) + " punti.__\n" return sendMessage(client,message,result) +""" + setto il wait time a true per via di un quiz in corso +""" +def set_wait_trivial(): + query = (waitTrivial + .update({waitTrivial.value: True})).execute() + if(query == 0): + wait_trivial = waitTrivial(value = True) + wait_trivial.save() + return + +""" + setto il wait time a false, è possibile lanciare un nuovo quiz +""" +def unset_wait_trivial(): + query = (waitTrivial + .update({waitTrivial.value: False})).execute() + if(query == 0): + wait_trivial = waitTrivial(value = False) + wait_trivial.save() + return + +""" + prelevo il valore del wait time +""" +def get_wait_trivial_value(): + query = waitTrivial.select() + for item in query: + return item.value + """ questa funzione fa una select dalla tabella User e restituisce gli id di tutti gli utenti registratii dentro una lista di int """ From 1dc21439d1bc9c30e242b88ac0be649128dc3b09 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 15:26:11 +0100 Subject: [PATCH 27/66] Add wait_trivial Added a wait between a quiz and the next one #75 --- modules/trivial.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index 73781ea..fb3271e 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -1,5 +1,5 @@ from utils.get_config import sendMessage,get_chat,get_id_msg,get_id_user -from utils.dbfunctions import personal_trivial_leaderboard,global_trivial_leaderboard,update_trivial_score +from utils.dbfunctions import personal_trivial_leaderboard,global_trivial_leaderboard,update_trivial_score,get_wait_trivial_value,set_wait_trivial,unset_wait_trivial from pyrogram import Client,errors from pyrogram.enums import PollType from pyrogram.handlers import PollHandler,RawUpdateHandler @@ -7,6 +7,7 @@ import requests import json import random +import time from bs4 import BeautifulSoup @@ -127,6 +128,10 @@ def html2text(strings): global categoria @Client.on_message() def send_question(query,client,message): + #check wait_quiz + wait_trivial = get_wait_trivial_value() + if wait_trivial: + return sendMessage(client,message,"__Un altro quiz è attualmente in corso.\nRiprova tra poco.__") #variabili globali per tenere traccia di alcune informazioni per la fine del poll global corretta global difficolta_domanda @@ -180,8 +185,9 @@ def send_question(query,client,message): incorrect = html2text(incorrect) #aggiungo handler per ricevere aggiornamenti sul quiz in corso - #riga commentata per quanto in futuro sarà possibile ricevere update anche sui quiz + #riga commentata per quando in futuro sarà possibile ricevere update anche sui quiz #client.add_handler(PollHandler(callback=check_trivial_updates)) + client.add_handler(RawUpdateHandler(callback=check_trivial_updates)) corretta = incorrect.index(correct) versione_domanda = tipo_domanda[question_type] @@ -189,7 +195,12 @@ def send_question(query,client,message): categoria = category.title() try: - msg = client.send_poll(get_chat(message),question="Category: " + category.title() + "\nDifficulty: " + difficulty.title() + "\n" + question,options=incorrect,type=PollType.QUIZ,correct_option_id=incorrect.index(correct),open_period=10,is_anonymous=False,reply_to_message_id=get_id_msg(message)) + msg = client.send_poll(get_chat(message),question="Category: " + category.title() + "\nDifficulty: " + difficulty.title() + "\n" + question,options=incorrect,type=PollType.QUIZ,correct_option_id=incorrect.index(correct),open_period=20,is_anonymous=False,reply_to_message_id=get_id_msg(message)) + #Setto il wait così che non ci siano due quiz in contemporanea + set_wait_trivial() + time.sleep(20) + #setto a false dopo la fine del quiz + unset_wait_trivial() except errors.exceptions.bad_request_400.PollAnswersInvalid: return sendMessage(client,message,"__Errore durante invio trivial__") From 156dd4ad913eea9510d464655d3c1c01ac323e26 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 19:42:11 +0100 Subject: [PATCH 28/66] Add route --- utils/controller.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/utils/controller.py b/utils/controller.py index 268fcf0..55e9c15 100644 --- a/utils/controller.py +++ b/utils/controller.py @@ -56,7 +56,8 @@ '/listrobuser' : udb.list_user, '/allrobuser' : udb.all_user, '/setrobadmin' : udb.set_admin, - '/delrobadmin' : udb.del_admin} + '/delrobadmin' : udb.del_admin, + '/setgroup' : udb.set_group} """ Questa funzione prende come argomento il match e la richiesta dal main e dirotta la richiesta sul file dedicato a quel comando From 7b659e217ac5de28593c0a6b9e54754e7c7b5fb4 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 21:45:54 +0100 Subject: [PATCH 29/66] :wrench: Add check group Added check on authorized commands in specific groups --- utils/controller.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/utils/controller.py b/utils/controller.py index 55e9c15..94a66dc 100644 --- a/utils/controller.py +++ b/utils/controller.py @@ -59,12 +59,18 @@ '/delrobadmin' : udb.del_admin, '/setgroup' : udb.set_group} +auth_command = ["/trivial"] + """ Questa funzione prende come argomento il match e la richiesta dal main e dirotta la richiesta sul file dedicato a quel comando """ def fetch_command(match,query,client,message): - udb.update_stats(ugc.get_id_user(message),match) - dictionary[match](query,client,message) + #controllo sui comandi autorizzati solo in determinate chat + if udb.check_group_command(match,message) and match in auth_command: + return ugc.sendMessage(client,message,"__Comando non autorizzato in questa chat.\nContatta @MasterCruelty per informazioni.__") + else: + udb.update_stats(ugc.get_id_user(message),match) + dictionary[match](query,client,message) """ Analogamente a fetch_command ma per i comandi esclusivi degli utenti admin """ From 94a4ca963e3d6c559a048fb7401ebd2a56a33d22 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 21:47:16 +0100 Subject: [PATCH 30/66] Create table create table group --- utils/dbtables.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/utils/dbtables.py b/utils/dbtables.py index 7e43917..519885f 100644 --- a/utils/dbtables.py +++ b/utils/dbtables.py @@ -40,6 +40,13 @@ class Trivial(BaseModel): category = CharField() points = IntegerField(default = 0) +""" + Tabella gruppi per autorizzare un comando solo all'interno di alcuni gruppi + Campi: + id gruppo + nome gruppo + nome comando +""" class Group(BaseModel): id_group = IntegerField(unique = True) title = CharField() @@ -53,7 +60,7 @@ class waitTrivial(BaseModel): db.connect() -db.create_tables([User,Stats,Trivial,waitTrivial]) +db.create_tables([User,Stats,Trivial,waitTrivial,Group]) #Inizializzo il wait trivial a False wait_trivial = waitTrivial(value = False) From 4f6d7cca788dc5c808bf3a32731394730c551991 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 22:04:48 +0100 Subject: [PATCH 31/66] Add routes --- utils/controller.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/utils/controller.py b/utils/controller.py index 94a66dc..285b856 100644 --- a/utils/controller.py +++ b/utils/controller.py @@ -57,7 +57,8 @@ '/allrobuser' : udb.all_user, '/setrobadmin' : udb.set_admin, '/delrobadmin' : udb.del_admin, - '/setgroup' : udb.set_group} + '/setgroup' : udb.set_group, + '/listgroup' : udb.list_group} auth_command = ["/trivial"] From a416dfe861fc5d39db823f2dcd0d6586f82d2a2e Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 22:10:16 +0100 Subject: [PATCH 32/66] Add route --- utils/controller.py | 3 ++- utils/dbfunctions.py | 52 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/utils/controller.py b/utils/controller.py index 285b856..032937b 100644 --- a/utils/controller.py +++ b/utils/controller.py @@ -58,7 +58,8 @@ '/setrobadmin' : udb.set_admin, '/delrobadmin' : udb.del_admin, '/setgroup' : udb.set_group, - '/listgroup' : udb.list_group} + '/listgroup' : udb.list_group, + '/delgroup' : udb.del_group} auth_command = ["/trivial"] diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index 9dd0b12..626f1be 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -124,6 +124,58 @@ def get_wait_trivial_value(): for item in query: return item.value +""" + Restituisce la lista dei gruppi autorizzati a certi comandi +""" +@Client.on_message() +def list_group(client,message): + result = "Gruppi salvati:\n\n" + query = Group.select() + for group in query: + result += str(group.id_group) + ";" + group.title + ";" + group.command + "\n" + return sendMessage(client,message,result) + + +""" + setto il gruppo come unico autorizzato a un particolare comando +""" +@Client.on_message() +def set_group(client,message,query): + #splitto sullo spazio poichè l'input è del tipo /setgroup + splitted = query.split(" ") + json_group = client.get_chat(splitted[0]) + group_id = json_group.id + title = json_group.title + command = splitted[1] + + #inserisco in db + group = Group(id_group = group_id,title = title,command = command) + group.save() + #verifico sia inserito correttamente + query = Group.select().where(Group.id_group == group_id) + for item in query: + result = "Gruppo " + str(item.id_group) + " registrato con comando " + command + return sendMessage(client,message,result) + + +""" + controllo se il gruppo è autorizzato a eseguire un determinato comando +""" +def check_group_command(match,message): + query = (Group + .select() + .where((Group.id_group == get_chat(message)) & + (Group.command == match))).execute() + + #controllo se vi è almeno un record + i = 0 + for item in query: + i = i + 1 + if i == 0: + return True + else: + return False + """ questa funzione fa una select dalla tabella User e restituisce gli id di tutti gli utenti registratii dentro una lista di int """ From b69c6e2003f83dc99782b75b9515146366bb4ac0 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 22:10:51 +0100 Subject: [PATCH 33/66] Add group functions Added a couple of functions to manage groups on db #53 --- utils/dbfunctions.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index 626f1be..fc0a380 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -157,6 +157,14 @@ def set_group(client,message,query): result = "Gruppo " + str(item.id_group) + " registrato con comando " + command return sendMessage(client,message,result) +""" + Cancella il gruppo selezionato dai gruppi autorizzati a determinati comandi +""" +@Client.on_message() +def del_group(client,message,query): + delete = Group.delete().where(Group.id_group == query).execute() + result = "Gruppo " + str(query) + " eliminato dai gruppi salvati." + return sendMessage(client,message,result) """ controllo se il gruppo è autorizzato a eseguire un determinato comando From e2d6dfa7283b0465a302e03c705317c6034afdc0 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 22:20:58 +0100 Subject: [PATCH 34/66] Update help --- help.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/help.json b/help.json index cf5e978..a59ea62 100644 --- a/help.json +++ b/help.json @@ -44,5 +44,6 @@ }, "openai":"**/ai 'input' ** => genera un testo in base all'input dato grazie alle api di OpenAI", "urban": "**/urban 'word' ** => restituisce la definizione di urban dictionary per la parola richiesta", - "default": "Cerca un comando in particolare come ad esempio:\n /helprob wiki\n__Comandi: wiki, lyrics, covid, vaccine, weather, urban, poll, reminder, tper, atm, treni, kart e mappe.\n\ncomandi admin: **playlotto, getmessage, weathermap, weathersat, openai e pingrob.**\nVuoi usarli? Diventa un utente premium! Contatta @MasterCruelty__" + "trivial": "__**Questo comando è disponibile solo in alcune chat decise dall'admin.\nI nomi delle categorie sono listati nel gruppo ufficiale del gioco.**__\n\n**/trivial** ==> quiz vero/falso oppure a scelta multipla in una categoria randomica.\n**/trivial tipo/categoria** ==> quiz del tipo scelto e categoria scelta.\n__Esempio: /trivial tf/history per vero/falso in storia.\n/trivial multi/history per risposta multipla in storia.__\n\n", + "default": "Cerca un comando in particolare come ad esempio:\n /helprob wiki\n__Comandi: wiki, lyrics, covid, vaccine, weather, urban, poll, reminder, tper, atm, treni, kart, trivial e mappe.\n\ncomandi admin: **playlotto, getmessage, weathermap, weathersat, openai e pingrob.**\nVuoi usarli? Diventa un utente premium! Contatta @MasterCruelty__" } From d0e65456a5a20e9130eb033b8300fbb01f8dd045 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 22:57:40 +0100 Subject: [PATCH 35/66] Add routes Add admin routes to manage delete on grop and force update;delete on stats #53 --- utils/controller.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/utils/controller.py b/utils/controller.py index 032937b..17ace60 100644 --- a/utils/controller.py +++ b/utils/controller.py @@ -59,7 +59,9 @@ '/delrobadmin' : udb.del_admin, '/setgroup' : udb.set_group, '/listgroup' : udb.list_group, - '/delgroup' : udb.del_group} + '/delgroup' : udb.del_group, + '/updatestat' : udb.force_update_stats, + '/delstat' : udb.force_delete_stats} auth_command = ["/trivial"] From a6c0ed0f486238d1ef864af2b904ba7f4c795c94 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 22:58:03 +0100 Subject: [PATCH 36/66] Add stats functions add a couple of functions to manage better stats table #53 --- utils/dbfunctions.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index fc0a380..fb4d195 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -26,6 +26,36 @@ def update_stats(utente,comando): stat.save() return +""" + Modifica forzata del numero di volte associato a un comando per un utente +""" +def force_update_stats(client,message,query): + splitted = query.split(" ") + userid = int(splitted[0]) + command = splitted[1] + value = int(splitted[2]) + query = (Stats + .update({Stats.times : value}) + .where((Stats.id_user == userid) & + (Stats.command == command))).execute() + return sendMessage(client,message,"__Valore aggiornato su " + command + " per " + str(userid) + "__") + + +""" + Cancella una riga dalla tabella per l'utente scelto e il comando selezionato +""" +def force_delete_stats(client,message,query): + splitted = query.split(" ") + userid = int(splitted[0]) + command = splitted[1] + query = (Stats + .delete() + .where((Stats.id_user == userid) & + (Stats.command == command))).execute() + result = "Comando " + command + " eliminato dalle statistiche di " + str(userid) + return sendMessage(client,message,result) + + """ @params client,message,id_utente @@ -43,6 +73,7 @@ def show_stats(utente,client,message): result += item.command + "__: Usato " + str(item.times) + " volte.__\n" return sendMessage(client,message,result) + """ @params utente,punteggio,categoria From 6fa103b07d184905e13399e1b8b6ffa00e97eae3 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 23:15:40 +0100 Subject: [PATCH 37/66] :wrench: handle exception --- utils/get_config.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/utils/get_config.py b/utils/get_config.py index bcf0ea0..a80e733 100644 --- a/utils/get_config.py +++ b/utils/get_config.py @@ -41,7 +41,10 @@ def get_id_user(message): Restituisce l'id della chat """ def get_chat(message): - return message.chat.id + try: + return message.chat.id + except AttributeError: + print("Error durante il prelievo dell'id chat") """ Restituisce il nome utente From 57a607fd40260c4fe918a0f55a1a0ac3305d5a03 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 27 Dec 2022 23:15:55 +0100 Subject: [PATCH 38/66] :wrench: Add position score --- utils/dbfunctions.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index fb4d195..48ff3d8 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -121,8 +121,10 @@ def global_trivial_leaderboard(client,message): .group_by(User.id_user)) result = "" + k = 1 for item in query: - result += item.user + ": __" + str(item.count) + " punti.__\n" + result += str(k) + ". " + item.user + ": __" + str(item.count) + " punti.__\n" + k = k + 1 return sendMessage(client,message,result) """ From f896d5b6227b8c2334e5df402c67533449e60cc1 Mon Sep 17 00:00:00 2001 From: Roberto Date: Wed, 28 Dec 2022 17:35:45 +0100 Subject: [PATCH 39/66] :wrench: avoid db bool Trying using a global variable to avoid using a db table just for a boolean value #75 #53 --- modules/trivial.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index fb3271e..f6c7596 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -126,10 +126,12 @@ def html2text(strings): global difficolta_domanda global versione_domanda global categoria +global wait_trivial +wait_trivial = False @Client.on_message() def send_question(query,client,message): #check wait_quiz - wait_trivial = get_wait_trivial_value() + #wait_trivial = get_wait_trivial_value() if wait_trivial: return sendMessage(client,message,"__Un altro quiz è attualmente in corso.\nRiprova tra poco.__") #variabili globali per tenere traccia di alcune informazioni per la fine del poll @@ -197,10 +199,12 @@ def send_question(query,client,message): try: msg = client.send_poll(get_chat(message),question="Category: " + category.title() + "\nDifficulty: " + difficulty.title() + "\n" + question,options=incorrect,type=PollType.QUIZ,correct_option_id=incorrect.index(correct),open_period=20,is_anonymous=False,reply_to_message_id=get_id_msg(message)) #Setto il wait così che non ci siano due quiz in contemporanea - set_wait_trivial() + #set_wait_trivial() + wait_trivial = True time.sleep(20) #setto a false dopo la fine del quiz - unset_wait_trivial() + wait_trivial = False + #unset_wait_trivial() except errors.exceptions.bad_request_400.PollAnswersInvalid: return sendMessage(client,message,"__Errore durante invio trivial__") From a3bc576c8329c73eee1ee199eef00a0a8d495ff1 Mon Sep 17 00:00:00 2001 From: Roberto Date: Wed, 28 Dec 2022 18:15:54 +0100 Subject: [PATCH 40/66] Add route --- utils/controller.py | 1 + 1 file changed, 1 insertion(+) diff --git a/utils/controller.py b/utils/controller.py index 17ace60..538f59b 100644 --- a/utils/controller.py +++ b/utils/controller.py @@ -53,6 +53,7 @@ dictionary_super = {'/setrobuser' : udb.set_user, '/delrobuser' : udb.del_user, + '/updaterobuser' : udb.update_user, '/listrobuser' : udb.list_user, '/allrobuser' : udb.all_user, '/setrobadmin' : udb.set_admin, From 183fe54dea933c90e4a18a9dcb39f1d873d9f073 Mon Sep 17 00:00:00 2001 From: Roberto Date: Wed, 28 Dec 2022 18:17:36 +0100 Subject: [PATCH 41/66] :wrench: Add function Add function to update user info on db and marked 'to delete' all three functions about wait_trivial #75 #53 --- utils/dbfunctions.py | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index 48ff3d8..dcff5d2 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -8,6 +8,9 @@ db.connect() +#################################################################### +#### FUNZIONI LEGATE ALLE STATISTICHE SUI COMANDI USATI DAGLI UTENTI +#################################################################### """ @params utente, comando @@ -74,6 +77,10 @@ def show_stats(utente,client,message): return sendMessage(client,message,result) +###################################### +#### FUNZIONI LEGATE AL GIOCO /TRIVIAL +###################################### + """ @params utente,punteggio,categoria @@ -130,6 +137,7 @@ def global_trivial_leaderboard(client,message): """ setto il wait time a true per via di un quiz in corso """ +#to delete def set_wait_trivial(): query = (waitTrivial .update({waitTrivial.value: True})).execute() @@ -141,6 +149,7 @@ def set_wait_trivial(): """ setto il wait time a false, è possibile lanciare un nuovo quiz """ +#to delete def unset_wait_trivial(): query = (waitTrivial .update({waitTrivial.value: False})).execute() @@ -152,11 +161,18 @@ def unset_wait_trivial(): """ prelevo il valore del wait time """ +#to delete def get_wait_trivial_value(): query = waitTrivial.select() for item in query: return item.value + + +############################################################################# +#### FUNZIONI LEGATE ALLA GESTIONE DEI GRUPPI SALVATI CON COMANDI AUTORIZZATI +############################################################################# + """ Restituisce la lista dei gruppi autorizzati a certi comandi """ @@ -216,7 +232,11 @@ def check_group_command(match,message): return True else: return False - + + +############################################################## +#### FUNZIONI LEGATE ALLA GESTIONE DEGLI UTENTI SALVATI SUL DB +############################################################## """ questa funzione fa una select dalla tabella User e restituisce gli id di tutti gli utenti registratii dentro una lista di int """ @@ -282,6 +302,21 @@ def set_user(client,message,query): result = "Utente " + str(user.id_user) + " salvato!" return sendMessage(client,message,result) +""" + update dei dati sul db di un utente specifico +""" +@Client.on_message() +def update_user(client,message,query): + json_user = client.get_users(query) + userid = json_user.id + nome_utente = json_user.first_name + username_utente = "@" + str(json_user.username) + query = (User + .update((name = nome_utente,username = username_utente)) + .where(User.id_user == userid)).execute() + result = "Dati aggiornati per utente " + str(userid) + return sendMessage(client,message,result) + """ Questa funzione elimina un utente dalla tabella User """ From cbe561a916b68f3b299ce3b3742566fd1515d91e Mon Sep 17 00:00:00 2001 From: Roberto Date: Wed, 28 Dec 2022 18:44:50 +0100 Subject: [PATCH 42/66] :recycle: refactor #75 --- modules/trivial.py | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index f6c7596..77d4fd4 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -118,9 +118,22 @@ def html2text(strings): result.append(zuppa.get_text()) return result +""" + randomizza se scegliere vero/falso o risposta multipla +""" +def get_question_type(): + #create question type in random mode + n = random.randint(0,100) + question_list = ["tf","multi"] + if n >= 65: + question_type = question_list[0] + else: + question_type = question_list[1] + return question_type """ Restituisce una domanda quiz tramite le api di opentdb.com + Definizione di alcune variabili globali per tenere dei valori in memoria tra una funzione e la callback """ global corretta global difficolta_domanda @@ -131,6 +144,7 @@ def html2text(strings): @Client.on_message() def send_question(query,client,message): #check wait_quiz + global wait_trivial #wait_trivial = get_wait_trivial_value() if wait_trivial: return sendMessage(client,message,"__Un altro quiz è attualmente in corso.\nRiprova tra poco.__") @@ -151,23 +165,24 @@ def send_question(query,client,message): values = categorie.values() #list comprehension per recuperare la chiave del dizionario categoria a partire dal valore random creato category = str({i for i in categorie if categorie[i] == category_number}).replace("{'","").replace("'}","") - #create question type in random mode - question_list = ["tf","multi"] - random.shuffle(question_list) - question_type = question_list[0] + question_type = get_question_type() #setting difficulty difficulty = set_difficulty() else: - splitted = query.split("/") + splitted = query.split(" ") try: - category= splitted[1] - question_type = splitted[0] + category = splitted[0].title() + for item in categorie: + if category in item: + category = categorie[item] + break + question_type = get_question_type() difficulty = set_difficulty() except IndexError: return sendMessage(client,message,"__Errore formato trivial.__") #build api url - api_url = "https://opentdb.com/api.php?amount=1&category=" + str(categorie[category.title()]) + "&difficulty=" + difficulty + "&type=" + tipo_domanda[question_type] + "&token=" + token + api_url = "https://opentdb.com/api.php?amount=1&category=" + str(category) + "&difficulty=" + difficulty + "&type=" + tipo_domanda[question_type] + "&token=" + token resp = requests.get(api_url) data = json.loads(resp.text) incorrect = [] From 595d53ca260ae3680292f74581c7184c114c35dc Mon Sep 17 00:00:00 2001 From: Roberto Date: Wed, 28 Dec 2022 19:04:49 +0100 Subject: [PATCH 43/66] Update README.md --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index 148d7b6..0bbd56f 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,11 @@ Le spiegazioni sono in Italiano, ma volendo si possono tradurre in qualsiasi lin * mostrare tutti gli utenti registrati: ```/listrobuser``` * mostrare il numero di utenti registrati: ```/allrobuser``` * verificare se il bot è online: ```/pingrob``` +* registrare un nuovo gruppo come unico autorizzato a ricevere un certo comando: `/setgroup` +* cancellare un gruppo salvato: `/delgroup` +* mostrare tutti i gruppi salvati: `/listgroup` +* modificare un valore nelle statistiche di un utente per un certo comando: `/updatestat` +* cancellare un comando dalle statistiche di un utente: `/delstat` ### Dipendenze @@ -112,6 +117,11 @@ This json file is only in Italian, but you can translate it in every languages b * How to list all user registered: ```/listrobuser``` * How to show ho many users are registered: ```/allrobuser``` * check if the bot is online: ```/pingrob``` +* Save a new group to make it the only one authorized to receive a specific command: `/setgroup` +* Delete a saved group: `/delgroup` +* Show all saved groups: `/listgroup` +* Update a value in a user's stat for a specific command: `/updatestat` +* Delete a command from a user's stat: `/delstat` ### Dependencies From ae26e93f9128d8298f2e3eedadca512e1d7eb6da Mon Sep 17 00:00:00 2001 From: Roberto Date: Wed, 28 Dec 2022 20:10:56 +0100 Subject: [PATCH 44/66] Add function --- utils/dbfunctions.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index dcff5d2..a551ab6 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -134,6 +134,22 @@ def global_trivial_leaderboard(client,message): k = k + 1 return sendMessage(client,message,result) +""" + classifica globale ma solo in una specifica categoria di domande +""" +def global_trivial_leaderboard_category(query,client,message): + query = (User + .select(User.name.alias('user'),fn.SUM(Trivial.points).alias('count')) + .join(Trivial, on(User.id_user == Trivial.id_user)) + .where(Trivial.category == query) + .order_by(fn.SUM(Trivial.points).desc()) + .group_by(User.id_user)) + result = "__" + query + "__" + k = 1 + for item in query: + result += str(k) + ". " + item.user + ": __" + str(item.count) + " punti.__\n" + return sendMessage(client,message,result) + """ setto il wait time a true per via di un quiz in corso """ From 95c0437076c28bd2217048afc4265318b7093ad8 Mon Sep 17 00:00:00 2001 From: Roberto Date: Wed, 28 Dec 2022 23:29:08 +0100 Subject: [PATCH 45/66] :bug: Fix query --- utils/dbfunctions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index a551ab6..daa3544 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -328,7 +328,7 @@ def update_user(client,message,query): nome_utente = json_user.first_name username_utente = "@" + str(json_user.username) query = (User - .update((name = nome_utente,username = username_utente)) + .update(name = nome_utente,username = username_utente) .where(User.id_user == userid)).execute() result = "Dati aggiornati per utente " + str(userid) return sendMessage(client,message,result) From def341a951110c1e49f06bddad495ea53863c2a1 Mon Sep 17 00:00:00 2001 From: Roberto Date: Wed, 28 Dec 2022 23:36:11 +0100 Subject: [PATCH 46/66] :x: Delete waitTrivial table --- utils/dbfunctions.py | 33 --------------------------------- utils/dbtables.py | 10 +--------- 2 files changed, 1 insertion(+), 42 deletions(-) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index daa3544..d41a0f7 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -150,39 +150,6 @@ def global_trivial_leaderboard_category(query,client,message): result += str(k) + ". " + item.user + ": __" + str(item.count) + " punti.__\n" return sendMessage(client,message,result) -""" - setto il wait time a true per via di un quiz in corso -""" -#to delete -def set_wait_trivial(): - query = (waitTrivial - .update({waitTrivial.value: True})).execute() - if(query == 0): - wait_trivial = waitTrivial(value = True) - wait_trivial.save() - return - -""" - setto il wait time a false, è possibile lanciare un nuovo quiz -""" -#to delete -def unset_wait_trivial(): - query = (waitTrivial - .update({waitTrivial.value: False})).execute() - if(query == 0): - wait_trivial = waitTrivial(value = False) - wait_trivial.save() - return - -""" - prelevo il valore del wait time -""" -#to delete -def get_wait_trivial_value(): - query = waitTrivial.select() - for item in query: - return item.value - ############################################################################# diff --git a/utils/dbtables.py b/utils/dbtables.py index 519885f..602381a 100644 --- a/utils/dbtables.py +++ b/utils/dbtables.py @@ -52,19 +52,11 @@ class Group(BaseModel): title = CharField() command = CharField() -""" - valore booleano necessario per non avere due quiz attivi in contemporanea -""" -class waitTrivial(BaseModel): - value = BooleanField() db.connect() -db.create_tables([User,Stats,Trivial,waitTrivial,Group]) +db.create_tables([User,Stats,Trivial,Group]) -#Inizializzo il wait trivial a False -wait_trivial = waitTrivial(value = False) -wait_trivial.save() #Inizializzo il super admin da file di configurazione overlord = User(id_user = id_super_admin[0], name = id_super_admin[1], username = id_super_admin[2], admin = True, superadmin = True) From c24c052f4d91087e432ea22721dbda7fa8e249c9 Mon Sep 17 00:00:00 2001 From: Roberto Date: Wed, 28 Dec 2022 23:36:51 +0100 Subject: [PATCH 47/66] :bug: :recycle: Fix & Refactor --- modules/trivial.py | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index 77d4fd4..95695c2 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -161,10 +161,6 @@ def send_question(query,client,message): if query == "/trivial": #Build random options for the request category_number = random.randint(9,32) - category_keys = list(categorie.keys()) - values = categorie.values() - #list comprehension per recuperare la chiave del dizionario categoria a partire dal valore random creato - category = str({i for i in categorie if categorie[i] == category_number}).replace("{'","").replace("'}","") question_type = get_question_type() #setting difficulty difficulty = set_difficulty() @@ -182,7 +178,7 @@ def send_question(query,client,message): return sendMessage(client,message,"__Errore formato trivial.__") #build api url - api_url = "https://opentdb.com/api.php?amount=1&category=" + str(category) + "&difficulty=" + difficulty + "&type=" + tipo_domanda[question_type] + "&token=" + token + api_url = "https://opentdb.com/api.php?amount=1&category=" + str(category_number) + "&difficulty=" + difficulty + "&type=" + tipo_domanda[question_type] + "&token=" + token resp = requests.get(api_url) data = json.loads(resp.text) incorrect = [] @@ -214,12 +210,10 @@ def send_question(query,client,message): try: msg = client.send_poll(get_chat(message),question="Category: " + category.title() + "\nDifficulty: " + difficulty.title() + "\n" + question,options=incorrect,type=PollType.QUIZ,correct_option_id=incorrect.index(correct),open_period=20,is_anonymous=False,reply_to_message_id=get_id_msg(message)) #Setto il wait così che non ci siano due quiz in contemporanea - #set_wait_trivial() wait_trivial = True time.sleep(20) #setto a false dopo la fine del quiz wait_trivial = False - #unset_wait_trivial() except errors.exceptions.bad_request_400.PollAnswersInvalid: return sendMessage(client,message,"__Errore durante invio trivial__") From f9f8274605b60f488d88b4c5f0df8a4683d61cb5 Mon Sep 17 00:00:00 2001 From: Roberto Date: Wed, 28 Dec 2022 23:46:43 +0100 Subject: [PATCH 48/66] :bug: Fix --- modules/trivial.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index 95695c2..5a69781 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -1,5 +1,5 @@ from utils.get_config import sendMessage,get_chat,get_id_msg,get_id_user -from utils.dbfunctions import personal_trivial_leaderboard,global_trivial_leaderboard,update_trivial_score,get_wait_trivial_value,set_wait_trivial,unset_wait_trivial +from utils.dbfunctions import personal_trivial_leaderboard,global_trivial_leaderboard,update_trivial_score from pyrogram import Client,errors from pyrogram.enums import PollType from pyrogram.handlers import PollHandler,RawUpdateHandler @@ -118,6 +118,14 @@ def html2text(strings): result.append(zuppa.get_text()) return result +""" + Come sopra ma per le stringhe singole e non liste +""" +def html2text_str(string): + zuppa = BeautifulSoup(string,features="lxml") + result = zuppa.get_text() + return result + """ randomizza se scegliere vero/falso o risposta multipla """ @@ -170,7 +178,7 @@ def send_question(query,client,message): category = splitted[0].title() for item in categorie: if category in item: - category = categorie[item] + category_number = categorie[item] break question_type = get_question_type() difficulty = set_difficulty() @@ -193,8 +201,8 @@ def send_question(query,client,message): incorrect.append(correct) random.shuffle(incorrect) #prepare question and send - zuppa = BeautifulSoup(question,features="lxml") - question = zuppa.get_text() + question = html2text_str(question) + correct = html2text_str(correct) incorrect = html2text(incorrect) #aggiungo handler per ricevere aggiornamenti sul quiz in corso From b09d73ca5f8db0dede667e25d5e27c3854531ed3 Mon Sep 17 00:00:00 2001 From: Roberto Date: Thu, 29 Dec 2022 00:18:02 +0100 Subject: [PATCH 49/66] :bug: Fix query --- utils/dbfunctions.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index d41a0f7..c9138c0 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -138,16 +138,19 @@ def global_trivial_leaderboard(client,message): classifica globale ma solo in una specifica categoria di domande """ def global_trivial_leaderboard_category(query,client,message): - query = (User - .select(User.name.alias('user'),fn.SUM(Trivial.points).alias('count')) - .join(Trivial, on(User.id_user == Trivial.id_user)) - .where(Trivial.category == query) - .order_by(fn.SUM(Trivial.points).desc()) - .group_by(User.id_user)) - result = "__" + query + "__" + if query == '/globaltscore': + return global_trivial_leaderboard(client,message) + query_sql = (User + .select(User.name.alias('user'),fn.SUM(Trivial.points).alias('count')) + .join(Trivial, on=(User.id_user == Trivial.id_user)) + .where(Trivial.category == query) + .order_by(fn.SUM(Trivial.points).desc()) + .group_by(User.id_user)) + result = "__" + query + "__\n" k = 1 - for item in query: + for item in query_sql: result += str(k) + ". " + item.user + ": __" + str(item.count) + " punti.__\n" + k = k + 1 return sendMessage(client,message,result) From fefe9548d3fa6e43bf93ccc953bf87161923e551 Mon Sep 17 00:00:00 2001 From: Roberto Date: Thu, 29 Dec 2022 00:18:16 +0100 Subject: [PATCH 50/66] :wrench: score category --- modules/trivial.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index 5a69781..0433f84 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -1,5 +1,5 @@ from utils.get_config import sendMessage,get_chat,get_id_msg,get_id_user -from utils.dbfunctions import personal_trivial_leaderboard,global_trivial_leaderboard,update_trivial_score +from utils.dbfunctions import personal_trivial_leaderboard,global_trivial_leaderboard_category,update_trivial_score from pyrogram import Client,errors from pyrogram.enums import PollType from pyrogram.handlers import PollHandler,RawUpdateHandler @@ -251,12 +251,16 @@ def check_trivial_updates(client,update,users,chat): """ richiamo funzione per punteggi personali """ -def get_personal_score(query,client,message): +def get_personal_score(client,message): return personal_trivial_leaderboard(get_id_user(message),client,message) """ richiamo funzione per classifica globale """ def get_global_score(query,client,message): - return global_trivial_leaderboard(client,message) + print(query) + for item in categorie: + if query.title() in item: + query = item + return global_trivial_leaderboard_category(query,client,message) From 0064cb61f85cb55d396f51b92b8a79db2262a7df Mon Sep 17 00:00:00 2001 From: Roberto Date: Thu, 29 Dec 2022 14:17:13 +0100 Subject: [PATCH 51/66] :bug: Fix match categories --- modules/trivial.py | 51 +++++++++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index 0433f84..b551db0 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -11,30 +11,30 @@ from bs4 import BeautifulSoup -categorie = {"General Knowledge" :9, - "Books" :10, - "Film" :11, - "Music" :12, - "Musical & Theatres" :13, - "Television" :14, - "Video Games" :15, - "Board Games" :16, - "Science & Nature" :17, - "Science & Computers" :18, - "Science & Mathematics" :19, - "Mythology" :20, - "Sports" :21, - "Geography" :22, - "History" :23, - "Politics" :24, - "Art" :25, - "Celebrities" :26, - "Animals" :27, - "Vehicles" :28, - "Comics" :29, - "Science & Gadgets" :30, - "Japanese Anime & Manga":31, - "Cartoon & Animations" :32} +categorie = {"General Knowledge" :9, + "Entertainment: Books" :10, + "Entertainment: Film" :11, + "Entertainment: Music" :12, + "Entertainment: Musical & Theatres" :13, + "Entertainment: Television" :14, + "Entertainment: Video Games" :15, + "Entertainment: Board Games" :16, + "Science & Nature" :17, + "Science: Computers" :18, + "Science: Mathematics" :19, + "Mythology" :20, + "Sports" :21, + "Geography" :22, + "History" :23, + "Politics" :24, + "Art" :25, + "Celebrities" :26, + "Animals" :27, + "Vehicles" :28, + "Entertainment: Comics" :29, + "Science: Gadgets" :30, + "Entertainment: Japanese Anime & Manga":31, + "Entertainment: Cartoon & Animations" :32} tipo_domanda = {"tf" :"boolean", @@ -251,14 +251,13 @@ def check_trivial_updates(client,update,users,chat): """ richiamo funzione per punteggi personali """ -def get_personal_score(client,message): +def get_personal_score(query,client,message): return personal_trivial_leaderboard(get_id_user(message),client,message) """ richiamo funzione per classifica globale """ def get_global_score(query,client,message): - print(query) for item in categorie: if query.title() in item: query = item From 6c1fd851b15b1423c0afce4d533e95e7da046286 Mon Sep 17 00:00:00 2001 From: Roberto <72561502+MasterCruelty@users.noreply.github.com> Date: Thu, 29 Dec 2022 16:55:34 +0100 Subject: [PATCH 52/66] Update README.md Add info about external project used --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 0bbd56f..8805c27 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,8 @@ Le spiegazioni sono in Italiano, ma volendo si possono tradurre in qualsiasi lin * [Tper open data](https://solweb.tper.it/web/tools/open-data/open-data.aspx) * [TrainMonitor per le API viaggiatreno](https://github.com/bluviolin/TrainMonitor) (Queste API non sono pubbliche, non abusate del servizio) * [Trenitalia-API di SimoDax per le API frecce.it](https://github.com/SimoDax/Trenitalia-API) (Queste API non sono pubbliche, non abusate del servizio) +* [Piste Kart Italia(scraping)](https://www.pistekartitalia.it) +* [Open Trivia Database](https://opentdb.com/) # **[ENG]** @@ -150,3 +152,5 @@ This json file is only in Italian, but you can translate it in every languages b * [Tper open data](https://solweb.tper.it/web/tools/open-data/open-data.aspx) * [TrainMonitor for viaggiatreno API](https://github.com/bluviolin/TrainMonitor) (These API aren't public, don't abuse the service) * [SimoDax's wiki for frecce.it API](https://github.com/SimoDax/Trenitalia-API) (These API aren't public, don't abuse the service) +* [Piste Kart Italia(scraping)](https://www.pistekartitalia.it) +* [Open Trivia Database](https://opentdb.com/) From c97cb8fe1d9a9eaa4457a52689fa16f575088c0c Mon Sep 17 00:00:00 2001 From: Roberto <72561502+MasterCruelty@users.noreply.github.com> Date: Thu, 29 Dec 2022 16:57:08 +0100 Subject: [PATCH 53/66] Update help.json update help /trivial --- help.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/help.json b/help.json index a59ea62..033dc9e 100644 --- a/help.json +++ b/help.json @@ -44,6 +44,6 @@ }, "openai":"**/ai 'input' ** => genera un testo in base all'input dato grazie alle api di OpenAI", "urban": "**/urban 'word' ** => restituisce la definizione di urban dictionary per la parola richiesta", - "trivial": "__**Questo comando è disponibile solo in alcune chat decise dall'admin.\nI nomi delle categorie sono listati nel gruppo ufficiale del gioco.**__\n\n**/trivial** ==> quiz vero/falso oppure a scelta multipla in una categoria randomica.\n**/trivial tipo/categoria** ==> quiz del tipo scelto e categoria scelta.\n__Esempio: /trivial tf/history per vero/falso in storia.\n/trivial multi/history per risposta multipla in storia.__\n\n", + "trivial": "__**Questo comando è disponibile solo in alcune chat decise dall'admin.\nI nomi delle categorie sono listati nel gruppo ufficiale del gioco.**__\n\n**/trivial** ==> quiz vero/falso oppure a scelta multipla in una categoria randomica.\n**/trivial categoria** ==> quiz della categoria scelta.\n__Esempio: /trivial history per un quiz in storia.__\n\n", "default": "Cerca un comando in particolare come ad esempio:\n /helprob wiki\n__Comandi: wiki, lyrics, covid, vaccine, weather, urban, poll, reminder, tper, atm, treni, kart, trivial e mappe.\n\ncomandi admin: **playlotto, getmessage, weathermap, weathersat, openai e pingrob.**\nVuoi usarli? Diventa un utente premium! Contatta @MasterCruelty__" } From 861b1709f46c3eed0a52d13de601d11361e43429 Mon Sep 17 00:00:00 2001 From: Roberto Date: Fri, 30 Dec 2022 00:05:48 +0100 Subject: [PATCH 54/66] :wrench: auto sign-up via trivial --- modules/trivial.py | 4 ++-- utils/dbfunctions.py | 11 +++++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index b551db0..38ea267 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -244,9 +244,9 @@ def check_trivial_updates(client,update,users,chat): if corretta == int_chosen: print(str(player) + " ha risposto correttamente") if versione_domanda.title() == 'Boolean': - update_trivial_score(player,1,categoria) + update_trivial_score(player,1,categoria,client,update) else: - update_trivial_score(player,punteggi[difficolta_domanda.title()],categoria) + update_trivial_score(player,punteggi[difficolta_domanda.title()],categoria,client,update) """ richiamo funzione per punteggi personali diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index c9138c0..028f0b0 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -3,6 +3,7 @@ from utils.dbtables import * from pyrogram import Client from utils.get_config import * +import peewee #Inizio della connessione con il db db.connect() @@ -86,14 +87,20 @@ def show_stats(utente,client,message): Aggiorna il punteggio dell'utente sulla categoria """ -def update_trivial_score(utente,punteggio,categoria): +def update_trivial_score(utente,punteggio,categoria,client,message): query = (Trivial .update({Trivial.points: Trivial.points + punteggio}) .where((Trivial.id_user == utente) & (Trivial.category == categoria))).execute() if(query == 0): score = Trivial(id_user = utente,category = categoria, points = punteggio) - score.save() + try: + score.save() + except peewee.PeeweeException: + #Se un utente non registrato vota su un quiz, viene registrato in automatico + set_user(client,message,utente) + score = Trivial(id_user = utente,category = categoria, points = punteggio) + score.save() return """ From 73988f04950b10bc09fcfa4de31db7fb9eac6b31 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 3 Jan 2023 00:24:09 +0100 Subject: [PATCH 55/66] Create table --- utils/dbtables.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/utils/dbtables.py b/utils/dbtables.py index 602381a..b309784 100644 --- a/utils/dbtables.py +++ b/utils/dbtables.py @@ -52,11 +52,20 @@ class Group(BaseModel): title = CharField() command = CharField() +""" + Tabella ausiliaria per salvare i dati del trivial mentre è in corso + Così da poter avere più trivial contemporaneamente in gioco. +""" +class TrivialSavedData(BaseModel): + id_chat = IntegerField(default = 0) + id_msg = IntegerField(unique = True) + diff = CharField() + category = CharField() + qtype = CharField() db.connect() -db.create_tables([User,Stats,Trivial,Group]) - +db.create_tables([User,Stats,Trivial,Group,TrivialSavedData]) #Inizializzo il super admin da file di configurazione overlord = User(id_user = id_super_admin[0], name = id_super_admin[1], username = id_super_admin[2], admin = True, superadmin = True) From 7c7f8dd90015ade4081972d4a65dde8d6387491f Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 3 Jan 2023 00:24:27 +0100 Subject: [PATCH 56/66] :wrench: Add functions --- utils/dbfunctions.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index 028f0b0..947ea37 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -161,6 +161,33 @@ def global_trivial_leaderboard_category(query,client,message): return sendMessage(client,message,result) +""" + Salva in db i dati del trivial in corso +""" +def save_trivial_data(group,msg,difficulty,categ,question_type): + trdata = TrivialSavedData(id_chat = group, id_msg = msg, diff = difficulty, category = categ,qtype = question_type) + trdata.save() + print("Dati trivial salvati") + return + +""" + prelevo i dati dei trivial salvati su db +""" +def get_trivial_data(): + query = TrivialSavedData.select() + print("Dati trivial prelevati") + return query + +""" + cancella un record dalla tabella dei trivial salvati +""" +def delete_trivial_data(msg): + query = (TrivialSavedData + .delete() + .where(TrivialSavedData.id_msg == msg)).execute() + print("Dati trivial concluso eliminati") + return + ############################################################################# #### FUNZIONI LEGATE ALLA GESTIONE DEI GRUPPI SALVATI CON COMANDI AUTORIZZATI From f0aa685550683a135ea666c45bfe4e4fb230ce93 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 3 Jan 2023 00:24:43 +0100 Subject: [PATCH 57/66] :rocket: multiple quiz at the same time --- modules/trivial.py | 47 ++++++++++++++++------------------------------ 1 file changed, 16 insertions(+), 31 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index 38ea267..dc107c1 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -1,5 +1,5 @@ from utils.get_config import sendMessage,get_chat,get_id_msg,get_id_user -from utils.dbfunctions import personal_trivial_leaderboard,global_trivial_leaderboard_category,update_trivial_score +from utils.dbfunctions import personal_trivial_leaderboard,global_trivial_leaderboard_category,update_trivial_score,get_trivial_data,save_trivial_data,delete_trivial_data from pyrogram import Client,errors from pyrogram.enums import PollType from pyrogram.handlers import PollHandler,RawUpdateHandler @@ -143,24 +143,8 @@ def get_question_type(): Restituisce una domanda quiz tramite le api di opentdb.com Definizione di alcune variabili globali per tenere dei valori in memoria tra una funzione e la callback """ -global corretta -global difficolta_domanda -global versione_domanda -global categoria -global wait_trivial -wait_trivial = False @Client.on_message() def send_question(query,client,message): - #check wait_quiz - global wait_trivial - #wait_trivial = get_wait_trivial_value() - if wait_trivial: - return sendMessage(client,message,"__Un altro quiz è attualmente in corso.\nRiprova tra poco.__") - #variabili globali per tenere traccia di alcune informazioni per la fine del poll - global corretta - global difficolta_domanda - global versione_domanda - global categoria #check token global token token = check_token() @@ -210,18 +194,12 @@ def send_question(query,client,message): #client.add_handler(PollHandler(callback=check_trivial_updates)) client.add_handler(RawUpdateHandler(callback=check_trivial_updates)) - corretta = incorrect.index(correct) - versione_domanda = tipo_domanda[question_type] - difficolta_domanda = difficulty - categoria = category.title() try: msg = client.send_poll(get_chat(message),question="Category: " + category.title() + "\nDifficulty: " + difficulty.title() + "\n" + question,options=incorrect,type=PollType.QUIZ,correct_option_id=incorrect.index(correct),open_period=20,is_anonymous=False,reply_to_message_id=get_id_msg(message)) - #Setto il wait così che non ci siano due quiz in contemporanea - wait_trivial = True - time.sleep(20) - #setto a false dopo la fine del quiz - wait_trivial = False + + #aggiungo su db dati sul trivial in corso + save_trivial_data(get_chat(message),msg.id,difficulty.title(),category.title(),tipo_domanda[question_type].title()) except errors.exceptions.bad_request_400.PollAnswersInvalid: return sendMessage(client,message,"__Errore durante invio trivial__") @@ -241,12 +219,19 @@ def check_trivial_updates(client,update,users,chat): player = data.user_id chosen = data.options[0] int_chosen = int.from_bytes(chosen,"big") - if corretta == int_chosen: - print(str(player) + " ha risposto correttamente") - if versione_domanda.title() == 'Boolean': - update_trivial_score(player,1,categoria,client,update) + query = get_trivial_data() + for item in query: + polldata = client.get_messages(item.id_chat,item.id_msg) + if int(polldata.poll.id) == int(data.poll_id): + if int(int_chosen) == int(polldata.poll.correct_option_id): + print(str(player) + " ha risposto correttamente") + if item.qtype == 'Boolean': + update_trivial_score(player,1,item.category,client,update) + else: + update_trivial_score(player,punteggi[item.diff],item.category,client,update) else: - update_trivial_score(player,punteggi[difficolta_domanda.title()],categoria,client,update) + if polldata.poll.is_closed: + delete_trivial_data(item.id_msg) """ richiamo funzione per punteggi personali From a8adbf8570812f7c16b2f8e1180e4407dc4950dd Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 3 Jan 2023 19:31:51 +0100 Subject: [PATCH 58/66] :wrench: fix code smell --- modules/trivial.py | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index dc107c1..46afacd 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -222,16 +222,14 @@ def check_trivial_updates(client,update,users,chat): query = get_trivial_data() for item in query: polldata = client.get_messages(item.id_chat,item.id_msg) - if int(polldata.poll.id) == int(data.poll_id): - if int(int_chosen) == int(polldata.poll.correct_option_id): - print(str(player) + " ha risposto correttamente") - if item.qtype == 'Boolean': - update_trivial_score(player,1,item.category,client,update) - else: - update_trivial_score(player,punteggi[item.diff],item.category,client,update) - else: - if polldata.poll.is_closed: - delete_trivial_data(item.id_msg) + if (int(polldata.poll.id) == int(data.poll_id)) and (int(int_chosen) == int(polldata.poll.correct_option_id)): + print(str(player) + " ha risposto correttamente") + if item.qtype == 'Boolean': + update_trivial_score(player,1,item.category,client,update) + else: + update_trivial_score(player,punteggi[item.diff],item.category,client,update) + elif polldata.poll.is_closed: + delete_trivial_data(item.id_msg) """ richiamo funzione per punteggi personali From e1432a0441475b148b7cb24394a824652f0967f7 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 3 Jan 2023 21:40:24 +0100 Subject: [PATCH 59/66] :wrench: fix code smells --- modules/trivial.py | 2 +- utils/dbfunctions.py | 37 +++++++++++++++++-------------------- 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/modules/trivial.py b/modules/trivial.py index 46afacd..cdd5a33 100644 --- a/modules/trivial.py +++ b/modules/trivial.py @@ -234,7 +234,7 @@ def check_trivial_updates(client,update,users,chat): """ richiamo funzione per punteggi personali """ -def get_personal_score(query,client,message): +def get_personal_score(_,client,message): return personal_trivial_leaderboard(get_id_user(message),client,message) """ diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index 947ea37..f5bb312 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -38,10 +38,10 @@ def force_update_stats(client,message,query): userid = int(splitted[0]) command = splitted[1] value = int(splitted[2]) - query = (Stats - .update({Stats.times : value}) - .where((Stats.id_user == userid) & - (Stats.command == command))).execute() + (Stats + .update({Stats.times : value}) + .where((Stats.id_user == userid) & + (Stats.command == command))).execute() return sendMessage(client,message,"__Valore aggiornato su " + command + " per " + str(userid) + "__") @@ -52,10 +52,10 @@ def force_delete_stats(client,message,query): splitted = query.split(" ") userid = int(splitted[0]) command = splitted[1] - query = (Stats - .delete() - .where((Stats.id_user == userid) & - (Stats.command == command))).execute() + (Stats + .delete() + .where((Stats.id_user == userid) & + (Stats.command == command))).execute() result = "Comando " + command + " eliminato dalle statistiche di " + str(userid) return sendMessage(client,message,result) @@ -101,14 +101,13 @@ def update_trivial_score(utente,punteggio,categoria,client,message): set_user(client,message,utente) score = Trivial(id_user = utente,category = categoria, points = punteggio) score.save() - return """ @params utente,client,message Restituisce le proprie statistiche sul gioco Trivial """ -def personal_trivial_leaderboard(utente,client,message): +def personal_trivial_leaderboard(_,client,message): id_utente = get_id_user(message) result = "Le tue statistiche su Trivial\n\n" query = (Trivial @@ -168,7 +167,6 @@ def save_trivial_data(group,msg,difficulty,categ,question_type): trdata = TrivialSavedData(id_chat = group, id_msg = msg, diff = difficulty, category = categ,qtype = question_type) trdata.save() print("Dati trivial salvati") - return """ prelevo i dati dei trivial salvati su db @@ -182,11 +180,10 @@ def get_trivial_data(): cancella un record dalla tabella dei trivial salvati """ def delete_trivial_data(msg): - query = (TrivialSavedData - .delete() - .where(TrivialSavedData.id_msg == msg)).execute() + (TrivialSavedData + .delete() + .where(TrivialSavedData.id_msg == msg)).execute() print("Dati trivial concluso eliminati") - return ############################################################################# @@ -231,7 +228,7 @@ def set_group(client,message,query): """ @Client.on_message() def del_group(client,message,query): - delete = Group.delete().where(Group.id_group == query).execute() + Group.delete().where(Group.id_group == query).execute() result = "Gruppo " + str(query) + " eliminato dai gruppi salvati." return sendMessage(client,message,result) @@ -246,7 +243,7 @@ def check_group_command(match,message): #controllo se vi è almeno un record i = 0 - for item in query: + for _ in query: i = i + 1 if i == 0: return True @@ -331,9 +328,9 @@ def update_user(client,message,query): userid = json_user.id nome_utente = json_user.first_name username_utente = "@" + str(json_user.username) - query = (User - .update(name = nome_utente,username = username_utente) - .where(User.id_user == userid)).execute() + (User + .update(name = nome_utente,username = username_utente) + .where(User.id_user == userid)).execute() result = "Dati aggiornati per utente " + str(userid) return sendMessage(client,message,result) From 7d7bb8505e9caadc2d9d67900f59449a5faf7f48 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 3 Jan 2023 21:40:41 +0100 Subject: [PATCH 60/66] Add get_chat_name --- utils/get_config.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/utils/get_config.py b/utils/get_config.py index a80e733..c0168a4 100644 --- a/utils/get_config.py +++ b/utils/get_config.py @@ -46,6 +46,15 @@ def get_chat(message): except AttributeError: print("Error durante il prelievo dell'id chat") +""" +Restituisce il titolo della chat +""" +def get_chat_name(message): + try: + return message.chat.title + except AttributeError: + print("Error durante il prelievo del nome della chat") + """ Restituisce il nome utente """ From 46e3af09f3ec8272354b388530b8459e5af0cb90 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 3 Jan 2023 21:41:02 +0100 Subject: [PATCH 61/66] Update app.py Wrapped chat name --- app.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app.py b/app.py index 0958ccc..202036e 100644 --- a/app.py +++ b/app.py @@ -1,7 +1,7 @@ from pyrogram import Client from utils.controller import * from utils.dbfunctions import * -from utils.get_config import get_config_file,get_username,get_text_message,get_chat,get_id_msg,get_id_user,get_first_name +from utils.get_config import get_config_file,get_username,get_text_message,get_chat,get_id_msg,get_id_user,get_first_name,get_chat_name from utils.sysfunctions import * config = get_config_file("config.json") @@ -20,7 +20,7 @@ def print_updates(client,message): chat = get_chat(message) id_messaggio = get_id_msg(message) utente = get_id_user(message) - nome_chat = message.chat.title + nome_chat = get_chat_name(message) nome_utente = get_first_name(message) username = get_username(message) messaggio = get_text_message(message) From ee0456b58d0169d72636eb7e0605e97d2795ec22 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 3 Jan 2023 22:28:58 +0100 Subject: [PATCH 62/66] Update .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 743c395..62fdf42 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,7 @@ json_message.json #Ignora file img e sat24.gif img.png sat24.gif +graph.png #Ignora log e aux file *.aux From a4bad6d0a4bb0208b9e7c407502ac70c99ea33bd Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 3 Jan 2023 22:29:53 +0100 Subject: [PATCH 63/66] :chart_qith_upwards_trend: Add piechart --- utils/dbfunctions.py | 40 ++++++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index f5bb312..82fa1da 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -4,6 +4,10 @@ from pyrogram import Client from utils.get_config import * import peewee +import matplotlib.pyplot as plt + +#setto stile matplotlib +plt.style.use('fivethirtyeight') #Inizio della connessione con il db db.connect() @@ -65,17 +69,37 @@ def force_delete_stats(client,message,query): La funzione restituisce tutti i dati sulle statistiche dei comandi usati dall'utente. """ -def show_stats(utente,client,message): +def show_stats(query,client,message): id_utente = get_id_user(message) result = "Le tue statistiche\n" - query = (Stats - .select() - .join(User, on=(User.id_user == Stats.id_user)) - .where(Stats.id_user == id_utente) - .order_by(Stats.times.desc())) - for item in query: + query_sql = (Stats + .select() + .join(User, on=(User.id_user == Stats.id_user)) + .where(Stats.id_user == id_utente) + .order_by(Stats.times.desc())) + values = [] + labels = [] + k = 0 + other_value = 0 + for item in query_sql: + if k < 8: + labels.append(item.command) + values.append(item.times) + else: + other_value += item.times result += item.command + "__: Usato " + str(item.times) + " volte.__\n" - return sendMessage(client,message,result) + k = k + 1 + labels.append('Altro') + values.append(other_value) + #controllo opzione piechart + if "-pie" in query: + #preparo il piechart + plt.pie(values,labels=labels) + plt.savefig('graph.png') + with open('graph.png',"rb") as image_file: + sendPhoto(client,message,image_file,'__Ecco il grafico a torta prodotto__') + else: + sendMessage(client,message,result) ###################################### From fbf4c200fbb280e6a96e4b59ec705bcb60d15560 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 3 Jan 2023 22:42:13 +0100 Subject: [PATCH 64/66] Add route --- utils/controller.py | 1 + 1 file changed, 1 insertion(+) diff --git a/utils/controller.py b/utils/controller.py index 538f59b..360fceb 100644 --- a/utils/controller.py +++ b/utils/controller.py @@ -61,6 +61,7 @@ '/setgroup' : udb.set_group, '/listgroup' : udb.list_group, '/delgroup' : udb.del_group, + '/updategroup' : udb.update_group, '/updatestat' : udb.force_update_stats, '/delstat' : udb.force_delete_stats} From b423ac8fc22aa7011e9a69c6cbf368cf034ad853 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 3 Jan 2023 22:42:42 +0100 Subject: [PATCH 65/66] :wrench: add function #53 --- utils/dbfunctions.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/utils/dbfunctions.py b/utils/dbfunctions.py index 82fa1da..ac6add6 100644 --- a/utils/dbfunctions.py +++ b/utils/dbfunctions.py @@ -152,7 +152,7 @@ def personal_trivial_leaderboard(_,client,message): """ def global_trivial_leaderboard(client,message): query = (User - .select(User.name.alias('user'),fn.SUM(Trivial.points).alias('count')) + .select(User.name.alias('user'),User.username.alias('nick'),fn.SUM(Trivial.points).alias('count')) .join(Trivial, on=(User.id_user == Trivial.id_user)) .order_by(fn.SUM(Trivial.points).desc()) .group_by(User.id_user)) @@ -160,7 +160,10 @@ def global_trivial_leaderboard(client,message): result = "" k = 1 for item in query: - result += str(k) + ". " + item.user + ": __" + str(item.count) + " punti.__\n" + if len(item.nick) > 15 or item.nick == "@None": + result += str(k) + ". " + item.user + ": __" + str(item.count) + " punti.__\n" + else: + result += str(k) + ". " + item.nick.replace("@","") + ": __" + str(item.count) + " punti.__\n" k = k + 1 return sendMessage(client,message,result) @@ -256,6 +259,18 @@ def del_group(client,message,query): result = "Gruppo " + str(query) + " eliminato dai gruppi salvati." return sendMessage(client,message,result) +""" + Aggiorna il nome di un gruppo sul db +""" +@Client.on_message() +def update_group(client,message,query): + json_group = client.get_chat(query) + (Group + .update({Group.title: json_group.title}) + .where(Group.id_group == json_group.id)).execute() + result = "Gruppo " + str(json_group.id ) + " aggiornato con successo!" + return sendMessage(client,message,result) + """ controllo se il gruppo è autorizzato a eseguire un determinato comando """ From 9dfb3f757c128a800d3bc5e3b470b4e339049ad6 Mon Sep 17 00:00:00 2001 From: Roberto Date: Tue, 3 Jan 2023 22:44:58 +0100 Subject: [PATCH 66/66] Update help --- help.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/help.json b/help.json index 033dc9e..e883f59 100644 --- a/help.json +++ b/help.json @@ -44,6 +44,6 @@ }, "openai":"**/ai 'input' ** => genera un testo in base all'input dato grazie alle api di OpenAI", "urban": "**/urban 'word' ** => restituisce la definizione di urban dictionary per la parola richiesta", - "trivial": "__**Questo comando è disponibile solo in alcune chat decise dall'admin.\nI nomi delle categorie sono listati nel gruppo ufficiale del gioco.**__\n\n**/trivial** ==> quiz vero/falso oppure a scelta multipla in una categoria randomica.\n**/trivial categoria** ==> quiz della categoria scelta.\n__Esempio: /trivial history per un quiz in storia.__\n\n", + "trivial": "__**Questo comando è disponibile solo in alcune chat decise dall'admin.\nI nomi delle categorie sono listati nel gruppo ufficiale del gioco.**__\n\n**/trivial** ==> quiz vero/falso oppure a scelta multipla in una categoria randomica.\n**/trivial categoria** ==> quiz della categoria scelta.\n__Esempio: /trivial history per un quiz in storia.__\n/globaltscore per classifica globale.\n/globaltscore 'categoria' per filtrare.\n/mytscore per quella personale.\n\n", "default": "Cerca un comando in particolare come ad esempio:\n /helprob wiki\n__Comandi: wiki, lyrics, covid, vaccine, weather, urban, poll, reminder, tper, atm, treni, kart, trivial e mappe.\n\ncomandi admin: **playlotto, getmessage, weathermap, weathersat, openai e pingrob.**\nVuoi usarli? Diventa un utente premium! Contatta @MasterCruelty__" }