Exemplo n.º 1
0
def switch_session_type_handler(call_back):
    bot_msg = bot.edit_message_text(
        text="{0}\U00002026".format(choice(loading_text["schedule"])),
        chat_id=call_back.message.chat.id,
        message_id=call_back.message.message_id
    )
    month = func.get_available_months(call_back.message.chat.id)
    if len(month) == 0:
        bot.send_message(call_back.message.chat.id, "<i>Нет событий</i>",
                         parse_mode="HTML")
        return
    inline_keyboard = InlineKeyboardMarkup()
    for key in month.keys():
        inline_keyboard.row(
            *[InlineKeyboardButton(text=month[key], callback_data=str(key))]
        )
    if call_back.data == "Сессия":
        answer = "Выбери месяц:"
        switch_button = "Допса"
    else:
        answer = "Выбери месяц для <b>допсы</b>:"
        switch_button = "Сессия"

    inline_keyboard.row(
        *[InlineKeyboardButton(text=switch_button, callback_data=switch_button)]
    )

    bot.edit_message_text(text=answer,
                          chat_id=call_back.message.chat.id,
                          message_id=bot_msg.message_id,
                          parse_mode="HTML",
                          reply_markup=inline_keyboard)
Exemplo n.º 2
0
def select_months_att_handler(call_back):
    bot_msg = bot.edit_message_text(
        text="{0}\U00002026".format(choice(loading_text["schedule"])),
        chat_id=call_back.message.chat.id,
        message_id=call_back.message.message_id
    )
    json_attestation = func.get_json_attestation(call_back.message.chat.id)
    answers = []
    is_full_place = func.is_full_place(call_back.message.chat.id)

    if call_back.message.text == "Выбери месяц:":
        schedule_variations = [(True, True, False), (False, True, False)]
    else:
        schedule_variations = [(True, False, True), (False, False, True)]

    for personal, session, only_resit in schedule_variations:
        answers = func.create_session_answers(json_attestation, call_back.data,
                                              call_back.message.chat.id,
                                              is_full_place, personal,
                                              session, only_resit)
        if answers:
            break
    if not answers:
        answers.append("<i>Нет событий</i>")
    try:
        bot.edit_message_text(text=answers[0],
                              chat_id=call_back.message.chat.id,
                              message_id=bot_msg.message_id,
                              parse_mode="HTML")
    except ApiException:
        func.send_long_message(bot, answers[0], call_back.message.chat.id)
    finally:
        for answer in answers[1:]:
            func.send_long_message(bot, answer, call_back.message.chat.id)
Exemplo n.º 3
0
def next_block_handler(call_back):
    data = func.get_current_block(call_back.message.text,
                                  call_back.message.chat.id)
    answer, events = data[0], data[1]
    events_keyboard = InlineKeyboardMarkup(True)
    for event in events:
        event_name = event.strip(" {0}".format(
            emoji["cross_mark"]))[3:-4].split(" - ")
        button_text = "{0} - {1}".format(event_name[0],
                                         event_name[1].split(". ")[-1])
        events_keyboard.row(*[
            InlineKeyboardButton(
                text=name, callback_data=name[:max_inline_button_text_len])
            for name in [button_text]
        ])
    events_keyboard.row(*[
        InlineKeyboardButton(text=emoji[name], callback_data=name)
        for name in ["prev_block", "Отмена", "next_block"]
    ])
    try:
        bot.edit_message_text(text=answer,
                              chat_id=call_back.message.chat.id,
                              message_id=call_back.message.message_id,
                              parse_mode="HTML",
                              reply_markup=events_keyboard)
    except ApiException:
        pass
