Ejemplo n.º 1
0
def my_d6(message):
    """
    рандомно выбирает элементы из списка значков
    TODO: желательно найти способ их увеличить или заменить на ASCII арт
    :param message:
    :return:
    """
    d6 = ["⚀", "⚁", "⚂", "⚃", "⚄", "⚅"]
    dice = 2
    roll_sum = 0
    symbols = ''
    for _ in str(message.text).lower().split():
        if not len(message.text.split()) == 1:
            try:
                dice = int(message.text.split()[1])
            except ValueError:
                my_bot.reply_to(message,
                                "Не понял число костей. "
                                "Пожалуйста, введи команду "
                                "в виде \'/d6 <int>\', "
                                "где <int> — целое от 1 до 10.")
                return
    if 0 < dice <= 10:
        max_result = dice * 6
        for count in range(dice):
            roll_index = random.randint(0, len(d6) - 1)
            roll_sum += roll_index + 1
            if count < dice - 1:
                symbols += '{0} + '.format(d6[roll_index])
            elif count == dice - 1:
                symbols += '{0} = {1}  ({2})'.format(d6[roll_index], roll_sum,
                                                     max_result)
        my_bot.reply_to(message, symbols)
        user_action_log(message, "got that D6 output: {0}".format(symbols))
Ejemplo n.º 2
0
def check_disa(message):
    # добавления счетчика в функцию
    if not hasattr(check_disa, "disa_counter"):
        check_disa.disa_counter = 0

    # проверяем Диса ли это
    if message.from_user.id != config.disa_id:
        return

    # проверяем что идет серия из коротких предложений
    if len(message.text) > config.length_of_stupid_message:
        check_disa.disa_counter = 0
        return

    check_disa.disa_counter += 1

    # проверяем, будем ли отвечать Дисе
    disa_trigger = random.randint(1, 6)
    if check_disa.disa_counter >= config.too_many_messages and disa_trigger == 2:
        my_bot.reply_to(message, random.choice(config.stop_disa))
        check_disa.disa_counter = 0

    # записываем в файл увеличенный счетчик хромосом
    try:
        with open(config.file_location_disa, 'r+', encoding='utf-8') as file:
            disa_chromo = str(int(file.read()) + 1)
            file.seek(0)
            file.write(disa_chromo)
            file.truncate()
    except Exception as ex:
        logging.error(ex)
        pass
Ejemplo n.º 3
0
def vk_post(message):
    if len(message.text.split()) > 1:
        post_id = message.text.split('wall')[-1]
        user_action_log(message, "has requested vk post: {}".format(post_id))
        response = requests.get('https://api.vk.com/method/wall.getById',
                                params={
                                    'access_token': tokens.vk,
                                    'posts': post_id,
                                    'extended': '1',
                                    'v': '5.68'
                                })
        response_list = response.json()['response']['items']
        if len(response_list) == 0:
            my_bot.reply_to(
                message,
                "Неудача! Использование: `/vk_post vk.com/wall-51776562_939`",
                parse_mode="Markdown")
            return
        post = vk_utils.VkPost(response_list[0])
        post.prepare_post()
        post.send_post(message.chat.id)
    else:
        my_bot.reply_to(message,
                        "Использование: `/vk_post vk.com/wall-51776562_939`",
                        parse_mode="Markdown")
Ejemplo n.º 4
0
def welcoming_task(message):
    chat_id = message.chat.id

    new_members_names = []
    new_members_info = []
    users = []

    for member in message.new_chat_members:
        new_members_names.append(member.first_name)
        new_members_info.append(user_info(member))
        if not member.is_bot:
            user = {
                'user_id': member.id,
                'chat_id': chat_id,
                'first_name': member.first_name,
                'last_name': member.last_name,
                'is_member': True
            }
            users.append(user)

    if users:  # Bot check
        with db.atomic():
            User.insert_many(users).on_conflict_replace().execute()

    if str(message.chat.id) == config.mm_chat:
        welcoming_msg = "{}, {}!\nЕсли здесь впервые, то ознакомься с правилами — /rules, " \
                        "и представься, если несложно.".format(random.choice(config.welcome_list),
                                                               ', '.join(new_members_names))
    else:
        welcoming_msg = "{}, {}!\n".format(random.choice(config.welcome_list),
                                           ', '.join(new_members_names))
    my_bot.reply_to(message, welcoming_msg)
    action_log("User(s) {} joined the chat.".format(
        ', '.join(new_members_info)))
Ejemplo n.º 5
0
def my_dn(message):
    roll_sum = 0
    symbols = ''
    if len(message.text.split()) == 3:
        try:
            dice_max = int(message.text.split()[1])
            dice_n = int(message.text.split()[2])
        except ValueError:
            return
        max_result = dice_n * dice_max
        for count in range(dice_n):
            try:
                roll = random.randint(0, dice_max)
                roll_sum += roll
                if count < dice_n - 1:
                    symbols += '{0} + '.format(roll)
                elif count == dice_n - 1:
                    symbols += '{0} = {1}  ({2})'.format(roll, roll_sum, max_result)
            except ValueError:
                pass
        if not len(symbols) > 4096:
            my_bot.reply_to(message, symbols)
            user_action_log(message,
                            "knew about /dn and got that output: {0}".format(symbols))
        else:
            my_bot.reply_to(message,
                            "Слишком большие числа. "
                            "Попробуй что-нибудь поменьше")
            user_action_log(message, "knew about /dn "
                                     "and the answer was too long "
                                     "to fit one message")
Ejemplo n.º 6
0
def admin_post(message):
    if len(message.text.split()) > 1:

        global_lock.acquire()
        if message.text.split()[1] == "edit":
            try:
                with open(config.file_location_lastbotpost,
                          'r',
                          encoding='utf-8') as file:
                    last_msg_id = int(file.read())
                my_edited_message = ' '.join(message.text.split()[2:])
                my_bot.edit_message_text(my_edited_message,
                                         config.my_chatID,
                                         last_msg_id,
                                         parse_mode="Markdown")
                user_action_log(
                    message, "has edited message {}:\n{}".format(
                        last_msg_id, my_edited_message))
            except (IOError, OSError):
                my_bot.reply_to(message, "Мне нечего редактировать.")
        else:
            my_message = ' '.join(message.text.split()[1:])
            sent_message = my_bot.send_message(config.my_chatID,
                                               my_message,
                                               parse_mode="Markdown")
            with open(config.file_location_lastbotpost, 'w',
                      encoding='utf-8') as file_lastmsgID_write:
                file_lastmsgID_write.write(str(sent_message.message_id))
            user_action_log(message,
                            "has posted this message:\n{}".format(my_message))
        global_lock.release()
    else:
        my_bot.reply_to(message, "Мне нечего постить.")
Ejemplo n.º 7
0
def welcoming_task(message):
    chat_id = message.chat.id

    new_members_names = []
    new_members_info = []
    users = []

    for member in message.new_chat_members:
        new_members_names.append(member.first_name)
        new_members_info.append(user_info(member))
        if not member.is_bot:
            user = {
                'user_id'   : member.id,
                'chat_id'   : chat_id,
                'first_name': member.first_name,
                'last_name' : member.last_name,
                'is_member' : True
            }
            users.append(user)

    if users:  # Bot check
        with db.atomic():
            User.insert_many(users).on_conflict_replace().execute()

    if str(message.chat.id) == config.mm_chat:
        welcoming_msg = "{}, {}!\nЕсли здесь впервые, то ознакомься с правилами — /rules, " \
                        "и представься, если несложно.".format(random.choice(config.welcome_list),
                                                               ', '.join(new_members_names))
    else:
        welcoming_msg = "{}, {}!\n".format(random.choice(config.welcome_list), ', '.join(new_members_names))
    my_bot.reply_to(message, welcoming_msg)
    action_log("User(s) {} joined the chat.".format(', '.join(new_members_info)))
