예제 #1
0
def evaluate_update(update: TelegramApi.Update):
    if not update.has_message():
        logger.warning('Eval: Update with no message')
        return

    msg = update.Message

    # Check if the message is from a new chat
    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()

    handled = handle_command_str(msg, telegram)

    if not handled:
        logger.debug("Not a command: " + msg.Text)
        # send eventual messages
        for response in WordMatchResponse.List:  # type: WordMatchResponse
            if response.matches(msg.Text):
                notify_new_match(response.Id, msg.Chat.Id)
                response.reply(msg, telegram)
                response.increment_match_counter()
예제 #2
0
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."
    )
예제 #3
0
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)
예제 #4
0
def handle_command_str(msg: TelegramApi.Message, telegram: TelegramApi):
    sender_id = get_user_chat_id(msg)
    if sender_id in active_commands:
        active_commands[sender_id]['func'](msg, telegram)
        return True
    elif is_command(msg):
        txt = msg.Text.lstrip()
        logger.info("Handling command: " + txt)

        for cmd in commands:
            m = cmd['cmdregex'].match(txt)
            if m is not None:
                txt = txt[m.end('cmd'):]
                logger.debug("Command identified: " + cmd['cmdname'])
                cmd['exec_func'](cmd['cmdname'],
                                 cmd['parse_func'](txt.splitlines()), msg,
                                 telegram)
                return True

    return False
예제 #5
0
 def query(q: str):
     params = {
         Constants.KEY_SQL_PSK: Constants.API_KEY,
         Constants.KEY_SQL_QUERY: q
     }
     logger.info("Querying data from database...")
     logger.debug("Query: " + q)
     r = requests.post(dburl, json=params)
     try:
         js = r.json()
         if Constants.KEY_SQL_SUCCESS not in js:
             logger.error('SQL query didn\'t return correct json')
             return {Constants.KEY_SQL_SUCCESS: False}
         else:
             logger.info("Done.")
             logger.debug(str(js))
             return js
     except ValueError:
         logger.error("Error reading response from server. Response: " +
                      r.text)
         return {Constants.KEY_SQL_SUCCESS: False}
예제 #6
0
def exec_match(cmd: str, cmddata: dict, msg: TelegramApi.Message,
               telegram: TelegramApi):
    logger.debug("exec_match")

    if cmd == '/match':
        mode = WordMatchMode.WORD
    elif cmd == '/matchany':
        mode = WordMatchMode.ANY
    elif cmd == '/matchmsg':
        mode = WordMatchMode.WHOLEMSG
    else:
        mode = None

    if cmddata is None or mode is None:
        send_match_help(msg, telegram)
        return

    p = cmddata['params']
    if 'm' in p:
        exec_match_media(cmd, mode, cmddata, msg, telegram)
    else:
        exec_match_oneshot(cmd, mode, cmddata, msg, telegram)
예제 #7
0
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
예제 #8
0
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.")