Example #1
0
def me_message(message):
    # В ЛС бот не может удалять сообщения пользователя
    try:
        my_bot.delete_message(chat_id=message.chat.id, message_id=message.message_id)
    except Exception:
        logging.exception("message")
    # Если у пользователя есть юзернэйм, то берём его как your_name
    if message.from_user.username is not None:
        your_name = '[@{}](tg://user?id={})'.format(message.from_user.username, message.from_user.id)
    # Иначе, берём имя пользователя, которое есть всегда
    else:
        your_name = '[{}](tg://user?id={})'.format(message.from_user.first_name, message.from_user.id)
    # Если /me непусто, берём всё, что после '/me '
    if len(message.text.split()) < 2:
        return
    your_message = message.text.split(maxsplit=1)[1]
    your_me = "{} {}".format(your_name, your_message)
    try:
        # Если /me было ответом на какое-то сообщение, то посылаем запрос как ответ
        # TODO: расширить эту фичу на все команды
        if getattr(message, 'reply_to_message') is not None:
            my_bot.send_message(message.chat.id, your_me, parse_mode="Markdown", disable_notification=True,
                                reply_to_message_id=message.reply_to_message.message_id)
        else:
            my_bot.send_message(message.chat.id, your_me, parse_mode="Markdown", disable_notification=True)
    except Exception:
        logging.exception("message")
    user_action_log(message, "called the me:\n{}".format(your_me))
Example #2
0
    def send_post(self, destination):
        try:
            # Отправляем текст, нарезая при необходимости
            for text in cut_long_text(self.final_text):
                my_bot.send_message(
                    destination,
                    text,
                    parse_mode="HTML",
                    disable_web_page_preview=self.web_preview_url == '')

            # Отправляем отображаемые приложения к посту
            for url in self.gif_links:
                my_bot.send_document(destination, url)
            if len(self.image_links) > 0:
                my_bot.send_media_group(
                    destination,
                    [InputMediaPhoto(url) for url in self.image_links])
            if len(self.video_links) > 0:
                my_bot.send_media_group(
                    destination,
                    [InputMediaVideo(url) for url in self.video_links])
            for url in self.audio_links:
                my_bot.send_audio(destination, url)
        except apihelper.ApiException:
            action_log("VK Error: api exception")
Example #3
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
Example #4
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
Example #5
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, "Мне нечего постить.")
Example #6
0
def morning_msg():
    text = ''

    # TODO: добавить генерацию разных вариантов приветствий
    text += 'Доброе утро, народ!'
    # TODO: Проверять на наличие картинки
    text += ' [😺](https://t.me/funkcat/{})'.format(random.randint(1, 826))
    text += '\n'

    month_names = [u'января', u'февраля', u'марта',
                   u'апреля', u'мая', u'июня',
                   u'июля', u'августа', u'сентября',
                   u'октября', u'ноября', u'декабря']

    weekday_names = [u'понедельник', u'вторник', u'среда', u'четверг', u'пятница', u'суббота', u'воскресенье']

    now = datetime.datetime.now(pytz.timezone('Europe/Moscow'))

    text += 'Сегодня *{} {}*, *{}*. Нас в чате *{}*!'.format(now.day, month_names[now.month - 1],
                                                             weekday_names[now.weekday()],
                                                             my_bot.get_chat_members_count(config.mm_chat))
    text += '\n\n'
    text += '{}'.format(daily_weather())
    text += '\n\n'

    text += 'Котик дня:'

    # Отправить и запинить сообщение без уведомления
    msg = my_bot.send_message(config.mm_chat, text, parse_mode="Markdown")
    my_bot.pin_chat_message(config.mm_chat, msg.message_id, disable_notification=True)

    action_log('Scheduled morning message sent: id = {}'.format(msg.message_id))
Example #7
0
def vk_listener():
    """
    Проверяет наличие новых постов в паблике мехмата и отправляет их при наличии
    :return: None
    """
    if tokens.vk == '':
        return

    try:
        vk_post = vk_get_last_post(config.mm_vk_group)

        if vk_post == 1:
            return
        if vk_post.not_posted():
            action_log("We have new post in mechmath public")

            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 != '':
                    try:
                        vk_post.send_post_fb(tokens.fb, config.mm_fb_album)
                    except facebook.GraphAPIError as ex:
                        logging.exception(ex)
                        scheduler.pause_job('vk_listener')
                        my_bot.send_message(config.mm_chat_debug,
                                            'Что-то не так с токеном у ФБ! Проверка новых постов приостановлена.\n'
                                            'Фиксики приде, порядок наведе!')
                        action_log('Error reposting a VK post to FB. Most likely there\'s invalid FB token.\n'
                                   'Job "vk_listener" has been paused.')
            except Exception as ex:
                logging.exception(ex)
                my_bot.send_message(config.mm_chat_debug,
                                    "Последний пост вызвал ошибку при репостинге! @rm_bk, выезжай.")
            vk_post.set_as_posted()

        time.sleep(5)

    except requests.exceptions.ReadTimeout:
        action_log("Read Timeout in vkListener() function")
    except requests.exceptions.ConnectionError:
        action_log("Connection Error in vkListener() function")
    except RuntimeError:
        action_log("Runtime Error in vkListener() function")