Ejemplo n.º 8
0
def my_d6(message):
    """
    рандомно выбирает элементы из списка значков
    TODO: желательно найти способ их увеличить или заменить на ASCII арт
    :param message:
    :return:
    """
    d6 = ["⚀", "⚁", "⚂", "⚃", "⚄", "⚅"]
    dice = 2
    roll_sum = 0
    symbols = ''
    for _ in str(message.text).lower().split():
        if not len(message.text.split()) == 1:
            try:
                dice = int(message.text.split()[1])
            except ValueError:
                my_bot.reply_to(message,
                                "Не понял число костей. "
                                "Пожалуйста, введи команду "
                                "в виде \'/d6 <int>\', "
                                "где <int> — целое от 1 до 10.")
                return
    if 0 < dice <= 10:
        max_result = dice * 6
        for count in range(dice):
            roll_index = random.randint(0, len(d6) - 1)
            roll_sum += roll_index + 1
            if count < dice - 1:
                symbols += '{0} + '.format(d6[roll_index])
            elif count == dice - 1:
                symbols += '{0} = {1}  ({2})'.format(d6[roll_index], roll_sum,
                                                     max_result)
        my_bot.reply_to(message, symbols)
        user_action_log(message, "got that D6 output: {0}".format(symbols))
Ejemplo n.º 9
0
def arxiv_search(query, message):
    try:
        arxiv_search_res = arxiv.query(search_query=query, max_results=3)
        query_answer = ''
        for paper in arxiv_search_res:
            end = '…' if len(paper['summary']) > 251 else ''
            a_name = paper['authors'][0]
            if len(paper['authors']) > 1:
                a_name += 'et al.'
            query_answer += \
                '• {0}. <a href="{1}">{2}</a>. {3}{4}\n'.format(
                        a_name, paper['arxiv_url'],
                        escape(paper['title'].replace('\n', ' ')),
                        escape(paper['summary'][0:250].replace('\n', ' ')),
                        end)
        print(query_answer)
        user_action_log(message,
                        "called arxiv search with query {}".format(query))
        my_bot.reply_to(message, query_answer, parse_mode="HTML")

    except Exception as ex:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        action_log("Unknown Exception:\n{}: {}\nat {} line {}\n"
                   "Creating the alert file.".format(exc_type, ex, fname,
                                                     exc_tb.tb_lineno))
Ejemplo n.º 10
0
def my_dn(message):
    roll_sum = 0
    symbols = ''
    if len(message.text.split()) == 3:
        try:
            dice_max = int(message.text.split()[1])
            dice_n = int(message.text.split()[2])
        except ValueError:
            return
        max_result = dice_n * dice_max
        for count in range(dice_n):
            try:
                roll = random.randint(0, dice_max)
                roll_sum += roll
                if count < dice_n - 1:
                    symbols += '{0} + '.format(roll)
                elif count == dice_n - 1:
                    symbols += '{0} = {1}  ({2})'.format(roll, roll_sum, max_result)
            except ValueError:
                pass
        if not len(symbols) > 4096:
            my_bot.reply_to(message, symbols)
            user_action_log(message,
                            "knew about /dn and got that output: {0}".format(symbols))
        else:
            my_bot.reply_to(message,
                            "Слишком большие числа. "
                            "Попробуй что-нибудь поменьше")
            user_action_log(message, "knew about /dn "
                                     "and the answer was too long "
                                     "to fit one message")
Ejemplo n.º 11
0
def your_gender(message):
    with open(config.file_location['/gender'], 'r',
              encoding='utf-8') as file_gender:
        gender = random.choice(file_gender.readlines())
        my_bot.reply_to(message, gender)
    user_action_log(
        message, "has discovered his gender:\n{0}".format(
            str(gender).replace("<br>", "\n")))
Ejemplo n.º 12
0
def ro_roll(text, chat_id=config.mm_chat, max_time=100):
    time.sleep(0.25)
    ro_roll_val = random.randint(1, max_time)
    release_time = time.time() + ro_roll_val * 60
    roll_bot_msg = my_bot.send_message(chat_id, "/ROll")
    my_bot.reply_to(roll_bot_msg, str(ro_roll_val).zfill(2))
    my_bot.send_message(chat_id, text.format(str(ro_roll_val).zfill(2)))
    return release_time
Ejemplo n.º 13
0
def ro_roll(text, chat_id=config.mm_chat, max_time=100):
    time.sleep(0.25)
    ro_roll_val = random.randint(1, max_time)
    release_time = time.time() + ro_roll_val * 60
    roll_bot_msg = my_bot.send_message(chat_id, "/ROll")
    my_bot.reply_to(roll_bot_msg, str(ro_roll_val).zfill(2))
    my_bot.send_message(chat_id, text.format(str(ro_roll_val).zfill(2)))
    return release_time
Ejemplo n.º 14
0
def update_bot(message):
    if not hasattr(update_bot, "check_sure"):
        update_bot.check_sure = True
        return

    my_bot.reply_to(message, "Ух, ухожу на обновление...")
    user_action_log(message, "remotely ran update script.")
    os.execl('/bin/bash', 'bash', 'bot_update.sh')
Ejemplo n.º 15
0
def my_truth(message):
    answers = [
        "да", "нет", "это не важно", "да, хотя зря", "никогда", "100%",
        "1 из 100"
    ]
    truth = random.choice(answers)
    my_bot.reply_to(message, truth)
    user_action_log(message, "has discovered the Truth:\n{0}".format(truth))
Ejemplo n.º 16
0
def rules_command(message):
    if str(message.chat.id) == config.mm_chat:
        with open(config.file_location['/rules'], 'r',
                  encoding='utf-8') as file:
            my_bot.reply_to(message,
                            file.read(),
                            parse_mode="HTML",
                            disable_web_page_preview=True)
        user_action_log(message, "called rules")
Ejemplo n.º 17
0
def my_new_data(message):
    command = message.text.lower().split()[0]
    command_raw = re.split("@+", command)[0]
    with open(config.file_location[command_raw], 'r',
              encoding='utf-8') as file:
        my_bot.reply_to(message,
                        file.read(),
                        parse_mode="HTML",
                        disable_web_page_preview=True)
    user_action_log(message, "called that command: {}".format(command))
Ejemplo n.º 18
0
def admin_clean(message):
    if not hasattr(admin_clean, "allow_long"):
        admin_clean.allow_long = False
    if not hasattr(admin_clean, "allow_long_id"):
        admin_clean.allow_long_id = -1

    if len(message.text.split()) == 1:
        if admin_clean.allow_long:
            user_action_log(message, "cancelled big cleanup")
            admin_clean.allow_long = False
        return
    else:
        num_str = message.text.split()[1]

    if not num_str.isdigit():
        if admin_clean.allow_long:
            user_action_log(message, "cancelled big cleanup")
            admin_clean.allow_long = False
        return

    num = int(num_str)
    allow_long_str = 'Long cleanup is allowed' if admin_clean.allow_long else 'Long cleanup is not allowed'
    user_action_log(
        message,
        "has launched cleanup of {} messages. {}".format(num, allow_long_str))

    if num > 500:
        my_bot.reply_to(
            message,
            "Тааак, падажжи, слишком большое число указал, больше 500 не принимаю"
        )
        return

    if num > 128 and (not admin_clean.allow_long
                      or admin_clean.allow_long_id != message.from_user.id):
        my_bot.reply_to(
            message,
            "Вы запросили очистку более 128 сообщений. Для подтверждения отправьте "
            "команду еще раз. Для отмены отправльте команду с текстовым параметром. "
            "С уважением, ваш раб")
        admin_clean.allow_long = True
        admin_clean.allow_long_id = message.from_user.id
        return

    count = 0
    msg_id = message.message_id
    while count < num:
        try:
            my_bot.delete_message(chat_id=message.chat.id, message_id=msg_id)
            count += 1
        except:
            pass
        msg_id -= 1

    user_action_log(message, "cleaned up {} messages".format(count))
