def aggiungi(mittente, comando, chat, dati, speech): messaggi = [] comando = comando.replace("/aggiungi", "", 1).strip() comando = comando.replace("/add", "", 1).strip() testo = comando.lower().strip() parametri = [] for line in testo: parametri.extend(line) global sacchetto sacchetto = [] stringa = "@" + str(mittente["username"]) + "\n\n" for digit in parametri: if digit != 'b' and digit != 'n' and digit != 'c': stringa += "Sono stati inseriti token non consentiti: " + str( parametri) + "\n\n" stringa += "Si ricorda che sono consentiti solo token: \"b\" o \"n\"" messaggi.append(Messaggio(stringa, chat["id"], speech)) return messaggi elif digit == 'c': digit = choice(['b', 'n']) sacchetto.append(digit) if len(sacchetto) <= 1: stringa += "Il sacchetto è vuoto o contiene un numero insufficente di token" else: stringa += ("Sacchetto creato!\n" + "Ci sono " + str(len(sacchetto)) + " token all'interno") messaggi.append(Messaggio(stringa, chat["id"], speech)) return messaggi
def character(mittente, comando, chat, dati, speech, logfile): messaggi = [] if comando.startswith("_lookat"): messaggi.append(Messaggio("Non implementato", chat["id"], speech)) elif comando.startswith("_new"): messaggi.append(Messaggio("Non implementato", chat["id"], speech)) elif comando.startswith("_edit"): messaggi.append(Messaggio("Non implementato", chat["id"], speech)) elif comando.startswith("_remove"): messaggi.append(Messaggio("Non implementato", chat["id"], speech)) else: messaggi.append( Messaggio( "Benvenuto nell' inventario, @" + str(mittente["username"]) + "\n" + "I comandi disponibili sono i seguenti:\n" + "/player_character_lookat - Esamina la tua scheda personaggio\n" + "/player_character_new - Crea una scheda personaggio\n" + "/player_character_edit - Aggiorna la tua scheda personaggio\n" + "/player_character_remove - Elimina la tua scheda personaggio", chat["id"], speech)) return messaggi
def tts(mittente, comando, chat, dati, logfile): messaggi = [] if comando.strip().startswith("/broadcast"): parametri = comando.split(" ", 2) for k, v in dati["canali"].items(): print(" - Found channel " + str(v) + " sending " + parametri[2].strip()) print(" - Found channel " + str(v) + " sending " + parametri[2].strip(), file=logfile) messaggi.append(Messaggio(parametri[2].strip(), k, True)) elif comando.strip().startswith("/sendto"): parametri = comando.split(" ", 2) for k, v in dati["canali"].items(): if parametri[1].strip().lower().startswith(v.lower()): print(" - Found channel " + str(v) + " sending " + parametri[2].strip()) print(" - Found channel " + str(v) + " sending " + parametri[2].strip(), file=logfile) messaggi.append(Messaggio(parametri[2].strip(), k, True)) break else: messaggi.append(Messaggio(comando.strip(), chat["id"], True)) return messaggi
def estrai(mittente, comando, chat, dati, speech): messaggi = [] estrazione = [] emojy = {'b': '\U000026AA ', 'n': '\U000026AB '} comando = comando.replace("/estrai", "", 1).strip() comando = comando.replace("/e", "", 1).strip() parametri = comando.lower().strip().split(" ") stringa = "@" + str(mittente["username"]) + "\n" try: num_token = [int(s) for s in parametri if s.isdigit()][0] if num_token > 4: stringa += "Il numero di token da estrarre non è valido.\n\n" + \ "Ricorda che puoi estrarre fino ad un massimo di 4 token alla volta dal sacchetto" messaggi.append(Messaggio(stringa, chat["id"], speech)) return messaggi elif num_token > len(sacchetto): stringa += "Il sacchetto contiene solo " + \ str(len(sacchetto)) + \ " token, non è possibile estrarne di più" messaggi.append(Messaggio(stringa, chat["id"], speech)) return messaggi for _ in range(num_token): token_estratto = choice(sacchetto) try: sacchetto.remove(token_estratto) except NameError: stringa += "Il sacchetto non è ancora stato riempito!\n\n" + \ "Usa il comando /aggiungi per inserire i token nel sacchetto" messaggi.append(Messaggio(stringa, chat["id"], speech)) return messaggi estrazione.append(token_estratto) stringa += "Sono stati estratti dal sacchetto " + str( num_token) + " token:\n\n " for token in estrazione: stringa += emojy[token] except IndexError: stringa += "Non è stato indicato nessun numero di token da estrarre" messaggi.append(Messaggio(stringa, chat["id"], speech)) return messaggi
def player(mittente, comando, chat, dati, speech, logfile): messaggi = [] if (chat["type"] != "private"): messaggi.append( Messaggio( "@" + str(mittente["username"]) + ", il menù del giocatore può essere acceduto solo nelle conversazioni private", chat["id"], speech)) messaggi.append( Messaggio( "@" + str(mittente["username"]) + ", i comandi possono essere inviati qui", mittente["id"], speech)) elif comando.startswith("_character"): print(" - navigated to /player_character") print(" - navigated to /player_character", file=logfile) messaggi = character.character(mittente, comando.replace("_character", "", 1), chat, dati, speech, logfile) elif comando.startswith("_inventory"): print(" - navigated to /player_inventory") print(" - navigated to /player_inventory", file=logfile) messaggi = inventory.inventory(mittente, comando.replace("_inventory", "", 1), chat, dati, speech, logfile) else: messaggi.append( Messaggio( "Benvenuto nel menù del giocatore, @" + str(mittente["username"]) + "\n" + "I comandi disponibili sono i seguenti:\n" + "/player_character - Accedi al personaggio\n" + "/player_inventory - Accedi all'inventario", chat["id"], speech)) return messaggi
def spells(mittente, comando, chat, dati, speech, logfile): messaggi = [] if (chat["type"] != "private"): messaggi.append( Messaggio( "@" + str(mittente["username"]) + ", il menù del giocatore può essere acceduto solo nelle conversazioni private", chat["id"], speech)) messaggi.append( Messaggio( "@" + str(mittente["username"]) + ", i comandi possono essere inviati qui", mittente["id"], speech)) else: token = comando.split() help_required = False if (len(token) == 0): help_required = True else: f_spells = path.join(getcwd(), "moduli", "moduli_spells", "spells.txt") f_classes = path.join(getcwd(), "moduli", "moduli_spells", "classes.txt") finder = SpellFinder(f_spells, f_classes) if (token[0].strip() == "find"): spell_name = " ".join(token[1:]) info = finder.getSpellDescription(spell_name) messaggi.append(Messaggio(info, chat["id"], speech)) elif (token[0].strip() == "list"): option = token[1].strip().lower() if (option == "all"): response = finder.getSpellsByClass( project=["name", "level"], sortby="level") s = "" for class_name in response: s += class_name + ":\n" for spell in response[class_name]: s += spell["name"] + " (" + spell["level"] + ")\n" messaggi.append(Messaggio(s, chat["id"], speech)) else: response = finder.getSpellsByClass( class_name=option.capitalize(), project=["name", "level"], sortby="level") s = "" for spell in response[option.capitalize()]: s += spell["name"] + " (" + spell["level"] + ")\n" messaggi.append(Messaggio(s, chat["id"], speech)) else: help_required = True if (help_required): s = "/spells find spell_name: Guarda la descrizione della spell" messaggi.append(Messaggio(s, chat["id"], speech)) return messaggi
def gestisci_comando(comando, messaggio, mittente, chat, start_time, dati, voce): messaggi = list() if comando == "/roll": parametri = messaggio.replace("/roll ", "").lower().strip().split(" ") somma_dadi = 0 somma_costanti = 0 expected_value = 0 stringa = "@" + str(mittente["username"]) + "\n" for token in parametri: if (token.find("d") < 0): somma_costanti += int(token) else: dice = token.split("d") dice_type = int(dice[1]) dice_number = 1 if (dice[0] != ""): dice_number = int(dice[0]) stringa += "Tirando " + str(dice_number) + " volte un D" + str( dice_type) + " ho ottenuto:\n" for _ in range(dice_number): dice_roll = randint(1, dice_type) stringa += "- " + str(dice_roll) + "\n" somma_dadi += dice_roll expected_value += (1 + dice_type) / 2 stringa += "Totale: " + str(somma_dadi) if (somma_costanti > 0): stringa += " + " + str(somma_costanti) + " -> " + str( somma_dadi + somma_costanti) stringa += "\n(Expected Value: " + str(expected_value + somma_costanti) + ")" messaggi.append(Messaggio(stringa, chat["id"], voce)) return messaggi
def gestisci_comando(comando, messaggio, mittente, chat, start_time, dati, voce): messaggi = list() if comando == "/stats": elapsedtime = time.time() - start_time canali_nomi = "" for i in dati["canali"].values(): canali_nomi = canali_nomi + "\n- " + i stringa = ("@" + str(mittente["username"]) + "\n" + "Il bot è in funzione da " + str(math.floor(elapsedtime % 60)) + " secondi, " + str(math.floor((elapsedtime / 60) % 60)) + " minuti, " + str(math.floor((elapsedtime / 60 / 60) % 24)) + " ore, " + str(math.floor( (elapsedtime / 60 / 60 / 24))) + " giorni\n" + "Inoltre sono presente nei seguenti canali:" + canali_nomi) messaggi.append(Messaggio(stringa, chat["id"], voce)) return messaggi
def roll(mittente, comando, chat, dati, speech): messaggi = [] parametri = comando.lower().strip().split(" ") somma_dadi = 0 somma_costanti = 0 expected_value = 0 stringa = "@" + str(mittente["username"]) + "\n" for token in parametri: if (token.find("d") < 0): somma_costanti += int(token) else: dice = token.split("d") dice_type = int(dice[1]) dice_number = 1 if (dice[0] != ""): dice_number = int(dice[0]) stringa += "Tirando " + str(dice_number) + " volte un D" + str( dice_type) + " ho ottenuto:\n" for _ in range(dice_number): dice_roll = randint(1, dice_type) stringa += "- " + str(dice_roll) + "\n" somma_dadi += dice_roll expected_value += (1 + dice_type) / 2 stringa += "Totale: " + str(somma_dadi) if (somma_costanti > 0): stringa += " + " + str(somma_costanti) + " -> " + str(somma_dadi + somma_costanti) stringa += "\n(Expected Value: " + str(expected_value + somma_costanti) + ")" messaggi.append(Messaggio(stringa, chat["id"], speech)) return messaggi
def handler_messaggio(msg): logfile = open(logfile_path, mode='a') try: # Estrazione elementi del messaggio chat = msg["chat"] mittente = msg["from"] comando = msg["text"] + " " comando = comando[:comando.find(" ")] messaggio = msg["text"] + " " risposta = None voce = False # Coda di messaggi messaggi = list() # Gestione username misti if (not ("username" in mittente)) or (mittente["username"] == None) or (mittente["username"] == ""): if ("first_name" in mittente): mittente["username"] = str( mittente["id"]) + " (" + mittente["first_name"] if ("last_name" in mittente): mittente["username"] = mittente[ "username"] + " " + mittente["last_name"] mittente["username"] = mittente["username"] + ")" # Logging dei canali/utenti if (((not (str(chat["id"]) in dati["canali"])) or (not (str(mittente["id"]) in dati["utenti"]))) and ((chat["type"] == "group") or (chat["type"] == "supergroup"))): dati["canali"][str(chat["id"])] = chat["title"] dati["utenti"][str(mittente["id"])] = mittente["username"] datafile = open(datafile_path, mode='w') json.dump(dati, datafile, sort_keys=True, indent=4) datafile.close() # Gestione risposte if "reply_to_message" in msg: risposta = msg["reply_to_message"] print(str(mittente["username"]) + " responded to me") print(str(time.time()) + " : " + str(mittente["username"]) + " responded to me", file=logfile) messaggi.append( Messaggio( "Il Male cortese risponde alla richiesta di @" + str(mittente["username"]) + "\n" + "Un assistente malvagio sarà presto mandato ad ascoltare la richiesta", chat["id"], False)) # Flag vocale if "-tts" in comando: voce = True # Comandi di sistema if comando == "/start": print(str(mittente["username"]) + " invoked /start") print(str(time.time()) + " : " + str(mittente["username"]) + " invoked /start", file=logfile) messaggi.append( Messaggio( "Il Male è sceso tra voi\n" + "Dal momento che i miei malefici assistenti sono in sciopero, le mie funzionalità sono limitate\n" + "Usa il comando /help per una lista delle funzionalità\n\n" + "Per qualsiasi problema, mandare un messaggio a @Marcvs101", chat["id"], False)) elif comando == "/help": print(str(mittente["username"]) + " invoked /help") print(str(time.time()) + " : " + str(mittente["username"]) + " invoked /help", file=logfile) messaggi.append( Messaggio( "Ecco quello che il Male è in grado di fare, @" + str(mittente["username"]) + "\n" + "/help - Mostra alcuni comandi a disposizione del bot\n" + "\n" + helpstr_moduli + "-tts aggiunto a qualsiasi comando genera una sintesi vocale", chat["id"], voce)) ## elif comando.startswith("/adminhelp"): ## print(str(mittente["username"])+" invoked /helpadmin") ## print(str(time.time())+" : "+str(mittente["username"])+" invoked /helpadmin",file=logfile) ## stringa = ("Ecco una lista di comandi di amministrazione, @"+str(mittente["username"])+"\n"+ ## "/sendto [CHAN] [MSG] - Manda un messaggio al canale\n"+ ## "/broadcast [MSG] - Manda un messaggio a tutti i canali\n"+ ## "/debug - Dump dello stato sul log") ## if speech: invia_voce(chat["id"],stringa) ## else: invia_testo(chat["id"],stringa) ## elif comando.startswith("/player"): ## print(str(mittente["username"])+" invoked /player in "+str(chat["type"])+" chat") ## print(str(time.time())+" : "+str(mittente["username"])+" invoked /player in "+str(chat["type"])+" chat",file=logfile) ## messaggi = player.player(mittente, comando.replace("/player","",1).strip(), chat, dati, speech, logfile) ## elif comando.startswith("/spells"): ## print(str(mittente["username"])+" invoked /spells in "+str(chat["type"])+" chat") ## print(str(time.time())+" : "+str(mittente["username"])+" invoked /spells in "+str(chat["type"])+" chat",file=logfile) ## messaggi = spells.spells(mittente, comando.replace("/spells","",1).strip(), chat, dati, speech, logfile) ## elif comando.startswith("/sendto"): ## print(str(mittente["username"])+" invoked /sendto") ## print(str(time.time())+" : "+str(mittente["username"])+" invoked /sendto",file=logfile) ## parametri = comando.split(" ",1) ## for k,v in canali.items(): ## if parametri[1].strip().lower().startswith(v.lower()): ## stringa = parametri[1][len(v):].strip() ## if speech: invia_voce(k,stringa) ## else: invia_testo(k,stringa) ## print(" - Found channel "+str(v)+" sending "+parametri[1][len(v):].strip()) ## print(" - Found channel "+str(v)+" sending "+parametri[1][len(v):].strip(),file=logfile) ## break ## elif comando.startswith("/broadcast"): ## print(str(mittente["username"])+" invoked /broadcast") ## print(str(time.time())+" : "+str(mittente["username"])+" invoked /broadcast",file=logfile) ## stringa = comando.split(" ",1)[1].strip() ## for k,v in canali.items(): ## if speech: invia_voce(k,stringa) ## else: invia_testo(k,stringa) ## print(" - Found channel "+str(v)+" sending "+stringa) ## print(" - Found channel "+str(v)+" sending "+stringa,file=logfile) ## elif comando.startswith("/tts"): ## print(str(mittente["username"])+" invoked /tts") ## print(str(time.time())+" : "+str(mittente["username"])+" invoked /tts",file=logfile) ## messaggi = tts.tts(mittente, comando.replace("/tts","",1).strip(), chat, dati, logfile) elif comando == "/debug": print( str(mittente["username"]) + " invoked /debug\n" + " - Start time: " + str(start_time) + "\n" + " - Elapsed time (seconds): " + str(time.time() - start_time) + "\n" + " - Current chats: " + str(len(dati["canali"])) + "\n" + " - Telegram token: " + Telegram_Token) print(str(time.time()) + " : " + str(mittente["username"]) + " invoked /debug\n" + " - Start time: " + str(start_time) + "\n" + " - Elapsed time (seconds): " + str(time.time() - start_time) + "\n" + " - Current chats: " + str(len(dati["canali"])) + "\n" + " - Telegram token: " + Telegram_Token, file=logfile) messaggi.append( Messaggio( "@" + str(mittente["username"]) + "\n" + "Informazioni di debug stampate sul terminale", chat["id"], False)) # Comandi dei moduli else: if (comando in comandi_moduli) and (comandi_moduli[comando] != None): try: modulo = comandi_moduli[comando] print("Module " + modulo + " is handling command " + comando) print(str(time.time()) + " : Module " + modulo + " is handling command " + comando, file=logfile) messaggi = moduli_caricati[modulo].gestisci_comando( comando, messaggio, mittente, chat, start_time, dati, voce) print("Module " + modulo + " has finished handling command " + comando) print(str(time.time()) + " : Module " + modulo + " has finished handling command " + comando, file=logfile) except Exception as em: print("Catastrophic failure in module " + modulo + " while trying to handle command " + comando + "\n" + str(em) + "\n") print(str(time.time()) + " : Catastrophic failure in module " + modulo + " while trying to handle command " + comando + "\n########\n" + str(em) + "\n########", file=logfile) # Invio della coda di messaggi for i in messaggi: if i.voce: invia_voce(i.canale, i.testo) else: invia_testo(i.canale, i.testo) except Exception as e: print("Catastrophic failure\n" + str(e) + "\n") print(str(time.time()) + " : Catastrophic failure\n########\n" + str(e) + "\n########", file=logfile) logfile.close() return
def gestisci_comando(comando,messaggio,mittente,chat,start_time,dati,voce): messaggi = list() if comando == "/aggiungi": testo = comando.lower().strip() parametri = [] for line in testo: parametri.extend(line) global sacchetto sacchetto = [] stringa = "@" + str(mittente["username"]) + "\n\n" for digit in parametri: if digit != 'b' and digit != 'n': stringa += "Sono stati inseriti token non consentiti: " + str(parametri) + "\n\n" stringa += "Si ricorda che sono consentiti solo token: \"b\" o \"n\"" messaggi.append(Messaggio(stringa, chat["id"])) return messaggi sacchetto.append(digit) if len(sacchetto) <= 1: stringa += "Il sacchetto è vuoto o contiene un numero insufficente di token" else: stringa += ("Sacchetto creato!\n" + "Ci sono " + str(len(sacchetto)) + " token all'interno") messaggi.append(Messaggio(stringa, chat["id"])) elif comando == "/estrai" or comando == "/e": return messaggi # Funzione di inserimento dei token def aggiungi(comando, messaggio, mittente, chat, dati, speech): messaggi = [] testo = comando.lower().strip() parametri = [] for line in testo: parametri.extend(line) global sacchetto sacchetto = [] stringa = "@" + str(mittente["username"]) + "\n\n" for digit in parametri: if digit != 'b' and digit != 'n': stringa += "Sono stati inseriti token non consentiti: " + str(parametri) + "\n\n" stringa += "Si ricorda che sono consentiti solo token: \"b\" o \"n\"" messaggi.append(Messaggio(stringa, chat["id"], speech)) return messaggi sacchetto.append(digit) if len(sacchetto) <= 1: stringa += "Il sacchetto è vuoto o contiene un numero insufficente di token" else: stringa += ("Sacchetto creato!\n" + "Ci sono " + str(len(sacchetto)) + " token all'interno") messaggi.append(Messaggio(stringa, chat["id"], speech)) return messaggi # Funzione di estrazione dei token def estrai(mittente, comando, chat, dati, speech): messaggi = [] estrazione = [] emojy = {'b': '\U000026AA ', 'n': '\U000026AB '} parametri = comando.lower().strip().split(" ") stringa = "@" + str(mittente["username"]) + "\n" try: num_token = [int(s) for s in parametri if s.isdigit()][0] if num_token > 4: stringa += "Il numero di token da estrarre non è valido.\n\n" + \ "Ricorda che puoi estrarre fino ad un massimo di 4 token alla volta dal sacchetto" messaggi.append(Messaggio(stringa, chat["id"], speech)) return messaggi elif num_token > len(sacchetto): stringa += "Il sacchetto contiene solo " + \ str(len(sacchetto)) + \ " token, non è possibile estrarne di più" messaggi.append(Messaggio(stringa, chat["id"], speech)) return messaggi for _ in range(num_token): token_estratto = choice(sacchetto) try: sacchetto.remove(token_estratto) except NameError: stringa += "Il sacchetto non è ancora stato riempito!\n\n" + \ "Usa il comando /aggiungi per inserire i token nel sacchetto" messaggi.append(Messaggio(stringa, chat["id"], speech)) return messaggi estrazione.append(token_estratto) stringa += "Sono stati estratti dal sacchetto " + str(num_token) + " token:\n\n " for token in estrazione: stringa += emojy[token] except IndexError: stringa += "Non è stato indicato nessun numero di token da estrarre" messaggi.append(Messaggio(stringa, chat["id"], speech)) return messaggi # Funzione per popolare il comando help def help(): helpstr = "/stats - Mostra le statistiche correnti del bot" return helpstr