Exemplo n.º 4
0
def select_place_educator_handler(call_back):
    message_text_data = call_back.message.text.split("\n\n")
    answer = "{0}\n\n{1}\n<b>{2}</b>\n{3}\n\nТипы: <b>{4}</b>\n\n" \
             "Дни: <b>{5}</b>\n\nВремя: <b>{6}</b>\n\n" \
             "Выбери, у каких преподавателей скрывать занятие:".format(
                      message_text_data[0], message_text_data[1].split("\n")[0],
                      message_text_data[1].split("\n")[1],
                      "\n".join(message_text_data[1].split("\n")[2:]),
                      message_text_data[2].split(": ")[1],
                      message_text_data[3].split(": ")[1],
                      call_back.data)
    place_educator_keyboard = InlineKeyboardMarkup(True)
    place_educator_keyboard.row(*[
        InlineKeyboardButton(text=name, callback_data=name)
        for name in ["Данные преподаватели"]
    ])
    place_educator_keyboard.row(*[
        InlineKeyboardButton(text=name, callback_data=name)
        for name in ["Отмена", "Любые"]
    ])
    bot.edit_message_text(text=answer,
                          chat_id=call_back.message.chat.id,
                          message_id=call_back.message.message_id,
                          parse_mode="HTML",
                          reply_markup=place_educator_keyboard)
Exemplo n.º 5
0
def main():
    fs_utils.start_cleanup()
    # Check if the bot is restarting
    if os.path.isfile(".restartmsg"):
        with open(".restartmsg") as f:
            chat_id, msg_id = map(int, f)
        bot.edit_message_text("Restarted successfully!", chat_id, msg_id)
        os.remove(".restartmsg")
    bot.set_my_commands(botcmds)

    start_handler = CommandHandler(BotCommands.StartCommand, start)
    ping_handler = CommandHandler(BotCommands.PingCommand, ping,
                                  filters=CustomFilters.authorized_chat | CustomFilters.authorized_user)
    restart_handler = CommandHandler(BotCommands.RestartCommand, restart,
                                     filters=CustomFilters.owner_filter | CustomFilters.sudo_user)
    help_handler = CommandHandler(BotCommands.HelpCommand,
                                  bot_help, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user)
    stats_handler = CommandHandler(BotCommands.StatsCommand,
                                   stats, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user)
    log_handler = CommandHandler(BotCommands.LogCommand, log, filters=CustomFilters.owner_filter | CustomFilters.sudo_user)
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(ping_handler)
    dispatcher.add_handler(restart_handler)
    dispatcher.add_handler(help_handler)
    dispatcher.add_handler(stats_handler)
    dispatcher.add_handler(log_handler)
    updater.start_polling()
    LOGGER.info("Bot Started!")
    signal.signal(signal.SIGINT, fs_utils.exit_clean_up)
Exemplo n.º 6
0
def week_day_schedule_handler(call_back):
    bot_msg = bot.edit_message_text(text="{0}\U00002026".format(
        choice(loading_text["schedule"])),
                                    chat_id=call_back.message.chat.id,
                                    message_id=call_back.message.message_id)
    is_next_week = False
    iso_day_date = list((datetime.today() + server_timedelta).isocalendar())
    if iso_day_date[2] == 7:
        iso_day_date[1] += 1
    if call_back.data == "Следующее":
        iso_day_date[1] += 1
        is_next_week = True
    iso_day_date[2] = week_day_number[week_day_titles[
        call_back.message.text.split(": ")[-1]]]
    day_date = func.date_from_iso(iso_day_date)
    json_day = func.get_json_day_data(call_back.message.chat.id,
                                      day_date,
                                      next_week=is_next_week)
    full_place = func.is_full_place(call_back.message.chat.id)
    answer = func.create_schedule_answer(json_day, full_place,
                                         call_back.message.chat.id)
    try:
        bot.edit_message_text(text=answer,
                              chat_id=call_back.message.chat.id,
                              message_id=bot_msg.message_id,
                              parse_mode="HTML")
    except ApiException:
        func.send_long_message(bot, answer, call_back.message.chat.id)
Exemplo n.º 7
0
def early_tomorrow_suburbans_handler(call_back):
    from_to_stations = call_back.message.text.split("\n\n")[0].split(" => ")
    from_station_title = from_to_stations[0]
    to_station_title = from_to_stations[1]
    from_station = all_stations[from_station_title]
    to_station = all_stations[to_station_title]

    server_datetime = datetime.combine(
        (datetime.today() + timedelta(days=1)).date(), time())

    data = get_yandex_timetable_data(from_station,
                                     to_station,
                                     server_datetime,
                                     limit=5)
    answer = data["answer"]

    update_keyboard = InlineKeyboardMarkup(True)
    if data["is_OK"]:
        update_keyboard.row(*[
            InlineKeyboardButton(text=name, callback_data=name)
            for name in ["Все на завтра"]
        ])

    try:
        bot.edit_message_text(text=answer,
                              chat_id=call_back.message.chat.id,
                              message_id=call_back.message.message_id,
                              parse_mode="HTML",
                              reply_markup=update_keyboard)
    except ApiException:
        pass