Ejemplo n.º 19
0
def welcoming_task(message):
    new_members_names = []
    new_members_info = []
    for member in message.new_chat_members:
        new_members_names.append(member.first_name)
        new_members_info.append(user_info(member))
    welcoming_msg = "{}, {}!\nЕсли здесь впервые, то ознакомься с правилами — /rules, " \
                    "и представься, если несложно.".format(random.choice(config.welcome_list),
                                                           ', '.join(new_members_names))
    my_bot.reply_to(message, welcoming_msg)
    action_log("User(s) {} joined the chat.".format(
        ', '.join(new_members_info)))
Ejemplo n.º 20
0
def get_random_user(message):
    if message.chat.type != 'private':
        chat_id = message.chat.id
        query = User.select().where(User.chat_id == chat_id, User.is_member).order_by(fn.Random())
        if query:
            user = query[0]
            my_bot.reply_to(message, 'Вам выпал: <a href="tg://user?id={}">{}</a>'.
                            format(user.user_id, strip_tags(user.first_name)), parse_mode='HTML')
        else:
            pass  # TODO: log that we do not have user base
    else:
        my_bot.reply_to(message, "КТО ВЫ ТО? Я ТУТ ОДИН!")
Ejemplo n.º 21
0
def wolfram_solver(message):
    """
    обрабатывает запрос и посылает пользователю картинку с результатом в случае удачи
    :param message:
    :return:
    """
    # сканируем и передаём всё, что ввёл пользователь после '/wolfram ' или '/wf '
    if not len(message.text.split()) == 1:
        my_bot.send_chat_action(message.chat.id, 'upload_photo')
        your_query = ' '.join(message.text.split()[1:])
        user_action_log(
            message,
            "entered this query for /wolfram:\n{0}".format(your_query))
        response = requests.get(
            "https://api.wolframalpha.com/v1/simple?appid=" + tokens.wolfram,
            params={'i': your_query})
        # если всё хорошо, и запрос найден
        if response.status_code == 200:
            img_original = Image.open(io.BytesIO(response.content))
            img_cropped = img_original.crop(
                (0, 95, 540, img_original.size[1] - 50))
            io_img = io.BytesIO()
            io_img.name = "wolfram {}.png".format(your_query.replace("/", "_"))
            img_cropped.save(io_img, format="png")
            io_img.seek(0)
            wolfram_max_ratio = 2.5
            if img_cropped.size[1] / img_cropped.size[0] > wolfram_max_ratio:
                my_bot.send_document(message.chat.id,
                                     io_img,
                                     reply_to_message_id=message.message_id)
            else:
                my_bot.send_photo(message.chat.id,
                                  io_img,
                                  reply_to_message_id=message.message_id)
            user_action_log(
                message,
                "has received this Wolfram output:\n{0}".format(response.url))
        # если всё плохо
        else:
            my_bot.reply_to(
                message, "Запрос не найдён.\nЕсли ты ввёл его на русском, "
                "то попробуй ввести его на английском.")
            user_action_log(message, "didn't received any data")
    # если пользователь вызвал /wolfram без аргумента
    else:
        my_bot.reply_to(
            message,
            "Использование: `/wolfram <запрос>` или `/wf <запрос>`",
            parse_mode="Markdown")
        user_action_log(message, "called /wolfram without any arguments")
Ejemplo n.º 22
0
def get_random_user(message):
    if message.chat.type != 'private':
        chat_id = message.chat.id
        query = User.select().where(User.chat_id == chat_id,
                                    User.is_member).order_by(fn.Random())
        if query:
            user = query[0]
            my_bot.reply_to(
                message,
                'Вам выпал: <a href="tg://user?id={}">{}</a>'.format(
                    user.user_id, strip_tags(user.first_name)),
                parse_mode='HTML')
        else:
            pass  # TODO: log that we do not have user base
    else:
        my_bot.reply_to(message, "КТО ВЫ ТО? Я ТУТ ОДИН!")
Ejemplo n.º 23
0
def admin_clean(message):
    if not hasattr(admin_clean, "allow_long"):
        admin_clean.allow_long = False
    if not hasattr(admin_clean, "allow_long_id"):
        admin_clean.allow_long_id = -1

    if len(message.text.split()) == 1:
        if admin_clean.allow_long:
            user_action_log(message, "cancelled big cleanup")
            admin_clean.allow_long = False
        return
    else:
        num_str = message.text.split()[1]

    if not num_str.isdigit():
        if admin_clean.allow_long:
            user_action_log(message, "cancelled big cleanup")
            admin_clean.allow_long = False
        return

    num = int(num_str)
    allow_long_str = 'Long cleanup is allowed' if admin_clean.allow_long else 'Long cleanup is not allowed'
    user_action_log(message, "has launched cleanup of {} messages. {}".format(num, allow_long_str))

    if num > 500:
        my_bot.reply_to(message, "Тааак, падажжи, слишком большое число указал, больше 500 не принимаю")
        return

    if num > 128 and (not admin_clean.allow_long or admin_clean.allow_long_id != message.from_user.id):
        my_bot.reply_to(message, "Вы запросили очистку более 128 сообщений. Для подтверждения отправьте "
                                 "команду еще раз. Для отмены отправльте команду с текстовым параметром. "
                                 "С уважением, ваш раб")
        admin_clean.allow_long = True
        admin_clean.allow_long_id = message.from_user.id
        return

    count = 0
    msg_id = message.message_id
    while count < num:
        try:
            my_bot.delete_message(chat_id=message.chat.id, message_id=msg_id)
            count += 1
        except:
            pass
        msg_id -= 1

    user_action_log(message, "cleaned up {} messages".format(count))
Ejemplo n.º 24
0
def vk_post(message):
    if len(message.text.split()) > 1:
        post_id = message.text.split('wall')[-1]
        user_action_log(message, "has requested vk post: {}".format(post_id))
        response = requests.get('https://api.vk.com/method/wall.getById',
                                params={'access_token': tokens.vk, 'posts': post_id, 'extended': '1',
                                        'v': config.vk_ver})
        response_list = response.json()['response']['items']
        if len(response_list) == 0:
            my_bot.reply_to(message, "Неудача! Использование: `/vk vk.com/wall-51776562_939`",
                            parse_mode="Markdown")
            return
        post = vk_utils.VkPost(response_list[0])
        post.prepare_post()
        post.send_post(message.chat.id)
    else:
        my_bot.reply_to(message, "Использование: `/vk vk.com/wall-51776562_939`", parse_mode="Markdown")
