Example #1
0
    def save_to_database(self):
        if not super().save_to_database():
            logger.error("Error saving 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:
            logger.info(word)
            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['response'], self.Id, resp['type']])

        logger.info(s)
        success = Database.query_bool(s)
        if not success:
            logger.error("Error saving to database.")
            return False

        return True
Example #2
0
    def _get_updates(self):
        req = self.url + 'getUpdates' + (
            ('?offset=' + str(self._offset)) if self._offset != 0 else '')

        response = requests.get(req).json()

        ok = bool(response.get('ok', True))

        updates = []

        if not ok:
            logger.error("Cannot get updates: %s",
                         response.get('description', 'No reason'))
            return updates

        updates_json = response.get('result')

        updates = self._parse_updates(
            updates_json)  # type: list[TelegramApi.Update]

        for upd in updates:
            if upd.Id >= self._offset:
                self._offset = upd.Id + 1
        logger.info("Current offset: {}\n".format(self._offset))
        return updates
Example #3
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."
    )
Example #4
0
    def increment_match_counter(self):
        self.MatchCounter += 1
        q = "UPDATE  " + Command.TABLE + " SET " + Command.COL_MATCH_COUNT + " = " + Command.COL_MATCH_COUNT \
            + " + 1 WHERE " + Command.COL_ID + " = " + str(self.Id)

        logger.info("Increment query: " + q)
        if not Database.query_bool(q):
            logger.error("Error incrementing match counter.")
Example #5
0
    def save_to_database(self):
        s = self.save_to_database_str(
        ) + "; SELECT LAST_INSERT_ID() AS 'lastid'"
        r = Database.query(s)
        success, rows = Database.get_rows(r, 0)

        if success and len(rows) == 1:
            self.Id = int(rows[0]['lastid'])
            return True
        else:
            logger.error(
                'Error on saving data to database: Cannot retrieve command id')
            return False
Example #6
0
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
Example #7
0
    def send_media(self, chat, type: str, file_id: str, reply_to_id=0):
        params = {'chat_id': chat, type: file_id}
        if reply_to_id != 0:
            params['reply_to_message_id'] = reply_to_id

        if type == "sticker":
            cmd = "sendSticker"
        elif type == "photo":
            cmd = "sendPhoto"
        elif type == "animation":
            cmd = "sendAnimation"
        else:
            logger.error("send_media: Unknown media type:", type)
            return

        response = requests.post(self.url + cmd, data=params)
        logger.info('Send_media response: %s', response.text)
        if response.status_code != requests.codes.ok:
            logger.info('Status code: %s', response.status_code)
        return response
Example #8
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}
Example #9
0
    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()
Example #10
0
 def query_bool(q: str):
     r = Database.query(q)
     if r.get(Constants.KEY_SQL_SUCCESS, False):
         return True
     else:
         logger.error(r)
Example #11
0
    def load_list_from_database():
        C = WordMatchResponse
        C.List = []

        # Load commands
        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 + '\'')]

        query = Database.select_str(cols, tables, equals)

        # Load match words
        cols = C.WORD_COLS

        tables = [C.WORDS_TABLE, Command.TABLE]
        equals = [(C.WORDS_COL_CMD_ID, Command.COL_ID),
                  (Command.COL_BOT_NAME, '\'' + Constants.APP_NAME + '\'')]

        query += ";" + Database.select_str(cols, tables, equals)

        # Load Responses
        cols = C.RESP_COLS

        tables = [C.RESPONSES_TABLE, Command.TABLE]
        equals = [(C.RESPONSES_COL_CMD_ID, Command.COL_ID),
                  (Command.COL_BOT_NAME, '\'' + Constants.APP_NAME + '\'')]

        query += ";" + Database.select_str(cols, tables, equals)

        query_result = Database.query(query)  #type: dict

        s1, rows_cmds = Database.get_rows(query_result, 0)
        s2, rows_words = Database.get_rows(query_result, 1)
        s3, rows_resps = Database.get_rows(query_result, 2)

        if not (s1 and s2 and s3):
            logger.error("Error loading data from database:")
            logger.error(str(query_result))
            return False
        cnt = 0
        for cmd in rows_cmds:
            cmdid = cmd[Command.COL_ID]
            words = [w for w in rows_words if w[C.WORDS_COL_CMD_ID] == cmdid]
            resps = [
                r for r in rows_resps if r[C.RESPONSES_COL_CMD_ID] == cmdid
            ]

            command = WordMatchResponse.from_database(cmd, words, resps)
            if command is not None:
                C.List.append(command)
                cnt += 1

        logger.info("Loaded {} commands from database.".format(cnt))
        return True
Example #12
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.")