예제 #1
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    config.logger.error(msg)
    try:
        last_name = msg.get('chat', {}).get('last_name', '')
        first_name = msg.get('chat', {}).get('first_name', '')
        username = msg.get('chat', {}).get('username', '')
        mongo.update_user_info(chat_id,
                               collection,
                               last_name=last_name,
                               first_name=first_name,
                               username=username)
    except Exception as exp:
        config.logger.exception("Error: Can't update user info {}".format(exp))
    oauth = mongo.check_user_id(chat_id, collection)
    if oauth:
        try:
            entities = msg.get('entities', None)[0]
            if entities:
                command_type = entities.get('type', None)
                if command_type == 'bot_command':
                    result = catch_bot_command(msg, chat_id)
        except TypeError as exp:
            config.logger.exception("Error: TypeError")
            text = u"К сожалению, я не настолько умный.\nЯ понимаю только "\
                   u"три команды, о которых вы можете узнать выполнив команду:\n"\
                   u"/help"
            send_message(text, 'text', bot, chat_id)
        except Exception as exp:
            config.logger.exception("Error: message analysis")
    else:
        try:
            entities = msg.get('entities', None)[0]
            if entities:
                command_type = entities.get('type', None)
                if command_type == 'bot_command':
                    result = catch_bot_command(msg, chat_id)
                    if result:
                        if result['command'] == 'start':
                            oauth = result.get('oauth', None)
        except Exception as exp:
            config.logger.exception("Error: message analysis")
        if not oauth:
            get_user_oauth(chat_id, client_id, bot)
        else:
            text = u"Все готово для работы с ботом.\n" \
                   u"Данные скоро начнут поступать.\n" \
                   u"Дополнительные настройки можно увидеть, выполнив команду:\n"\
                   u"/settings"
            send_message(text, 'text', bot, chat_id)
            try:
                send_message(
                    u'Йеху! Новый пользователь!\n'
                    '{}'.format(msg['chat']), 'text', bot, 12452435)
            except Exception:
                pass
예제 #2
0
def catch_bot_command(msg, chat_id):
    result = {}
    settings_command = [
        'feed_type_personal', 'feed_type_main', 'feed_type_mixed',
        'threshold_rating_easy', 'threshold_rating_medium',
        'threshold_rating_normal', 'threshold_rating_hard',
        'threshold_rating_hardcore', 'threshold_rating_nightmare'
    ]
    try:
        command_list = msg['text'].split()
        command = command_list[0].lower().lstrip('/')
        if command == 'start' and len(command_list) > 1:
            oauth_key = command_list[1]
            if oauth_key == 'start':
                get_user_oauth(chat_id, client_id, bot)
            else:
                mongo.update_user_oauth(chat_id, oauth_key, collection)
                oauth = mongo.check_user_id(chat_id, collection)
                result['command'] = command
                result['oauth'] = oauth
        elif command == 'start' and len(command_list) < 2:
            text = u'Команда /start должна вызываться вместе с токеном от сайта.'
            send_message(text, 'text', bot, chat_id)
        elif command == 'stop':
            result = mongo.delete_user(chat_id, collection)
            if result:
                images = [x for x in os.listdir('img/') if 'stop' in x]
                num = randint(1, len(images))
                text = u'Рады были вас видеть!'
                send_message(text, 'text', bot, chat_id)
                data = "img/stop{}.jpg".format(num)
                send_message(data, 'photo', bot, chat_id)
        elif command == 'help':
            text = u"""Поддерживаются следующие команды:
/help - эта помощь
/settings - настройки ленты и её содержимого
/stop - прекращение работы с ботом
Пообщаться с создателем бота можно в телеграме @azalio
            """
            send_message(text, 'text', bot, chat_id)
        elif command == 'settings':
            data = u"""
Настройка канала:
            /feed_type_personal - только подлепры
            /feed_type_main - главная без подлепр
            /feed_type_mixed - главная с подлепрами

Настройка отображения:
            /threshold_rating_easy - 1000+
            /threshold_rating_medium - 500
            /threshold_rating_normal - 250
            /threshold_rating_hard - 50
            /threshold_rating_hardcore - 0
            /threshold_rating_nightmare - all
            """
            # print(text)
            send_message(data, 'text', bot, chat_id)
            result['command'] = command_list[0]
        elif command in settings_command:
            mongo.update_user_settings(chat_id, command, collection)
    except Exception as exp:
        config.logger.exception("Error: in catch_bot_command function")
        return False
    else:
        return result