Ejemplo n.º 25
0
def rand_image_task(message):
    path = config.task_dir
    difficulty = ["1", "2", "3"]

    user_action_log(message, "asked for a challenge")
    if not len(message.text.split()) == 1:
        your_difficulty = message.text.split()[1]
        if your_difficulty in difficulty:
            all_imgs = os.listdir(path)
            rand_img = random.choice(all_imgs)
            while not rand_img.startswith(your_difficulty):
                rand_img = random.choice(all_imgs)
            your_img = open(path + rand_img, "rb")
            my_bot.send_photo(message.chat.id,
                              your_img,
                              reply_to_message_id=message.message_id)
            user_action_log(
                message, "chose a difficulty level '{0}' "
                "and got that image:\n{1}".format(your_difficulty,
                                                  your_img.name))
            your_img.close()
        else:
            my_bot.reply_to(
                message, "Доступно только три уровня сложности:\n"
                "{0}"
                "\nВыбираю рандомную задачу:".format(difficulty))
            all_imgs = os.listdir(path)
            rand_img = random.choice(all_imgs)
            your_img = open(path + rand_img, "rb")
            my_bot.send_photo(message.chat.id,
                              your_img,
                              reply_to_message_id=message.message_id)
            user_action_log(
                message, "chose a non-existent difficulty level '{0}' "
                "and got that image:\n{1}".format(your_difficulty,
                                                  your_img.name))
            your_img.close()
    else:
        all_imgs = os.listdir(path)
        rand_img = random.choice(all_imgs)
        your_img = open(path + rand_img, "rb")
        my_bot.send_photo(message.chat.id,
                          your_img,
                          reply_to_message_id=message.message_id)
        user_action_log(message, "got that image:\n{0}".format(your_img.name))
        your_img.close()
Ejemplo n.º 26
0
def rand_image_maths(message):
    path = config.math_dir
    subjects = ["algebra", "calculus", "funcan"]

    user_action_log(message, "asked for maths")
    if not len(message.text.split()) == 1:
        your_subject = message.text.split()[1].lower()
        if your_subject in subjects:
            all_imgs = os.listdir(path)
            rand_img = random.choice(all_imgs)
            while not rand_img.startswith(your_subject):
                rand_img = random.choice(all_imgs)
            your_img = open(path + rand_img, "rb")
            my_bot.send_photo(message.chat.id,
                              your_img,
                              reply_to_message_id=message.message_id)
            user_action_log(
                message, "chose subject '{0}' "
                "and got that image:\n"
                "{1}".format(your_subject, your_img.name))
            your_img.close()
        else:
            my_bot.reply_to(
                message, "На данный момент доступны факты"
                " только по следующим предметам:\n{0}\n"
                "Выбираю рандомный факт:".format(subjects))
            all_imgs = os.listdir(path)
            rand_img = random.choice(all_imgs)
            your_img = open(path + rand_img, "rb")
            my_bot.send_photo(message.chat.id,
                              your_img,
                              reply_to_message_id=message.message_id)
            user_action_log(
                message, "chose a non-existent subject '{0}' "
                "and got that image:\n"
                "{1}".format(your_subject, your_img.name))
            your_img.close()
    else:
        all_imgs = os.listdir(path)
        rand_img = random.choice(all_imgs)
        your_img = open(path + rand_img, "rb")
        my_bot.send_photo(message.chat.id,
                          your_img,
                          reply_to_message_id=message.message_id)
        user_action_log(message, "got that image:\n{0}".format(your_img.name))
        your_img.close()
Ejemplo n.º 27
0
def rand_image_maths(message):
    path = config.math_dir
    subjects = ["algebra", "calculus", "funcan"]

    user_action_log(message, "asked for maths")
    if not len(message.text.split()) == 1:
        your_subject = message.text.split()[1].lower()
        if your_subject in subjects:
            all_imgs = os.listdir(path)
            rand_img = random.choice(all_imgs)
            while not rand_img.startswith(your_subject):
                rand_img = random.choice(all_imgs)
            your_img = open(path + rand_img, "rb")
            my_bot.send_photo(message.chat.id, your_img,
                              reply_to_message_id=message.message_id)
            user_action_log(message,
                            "chose subject '{0}' "
                            "and got that image:\n"
                            "{1}".format(your_subject, your_img.name))
            your_img.close()
        else:
            my_bot.reply_to(message,
                            "На данный момент доступны факты"
                            " только по следующим предметам:\n{0}\n"
                            "Выбираю рандомный факт:".format(subjects)
                            )
            all_imgs = os.listdir(path)
            rand_img = random.choice(all_imgs)
            your_img = open(path + rand_img, "rb")
            my_bot.send_photo(message.chat.id, your_img,
                              reply_to_message_id=message.message_id)
            user_action_log(message,
                            "chose a non-existent subject '{0}' "
                            "and got that image:\n"
                            "{1}".format(your_subject, your_img.name))
            your_img.close()
    else:
        all_imgs = os.listdir(path)
        rand_img = random.choice(all_imgs)
        your_img = open(path + rand_img, "rb")
        my_bot.send_photo(message.chat.id, your_img,
                          reply_to_message_id=message.message_id)
        user_action_log(message,
                        "got that image:\n{0}".format(your_img.name))
        your_img.close()
Ejemplo n.º 28
0
def check_disa(message):
    empty_name = ''
    # добавления счетчика в функцию
    if not hasattr(check_disa, "disa_counter"):
        check_disa.disa_counter = 0

    # проверяем что идет серия из коротких предложений
    try:
        msg_len = len(message.text)
    except TypeError:
        msg_len = 0
    if message.from_user.id != config.disa_id or msg_len > config.length_of_stupid_message:
        check_disa.disa_counter = 0
        return

    check_disa.disa_counter += 1

    # проверяем, будем ли отвечать Дисе
    disa_trigger = random.randint(1, 2)
    if check_disa.disa_counter >= config.too_many_messages and disa_trigger == 2:
        # my_bot.reply_to(message, random.choice(config.stop_disa))
        ro_roll = random.randint(0, 100)
        release_time = time.time() + ro_roll * 60
        my_bot.restrict_chat_member(chat_id=config.mm_chat,
                                    user_id=config.disa_id,
                                    until_date=release_time,
                                    can_send_messages=False,
                                    can_send_media_messages=False,
                                    can_send_other_messages=False,
                                    can_add_web_page_previews=False)
        compress_msgs(message, empty_name, message.from_user.first_name,
                      message.from_user.last_name, message.from_user.id, 4)
        time.sleep(0.25)
        roll_bot_msg = my_bot.send_message(config.mm_chat, "/ROll")
        my_bot.reply_to(roll_bot_msg, str(ro_roll).zfill(2))
        my_bot.send_message(
            config.mm_chat,
            "Эй, {}.\nТвой флуд обеспечил тебе {} мин. РО. Поздравляю!".format(
                message.from_user.first_name,
                str(ro_roll).zfill(2)))
        check_disa.disa_counter = 0

    # записываем в файл увеличенный счетчик хромосом
    disa_chromo = value_from_file(config.file_location['chromo'], 46)
    value_to_file(config.file_location['chromo'], disa_chromo + 1)
Ejemplo n.º 29
0
def update_bot(message):
    if not hasattr(update_bot, "check_sure"):
        update_bot.check_sure = True
        return

    global_lock.acquire()
    try:
        file_update_write = open(config.bot_update_filename,
                                 'w',
                                 encoding='utf-8')
        file_update_write.close()
    except RuntimeError:
        pass
    global_lock.release()

    my_bot.reply_to(message, "Ух, ухожу на обновление...")
    user_action_log(message, "remotely ran update script.")
    os.execl('/bin/bash', 'bash', 'bot_update.sh')
