Exemplo n.º 1
0
    def load_from_database(self, cmddata: dict):
        C = WordMatchResponse
        super().load_from_database(cmddata)
        self.Mode = WordMatchMode(int(cmddata[WordMatchResponse.COL_TYPE]))
        id = cmddata[Command.COL_ID]

        query = Database.select_str([C.WORDS_COL_CMD_ID, C.WORDS_COL_TEXT],
                                    [C.WORDS_TABLE],
                                    [(C.WORDS_COL_CMD_ID, str(id))])
        query += '; '
        query += Database.select_str(
            [C.RESPONSES_COL_ID, C.RESPONSES_COL_TEXT], [C.RESPONSES_TABLE],
            [(C.RESPONSES_COL_CMD_ID, str(id))])

        data = Database.query(query)

        success, rows = Database.get_rows(data, 0)
        if not success:
            return False

        for row in rows:
            self.Matchwords.append(row[C.WORDS_COL_TEXT])

        success, rows = Database.get_rows(data, 1)
        if not success:
            return False

        for row in rows:
            self.Responses.append(row[C.RESPONSES_COL_TEXT])

        return True
Exemplo n.º 2
0
    def add_list_from_database():
        C = WordMatchResponse
        C.List = []

        cols = [Command.COL_ID]
        cols.extend(Command.COLS)
        cols.extend(C.COLS)
        cols.extend(User.COLS)
        cols.extend(Chat.COLS)

        tables = [C.TABLE, Command.TABLE, User.TABLE, Chat.TABLE]
        equals = [(C.COL_ID, Command.COL_ID),
                  (User.COL_ID, Command.COL_USER_ID),
                  (Chat.COL_ID, Command.COL_CHAT_ID),
                  (Command.COL_BOT_NAME, '\'' + Constants.APP_NAME + '\'')]

        r = Database.select(cols, tables, equals)

        success, rows = Database.get_rows(r, -1)

        if success:
            for row in rows:
                cls = WordMatchResponse.from_database(row)
                if cls is not None:
                    C.List.append(cls)

        return True
Exemplo n.º 3
0
def load_chats():
    cols = [Chat.COL_ID]
    cols.extend(Chat.COLS)
    data = Database.select(cols, [Chat.TABLE])
    [result, rows] = Database.get_rows(data, 0)
    if result:
        for row in rows:
            chats.append(Chat.from_database(row))
Exemplo n.º 4
0
    def save_to_database(self):
        if not super().save_to_database():
            return False

        C = WordMatchResponse

        cols = [C.COL_ID]
        cols.extend(C.COLS)

        s = Database.insert_str(C.TABLE, cols, [self.Id, int(self.Mode)])

        for word in self.Matchwords:
            s += '; ' + Database.insert_str(C.WORDS_TABLE, C.WORD_COLS,
                                            [word, self.Id])

        for resp in self.Responses:
            s += '; ' + Database.insert_str(C.RESPONSES_TABLE, C.RESP_COLS,
                                            [resp, self.Id])

        logger.info(s)
        return Database.query_bool(s)
Exemplo n.º 5
0
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']))
Exemplo n.º 6
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