Exemplo n.º 8
0
def types_selected_handler(call_back):
    message_text_data = call_back.message.text.split("\n\n")
    answer = "{0}\n\n{1}\n<b>{2}</b>\n{3}\n\nТипы: <b>{4}</b>\n\n".format(
        message_text_data[0], message_text_data[1].split("\n")[0],
        message_text_data[1].split("\n")[1],
        "\n".join(message_text_data[1].split("\n")[2:]),
        message_text_data[2].split(": ")[1])
    days_keyboard = InlineKeyboardMarkup(True)
    day_title = message_text_data[0].split(" ")[-1][1:-1]
    if day_title == "Понедельник" or day_title == "Вторник" or \
                    day_title == "Четверг":
        day_title += "и"
    else:
        day_title = day_title[:-1] + "ы"
    days_keyboard.row(*[
        InlineKeyboardButton(text=name, callback_data=name)
        for name in ["Все {0}".format(day_title.lower())]
    ])
    days_keyboard.row(*[
        InlineKeyboardButton(text=name, callback_data=name)
        for name in ["Отмена", "Все дни"]
    ])
    answer += "Выбери дни для скрытия занятия:"
    bot.edit_message_text(text=answer,
                          chat_id=call_back.message.chat.id,
                          message_id=call_back.message.message_id,
                          parse_mode="HTML",
                          reply_markup=days_keyboard)
Exemplo n.º 9
0
def dict_training_phrase(callback: CallbackQuery, user: User, dict_id: str,
                         phrase_id: str, dst_lang_id: str, is_guessed: str):
    qs = Dictionary.objects.for_user(user)
    dictionary = qs.filter(id=dict_id).first()
    phrase = Phrase.objects.filter(
        id=phrase_id, phrase_groups__dictionaries=dictionary).first()
    dst_lang = Language.objects.filter(id=dst_lang_id).first()

    if not (dictionary and phrase and dst_lang):
        return responses.dict_list(
            qs, text=_('Language or phrase not found.')).replace_prev(callback)

    phrase.guessed_or_not(user, dictionary, int(is_guessed))

    # убираем клавиатуру в предыдущем сообщении и показываем перевод
    bot.edit_message_text(
        phrase.verbose_translations(dst_lang),
        chat_id=callback.message.chat.id,
        message_id=callback.message.message_id,
    )

    stats = dictionary.get_user_training_stats(user)
    if stats.is_training_completed(phrase.lang, dst_lang):
        responses.training_done(stats).answer_to_callback(callback)
    else:
        responses.training(user, dictionary, phrase.lang,
                           dst_lang).answer_to_callback(callback)
Exemplo n.º 10
0
def less_suburbans_handler(call_back):
    from_to_stations = call_back.message.text.split("\n\n")[0].split(" => ")
    from_station_title = from_to_stations[0]
    to_station_title = from_to_stations[1]
    from_station = all_stations[from_station_title]
    to_station = all_stations[to_station_title]
    server_datetime = datetime.today() + server_timedelta
    data = get_yandex_timetable_data(from_station, to_station, server_datetime)
    answer = data["answer"]

    update_keyboard = InlineKeyboardMarkup(True)
    if data["is_OK"]:
        if data["is_tomorrow"]:
            inline_answer = emoji["warning"] + " На сегодня нет электричек"
            bot.answer_callback_query(call_back.id,
                                      inline_answer,
                                      show_alert=True)
            update_keyboard.row(*[
                InlineKeyboardButton(text=name, callback_data=name)
                for name in ["Все на завтра"]
            ])
        else:
            update_keyboard.row(*[
                InlineKeyboardButton(text=name, callback_data=name)
                for name in ["Оставшиеся", "Обновить"]
            ])

    try:
        bot.edit_message_text(text=answer,
                              chat_id=call_back.message.chat.id,
                              message_id=call_back.message.message_id,
                              parse_mode="HTML",
                              reply_markup=update_keyboard)
    except ApiException:
        pass