Ejemplo n.º 30
0
def rand_image_task(message):
    path = config.task_dir
    difficulty = ["1", "2", "3"]

    user_action_log(message, "asked for a challenge")
    if not len(message.text.split()) == 1:
        your_difficulty = message.text.split()[1]
        if your_difficulty in difficulty:
            all_imgs = os.listdir(path)
            rand_img = random.choice(all_imgs)
            while not rand_img.startswith(your_difficulty):
                rand_img = random.choice(all_imgs)
            your_img = open(path + rand_img, "rb")
            my_bot.send_photo(message.chat.id, your_img,
                              reply_to_message_id=message.message_id)
            user_action_log(message,
                            "chose a difficulty level '{0}' "
                            "and got that image:\n{1}".format(your_difficulty, your_img.name))
            your_img.close()
        else:
            my_bot.reply_to(message,
                            "Доступно только три уровня сложности:\n"
                            "{0}"
                            "\nВыбираю рандомную задачу:".format(difficulty))
            all_imgs = os.listdir(path)
            rand_img = random.choice(all_imgs)
            your_img = open(path + rand_img, "rb")
            my_bot.send_photo(message.chat.id, your_img,
                              reply_to_message_id=message.message_id)
            user_action_log(message,
                            "chose a non-existent difficulty level '{0}' "
                            "and got that image:\n{1}".format(your_difficulty, your_img.name))
            your_img.close()
    else:
        all_imgs = os.listdir(path)
        rand_img = random.choice(all_imgs)
        your_img = open(path + rand_img, "rb")
        my_bot.send_photo(message.chat.id, your_img,
                          reply_to_message_id=message.message_id)
        user_action_log(message,
                        "got that image:\n{0}".format(your_img.name))
        your_img.close()
Ejemplo n.º 31
0
def command_or(message):
    user_action_log(message, "called: " + message.text)
    # Shitcode alert!
    or_lang = "ru"
    if len(message.text.split()) < 4:
        return
    or_message = message.text.split(' ', 1)[1]
    if "or" in message.text.split():
        make_choice = re.split(r'[ ](?:or)[, ]', or_message)
        or_lang = "en"
    else:
        make_choice = re.split(r'[ ](?:или)[, ]', or_message)
    if len(make_choice) > 1 and not ((message.text.split()[1] == "или") or (message.text.split()[1] == "or")):
        choosen_answer = random.choice(make_choice)
        if or_lang == "ru":
            choosen_answer = re.sub(r'(?i)\bя\b', 'ты', choosen_answer)
        else:
            choosen_answer = re.sub(r'(?i)\bi\b', 'you', choosen_answer)
        # more subs to come
        my_bot.reply_to(message, choosen_answer)
Ejemplo n.º 32
0
def disa_vk_report(disa_chromo, message):
    login, password = tokens.vk_disa_login, tokens.vk_disa_password
    vk_session = vk_api.VkApi(login, password)
    vk_session.auth()
    vk = vk_session.get_api()
    wall = vk.wall.get(owner_id=config.vk_disa_groupID, count=1)
    if time.localtime(wall['items'][0]['date'])[2] == time.localtime()[2]:
        disa_chromo_post = disa_chromo - 46
        try:
            old_chromo = int(wall['items'][0]['text'])
            disa_chromo_post += old_chromo
        except Exception as ex:
            logging.error(ex)
            disa_chromo_post = disa_chromo
        vk.wall.edit(owner_id=config.vk_disa_groupID,
                     post_id=wall['items'][0]['id'],
                     message=str(disa_chromo_post))
    else:
        disa_chromo_post = 46 + disa_chromo
        vk.wall.post(owner_id=config.vk_disa_groupID,
                     message=str(disa_chromo_post))

    if 1 < disa_chromo - 46 % 10 < 5:
        chromo_end = "ы"
    elif disa_chromo - 46 % 10 == 1:
        chromo_end = "а"
    else:
        chromo_end = ""

    my_bot.reply_to(
        message, "С последнего репорта набежало {0} хромосом{1}.\n"
        "Мы успешно зарегистрировали этот факт: "
        "https://vk.com/disa_count".format((disa_chromo - 46), chromo_end))
    action_log("Disa summary printed")
    disa_chromo = 46
    global_lock.acquire()
    with open(config.file_location_disa, 'w',
              encoding='utf-8') as file_disa_write:
        file_disa_write.write(str(disa_chromo))
    global_lock.release()
    disa.disa_first = True
Ejemplo n.º 33
0
def command_or(message):
    user_action_log(message, "called: " + message.text)
    # Shitcode alert!
    or_lang = "ru"
    if len(message.text.split()) < 4:
        return
    or_message = message.text.split(' ', 1)[1]
    if "or" in message.text.split():
        make_choice = re.split(r'[ ](?:or)[, ]', or_message)
        or_lang = "en"
    else:
        make_choice = re.split(r'[ ](?:или)[, ]', or_message)
    if len(make_choice) > 1 and not ((message.text.split()[1] == "или") or
                                     (message.text.split()[1] == "or")):
        choosen_answer = random.choice(make_choice)
        if or_lang == "ru":
            choosen_answer = re.sub(r'(?i)\bя\b', 'ты', choosen_answer)
        else:
            choosen_answer = re.sub(r'(?i)\bi\b', 'you', choosen_answer)
        ## more subs to come
        my_bot.reply_to(message, choosen_answer)
Ejemplo n.º 34
0
def my_weather(message):
    """
    Получает погоду в Москве на сегодня и на три ближайших дня, пересылает пользователю
    :param message:
    :return:
    """
    try:
        my_owm = pyowm.OWM(tokens.owm)
        # где мы хотим узнать погоду
        my_obs = my_owm.weather_at_place('Moscow')
    except pyowm.exceptions.unauthorized_error.UnauthorizedError:
        print("Your API subscription level does not allow to check weather")
        return
    w = my_obs.get_weather()
    # статус погоды сейчас
    status = w.get_detailed_status()
    # температура сейчас
    temp_now = w.get_temperature('celsius')
    # limit=4, т.к. первый результат — текущая погода
    my_forecast = my_owm.daily_forecast('Moscow,RU', limit=4)
    my_fc = my_forecast.get_forecast()
    # температуры на следующие три дня
    my_fc_temps = []
    # статусы на следующие три дня
    my_fc_statuses = []
    for wth in my_fc:
        my_fc_temps.append(str(wth.get_temperature('celsius')['day']))
        my_fc_statuses.append(str(wth.get_status()))
    # если всё нормально, то выводим результаты
    else:
        forecast = "The current temperature in Moscow is {} C, " \
                   "and it is {}.\n\n" \
                   "Tomorrow it will be {} C, {}.\n" \
                   "In 2 days it will be {}, {}.\n" \
                   "In 3 days it will be {} C, {}.".format(temp_now['temp'], status,
                                                           my_fc_temps[1], my_fc_statuses[1],
                                                           my_fc_temps[2], my_fc_statuses[2],
                                                           my_fc_temps[3], my_fc_statuses[3])
        my_bot.reply_to(message, forecast)
        user_action_log(message, "got that weather forecast")