Example #8
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)
Example #9
0
    def send_post(self, destination):
        try:
            # Отправляем текст, нарезая при необходимости
            for text in cut_long_text(self.final_text):
                my_bot.send_message(destination, text, parse_mode="HTML",
                                    disable_web_page_preview=self.web_preview_url == '')

            # Отправляем отображаемые приложения к посту
            for url in self.gif_links:
                my_bot.send_document(destination, url)
            if len(self.image_links) > 0:
                my_bot.send_media_group(destination, [InputMediaPhoto(url) for url in self.image_links])
            if len(self.video_links) > 0:
                my_bot.send_media_group(destination, [InputMediaVideo(url) for url in self.video_links])
            for url in self.audio_links:
                my_bot.send_audio(destination, url)
        except apihelper.ApiException:
            action_log("VK Error: api exception")
Example #10
0
    def send_post(self, destination):
        # Отправляем текст, нарезая при необходимости
        for text in cut_long_text(self.final_text):
            my_bot.send_message(
                destination,
                text,
                parse_mode="HTML",
                disable_web_page_preview=self.web_preview_url == '')

        # Отправляем отображаемые приложения к посту
        for url in self.video_links:
            my_bot.send_message(destination, url)
        for url in self.gif_links:
            my_bot.send_document(destination, url)
        for url in self.image_links:
            my_bot.send_photo(destination, url)
        for url in self.audio_links:
            my_bot.send_audio(destination, url)
Example #11
0
def vk_get_last_post(vkgroup_id):
    try:
        # Берём первые два поста
        response = requests.get('https://api.vk.com/method/wall.get',
                                params={'access_token': tokens.vk, 'owner_id': vkgroup_id, 'count': 2, 'offset': 0,
                                        'v': config.vk_ver})
        # print(response.json())
        # Cоздаём json-объект для работы
        posts = response.json()['response']['items']
        # Cверяем два верхних поста на предмет свежести, т.к. верхний может быть запинен
        post = posts[0] if posts[0]['date'] >= posts[1]['date'] else posts[1]
        return VkPost(post)
    except KeyError as ex:
        logging.exception(ex)
        if response.json()['error']['error_code'] == 5:
            scheduler.pause_job('vk_listener')
            my_bot.send_message(config.mm_chat_debug,
                                'Что-то не так с токеном у ВК! Проверка новых постов приостановлена.\n'
                                'Фиксики приде, порядок наведе!')
            action_log('KeyError exception in vk_listener. Most likely there\'s invalid token.\n'
                       'Job "vk_listener" has been paused.')
        return 1
Example #12
0
def vk_listener():
    """
    Проверяет наличие новых постов в паблике мехмата и отправляет их при наличии
    :return: None
    """
    if tokens.vk == '':
        return

    try:
        vk_post = vk_get_last_post(config.mm_vk_group)

        if vk_post.not_posted():
            action_log("We have new post in mechmath public")

            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)
                my_bot.send_message(
                    config.mm_chat_debug,
                    "Последний пост вызвал ошибку при репостинге! @rm_bk, выезжай."
                )
            vk_post.set_as_posted()

        time.sleep(5)

    except requests.exceptions.ReadTimeout:
        action_log("Read Timeout in vkListener() function")
    except requests.exceptions.ConnectionError:
        action_log("Connection Error in vkListener() function")
    except RuntimeError:
        action_log("Runtime Error in vkListener() function")
Example #13
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, "Мне нечего постить.")
Example #14
0
def morning_msg():
    text = ''

    # TODO: добавить генерацию разных вариантов приветствий
    text += 'Доброе утро, народ!'
    # TODO: Проверять на наличие картинки
    text += ' [😺](https://t.me/funkcat/{})'.format(random.randint(1, 826))
    text += '\n'

    month_names = [
        u'января', u'февраля', u'марта', u'апреля', u'мая', u'июня', u'июля',
        u'августа', u'сентября', u'октября', u'ноября', u'декабря'
    ]

    weekday_names = [
        u'понедельник', u'вторник', u'среда', u'четверг', u'пятница',
        u'суббота', u'воскресенье'
    ]

    now = datetime.datetime.now(pytz.timezone('Europe/Moscow'))

    text += 'Сегодня *{} {}*, *{}*. Нас в чате *{}*!'.format(
        now.day, month_names[now.month - 1], weekday_names[now.weekday()],
        my_bot.get_chat_members_count(config.mm_chat))
    text += '\n\n'
    text += '{}'.format(daily_weather())
    text += '\n\n'

    text += 'Котик дня:'

    # Отправить и запинить сообщение без уведомления
    msg = my_bot.send_message(config.mm_chat, text, parse_mode="Markdown")
    my_bot.pin_chat_message(config.mm_chat,
                            msg.message_id,
                            disable_notification=True)

    action_log('Scheduled morning message sent: id = {}'.format(
        msg.message_id))