Exemplo n.º 11
0
def main():
    fs_utils.start_cleanup()

    if IS_VPS:
        asyncio.get_event_loop().run_until_complete(start_server_async(SERVER_PORT))

    # Check if the bot is restarting
    if os.path.isfile(".restartmsg"):
        with open(".restartmsg") as f:
            chat_id, msg_id = map(int, f)
        bot.edit_message_text("Restarted successfully!", chat_id, msg_id)
        os.remove(".restartmsg")
    bot.set_my_commands(botcmds)

    start_handler = CommandHandler(BotCommands.StartCommand, start, run_async=True)
    ping_handler = CommandHandler(BotCommands.PingCommand, ping,
                                  filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
    restart_handler = CommandHandler(BotCommands.RestartCommand, restart,
                                     filters=CustomFilters.owner_filter | CustomFilters.sudo_user, run_async=True)
    help_handler = CommandHandler(BotCommands.HelpCommand,
                                  bot_help, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
    stats_handler = CommandHandler(BotCommands.StatsCommand,
                                   stats, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
    log_handler = CommandHandler(BotCommands.LogCommand, log, filters=CustomFilters.owner_filter | CustomFilters.sudo_user, run_async=True)
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(ping_handler)
    dispatcher.add_handler(restart_handler)
    dispatcher.add_handler(help_handler)
    dispatcher.add_handler(stats_handler)
    dispatcher.add_handler(log_handler)
    updater.start_polling(drop_pending_updates=IGNORE_PENDING_REQUESTS)
    LOGGER.info("Bot Started!")
    signal.signal(signal.SIGINT, fs_utils.exit_clean_up)
Exemplo n.º 12
0
def select_block_choose_lesson_handler(call_back):
    bot.edit_message_text(chat_id=call_back.message.chat.id,
                          text="{0} {1}".format(emoji["calendar"],
                                                call_back.data),
                          message_id=call_back.message.message_id)

    selective_blocks = func.get_selective_blocks(call_back.message.chat.id)

    answer, lessons = func.create_selective_block_answer(
        call_back.message.chat.id, selective_blocks[call_back.data],
        call_back.data.lower())

    inline_keyboard = InlineKeyboardMarkup()
    for lesson in lessons:
        inline_keyboard.row(*[
            InlineKeyboardButton(text=name, callback_data=name)
            for name in [lesson]
        ])
    inline_keyboard.row(*[
        InlineKeyboardButton(text=name, callback_data=name)
        for name in ["Отмена"]
    ])

    answer = "Вот список занятий, проходящих в данное время:\n\n" \
             "{0}" \
             "Выбери занятие, которое хочешь оставить:".format(answer)

    bot.send_message(chat_id=call_back.message.chat.id,
                     text=answer,
                     reply_markup=inline_keyboard,
                     parse_mode="HTML")
Exemplo n.º 13
0
def select_educator_handler(call_back):
    message_text_data = call_back.message.text.split("\n\n")[1:-1]
    chosen_event_number = int(call_back.data.split(". ")[0]) - 1
    chosen_event = ". ".join(
        message_text_data[chosen_event_number].split(". ")[1:])
    chosen_event_data = chosen_event.split("\n")
    available_educators = []
    for place_edu in chosen_event_data[1:]:
        if "(" not in place_edu:
            continue

        place_edu = place_edu.strip(" {0}".format(emoji["heavy_check_mark"]))
        available_educators.append(place_edu.split("(")[1][:-1])

    inline_keyboard = InlineKeyboardMarkup(row_width=1)
    inline_keyboard.add(*[
        InlineKeyboardButton(text=name,
                             callback_data=name[:max_inline_button_text_len])
        for name in available_educators
    ])
    inline_keyboard.row(
        InlineKeyboardButton(text="Отмена", callback_data="Отмена"))
    answer = "Выбранное занятие:\n<b>{0}</b>\n\nВыбери преподавателя, " \
             "которого оставить:".format(
                chosen_event_data[0].strip(" {0}".format(emoji["cross_mark"])))
    bot.edit_message_text(text=answer,
                          chat_id=call_back.message.chat.id,
                          message_id=call_back.message.message_id,
                          parse_mode="HTML",
                          reply_markup=inline_keyboard)
Exemplo n.º 14
0
def select_day_choose_educator_handler(call_back):
    iso_day_date = list((datetime.today() + server_timedelta).isocalendar())
    if iso_day_date[2] == 7:
        iso_day_date[1] += 1
    iso_day_date[2] = week_day_number[week_day_titles[call_back.data]]
    day_date = func.date_from_iso(iso_day_date)

    answer_data = func.get_lessons_with_educators(call_back.message.chat.id,
                                                  day_date)
    day_string = answer_data["date"]
    bot.edit_message_text(chat_id=call_back.message.chat.id,
                          text="{0} {1}".format(emoji["calendar"], day_string),
                          message_id=call_back.message.message_id)
    answer = "Вот список подходящих занятий:\n\n"
    answer += answer_data["answer"]
    inline_keyboard = InlineKeyboardMarkup()
    if not answer_data["is_empty"]:
        for event in answer_data["answer"].split("\n\n"):
            button_text = "{0}".format(
                event.split("\n")[0].strip(" {0}".format(
                    emoji["cross_mark"]))[3:-4])
            inline_keyboard.row(*[
                InlineKeyboardButton(
                    text=name, callback_data=name[:max_inline_button_text_len])
                for name in [button_text]
            ])
        inline_keyboard.row(
            InlineKeyboardButton(text="Отмена", callback_data="Отмена"))
        answer += "\n\nВыбери необходиое занятие:"
    bot.send_message(text=answer,
                     chat_id=call_back.message.chat.id,
                     parse_mode="HTML",
                     reply_markup=inline_keyboard)
Exemplo n.º 15
0
def editMessage(text: str, message: Message, reply_markup=None):
    try:
        bot.edit_message_text(text=text, message_id=message.message_id,
                              chat_id=message.chat.id,reply_markup=reply_markup,
                              parse_mode='HTMl')
    except Exception as e:
        LOGGER.error(str(e))
Exemplo n.º 16
0
def not_exist_user_callback_handler(call_back):
    answer = "Чтобы пользоваться сервисом, необходимо " \
             "зарегистрироваться.\nВоспользуйся коммандой /start"
    bot.edit_message_text(text=answer,
                          chat_id=call_back.message.chat.id,
                          message_id=call_back.message.message_id,
                          parse_mode="HTML")
Exemplo n.º 17
0
def editor_choose_educator_handler(call_back):
    answer = "Выбери день, в котором есть занятие с большим количеством " \
             "преподавателей:"
    json_week_data = func.get_json_week_data(call_back.message.chat.id)
    days = json_week_data["Days"]
    days_keyboard = InlineKeyboardMarkup(True)
    for day in days:
        data = datetime.strptime(day["Day"], "%Y-%m-%dT%H:%M:%S").date()
        answer_data = func.get_lessons_with_educators(
            call_back.message.chat.id, data)
        if answer_data["is_empty"]:
            continue
        days_keyboard.row(*[
            InlineKeyboardButton(text=name, callback_data=name)
            for name in [day["DayString"].split(", ")[0].capitalize()]
        ])
    if len(days_keyboard.to_dic()["inline_keyboard"]):
        days_keyboard.row(*[
            InlineKeyboardButton(text=name, callback_data=name)
            for name in ["Отмена"]
        ])
    else:
        answer = "Нет занятий с большим количеством преподавателей"
    bot.edit_message_text(text=answer,
                          chat_id=call_back.message.chat.id,
                          message_id=call_back.message.message_id,
                          reply_markup=days_keyboard)
Exemplo n.º 18
0
def cancel_handler(call_back):
    answer = "Отмена"
    try:
        bot.edit_message_text(text=answer,
                              chat_id=call_back.message.chat.id,
                              message_id=call_back.message.message_id)
    except ApiException:
        pass
Exemplo n.º 19
0
def sending_on_handler(call_back):
    func.set_sending(call_back.message.chat.id, True)
    answer = "{0} Рассылка <b>активирована</b>\nЖди рассылку в 21:00" \
             "".format(emoji["mailbox_on"])
    bot.edit_message_text(text=answer,
                          chat_id=call_back.message.chat.id,
                          message_id=call_back.message.message_id,
                          parse_mode="HTML")
Exemplo n.º 20
0
def editMessage(text: str, message: Message):
    try:
        bot.edit_message_text(text=text,
                              message_id=message.message_id,
                              chat_id=message.chat.id,
                              parse_mode='HTMl')
    except TimedOut as e:
        LOGGER.error(str(e))
        pass
Exemplo n.º 21
0
def show_full_info(call_back):
    answer = special_thanks
    bot.edit_message_text(text=answer,
                          chat_id=call_back.message.chat.id,
                          message_id=call_back.message.message_id,
                          parse_mode="HTML",
                          disable_web_page_preview=True)
    inline_answer = "И тебе :)"
    bot.answer_callback_query(call_back.id, inline_answer, cache_time=1)
Exemplo n.º 22
0
def editMessage(text: str, message: Message):
    try:
        bot.edit_message_text(text=text,
                              message_id=message.message_id,
                              chat_id=message.chat.id,
                              parse_mode=ParseMode.MARKDOWN,
                              disable_web_page_preview=True)
    except Exception as e:
        LOGGER.error(str(e))
Exemplo n.º 23
0
def delete_current_group_handler(call_back):
    user_id = call_back.message.chat.id
    group_data = func.get_current_group(user_id)
    func.delete_group(group_data[0], user_id)
    answer = "Группа <b>{0}</b> удалена".format(group_data[1])
    bot.edit_message_text(text=answer,
                          chat_id=user_id,
                          message_id=call_back.message.message_id,
                          parse_mode="HTML")
Exemplo n.º 24
0
def change_group_handler(call_back):
    answer = "{0}\nДля отмены используй /home".format(call_back.data)
    bot.edit_message_text(text=answer,
                          chat_id=call_back.message.chat.id,
                          message_id=call_back.message.message_id,
                          parse_mode="HTML")
    call_back.message.text = call_back.data
    start_handler(call_back.message)
    return
Exemplo n.º 25
0
def main():
    fs_utils.start_cleanup()
    # Check if the bot is restarting
    SUPPORT_GROUP = "tgelkayb0ts"
    if SUPPORT_GROUP is not None and isinstance(SUPPORT_GROUP, str):
        try:
            dispatcher.bot.sendMessage(f"@{SUPPORT_GROUP}", "Bot Restarted!")
        except Unauthorized:
            LOGGER.warning(
                "Bot isnt able to send message to support_chat, go and check!")
        except BadRequest as e:
            LOGGER.warning(e.message)
    if os.path.isfile(".restartmsg"):
        with open(".restartmsg") as f:
            chat_id, msg_id = map(int, f)
        bot.edit_message_text("Restarted successfully!", chat_id, msg_id)
        os.remove(".restartmsg")
    bot.set_my_commands(botcmds)

    start_handler = CommandHandler(BotCommands.StartCommand,
                                   start,
                                   run_async=True)
    ping_handler = CommandHandler(BotCommands.PingCommand,
                                  ping,
                                  filters=CustomFilters.authorized_chat
                                  | CustomFilters.authorized_user,
                                  run_async=True)
    restart_handler = CommandHandler(BotCommands.RestartCommand,
                                     restart,
                                     filters=CustomFilters.owner_filter
                                     | CustomFilters.sudo_user,
                                     run_async=True)
    help_handler = CommandHandler(BotCommands.HelpCommand,
                                  bot_help,
                                  filters=CustomFilters.authorized_chat
                                  | CustomFilters.authorized_user,
                                  run_async=True)
    stats_handler = CommandHandler(BotCommands.StatsCommand,
                                   stats,
                                   filters=CustomFilters.authorized_chat
                                   | CustomFilters.authorized_user,
                                   run_async=True)
    log_handler = CommandHandler(BotCommands.LogCommand,
                                 log,
                                 filters=CustomFilters.owner_filter
                                 | CustomFilters.sudo_user,
                                 run_async=True)
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(ping_handler)
    dispatcher.add_handler(restart_handler)
    dispatcher.add_handler(help_handler)
    dispatcher.add_handler(stats_handler)
    dispatcher.add_handler(log_handler)
    updater.start_polling(drop_pending_updates=IGNORE_PENDING_REQUESTS)
    LOGGER.info("Bot Started!")
    signal.signal(signal.SIGINT, fs_utils.exit_clean_up)
Exemplo n.º 26
0
def process_ask_question_callback(query):
    try:
        if query.data in ['instant_cancel', 'scheduled_cancel']:
            bot.delete_message(query.message.chat.id, query.message.message_id)
            return

        edited_text = 'Спрашиваем...' if query.data == 'instant_question' else 'Планируем...'
        bot.edit_message_text(chat_id=query.message.chat.id,
                              message_id=query.message.message_id,
                              text=edited_text)
        message_parts = query.message.text.split('\n', maxsplit=1)
        text = message_parts[1].strip()
        full_name, username = UserNamesExtractor.get_fullname_and_username(
            query.message.chat)
        added_by_name = full_name if full_name else (
            username if username else query.message.chat.id)
        now = datetime.utcnow()

        if query.data == 'instant_question':
            try:
                QuestionAsker.ask(text)
                questions_queue_repository.add(
                    QuestionQueueItem(
                        text=text,
                        time_created=now,
                        time_planned=now,
                        time_sent=now,
                        status=QuestionQueueItemStatus.InstantlyInserted,
                        added_by_id=query.message.chat.id,
                        added_by_name=added_by_name,
                        has_answer=False))
            except:
                bot.edit_message_text(chat_id=query.message.chat.id,
                                      message_id=query.message.message_id,
                                      text='К сожалению, что-то сгнило!')
        else:
            regex = re.compile(
                r'^.+(?P<datetime>\d\d\.\d\d\.\d\d\d\d\s+\d\d\:\d\d).+$')
            match = regex.match(message_parts[0])
            planned_time = DatetimeUtils.parse_dmy_hm(match.group('datetime'),
                                                      timedelta(hours=-3))
            questions_queue_repository.add(
                QuestionQueueItem(text=text,
                                  time_created=now,
                                  time_planned=planned_time,
                                  time_sent=None,
                                  status=QuestionQueueItemStatus.Unprocessed,
                                  added_by_id=query.message.chat.id,
                                  added_by_name=added_by_name,
                                  has_answer=False))

        bot.delete_message(query.message.chat.id, query.message.message_id)
        bot.send_sticker(query.message.chat.id, StickerIds.done)
    finally:
        requests_notifier.notify(query.message.chat.id, query.data)
Exemplo n.º 27
0
    def replace_prev(self, callback: CallbackQuery):
        msg = callback.message
        bot.edit_message_text(force_text(self.text),
                              chat_id=msg.chat.id,
                              message_id=msg.message_id,
                              reply_markup=self.reply_markup,
                              parse_mode=self.parse_mode)

        TelegramLogEntry(text=callback.data,
                         profile_id=msg.chat.id,
                         response=str(self)).save()
Exemplo n.º 28
0
def change_start_station_handler(call_back):
    answer = "Выбери начальную станцию:"
    start_station_keyboard = InlineKeyboardMarkup(True)
    for station_title in all_stations.keys():
        start_station_keyboard.row(*[
            InlineKeyboardButton(text=name, callback_data=name)
            for name in [station_title]
        ])
    bot.edit_message_text(text=answer,
                          chat_id=call_back.message.chat.id,
                          message_id=call_back.message.message_id,
                          reply_markup=start_station_keyboard)
Exemplo n.º 29
0
def feedback_handler(call_back):
    markup = ForceReply(False)
    try:
        bot.edit_message_text(text="Обратная связь",
                              chat_id=call_back.message.chat.id,
                              message_id=call_back.message.message_id)
    except ApiException:
        pass
    finally:
        answer = "Напиши мне что-нибудь:"
        bot.send_message(call_back.message.chat.id,
                         answer,
                         reply_markup=markup)
Exemplo n.º 30
0
def classroom_list_view(user, message_to_edit=None):
    text = '*Классные комнаты*' if user.language_code == 'ru' else '*Classrooms*'
    if message_to_edit:
        bot.edit_message_text(
            text,
            chat_id=user.id,
            message_id=message_to_edit.message_id,
            reply_markup=get_classroom_list_inline_markup(user),
            parse_mode='Markdown')
    else:
        bot.send_message(user.id,
                         text,
                         reply_markup=get_classroom_list_inline_markup(user),
                         parse_mode='Markdown')