Ejemplo n.º 35
0
def vk_post_last(message):
    if len(message.text.split()) > 1:
        count = message.text.split()[1]
        if not count.isdigit():
            my_bot.reply_to(message, "Неудача! Использование: `/vk_post_last [N]`",
                            parse_mode="Markdown")
            return

        response = requests.get('https://api.vk.com/method/wall.get',
                                params={'access_token': tokens.vk, 'owner_id': config.mm_vk_group, 'count': count,
                                        'offset': 0, 'v': config.vk_ver})

        posts = response.json()['response']['items']
        if len(posts) == 0:
            my_bot.reply_to(message, "Неудача! Использование: `/vk_post_last [N]`",
                            parse_mode="Markdown")
            return

        for post in reversed(posts):
            post_vk = vk_utils.VkPost(post)

            post_vk.prepare_post()
            try:
                if config.mm_chat != '':
                    post_vk.send_post(config.mm_chat)
                if config.mm_channel != '':
                    post_vk.send_post(config.mm_channel)
                if tokens.fb != '' and config.mm_fb_album != '':
                    post_vk.send_post_fb(tokens.fb, config.mm_fb_album)
            except Exception as ex:
                logging.exception(ex)
    else:
        my_bot.reply_to(message, "Использование: `/vk_post_last [N]`", parse_mode="Markdown")
Ejemplo n.º 36
0
def my_weather(message):
    """
    Получает погоду в Москве на сегодня и на три ближайших дня, пересылает пользователю
    :param message:
    :return:
    """
    try:
        my_owm = pyowm.OWM(tokens.owm)
        # где мы хотим узнать погоду
        my_obs = my_owm.weather_at_place('Moscow')
    except pyowm.exceptions.unauthorized_error.UnauthorizedError:
        print("Your API subscription level does not allow to check weather")
        return
    w = my_obs.get_weather()
    # статус погоды сейчас
    status = w.get_detailed_status()
    # температура сейчас
    temp_now = w.get_temperature('celsius')
    # limit=4, т.к. первый результат — текущая погода
    my_forecast = my_owm.daily_forecast('Moscow,RU', limit=4)
    my_fc = my_forecast.get_forecast()
    # температуры на следующие три дня
    my_fc_temps = []
    # статусы на следующие три дня
    my_fc_statuses = []
    for wth in my_fc:
        my_fc_temps.append(str(wth.get_temperature('celsius')['day']))
        my_fc_statuses.append(str(wth.get_status()))
    # если всё нормально, то выводим результаты
    else:
        forecast = "The current temperature in Moscow is {} C, " \
                   "and it is {}.\n\n" \
                   "Tomorrow it will be {} C, {}.\n" \
                   "In 2 days it will be {}, {}.\n" \
                   "In 3 days it will be {} C, {}.".format(temp_now['temp'], status,
                                                           my_fc_temps[1], my_fc_statuses[1],
                                                           my_fc_temps[2], my_fc_statuses[2],
                                                           my_fc_temps[3], my_fc_statuses[3])
        my_bot.reply_to(message, forecast)
        user_action_log(message, "got that weather forecast")
Ejemplo n.º 37
0
def wolfram_solver(message):
    """
    обрабатывает запрос и посылает пользователю картинку с результатом в случае удачи
    :param message:
    :return:
    """
    # сканируем и передаём всё, что ввёл пользователь после '/wolfram ' или '/wf '
    if not len(message.text.split()) == 1:
        my_bot.send_chat_action(message.chat.id, 'upload_photo')
        your_query = ' '.join(message.text.split()[1:])
        user_action_log(message, "entered this query for /wolfram:\n{0}".format(your_query))
        response = requests.get("https://api.wolframalpha.com/v1/simple?appid=" + tokens.wolfram,
                                params={'i': your_query})
        # если всё хорошо, и запрос найден
        if response.status_code == 200:
            img_original = Image.open(io.BytesIO(response.content))
            img_cropped = img_original.crop((0, 95, 540, img_original.size[1] - 50))
            io_img = io.BytesIO()
            io_img.name = "wolfram {}.png".format(your_query.replace("/", "_"))
            img_cropped.save(io_img, format="png")
            io_img.seek(0)
            wolfram_max_ratio = 2.5
            if img_cropped.size[1] / img_cropped.size[0] > wolfram_max_ratio:
                my_bot.send_document(message.chat.id, io_img,
                                     reply_to_message_id=message.message_id)
            else:
                my_bot.send_photo(message.chat.id, io_img,
                                  reply_to_message_id=message.message_id)
            user_action_log(message, "has received this Wolfram output:\n{0}".format(response.url))
        # если всё плохо
        else:
            my_bot.reply_to(message,
                            "Запрос не найдён.\nЕсли ты ввёл его на русском, "
                            "то попробуй ввести его на английском.")
            user_action_log(message, "didn't received any data")
    # если пользователь вызвал /wolfram без аргумента
    else:
        my_bot.reply_to(message, "Использование: `/wolfram <запрос>` или `/wf <запрос>`", parse_mode="Markdown")
        user_action_log(message, "called /wolfram without any arguments")
Ejemplo n.º 38
0
def admin_post(message):
    if len(message.text.split()) > 1:

        global_lock.acquire()
        if message.text.split()[1] == "edit":
            try:
                with open(config.file_location['last_post'], 'r', encoding='utf-8') as file:
                    last_msg_id = int(file.read())
                my_edited_message = ' '.join(message.text.split()[2:])
                my_bot.edit_message_text(my_edited_message, config.mm_chat, last_msg_id, parse_mode="Markdown")
                user_action_log(message, "has edited message {}:\n{}".format(last_msg_id, my_edited_message))
            except (IOError, OSError):
                my_bot.reply_to(message, "Мне нечего редактировать.")
        else:
            my_message = ' '.join(message.text.split()[1:])
            sent_message = my_bot.send_message(config.mm_chat, my_message, parse_mode="Markdown")
            with open(config.file_location['last_post'], 'w', encoding='utf-8') as file_lastmsgID_write:
                file_lastmsgID_write.write(str(sent_message.message_id))
            user_action_log(message, "has posted this message:\n{}".format(my_message))
        global_lock.release()
    else:
        my_bot.reply_to(message, "Мне нечего постить.")
Ejemplo n.º 39
0
def disa_vk_report(disa_chromo, message):
    login, password = tokens.vk_disa_login, tokens.vk_disa_password
    vk_session = vk_api.VkApi(
        login, password, config_filename=config.file_location['vk_config'])
    vk_session.auth()
    vk = vk_session.get_api()
    wall = vk.wall.get(owner_id=config.disa_vk_group, count=1)
    if time.localtime(wall['items'][0]['date'])[2] == time.localtime()[2]:
        disa_chromo_post = disa_chromo - 46
        try:
            old_chromo = int(wall['items'][0]['text'])
            disa_chromo_post += old_chromo
        except Exception as ex:
            logging.error(ex)
            disa_chromo_post = disa_chromo
        vk.wall.edit(owner_id=config.disa_vk_group,
                     post_id=wall['items'][0]['id'],
                     message=str(disa_chromo_post))
    else:
        disa_chromo_post = 46 + disa_chromo
        vk.wall.post(owner_id=config.disa_vk_group,
                     message=str(disa_chromo_post))

    if 1 < disa_chromo - 46 % 10 < 5:
        chromo_end = "ы"
    elif disa_chromo - 46 % 10 == 1:
        chromo_end = "а"
    else:
        chromo_end = ""

    my_bot.reply_to(
        message, "С последнего репорта набежало {0} хромосом{1}.\n"
        "Мы успешно зарегистрировали этот факт: "
        "https://vk.com/disa_count".format((disa_chromo - 46), chromo_end))
    action_log("Disa summary printed")

    value_to_file(config.file_location['chromo'], 46)
    disa.disa_first = True