예제 #3
0
def on_chat_message(msg):
    """
    Main function. 
    :param msg: 
    :return: 
    """
    def response_status(status):
        if status == 403:
            logging.debug(u'Кажется папка пользователя удалена.\n')
            disk_bot.sendMessage(
                chat_id, u'К сожалению, не удалось записать файл.\n'
                u'Пожалуйста, проверьте, что существует папка {}'.format(
                    path_to_app))

        elif status == 502:
            disk_bot.sendMessage(
                chat_id, u'К сожалению, не удалось записать файл.\n'
                u'Яндекс.Диск вернул внутреннюю ошибку сервера.\n'
                u'Пожалуйста, попробуйте еще раз.\n')
        elif status['status_code'] == 200:
            disk_bot.sendMessage(
                chat_id, u'Загрузка файла на диск успешна.\n'
                u'Если вы хотите получить публичную ссылку на файл, то выполните,'
                u' пожалуйста, команду /link')
            mongo.update_last_file(chat_id, collection, status['path_to_file'])

        else:
            disk_bot.sendMessage(
                chat_id,
                u'Что-то пошло нет так, попробуйте, пожалуйста, еще раз.')

    logging.debug(type(msg))
    logging.debug(msg)
    content_type, chat_type, chat_id = telepot.glance(msg)
    logging.debug("content_type: {}\nchat_type: {}\nchat_id: {}\n".format(
        content_type, chat_type, chat_id))
    # Get yandex OAuth token
    oauth = mongo.check_user_id(chat_id, collection)
    # Update user info, if fail - nevermind
    try:
        last_name = msg.get('chat', {}).get('last_name', '')
        first_name = msg.get('chat', {}).get('first_name', '')
        username = msg.get('chat', {}).get('username', '')
        update_user_info = mongo.update_user_info(chat_id,
                                                  collection,
                                                  last_name=last_name,
                                                  first_name=first_name,
                                                  username=username)
    except Exception:
        pass
    if oauth == 1:  # user exist, but don't have OAuth token.
        user_is_here = 0
    else:
        user_is_here = 1
        try:
            # if OAuth key changed.
            command, oauth_key = msg['text'].split()
            if command == '/start' and len(oauth_key) > 0:
                mongo.update_user_oauth(chat_id, oauth_key, collection)
                oauth = mongo.check_user_id(chat_id, collection)
        except Exception:
            pass
        # Check that we have permission to ya.disk folder.
        path_to_app = ya_disk.get_info(oauth)
        if path_to_app == 401:
            get_user_oauth(chat_id)
            return True

    logging.debug('Chat Message: {} {} {}'.format(content_type, chat_type,
                                                  chat_id))
    for key in msg:
        logging.debug("{}: {}".format(key, msg[key]))
    logging.debug("*" * 80)

    if user_is_here:
        if 'text' in msg:
            if re.match('^/', msg['text']):
                is_bot_command_here = True  # we catch bot command.
            else:
                is_bot_command_here = False
        else:
            is_bot_command_here = False

        if is_bot_command_here:
            command = msg['text']
            if re.match('^/help', command):
                message = u'Я понимаю следующие команды:\n' \
                          u'/help - эта справка\n' \
                          u'/link - получение публичной ссылки на последний загруженный файл\n' \
                          u'/stop - удаление вашего OAuth токена из базы данных\n' \
                          u'Пожалуйста, оцените меня: https://telegram.me/storebot?start=yadisk_bot'
                disk_bot.sendMessage(chat_id, message)
            elif re.match('^/stop', command):
                if mongo.delete_user(chat_id, collection):
                    message = u'Ваш токен удален из базы данных\n' \
                              u'Хорошего дня!\n'
                    disk_bot.sendMessage(chat_id, message)
                    try:
                        disk_bot.sendMessage(
                            12452435, u'Пользователь удалился :(\n'
                            '{}'.format(msg['chat']))
                    except Exception:
                        pass
                else:
                    message = u'Что-то пошло не так.\n' \
                              u'Пожалуйста, попробуйте еще раз или напишите моему создателю @azalio\n'
                    disk_bot.sendMessage(chat_id, message)
            elif re.match('^/start', command):
                disk_bot.sendMessage(
                    chat_id, u'Все готово для работы с Яндекс Диском!\n'
                    u'Попробуйте мне послать какой-нибудь файл или'
                    u' просто что-нибудь написать.')
            # Sharing.
            elif re.match('^/link', command):
                try:
                    oauth, last_file = mongo.get_user_last_file(
                        chat_id, collection)
                except Exception:
                    disk_bot.sendMessage(
                        chat_id,
                        u'Ошибка соединения с базой данных, попробуйте, пожалуйста, еще раз.'
                    )

                public_url = ya_disk.get_public_link_to_file(oauth, last_file)
                if public_url:
                    disk_bot.sendMessage(
                        chat_id,
                        u'Публичная ссылка на файл: {}'.format(public_url))
                else:
                    disk_bot.sendMessage(
                        chat_id,
                        u'К сожалению, не удалось сформировать публичную ссылку.'
                    )
            else:
                message = u'К сожалению, я не понял данной команды.\n'
                disk_bot.sendMessage(chat_id, message)

        else:  # not bot command.
            if content_type in text_documents:
                filepath = '/tmp/' + str(chat_id) + '_' + str(
                    msg['date']) + '_' + str(msg['message_id']) + '.txt'
                logging.debug(filepath)

                with open(filepath, 'w') as f:
                    if 'forward_from_chat' in msg:
                        forward_info = "From {}: {}\n".format(
                            msg['forward_from_chat']['type'],
                            msg['forward_from_chat']['title'])
                        f.write(forward_info)
                    if content_type == 'text':
                        f.write(msg['text'])
                    else:
                        data = []
                        for key in msg[content_type]:
                            value = msg[content_type][key]

                            if type(value) != str:
                                print("value type is: {}".format(type(value)))
                                value = str(value)
                            data.append(key + u': ' + value + u'\n')
                        logging.debug(data)
                        data = ''.join(data)
                        logging.debug(data)
                        f.write(data.encode('utf-8'))
                    if content_type == 'location':
                        address = util.get_location_address(
                            msg['location']['latitude'],
                            msg['location']['longitude'])
                        f.write(address.encode('utf-8'))
                    f.close()
                status = ya_disk.upload_to_ya_disk(path_to_app, filepath,
                                                   content_type)
                response_status(status)

            elif content_type in file_documents:
                response = ''
                if content_type == 'photo':
                    try:
                        response = disk_bot.getFile(
                            msg[content_type].pop()['file_id'])
                    except telepot.exception.TelegramError as ex:
                        send_message_on_error(
                            chat_id, u'К сожалению, загрузка не удалась.\n'
                            u'Размер файла не должен превышать 20МB', ex)
                else:
                    try:
                        response = disk_bot.getFile(
                            msg[content_type]['file_id'])
                    except telepot.exception.TelegramError as ex:
                        send_message_on_error(
                            chat_id, u'К сожалению, загрузка не удалась.\n'
                            u'Размер файла не должен превышать 20МB', ex)
                logging.debug(response)
                if response != '':
                    url = 'https://api.telegram.org/file/bot' + token + '/' + response[
                        'file_path']
                    logging.debug(url)
                    filepath = url
                    if 'file_name' in msg[content_type]:
                        filename = msg[content_type]['file_name']
                    else:
                        filename = ''
                    status = ya_disk.upload_to_ya_disk(path_to_app,
                                                       filepath,
                                                       content_type,
                                                       filename=filename)
                    response_status(status)

    else:  # user don't exits.
        command = ''
        logging.debug(msg)
        if 'entities' in msg:
            if 'bot_command' in msg['entities'][0].values():
                try:
                    command, text = msg['text'].split()
                    if command == '/start' and text == 'start':
                        get_user_oauth(chat_id)
                    elif command == '/start' and len(text) > 0:
                        logging.debug(text)
                        mongo.update_user_oauth(chat_id, text, collection)
                        oauth = mongo.check_user_id(chat_id, collection)
                        path_to_app = ya_disk.get_info(oauth)
                        if path_to_app == 401:
                            disk_bot.sendMessage(
                                chat_id,
                                u'Возникли проблемы с авторизаций на Яндекс.Диске'
                            )
                            get_user_oauth(chat_id)
                        else:
                            disk_bot.sendMessage(
                                chat_id,
                                u'Все готово для работы с Яндекс Диском!\n'
                                u'Попробуйте мне послать какой-нибудь файл или'
                                u' просто что-нибудь написать.')
                            try:
                                disk_bot.sendMessage(
                                    12452435, u'Йеху! Новый пользователь!\n'
                                    '{}'.format(msg['chat']))
                            except Exception:
                                pass
                except ValueError:
                    pass

        if command == '':
            get_user_oauth(chat_id)