def exec_match_media(cmd: str, mode, cmddata: dict, msg: TelegramApi.Message, telegram: TelegramApi): logger.debug("exec_match_media") if cmddata is None or mode is None: logger.error("CmdData is none: {}, mode is none: {}".format( cmddata is None, mode is None)) telegram.send_message( msg.Chat.Id, "Utilizzo:\n{}\nparole 1\nparole 2\nparole N\n\n[risposte 1]\n[risposte 2]\n[risposte N]" .format("/match[msg|any] [-(s|m)]") + "\n\n-->In nuovi messaggi: eventuali media (sticker, foto, gif).") return sender_id = get_user_chat_id(msg) active_commands[sender_id] = { 'cmd': cmd, 'func': func_save_media, 'mode': mode, 'matchwords': cmddata['matchwords'], 'text_responses': cmddata.get('responses', []), 'params': cmddata['params'], 'media_responses': [] } telegram.send_message( msg.Chat.Id, "Ora manda i media. Scrivi /end quando hai finito, /cancel per annullare." )
def reply(self, msg: TelegramApi.Message, telegram: TelegramApi): answ = random.choice(self.Responses) # type: try: answ = answ.format(Msg=msg) except (KeyError, AttributeError): pass telegram.send_message(msg.Chat.Id, answ)
def exec_match_oneshot(cmd: str, mode, cmddata: dict, msg: TelegramApi.Message, telegram: TelegramApi): if len(cmddata['responses']) == 0: send_match_help(msg, telegram) return responses = [{'response': x, 'type': 'text'} for x in cmddata['responses']] WordMatchResponse.add_to_list_from_message(cmddata['matchwords'], responses, mode, 'a' in cmddata['params'], msg) telegram.send_message(msg.Chat.Id, "Comando aggiunto!")
def exec_cmdcount(cmd: str, cmddata: dict, msg: TelegramApi.Message, telegram: TelegramApi): if cmddata is None: telegram.send_message(msg.Chat.Id, "Utilizzo:\n/count [cmdid]") return if cmddata['hasid']: cmdid = cmddata['id'] msgstr = "Il comando n. {}" else: cmdid = last_match_cmdid.get(msg.Chat.Id) msgstr = "L'ultimo comando (n. {})" if cmdid is None: telegram.send_message(msg.Chat.Id, "Nessun comando utlizzato recentemente.") return for wmr in WordMatchResponse.List: # type: WordMatchResponse if wmr.Id == cmdid: telegram.send_message( msg.Chat.Id, "{} è stato utilizzato {} volt{}".format( msgstr.format(cmdid), wmr.MatchCounter, 'a' if wmr.MatchCounter == 1 else 'e')) return telegram.send_message( msg.Chat.Id, "Nessun messaggio con l'id specificato: {}.".format(cmddata['id']))
def exec_cmdinfo(cmd: str, cmddata: dict, msg: TelegramApi.Message, telegram: TelegramApi): if cmddata is None: telegram.send_message(msg.Chat.Id, "Utilizzo:\n/cmdinfo [cmdid]") return if cmddata['hasid']: cmdid = cmddata['id'] else: cmdid = last_match_cmdid.get(msg.Chat.Id) if cmdid is None: telegram.send_message(msg.Chat.Id, "Nessun comando utlizzato recentemente.") return for wmr in WordMatchResponse.List: # type: WordMatchResponse if wmr.Id == cmdid: msgtext = 'id: ' + str(wmr.Id) + ' -> ' + WordMatchMode.to_string(wmr.Mode) + "\n" \ + "Match: " + list_strings(wmr.Matchwords) + '\nRisposte: ' \ + list_strings([x['response'] if x['type'] == 'text' else "Media: " + x['response'] for x in wmr.Responses]) + '\n' msgtext += 'creator: ' + wmr.User.FirstName + ' ' + wmr.User.LastName + ' ' + wmr.User.Username + '\n' msgtext += 'count: ' + str(wmr.MatchCounter) telegram.send_message(msg.Chat.Id, msgtext) return telegram.send_message( msg.Chat.Id, "Nessun messaggio con l'id specificato: {}.".format(cmddata['id']))
def evaluate(telegram: TelegramApi, update: TelegramApi.Update): if not update.has_message(): logger.warning('Eval: Update with no message') return msg = update.Message chat_found = False for chat in chats: if chat.Id == msg.Chat.Id: chat_found = True break if not chat_found: c = Chat.from_message(msg) chats.append(c) c.save_to_database() logger.info("Received message: " + msg.Text) text = msg.Text.replace('\n', ' ').replace('\r', '') # type: str cmd = parse_command(text) if cmd.Found: if cmd.Op.Result: logger.info('Received command:' + text) if exec_command(cmd, msg, telegram): return else: logger.info('Command contains errors:' + text + " -- " + cmd.Op.Text + "(" + str(cmd.Op.Index) + ")") telegram.send_message(msg.Chat.Id, "Errore: " + cmd.Op.Text + ". Posizione: " + str(cmd.Op.Index)) return if msg.Chat.Id == my_chat_id and echo_to_id != 0: telegram.send_message(echo_to_id, msg.Text) else: logger.debug("Iterating answers (%d):", len(WordMatchResponse.List)) for response in WordMatchResponse.List: if response.matches(msg.Text): logger.debug('Matched: %s', response.Matchwords[0]) response.reply(msg, telegram)
def reply(self, msg: TelegramApi.Message, telegram: TelegramApi): answ = random.choice(self.Responses) # type: text = answ['response'] if self.Reply: reply_id = msg.Id else: reply_id = 0 if answ['type'] == 'text': try: text = text.format(Msg=msg, count=self.MatchCounter) except (KeyError, AttributeError): pass r = telegram.send_message(msg.Chat.Id, text, reply_id) else: r = telegram.send_media(msg.Chat.Id, answ["type"], text, reply_id) if r.status_code != requests.codes.ok: logger.error("Error posting message: {} - {}".format( r.status_code, r.reason)) else: r.json()
def exec_list(cmd: str, cmddata: dict, msg: TelegramApi.Message, telegram: TelegramApi): if cmddata is None: telegram.send_message( msg.Chat.Id, "Utilizzo:\n/listmatching <messaggio da matchare>") return s = cmddata['str'] matching = [] # type: list for r in WordMatchResponse.List: if r.matches(s): matching.append(r) msgtext = 'Comandi corrispondenti: \n' for m in matching: msgtext += 'id: ' + str(m.Id) + ' -> ' + WordMatchMode.to_string(m.Mode) + "\n" \ + "Match: " + list_strings(m.Matchwords) + '\nRisposte: ' \ + list_strings([x['response'] if x['type'] == 'text' else "Media: " + x['response'] for x in m.Responses]) + '\n' msgtext += "\nUsa /cmdinfo <cmdid> per ottenere ulteriori informazioni." telegram.send_message(msg.Chat.Id, msgtext)
def exec_remove(cmd: str, cmddata: dict, msg: TelegramApi.Message, telegram: TelegramApi): if cmddata is None: telegram.send_message(msg.Chat.Id, "Utilizzo:\n/remove <id>") return id = cmddata['id'] # type:int table = Command.TABLE col = Command.COL_ID success = Database.delete(table, [(col, id)]) if success: telegram.send_message(msg.Chat.Id, "Comando rimosso con successo.") WordMatchResponse.load_list_from_database() else: telegram.send_message( msg.Chat.Id, "Nessun messaggio con l'id specificato: {}.".format(cmddata['id']))
def exec_command(cmd: ParseResult, msg: TelegramApi.Message, telegram: TelegramApi): cmdstr = cmd.Command # type: str if cmdstr.startswith('!'): # Special commands if cmdstr == '!reload': reload_commands() telegram.send_message(msg.Chat.Id, 'Comandi ricaricati.') else: telegram.send_message(msg.Chat.Id, cmd.Data) elif cmdstr == 'echo': if msg.Chat.Id != 227067835: return False global echo_to_id echo_to_id = cmd.Data if echo_to_id == 0: telegram.send_message(msg.Chat.Id, 'Echo disattivato.') else: found = False for chat in chats: if chat.Id == echo_to_id: found = True break if not found: echo_to_id = 0 telegram.send_message(msg.Chat.Id, 'Chat non trovata.') else: telegram.send_message(msg.Chat.Id, 'Echo a ' + str(echo_to_id)) elif cmdstr == "listchats": if msg.Chat.Id != my_chat_id: return False msgtext = '' for chat in chats: if chat.Type == 'private': msgtext += "[%s] %s\n" % (chat.Id, chat.FirstName) elif chat.Type == 'group' or chat.Type == 'supergroup': msgtext += "[%s] %s\n" % (chat.Id, chat.Title) if len(msgtext) > 4096: msgtext = msgtext[:4096] break telegram.send_message(msg.Chat.Id, msgtext) elif cmdstr.startswith('match'): data = cmd.Data # type:MatchData logger.debug("[%s] Adding matches: %s", cmd.Command, str(data.Words)) if cmdstr == 'matchwords': mode = WordMatchMode.WHOLE elif cmdstr == 'matchany': mode = WordMatchMode.ANY else: mode = WordMatchMode.MSG WordMatchResponse.add_list_from_message(data.Words, data.Responses, mode, msg) telegram.send_message(msg.Chat.Id, "Comando aggiunto! ") elif cmdstr == 'listmatching': s = cmd.Data matching = [] # type: list[WordMatchResponse] for r in WordMatchResponse.List: if r.matches(s): matching.append(r) msgtext = 'Comandi corrispondenti: \n' for m in matching: msgtext += '--id: ' + str(m.Id) + ' -> ' + WordMatchMode.to_string(m.Mode) + ' ' + \ list_strings(m.Matchwords) + ' : ' + list_strings(m.Responses) + '\n' telegram.send_message(msg.Chat.Id, msgtext) elif cmdstr.startswith('add'): data = cmd.Data # type:AddData if cmdstr == 'addwords': word = 'parole' table = WordMatchResponse.WORDS_TABLE cols = WordMatchResponse.WORD_COLS else: word = 'risposte' table = WordMatchResponse.RESPONSES_TABLE cols = WordMatchResponse.RESP_COLS id = data.Id succ = 0 error = False for s in data.Strings: r = Database.insert(table, cols, [s, id]) if r: succ += 1 else: error = True break if not error: telegram.send_message(msg.Chat.Id, word + " aggiunte con successo.") else: msgtext = "Errore: %d su %d %s aggiunte con successo" % (succ, len(data.Strings), word) telegram.send_message(msg.Chat.Id, msgtext) if succ > 0: reload_commands() elif cmdstr.startswith('remove'): id = cmd.Data # type:str table = Command.TABLE col = Command.COL_ID success = Database.delete(table, [(col, id)]) if success: telegram.send_message(msg.Chat.Id, "Comando rimosso con successo.") reload_commands() else: telegram.send_message(msg.Chat.Id, "Errore rimozione comando.") return True
import os from flask import Flask, request from dadabot.shared_data import Constants from dadabot.logs import logger from dadabot.telegramapi import TelegramApi from dadabot.data import Database, Chat, WordMatchResponse from dadabot.commands import handle_command_str, notify_new_match app = Flask(__name__) telegram = TelegramApi(Constants.API_KEY, Constants.APP_NAME) chats: list = [] @app.route('/' + Constants.API_KEY, methods=['POST']) def webhook(): logger.info('Received webhook') if request.method == 'POST' and request.is_json: j = request.get_json(silent=True) if j is None: logger.error('request.get_json() returned None') return '', 400 telegram.process_update_json(j, evaluate_update) return '', 200 else: logger.warning('Received non-json request: ' + request.data) return '', 400
def func_save_media(msg: TelegramApi.Message, telegram: TelegramApi): logger.debug("func_save_media") sender_id = get_user_chat_id(msg) if msg.is_media(): if msg.is_sticker(): active_commands[sender_id]['media_responses'].append({ "fileid": msg.Sticker.FileId, "type": "sticker" }) elif msg.is_photo(): active_commands[sender_id]['media_responses'].append({ "fileid": msg.Photo.FileId, "type": "photo" }) elif msg.is_animation(): active_commands[sender_id]['media_responses'].append({ "fileid": msg.Animation.FileId, "type": "animation" }) else: logger.error("Media type not recognized") return elif matches_command(msg.Text, '/end'): responses = [{ 'response': x, 'type': 'text' } for x in active_commands[sender_id]['text_responses']] responses += [{ 'response': x["fileid"], 'type': x["type"] } for x in active_commands[sender_id]['media_responses']] if len(responses) == 0: telegram.send_message( msg.Chat.Id, "Utilizzo:\n{}\nparole 1\nparole 2\nparole N\n\n[risposte 1]\n[risposte 2]\n[risposte N]" .format("/match[msg|any] [-(m|s)]") + "\n\n-->In nuovi messaggi: eventuali sticker.") else: reply = 'a' in active_commands[sender_id]['params'] WordMatchResponse.add_to_list_from_message( active_commands[sender_id]['matchwords'], responses, active_commands[sender_id]['mode'], reply, msg) telegram.send_message(msg.Chat.Id, "Comando aggiunto!") del active_commands[sender_id] elif matches_command(msg.Text, '/cancel'): del active_commands[sender_id] telegram.send_message(msg.Chat.Id, "Comando annullato.") else: fail_count = active_commands[sender_id].get('fail_count', 0) active_commands[sender_id]['fail_count'] = fail_count + 1 if fail_count < 2: telegram.send_message( msg.Chat.Id, "{}, Scrivi /end per terminare l'aggiunta di media, /cancel per annullarla." .format(msg.Sender.FirstName)) elif fail_count == 2: telegram.send_message( msg.Chat.Id, "{}, SCRIVI /end OPPURE /cancel PER TERMINARE L'AGGIUNTA DI MEDIA!" .format(msg.Sender.FirstName)) else: del active_commands[sender_id] telegram.send_message(msg.Chat.Id, "Comando annullato.")
def send_match_help(msg: TelegramApi.Message, telegram: TelegramApi): telegram.send_message( msg.Chat.Id, "Utilizzo:\n{} -[a|s]\nparole 1\nparole 2\nparole N\n\nrisposte 1\nrisposte 2\nrisposte N" .format("/match[any|msg]"))