Ejemplo n.º 40
0
def disa_vk_report(disa_chromo, message):
    login, password = tokens.vk_disa_login, tokens.vk_disa_password
    vk_session = vk_api.VkApi(login, password, config_filename=config.file_location['vk_config'])
    vk_session.auth()
    vk = vk_session.get_api()
    wall = vk.wall.get(owner_id=config.disa_vk_group, count=1)
    if time.localtime(wall['items'][0]['date'])[2] == time.localtime()[2]:
        disa_chromo_post = disa_chromo - 46
        try:
            old_chromo = int(wall['items'][0]['text'])
            disa_chromo_post += old_chromo
        except Exception as ex:
            logging.error(ex)
            disa_chromo_post = disa_chromo
        vk.wall.edit(owner_id=config.disa_vk_group,
                     post_id=wall['items'][0]['id'],
                     message=str(disa_chromo_post))
    else:
        disa_chromo_post = 46 + disa_chromo
        vk.wall.post(owner_id=config.disa_vk_group,
                     message=str(disa_chromo_post))

    if 1 < disa_chromo - 46 % 10 < 5:
        chromo_end = "ы"
    elif disa_chromo - 46 % 10 == 1:
        chromo_end = "а"
    else:
        chromo_end = ""

    my_bot.reply_to(message,
                    "С последнего репорта набежало {0} хромосом{1}.\n"
                    "Мы успешно зарегистрировали этот факт: "
                    "https://vk.com/disa_count".format((disa_chromo - 46), chromo_end))
    action_log("Disa summary printed")

    value_to_file(config.file_location['chromo'], 46)
    disa.disa_first = True
Ejemplo n.º 41
0
def arxiv_search(query, message):
    try:
        arxiv_search_res = arxiv.query(search_query=query, max_results=3)
        query_answer = ''
        for paper in arxiv_search_res:
            end = '…' if len(paper['summary']) > 251 else ''
            a_name = paper['authors'][0]
            if len(paper['authors'])>1:
                a_name += 'et al.'
            query_answer += \
                '• {0}. <a href="{1}">{2}</a>. {3}{4}\n'.format(
                        a_name, paper['arxiv_url'],
                        escape(paper['title'].replace('\n', ' ')),
                        escape(paper['summary'][0:250].replace('\n', ' ')),
                        end)
        print(query_answer)
        user_action_log(message, "called arxiv search with query {}".format(query))
        my_bot.reply_to(message, query_answer, parse_mode="HTML")

    except Exception as ex:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        action_log("Unknown Exception:\n{}: {}\nat {} line {}\n"
                   "Creating the alert file.".format(exc_type, ex, fname, exc_tb.tb_lineno))
Ejemplo n.º 42
0
def vk_post_last(message):
    if len(message.text.split()) > 1:
        count = message.text.split()[1]
        if not count.isdigit():
            my_bot.reply_to(message,
                            "Неудача! Использование: `/vk_post_last [N]`",
                            parse_mode="Markdown")
            return

        response = requests.get('https://api.vk.com/method/wall.get',
                                params={
                                    'access_token': tokens.vk,
                                    'owner_id': config.mm_vk_group,
                                    'count': count,
                                    'offset': 0,
                                    'v': config.vk_ver
                                })

        posts = response.json()['response']['items']
        if len(posts) == 0:
            my_bot.reply_to(message,
                            "Неудача! Использование: `/vk_post_last [N]`",
                            parse_mode="Markdown")
            return

        for post in reversed(posts):
            vk_post = vk_utils.VkPost(post)

            vk_post.prepare_post()
            try:
                if config.mm_chat != '':
                    vk_post.send_post(config.mm_chat)
                if config.mm_channel != '':
                    vk_post.send_post(config.mm_channel)
                if tokens.fb != '' and config.mm_fb_album != '':
                    vk_post.send_post_fb(tokens.fb, config.mm_fb_album)
            except Exception as ex:
                logging.exception(ex)
    else:
        my_bot.reply_to(message,
                        "Использование: `/vk_post_last [N]`",
                        parse_mode="Markdown")
Ejemplo n.º 43
0
def rules_command(message):
    if str(message.chat.id) == config.mm_chat:
        with open(config.file_location['/rules'], 'r', encoding='utf-8') as file:
            my_bot.reply_to(message, file.read(), parse_mode="HTML", disable_web_page_preview=True)
        user_action_log(message, "called rules")
Ejemplo n.º 44
0
def get_log(message):
    user_action_log(message, "requested bot logs")
    with open(config.file_location['bot_logs'], 'r', encoding='utf-8') as file:
        lines = file.readlines()[-100:]
        for text in cut_long_text(''.join(lines), max_len=3500):
            my_bot.reply_to(message, "{}".format(text))
Ejemplo n.º 45
0
def get_uid(message):
    if getattr(message, 'reply_to_message') is None:
        return
    my_bot.reply_to(message, '`{}`'.format(str(message.reply_to_message.from_user.id)), parse_mode="Markdown")
Ejemplo n.º 46
0
def my_new_data(message):
    command = message.text.lower().split()[0]
    command_raw = re.split("@+", command)[0]
    with open(config.file_location[command_raw], 'r', encoding='utf-8') as file:
        my_bot.reply_to(message, file.read(), parse_mode="HTML", disable_web_page_preview=True)
    user_action_log(message, "called that command: {}".format(command))
Ejemplo n.º 47
0
def id_reply(message):
    my_bot.reply_to(message, message.text)
    user_action_log(message, "called echo:\n{}".format(message.text))
Ejemplo n.º 48
0
def get_uid(message):
    if getattr(message, 'reply_to_message') is None:
        return
    my_bot.reply_to(message,
                    '`{}`'.format(str(message.reply_to_message.from_user.id)),
                    parse_mode="Markdown")
Ejemplo n.º 49
0
def underscope_reply(message):
    my_bot.reply_to(message, "_\\")
    user_action_log(message, "called the _\\")
Ejemplo n.º 50
0
def my_wiki(message):
    """
    Обрабатывает запрос и пересылает результат.
    Если запроса нет, выдаёт рандомный факт.
    :param message:
    :return:
    """
    # обрабатываем всё, что пользователь ввёл после '/wiki '
    if not len(message.text.split()) == 1:
        your_query = ' '.join(message.text.split()[1:])
        user_action_log(message,
                        "entered this query for /wiki:\n{0}".format(your_query))
        try:
            # определяем язык запроса. Эвристика для английского и русского
            if all(ord(x) < 127 or not x.isalpha() for x in your_query):
                wikipedia.set_lang('en')
            # TODO: a bit dirty condition
            elif all(ord(x) < 127 or (ord('Ё') <= ord(x) <= ord('ё')) or not x.isalpha() for x in your_query):
                wikipedia.set_lang('ru')
            else:
                wikipedia.set_lang(detect(your_query))
            wiki_response = wikipedia.summary(your_query, sentences=7)
            if '\n  \n' in str(wiki_response):
                wiki_response = "{}...\n\n" \
                                "<i>В данной статье " \
                                "имеется математическая вёрстка. " \
                                "Ссылка на статью:</i>".format(str(wiki_response).split('\n  \n', 1)[0])
            # print(wiki_response)
            # извлекаем ссылку на саму статью
            wiki_url = parse.unquote(wikipedia.page(your_query).url)
            # извлекаем название статьи
            wiki_title = wikipedia.page(your_query).title
            my_bot.reply_to(message, "<b>{0}.</b>\n{1}\n\n{2}".format(
                    wiki_title,
                    wiki_response,
                    wiki_url),
                            parse_mode="HTML")
            user_action_log(message,
                            "got Wikipedia article\n{0}".format(str(wiki_title)))
        # всё плохо, ничего не нашли
        except wikipedia.exceptions.PageError:
            my_bot.reply_to(message, "Запрос не найден.")
            user_action_log(message, "didn't received any data.")
        # нашли несколько статей, предлагаем пользователю список
        except wikipedia.exceptions.DisambiguationError as ex:
            wiki_options = ex.options
            my_bot.reply_to(message,
                            "Пожалуйста, уточни запрос. "
                            "Выбери, что из перечисленного имелось в виду, "
                            "и вызови /wiki ещё раз.\n"
                            + "\n".join(map(str, wiki_options)))
            print("There are multiple possible pages for that article.\n")
            # берём рандомную статью на рандомном языке (языки в config.py)
    else:
        wikipedia.set_lang(random.choice(['en', 'ru']))
        wikp = wikipedia.random(pages=1)
        try:
            print("Trying to get Wikipedia article\n{0}".format(str(wikp)))
            wikpd = wikipedia.page(wikp)
            wiki_fact = wikipedia.summary(wikp, sentences=3)
            my_bot.reply_to(message, "<b>{0}.</b>\n{1}".format(wikpd.title, wiki_fact), parse_mode="HTML")
            user_action_log(message, "got Wikipedia article\n{0}".format(str(wikp)))
        except wikipedia.exceptions.DisambiguationError:
            wikp = wikipedia.random(pages=1)
            try:
                print("Trying to get Wikipedia article\n{0}".format(str(wikp)))
                wiki_var = wikipedia.search(wikp, results=1)
                print("There are multiple possible pages for that article.\n")
                # wikpd = wikipedia.page(str(wiki_var[0]))
                wiki_fact = wikipedia.summary(wiki_var, sentences=4)
                my_bot.reply_to(message, "<b>{0}.</b>\n{1}".format(wikp, wiki_fact), parse_mode="HTML")
            except wikipedia.exceptions.PageError:
                print("Page error for Wikipedia article\n{0}".format(str(wikp)))
                my_bot.reply_to(message, "<b>{0}.</b>".format("You're even unluckier"), parse_mode="HTML")
            except Exception as ex:
                exc_type, exc_obj, exc_tb = sys.exc_info()
                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                action_log("Unknown Exception in Wikipedia: {}: {}\nat {} line {}".format(exc_type, ex,
                                                                                          fname, exc_tb.tb_lineno))
        except wikipedia.exceptions.PageError:
            print("Page error for Wikipedia article\n{0}".format(str(wikp)))
            my_bot.reply_to(message, "<b>{0}.</b>".format("You're very unlucky bastard"), parse_mode="HTML")

        except Exception as ex:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            action_log("Unknown Exception in Wikipedia: {}: {}\nat {} line {}".format(exc_type, ex,
                                                                                      fname, exc_tb.tb_lineno))
Ejemplo n.º 51
0
def your_gender(message):
    with open(config.file_location['/gender'], 'r', encoding='utf-8') as file_gender:
        gender = random.choice(file_gender.readlines())
        my_bot.reply_to(message, gender)
    user_action_log(message, "has discovered his gender:\n{0}".format(str(gender).replace("<br>", "\n")))
Ejemplo n.º 52
0
def my_roll(message):
    rolled_number = random.randint(0, 100)
    my_bot.reply_to(message, str(rolled_number).zfill(2))
    user_action_log(message, "recieved {0}".format(rolled_number))
Ejemplo n.º 53
0
def my_truth(message):
    answers = ["да", "нет", "это не важно", "да, хотя зря", "никогда", "100%", "1 из 100"]
    truth = random.choice(answers)
    my_bot.reply_to(message, truth)
    user_action_log(message, "has discovered the Truth:\n{0}".format(truth))
Ejemplo n.º 54
0
def id_reply(message):
    my_bot.reply_to(message, "/id")
    user_action_log(message, "called the id")
Ejemplo n.º 55
0
def id_reply(message):
    my_bot.reply_to(message, message.text)
    user_action_log(message, "called echo:\n{}".format(message.text))
Ejemplo n.º 56
0
def id_reply(message):
    my_bot.reply_to(message, "/id")
    user_action_log(message, "called the id")
Ejemplo n.º 57
0
def arxiv_random(message):
    user_action_log(message, "made arxiv random query")
    try:
        eastern = pytz.timezone('US/Eastern')
        eastern_time = datetime.datetime.now(eastern)
        # publications on 20:00
        if eastern_time.hour < 20:
            eastern_time -= datetime.timedelta(days=1)
        # no publications on friday and saturday
        if eastern_time.weekday() == 5:
            eastern_time -= datetime.timedelta(days=2)
        elif eastern_time.weekday() == 4:
            eastern_time -= datetime.timedelta(days=1)
        last_published_date = eastern_time.strftime("%Y-%m-%d")
        response = requests.get('http://export.arxiv.org/oai2',
                                params={'verb'          : 'ListIdentifiers',
                                        'set'           : 'math',
                                        'metadataPrefix': 'oai_dc',
                                        'from'          : last_published_date})
        action_log("Random arxiv paper since {}".format(last_published_date))
        # если всё хорошо
        if response.status_code == 200:
            response_tree = ElementTree.fromstring(response.content)
            num_of_papers = len(response_tree[2])
            paper_index = random.randint(0, num_of_papers)
            paper_arxiv_id = response_tree[2][paper_index][0].text.split(':')[-1]  # hardcoded
            papep_obj = arxiv.query(id_list=[paper_arxiv_id])[0]
            paper_link = papep_obj['pdf_url'].replace('http://', 'https://') + '.pdf'
            paper_link_name = paper_link.split("/pdf/")[1]
            print(paper_link)
            print(paper_link_name)
            req_pdf_size = requests.head(paper_link)
            pdf_size = round(int(req_pdf_size.headers["Content-Length"]) / 1024 / 1024, 2)
            
            a_name = papep_obj['authors'][0]
            if len(papep_obj['authors'])>1:
                a_name += 'et al.'
                
            query_answer = '{}. <a href="{}">{}</a>. {}\n\n— <a href="{}">{}</a>, {} Мб\n'.format(
                    a_name,
                    papep_obj['arxiv_url'],
                    escape(papep_obj['title'].replace('\n', ' ')),
                    escape(papep_obj['summary'].replace('\n', ' ')),
                    paper_link,
                    paper_link_name,
                    pdf_size
            )
            my_bot.reply_to(message, query_answer, parse_mode="HTML", disable_web_page_preview=False)
            user_action_log(message,
                            "arxiv random query was successful: "
                            "got paper {}".format(papep_obj['arxiv_url']))
            # TODO(randl): doesn't send. Download and delete?
            # my_bot.send_document(message.chat.id, data=paper_link)
        elif response.status_code == 503:
            # слишком часто запрашиваем
            action_log("Too much queries. 10 minutes break should be enough")
            arxiv_checker.last_call = datetime.datetime.utcnow() - datetime.timedelta(seconds=610)
        else:
            # если всё плохо
            user_action_log(message, "arxiv random query failed: response {}".format(response.status_code))

    except Exception as ex:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        action_log("Unknown Exception: {}: {}\nat {} line {}".format(exc_type, ex, fname, exc_tb.tb_lineno))
Ejemplo n.º 58
0
def get_log(message):
    user_action_log(message, "requested bot logs")
    with open(config.file_location['bot_logs'], 'r', encoding='utf-8') as file:
        lines = file.readlines()[-100:]
        for text in cut_long_text(''.join(lines), max_len=3500):
            my_bot.reply_to(message, "{}".format(text))