예제 #1
0
def start_vote(bot, update):
    mes = update.message
    if not check_access(mes.from_user.id):
        return
    vote_id = re.search("_(\\d+)", mes.text)
    if vote_id is None:
        bot.send_message(chat_id=mes.chat_id, text="Неверный синтаксис.")
        return
    vote_id = int(vote_id.group(1))
    vote = Vote.get_vote(vote_id)
    if vote is None:
        bot.send_message(chat_id=mes.chat_id, text="Голосование не найдено.")
        return
    if len(vote.variants) <= 0:
        bot.send_message(chat_id=mes.chat_id, text="Необходимо задать хотя бы один ответ.")
        return
    if vote.duration is None:
        bot.send_message(chat_id=mes.chat_id, text="Необходимо задать длительность голосования.")
        return
    if vote.started is not None:
        bot.send_message(chat_id=mes.chat_id, text="Голосование уже началось!")
        return
    vote.started = datetime.datetime.now(tz=moscow_tz).replace(tzinfo=None)
    vote.update()
    bot.send_message(chat_id=mes.chat_id, text="Голосование <b>{}</b> началось!".format(vote.name), parse_mode='HTML')
    Vote.fill_active_votes()
예제 #2
0
def guild_unvoted_list(bot, update):
    mes = update.message
    if mes.from_user.id != SUPER_ADMIN_ID:
        return
    parse = re.search(" (\\d+) (.*)", mes.text)
    if parse is None:
        bot.send_message(chat_id=mes.chat_id, text="Неверный синтаксис.\n\nСинтаксис: /guild_unvoted_list {vote_id} "
                                                   "{guild_tag}")
        return
    vote_id = int(parse.group(1))
    guild_tag = parse.group(2)
    vote = Vote.get_vote(vote_id)
    if vote is None:
        bot.send_message(chat_id=mes.chat_id, text="Голосование не найдено.")
        return
    guild = Guild.get_guild(guild_tag=guild_tag)
    if guild is None:
        bot.send_message(chat_id=mes.chat_id, text="Гильдия не найдена.")
        return
    response = "Не проголосовали в гильдии <b>{}</b>:\n".format(guild.tag)
    for player_id in guild.members:
        voted = False
        for ch in vote.choices:
            if player_id in ch:
                voted = True
                break
        if not voted:
            player = Player.get_player(player_id)
            response += "@{} ".format(player.username)
    bot.send_message(chat_id=mes.chat_id, text=response, parse_mode='HTML')
예제 #3
0
def vote_results(bot, update):
    mes = update.message
    if mes.from_user.id != SUPER_ADMIN_ID and mes.from_user.id != 116028074:
        return
    vote_id = re.search("_(\\d+)", mes.text)
    if vote_id is None:
        bot.send_message(chat_id=mes.chat_id, text="Неверный синтаксис.")
        return
    vote_id = int(vote_id.group(1))
    vote = Vote.get_vote(vote_id)
    if vote is None:
        bot.send_message(chat_id=mes.chat_id, text="Голосование не найдено.")
        return
    results = {}
    total_voices = 0
    for i, ch in enumerate(vote.choices):
        variant_count = 0
        for player_id in ch:
            if player_id != 0:
                variant_count += 1
        results.update({vote.variants[i]: variant_count})
        total_voices += variant_count
    results = sorted(list(results.items()), key=lambda x: x[1], reverse=True)
    response = "Результаты <b>{}</b>:\n".format(vote.name)
    for res in results:
        response += "{} —— <code>{}</code> (<code>{:.0f}%</code>)\n".format(res[0], res[1], res[1]/total_voices*100)
    response += "\n<em>Всего голосов:</em> <b>{}</b>".format(total_voices)
    bot.send_message(chat_id=mes.chat_id, text=response, parse_mode='HTML')
예제 #4
0
def set_vote_classes(bot, update):
    mes = update.message
    if not check_access(mes.from_user.id):
        return
    vote_id = re.search("_(\\d+)", mes.text)
    if vote_id is None:
        bot.send_message(chat_id=mes.chat_id, text="Неверный синтаксис.")
        return
    vote_id = int(vote_id.group(1))
    vote = Vote.get_vote(vote_id)
    if vote is None:
        bot.send_message(chat_id=mes.chat_id, text="Голосование не найдено.")
        return
    vote.classes = []
    for i in classes_list:
        vote.classes.append(False)
    try:
        classes = list(mes.text.split()[1:])
    except IndexError:
        for i in range(len(vote.classes)):
            vote.classes[i] = True
        bot.send_message(chat_id=mes.chat_id, text="Голосование <b>{}</b> разрешено для всех классов".format(vote.name),
                         parse_mode='HTML')
        return
    for cl in classes:
        try:
            print(cl, classes_list.index(cl))
            vote.classes[classes_list.index(cl)] = True
        except ValueError:
            continue
    print(vote.classes)
    vote.update()
    bot.send_message(chat_id=mes.chat_id, text="Классы голосования <b>{}</b> обновлены.".format(vote.name),
                     parse_mode='HTML')
예제 #5
0
def request_change_vote_duration(bot, update, user_data):
    mes = update.message
    if not check_access(mes.from_user.id):
        return
    vote_id = re.search("_(\\d+)", mes.text)
    if vote_id is None:
        bot.send_message(chat_id=mes.chat_id, text="Неверный синтаксис.")
        return
    vote_id = int(vote_id.group(1))
    vote = Vote.get_vote(vote_id)
    if vote is None:
        bot.send_message(chat_id=mes.chat_id, text="Голосование не найдено.")
        return
    user_data.update({"status": "editing_vote_duration", "vote_id": vote_id})
    bot.send_message(chat_id=mes.chat_id, text="Изменение длительности <b>{}</b>\nДайте ответ в виде %HH %MM %SS"
                                               "".format(vote.name), parse_mode='HTML')
예제 #6
0
def vote(bot, update):
    mes = update.message
    player = Player.get_player(mes.from_user.id)
    if player is None:
        return
    if player.castle != '🖤':
        bot.send_message(chat_id=mes.chat_id, text="Голосование доступно только жителям 🖤Скалы!")
        return
    if player.guild is None and player.id not in ALLOWED_LIST:
        bot.send_message(chat_id=mes.chat_id, text="Голосование доступно только членам гильдий.")
        return
        pass
    if Guild.get_guild(player.guild).is_academy():
        bot.send_message(chat_id=mes.chat_id, text="Ученикам Академии запрещено голосовать.")
        return
    vote_id = re.search("_(\\d+)", mes.text)
    if vote_id is None:
        bot.send_message(chat_id=mes.chat_id, text="Неверный синтаксис.")
        return
    vote_id = int(vote_id.group(1))
    vote = Vote.get_vote(vote_id)
    if vote is None:
        bot.send_message(chat_id=mes.chat_id, text="Голосование не найдено.")
        return
    if player.last_updated < vote.started:
        bot.send_message(chat_id=mes.chat_id, text="Для принятия участия в этом голосовании необходимо обновить "
                                                   "профиль после его начала.")
        return
    try:
        if vote.classes is not None and vote.classes and (player.game_class is None or
                                                          vote.classes[classes_list.index(player.game_class)] is False):
            bot.send_message(chat_id=mes.chat_id, text="Голосование недоступно для вашего класса.\n\n<em>В случае, "
                                                       "если ваш класс указан неверно, его можно обновить, "
                                                       "прислав форвард ответа </em>@ChatWarsBot<em> на </em>/me",
                             parse_mode='HTML')
            try:
                bot.answerCallbackQuery(callback_query_id=update.callback_query.id)
            except Exception:
                pass
            return
    except Exception:
        logging.error(traceback.format_exc())
    choice = vote.get_choice(player.id)
    response = get_vote_text(vote, choice)
    buttons = get_vote_buttons(vote, choice)
    bot.send_message(chat_id=mes.chat_id, text=response, reply_markup=buttons, parse_mode='HTML')
예제 #7
0
def wide_vote_results(bot, update):
    # Пока ничего, заготовка под результаты, отсортированные по гильдиям
    mes = update.message
    if mes.from_user.id != SUPER_ADMIN_ID and mes.from_user.id != 116028074:
        return
    vote_id = re.search("_(\\d+)", mes.text)
    if vote_id is None:
        bot.send_message(chat_id=mes.chat_id, text="Неверный синтаксис.")
        return
    vote_id = int(vote_id.group(1))
    vote = Vote.get_vote(vote_id)
    if vote is None:
        bot.send_message(chat_id=mes.chat_id, text="Голосование не найдено.")
        return
    results = {}
    total_voices = 0
    for i, ch in enumerate(vote.choices):
        for player_id in ch:
            player = Player.get_player(player_id)
예제 #8
0
def change_vote_duration(bot, update, user_data):
    mes = update.message
    if not check_access(mes.from_user.id):
        return
    vote_id = user_data.get("vote_id")
    if vote_id is None:
        bot.send_message(chat_id=mes.chat_id, text="Произошла ошибка. Начните сначала.")
        return
    vote = Vote.get_vote(vote_id)
    if vote is None:
        bot.send_message(chat_id=mes.chat_id, text="Голосование не найдено.")
        return
    parse = mes.text.split()
    hours = int(parse[0])
    minutes = int(parse[1]) if len(parse) > 1 else 0
    seconds = int(parse[2]) if len(parse) > 2 else 0
    vote.duration = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)
    vote.update()
    user_data.pop("status")
    user_data.pop("vote_id")
    bot.send_message(chat_id=mes.chat_id, text="Длительность <b>{}</b> успешно изменена!".format(vote.name),
                     parse_mode='HTML')
예제 #9
0
def set_vote_variant(bot, update):
    data = update.callback_query.data
    mes = update.callback_query.message
    player = Player.get_player(update.callback_query.from_user.id)
    if player is None:
        return
    if player.castle != '🖤':
        bot.send_message(chat_id=mes.chat_id, text="Голосование доступно только жителям 🖤Скалы!")
        return
    if player.guild is None and player.id not in ALLOWED_LIST:
        bot.send_message(chat_id=mes.chat_id, text="Голосование доступно только членам гильдий.")
        return
        pass
    if Guild.get_guild(player.guild).is_academy():
        bot.send_message(chat_id=mes.chat_id, text="Ученикам Академии запрещено голосовать.")
        return
    parse = re.search("_(\\d+)_(\\d+)", data)
    if parse is None:
        bot.send_message(chat_id=mes.chat_id, text="Неверный синтаксис.")
        return
    vote_id = int(parse.group(1))
    variant = int(parse.group(2))
    vote = Vote.get_vote(vote_id)
    if vote is None:
        bot.send_message(chat_id=mes.chat_id, text="Голосование не найдено.")
        return
    if player.last_updated < vote.started:
        bot.send_message(chat_id=mes.chat_id, text="Для принятия участия в этом голосовании необходимо обновить "
                                                   "профиль после его начала.")
        return
    try:
        if vote.classes is not None and vote.classes and (player.game_class is None or
                                        vote.classes[classes_list.index(player.game_class)] is False):
            bot.send_message(chat_id=mes.chat_id, text="Голосование недоступно для вашего класса.\n\n<em>В случае, "
                                                       "если ваш класс указан неверно, его можно обновить, "
                                                       "прислав форвард ответа </em>@ChatWarsBot<em> на </em>/me",
                             parse_mode='HTML')
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id)
            return
    except Exception:
        logging.error(traceback.format_exc())
    if vote.started + vote.duration < datetime.datetime.now(tz=moscow_tz).replace(tzinfo=None):
        bot.send_message(chat_id=mes.chat_id, text="Голосование уже завершено.")
        return
    for ch in vote.choices:
        if player.id in ch:
            ch.remove(player.id)
    vote.choices[variant].append(player.id)
    vote.update()
    choice = None
    for i, ch in enumerate(vote.choices):
        if player.id in ch:
            choice = i
            break
    response = get_vote_text(vote, choice=choice)
    buttons = get_vote_buttons(vote, choice=choice)
    try:
        bot.editMessageText(chat_id=mes.chat_id, message_id=mes.message_id, text=response,
                            reply_markup=buttons, parse_mode='HTML')
    # except Exception:
        # logging.error(traceback.format_exc())
    except BadRequest:
        pass
    except TelegramError:
        pass
    bot.answerCallbackQuery(callback_query_id=update.callback_query.id)
예제 #10
0
def castle_bot_processing():

    # Хендлеры для инлайн кнопок в топах
    dispatcher.add_handler(CallbackQueryHandler(send_new_top, pattern="top_[^_]+_.*"))

    # Хендлеры для инлайн кнопок мобов
    dispatcher.add_handler(CallbackQueryHandler(mob_help, pattern="mob_partify_.*"))
    dispatcher.add_handler(CallbackQueryHandler(fight_club_help, pattern="fight_club_partify_.*"))

    # Хендлеры для инлайн кнопок профиля
    dispatcher.add_handler(CallbackQueryHandler(guild_history, pattern="pr_guild_history_\\d+"))
    dispatcher.add_handler(CallbackQueryHandler(reports_history, pattern="pr_reports_history_\\d+"))
    dispatcher.add_handler(CallbackQueryHandler(profile_settings, pattern="pr_settings_\\d+"))
    dispatcher.add_handler(CallbackQueryHandler(profile_exp, pattern="pr_exp_\\d+"))

    dispatcher.add_handler(CallbackQueryHandler(change_profile_setting, pattern="prs.*_\\d+"))

    # Хендлеры для инлайн кнопок гильдий
    dispatcher.add_handler(CallbackQueryHandler(edit_guild_commander, pattern="gccmdr_\\d+", pass_user_data=True))
    dispatcher.add_handler(CallbackQueryHandler(edit_guild_chat, pattern="gccht_\\d+", pass_user_data=True))
    dispatcher.add_handler(CallbackQueryHandler(edit_guild_division, pattern="gcdvs_\\d+", pass_user_data=True))

    # Хендлер на любые изменения булеанов в гильдиях
    dispatcher.add_handler(CallbackQueryHandler(change_guild_bool_state, pattern="gc[opnm]_\\d+.*"))

    dispatcher.add_handler(CallbackQueryHandler(list_players, pattern="gipl_\\d+"))
    dispatcher.add_handler(CallbackQueryHandler(assistants, pattern="giass_\\d+"))
    dispatcher.add_handler(CallbackQueryHandler(guild_reports, pattern="girep_\\d+"))
    dispatcher.add_handler(CallbackQueryHandler(leave_guild, pattern="gilv_\\d+"))
    dispatcher.add_handler(CallbackQueryHandler(leave_guild_confirm, pattern="leave_guild_(yes|no)"))

    dispatcher.add_handler(CallbackQueryHandler(guild_equipment, pattern="gieq_\\d+", pass_user_data=True))
    dispatcher.add_handler(CallbackQueryHandler(change_guild_equipment_param, pattern="guild_equipment_\\w+_\\d+_\\d+",
                                                pass_user_data=True))

    dispatcher.add_handler(CallbackQueryHandler(craft_action,
                                                pattern="craft_(withdraw|buy|fewer|more|go)_(\\w+)_(\\w+)"))
    dispatcher.add_handler(CallbackQueryHandler(set_craft_possible_tier, pattern="craft_possible_tier_\\d+",
                                                pass_user_data=True))


    dispatcher.add_handler(CallbackQueryHandler(guild_setting, pattern="giset_\\d+"))
    dispatcher.add_handler(CallbackQueryHandler(edit_guild_setting, pattern="gs.*_\\d+"))

    dispatcher.add_handler(CallbackQueryHandler(delete_guild, pattern="g_delete_confirm_\\d+"))
    dispatcher.add_handler(CallbackQueryHandler(cancel_delete_guild, pattern="g_delete_cancel_\\d+"))

    dispatcher.add_handler(CallbackQueryHandler(set_own_status, pattern="p_own_status.*"))
    dispatcher.add_handler(CallbackQueryHandler(moderate_status, pattern="p_moderate_status_\\d+.*"))

    dispatcher.add_handler(CallbackQueryHandler(answer_reward, pattern="p_reward.*", pass_user_data=True))
    dispatcher.add_handler(CallbackQueryHandler(moderate_reward, pattern="p_moderate_reward_\\d+.*"))

    dispatcher.add_handler(CallbackQueryHandler(new_roulette_top, pattern="roulette_top_.*"))

    dispatcher.add_handler(CallbackQueryHandler(set_vote_variant, pattern="vote_\\d+_\\d+"))

    dispatcher.add_handler(CallbackQueryHandler(edit_guild_inline, pattern="guilds_divisions_\\d+"))
    dispatcher.add_handler(CallbackQueryHandler(inline_edit_guild_division, pattern="guild_change_division_\\d+.*"))
    dispatcher.add_handler(CallbackQueryHandler(guilds_division_change_page, pattern="guilds_divisions_page_\\d+"))

    dispatcher.add_handler(CallbackQueryHandler(alliance_stats, pattern="ga_stats_\\d+"))

    dispatcher.add_handler(CallbackQueryHandler(skip))

    #

    # Конец хендлеров инлайн кнопок  ---------------------------------------------------------------------------------

    # dispatcher.add_handler(MessageHandler(Filters.all & filter_forbidden, skip))  # Отключение регистрации
    dispatcher.add_handler(MessageHandler(
        Filters.update.edited_message | Filters.update.channel_posts, skip))  # Скип всех сообщений с каналов,
    #                                                                         # редактирований сообщений
    dispatcher.add_handler(CommandHandler('start', start, filters=filter_is_pm, pass_user_data=True))
    dispatcher.add_handler(CommandHandler('cancel', cancel, pass_user_data=True))

    dispatcher.add_handler(CommandHandler('pop_from_user_data', pop_from_user_data))
    dispatcher.add_handler(CommandHandler('show_data', show_data, filters=filter_is_pm, pass_user_data=True,
                                          pass_args=True))

    dispatcher.add_handler(CommandHandler('dokument', view_profile))
    dispatcher.add_handler(CommandHandler('document', view_profile))
    dispatcher.add_handler(CommandHandler('dok', view_profile))
    dispatcher.add_handler(CommandHandler('doc', view_profile))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_is_hero, hero, pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.all & filter_not_registered_do_not_notify & filter_joined_castle_chat,
                                          castle_hello))
    dispatcher.add_handler(MessageHandler(Filters.all & filter_in_castle_chat, skip))

    dispatcher.add_handler(MessageHandler(Filters.all & filter_reward_delete_message, delete_message))

    dispatcher.add_handler(MessageHandler((Filters.command | Filters.text) & filter_is_trigger, send_trigger))

    dispatcher.add_handler(CommandHandler('change_rp', change_rp, pass_user_data=True))

    # Язык бота
    dispatcher.add_handler(CommandHandler('en', change_lang, filters=filter_is_pm, pass_user_data=True))
    dispatcher.add_handler(CommandHandler('ru', change_lang, filters=filter_is_pm, pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_is_profile, add_class_from_player))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_set_class, update_ranger_class_skill_lvl))

    # API
    dispatcher.add_handler(CommandHandler('auth', auth, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('update_guild', update_guild, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('update_stock', update_stock, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('update', update, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('stock', stock, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('guild_stock', stock, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('g_stock_res', stock, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('g_stock_misc', stock, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('g_stock_alch', stock, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('g_stock_equip', stock, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('g_stock_other', stock, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('repair', repair))
    dispatcher.add_handler(CommandHandler('ws', ws, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('ws_full', ws, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('autospend_gold', autospend_gold, filters=filter_is_pm))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_grant_auth_code, grant_auth_token))

    # Альянсы
    dispatcher.add_handler(MessageHandler(Filters.text & filter_view_alliance, view_alliance))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_alliance_roster, alliance_roster))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_alliance_info, update_alliance))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_alliance_location, add_alliance_location))
    dispatcher.add_handler(MessageHandler((Filters.text | Filters.command) & filter_alliance_pin, alliance_pin))
    dispatcher.add_handler(CommandHandler('ga', ga))
    dispatcher.add_handler(CommandHandler('ga_map', ga_map))
    dispatcher.add_handler(CommandHandler('ga_expire', ga_expire))
    dispatcher.add_handler(CommandHandler('set_alliance_hq_chat', set_alliance_hq_chat, pass_args=True))

    # Профсоюзы
    dispatcher.add_handler(MessageHandler(Filters.text & filter_trade_union, add_union))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_union_list, union_list))
    dispatcher.add_handler(CommandHandler('set_union_chat', add_union_chat_id))
    dispatcher.add_handler(CommandHandler('clear_union_list', clear_union_list))
    dispatcher.add_handler(CommandHandler('union_list', print_union_players))
    dispatcher.add_handler(CommandHandler('union_stats', count_union_stats))
    dispatcher.add_handler(CommandHandler('guild_union_players', view_guild_players_in_union))
    dispatcher.add_handler(CommandHandler('guild_unions', view_guild_unions))
    dispatcher.add_handler(CommandHandler('add_to_union_user_id', add_to_union_user_id))
    dispatcher.add_handler(CommandHandler('add_union_assistant', add_union_assistant))
    dispatcher.add_handler(CommandHandler('del_union_assistant', del_union_assistant))
    dispatcher.add_handler(CommandHandler('top_union_attack', top_union_stats))
    dispatcher.add_handler(CommandHandler('top_union_defense', top_union_stats))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_split_union, split_union))
    dispatcher.add_handler(MessageHandler(Filters.all & filter_need_to_ban_in_union_chat, check_and_kick))

    dispatcher.add_handler(MessageHandler(Filters.all & filter_not_registered_do_not_notify & ~filter_is_pm, skip))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_not_registered & filter_is_pm, unknown_input,
                                          pass_user_data=True))

    # Мобы
    dispatcher.add_handler(MessageHandler(Filters.text & filter_fight_club_message, fight_club))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_mob_message, mob))
    dispatcher.add_handler(CommandHandler('pretend', pretend))
    dispatcher.add_handler(CommandHandler('mobs_notify', mobs_notify))

    # Приём репортов
    dispatcher.add_handler(MessageHandler(Filters.text & filter_is_report, add_report, pass_user_data=True))

    dispatcher.add_handler(CommandHandler('battle_equip', battle_equip))
    dispatcher.add_handler(CommandHandler('battle_equip_full', battle_equip))
    dispatcher.add_handler(CommandHandler('battle_drop', battle_drop))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_view_hero, profile, pass_user_data=True))

    # Классовые штуки, ачивки и тп
    dispatcher.add_handler(MessageHandler(Filters.text & filter_archer_trap, add_trap))
    dispatcher.add_handler(CommandHandler('trap_stats', trap_stats))

    # Всякие команды в личке у бота
    dispatcher.add_handler(MessageHandler(Filters.text & filter_guild_stock_parts, guild_parts, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_guild_stock_recipes, guild_recipes,
                                          pass_user_data=True))

    dispatcher.add_handler(CommandHandler('set_withdraw_res', set_withdraw_res, pass_user_data=True, pass_args=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_guild_stock_resources, withdraw_resources,
                                          pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_player_alch_craft, alch_possible_craft))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_is_pm & filter_player_stock_resources, deposit))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_is_pm & filter_player_auction, deposit))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_is_pm & filter_player_misc, deposit))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_is_pm & filter_player_alch, deposit))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_reply_deposit, deposit))

    dispatcher.add_handler(MessageHandler((Filters.text | Filters.command) & filter_craft & filter_is_pm, craft))

    # Хендлеры для команд гильдий
    dispatcher.add_handler(MessageHandler(Filters.text & filter_view_guild, guild_info))

    dispatcher.add_handler(MessageHandler(Filters.command & filter_view_profile, view_profile))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_remove_player, remove_player))

    # dispatcher.add_handler(MessageHandler(Filters.text & filter_view_guilds_commanders, guild_commanders))

    dispatcher.add_handler(CommandHandler('leave_guild', leave_guild))

    dispatcher.add_handler(CommandHandler('add', add))
    dispatcher.add_handler(CommandHandler('add_assistant', add_assistant))
    dispatcher.add_handler(CommandHandler('del_assistant', del_assistant))

    dispatcher.add_handler(CommandHandler('guild_reports', guild_reports))
    dispatcher.add_handler(CommandHandler('guild_repair', guild_repair))

    dispatcher.add_handler(CommandHandler('change_reputation', change_reputation))
    dispatcher.add_handler(CommandHandler('change_guilds_reputation', change_guilds_reputation))

    dispatcher.add_handler(CommandHandler('guild_top_battles', guild_top_battles, filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('academy_top_battles', guild_top_battles, filters=filter_is_pm))

    # Хендлеры академки
    dispatcher.add_handler(CommandHandler('add_teacher', add_teacher))
    dispatcher.add_handler(CommandHandler('del_teacher', del_teacher))

    dispatcher.add_handler(CommandHandler('view_academy', guild_info))

    dispatcher.add_handler(CommandHandler('g_info', g_info))
    dispatcher.add_handler(CommandHandler('guild_commanders', guild_commanders))

    dispatcher.add_handler(CommandHandler('d2', drop_table))
    dispatcher.add_handler(CommandHandler('d3', drop_table))
    dispatcher.add_handler(CommandHandler('d4', drop_table))
    dispatcher.add_handler(CommandHandler('dc', drop_table))
    dispatcher.add_handler(CommandHandler('drop', send_search_bot, pass_args=True))

    dispatcher.add_handler(CommandHandler('set_status', set_status))
    dispatcher.add_handler(CommandHandler('set_own_status', request_set_own_status))

    # Хендлеры для чата гильдий
    dispatcher.add_handler(MessageHandler(Filters.text & filter_guild_list, notify_guild_attack))
    dispatcher.add_handler(CommandHandler('notify_guild_sleeping', notify_guild_to_battle))
    dispatcher.add_handler(CommandHandler('notify_guild_not_ready', notify_guild_to_battle))

    dispatcher.add_handler(CommandHandler('ro', mute, pass_args=True))
    dispatcher.add_handler(CommandHandler('unrestrict', unrestrict, pass_args=True))
    dispatcher.add_handler(CommandHandler('send_message_to_chat', send_message_to_chat))

    dispatcher.add_handler(CommandHandler('worldtop', show_worldtop, pass_args=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_stock_withdraw, send_withdraw))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_give_resource, send_withdraw))

    # Кик из классовых и замковых чатов
    dispatcher.add_handler(MessageHandler(Filters.all & filter_kick_from_castle_chat, class_chat_kick))
    dispatcher.add_handler(CommandHandler('revoke_all_class_links', revoke_all_class_links))

    dispatcher.add_handler(CommandHandler('get_rangers', get_rangers))

    dispatcher.add_handler(CommandHandler('set_castle_chat', set_castle_chat))
    dispatcher.add_handler(MessageHandler(filter_kick_from_castle_chat, remove_players_from_chat))

    # Хендлеры голосований
    dispatcher.add_handler(CommandHandler('create_vote', create_vote, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_add_vote_text, add_vote_text, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_add_vote_variant, add_vote_variant,
                                          pass_user_data=True))
    dispatcher.add_handler(CommandHandler('finish_vote', finish_vote, pass_user_data=True))

    dispatcher.add_handler(CommandHandler('guild_unvoted', guild_unvoted_list))

    dispatcher.add_handler(MessageHandler(Filters.command & filter_view_vote, view_vote))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_request_edit_vote_duration,
                                          request_change_vote_duration, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_edit_vote_duration,
                                          change_vote_duration, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_edit_vote_classes, set_vote_classes))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_start_vote, start_vote))
    dispatcher.add_handler(CommandHandler('votes', votes))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_vote_results, vote_results))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_vote, vote))

    # Хендлеры для виртуального замка
    dispatcher.add_handler(MessageHandler(Filters.text & filter_back, back, pass_user_data=True))

    # dispatcher.add_handler(MessageHandler(Filters.text & filter_not_constructed, not_constructed))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_not_constructed, construct, pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_guide_signs, guide_signs))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_barracks, barracks, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_throne_room, throne_room, pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_technical_tower, technical_tower, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_manuscript, manuscript, pass_user_data=True))
    # dispatcher.add_handler(MessageHandler(Filters.text & filter_guides, guides, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_view_manuscript_category, view_manuscript_category))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_commits_history, last_commits))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_my_cabinet, my_cabinet, pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_treasury, treasury, pass_user_data=True))

    dispatcher.add_handler(CommandHandler('statuses', statuses))
    dispatcher.add_handler(CommandHandler('status_shop', status_shop))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_status_shop, status_shop))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_is_pm & Filters.regex('buy_status_\\d+'), buy_status))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_is_pm & Filters.regex('status_on_\\d+'), status_on))

    # Хендлеры для строительства в замке
    dispatcher.add_handler(MessageHandler(Filters.text & filter_sawmill, sawmill, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_quarry, quarry, pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_construction_plate, construction_plate,
                                          pass_user_data=True))
    dispatcher.add_handler(MessageHandler((Filters.text | Filters.command) & filter_construct, construct,
                                          pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_king_cabinet_construction, king_cabinet_construction))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_begin_construction, begin_construction))

    # Хендлеры на квесты
    dispatcher.add_handler(MessageHandler(Filters.text & filter_tea_party, tea_party, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_tea_party_quest, tea_party_quest, pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.command & filter_two_go_quest, two_quest_pressed_go, pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_cw_quest_result, add_cw_quest_result))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_cw_arena_result, add_arena_result))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_roulette, roulette_main, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_request_roulette_bet, request_roulette_bet,
                                          pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_place_roulette_bet, place_roulette_bet,
                                          pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_is_pm & filter_roulette_tops, roulette_tops))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_smuggler, smuggler))
    dispatcher.add_handler(CommandHandler('castle_message_change', request_get_reward, pass_user_data=True,
                                          filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('castle_mailing', request_get_reward, pass_user_data=True,
                                          filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('castle_global_trigger', request_get_reward, pass_user_data=True,
                                          filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('castle_delete_global_trigger', request_get_reward, pass_user_data=True,
                                          filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('castle_change_chat_picture', request_get_reward, pass_user_data=True,
                                          filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('castle_g_def', request_get_reward, pass_user_data=True,
                                          filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('castle_request_pin', request_get_reward, pass_user_data=True,
                                          filters=filter_is_pm))
    dispatcher.add_handler(CommandHandler('castle_ro', request_get_reward, pass_user_data=True,
                                          filters=filter_is_pm))

    dispatcher.add_handler(MessageHandler(Filters.all & filter_get_reward, get_reward, pass_user_data=True))

    dispatcher.add_handler(CommandHandler('request_kabala', request_kabala))
    dispatcher.add_handler(CommandHandler('kabala', kabala, pass_user_data=True))

    # Продолжаются хендлеры замка
    dispatcher.add_handler(MessageHandler(Filters.text & filter_request_bot_guild_message_notify,
                                          request_bot_guild_message_notify, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_send_bot_guild_message_notify,
                                          send_bot_guild_message_notify, pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_request_change_update_message,
                                          request_change_update_message, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_change_update_message,
                                          change_update_message, pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_update_history, update_history))

    dispatcher.add_handler(CallbackQueryHandler(change_update_history, pattern="uh[lr]_\\d+"))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_watch_portraits, watch_portraits))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_headquarters, headquarters, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_request_change_debrief,
                                          request_change_debrief, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_change_debrief, change_debrief, pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_request_guild_message_notify,
                                          request_guild_message_notify, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.all & filter_send_guild_message_notify,
                                          send_guild_message_notify, pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_king_cabinet, king_cabinet, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_add_general, add_general, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_adding_general, adding_general, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_remove_general, remove_general,
                                          pass_user_data=False))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_request_change_castle_message,
                                          request_change_castle_message, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_change_castle_message, change_castle_message,
                                          pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_hall_of_fame, hall_of_fame, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_tops, tops, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_top_stat, top_stat))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_begin_duty, begin_duty, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_end_duty, end_duty, pass_user_data=True))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_request_duty_feedback, request_duty_feedback,
                                          pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.all & filter_send_duty_feedback, send_duty_feedback,
                                          pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.all & filter_reply_to_duty_feedback, send_reply_to_duty_request))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_request_audience, request_king_audience,
                                          pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_accept_audience, accept_king_audience))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_decline_audience, decline_king_audience))

    dispatcher.add_handler(MessageHandler(Filters.text & filter_request_mid_feedback, request_mid_feedback,
                                          pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.all & filter_send_mid_feedback, send_mid_feedback,
                                          pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.all & filter_reply_to_mid_feedback, send_reply_to_mid_request))

    dispatcher.add_handler(MessageHandler(Filters.command & filter_restrict_feedback, restrict_feedback))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_unrestrict_feedback, unrestrict_feedback))

    dispatcher.add_handler(MessageHandler(Filters.all & filter_ban_in_duty_chat, check_ban_in_duty_chat))

    # Хендлеры для триггеров - тоже как можно ниже, из-за возможного совпадения глобальных триггеров с командами бота
    dispatcher.add_handler(CommandHandler('create_trigger', add_trigger))
    dispatcher.add_handler(CommandHandler('create_global_trigger', add_trigger))
    dispatcher.add_handler(CommandHandler('delete_trigger', remove_trigger))
    dispatcher.add_handler(CommandHandler('triggers', triggers))
    dispatcher.add_handler(CommandHandler('info_trigger', info_trigger))
    dispatcher.add_handler(CommandHandler('replace_trigger', replace_trigger))
    dispatcher.add_handler(CommandHandler('import_triggers', import_triggers, pass_args=True))

    # Хендлеры далее специально ниже всех остальных, ибо невозможно проверять статус на эту исполнение этих команд
    dispatcher.add_handler(MessageHandler(Filters.text & filter_castle_gates, castle_gates, pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_central_square, central_square, pass_user_data=True))

    dispatcher.add_handler(CommandHandler('chat_info', chat_info))

    dispatcher.add_handler(MessageHandler(Filters.all & ~filter_has_access & ~filter_is_merc, unknown_input,
                                          pass_user_data=True))
    # Restricted access---------------------------------------------------------------------------------------------

    dispatcher.add_handler(CommandHandler('count_reputation_sum', count_reputation_sum))

    dispatcher.add_handler(CommandHandler('guilds', guilds))
    dispatcher.add_handler(CommandHandler('list_guilds', list_guilds))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_battle_stats, battle_stats))

    dispatcher.add_handler(MessageHandler(Filters.all & filter_is_merc, unknown_input, pass_user_data=True))
    dispatcher.add_handler(CommandHandler('create_guild', create_guild))

    dispatcher.add_handler(MessageHandler(Filters.command & filter_mailing_pin, mailing_pin))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_mailing, mailing))

    dispatcher.add_handler(MessageHandler(Filters.command & filter_edit_guild, edit_guild))
    dispatcher.add_handler(MessageHandler(Filters.command & filter_delete_guild, request_delete_guild))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_change_guild_commander, change_guild_commander,
                                          pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_change_guild_chat, change_guild_chat,
                                          pass_user_data=True))
    dispatcher.add_handler(MessageHandler(Filters.text & filter_change_guild_division, change_guild_division,
                                          pass_user_data=True))

    dispatcher.add_handler(CommandHandler('sql', sql))

    dispatcher.add_handler(CommandHandler('revoke_duty_link', revoke_duty_link))
    # End of the restrictions---------------------------------------------------------------------------------------

    dispatcher.add_handler(MessageHandler(Filters.text & filter_is_pm, unknown_input, pass_user_data=True))

    # Загрузка user_data с диска
    load_data()
    # Всякие действия при старте бота
    Guild.fill_guild_ids()
    fill_mid_players()
    fill_allowed_list()
    fill_triggers_lists()
    plan_battle_jobs()
    plan_daily_tasks()
    fill_union_chats()
    load_construction_jobs()
    Vote.fill_active_votes()
    # Запуск потоков и процессов
    processes = []
    file_globals.processing = True
    file_globals.began = True
    # Поток, сохраняющий user_data на диск
    save_user_data = threading.Thread(target=save_data, name="Save User Data", args=())
    save_user_data.start()
    processes.append(save_user_data)

    unloading_resources = threading.Thread(target=resources_monitor, name="Castle Unloading Resources", args=())
    unloading_resources.start()
    processes.append(unloading_resources)

    mobs_messages_updating = threading.Thread(target=mobs_messages_update_monitor,
                                              name="Mobs messages update Monitor", args=())
    mobs_messages_updating.start()
    processes.append(mobs_messages_updating)

    if enable_telethon:
        telethon_script = multiprocessing.Process(target=script_work, name="Telethon Parse Channels", args=())
        telethon_script.start()
        processes.append(telethon_script)

        parse_stats_pr = threading.Thread(target=parse_stats, name="Stats Parse")
        parse_stats_pr.start()
        processes.append(parse_stats_pr)

    if enable_api:
        api = threading.Thread(target=start_api, args=[])
        api.start()
        processes.append(api)

        players_update = threading.Thread(target=players_update_monitor, args=[])
        players_update.start()
        processes.append(players_update)

    # text = """"""
    # direct_send_message([485596730, 455422372, 575592214, 683640549, 669515343, 260550882, 187299899], text)

    if CONNECT_TYPE == 'webhook':
        updater.start_webhook(listen='0.0.0.0',
                              port=80,
                              url_path=Production_castle_token,
                              key='./private.key',
                              cert='./cert.pem',
                              webhook_url='https://{}:80/{}'.format(ServerIP, Production_castle_token))
        # updater.bot.setWebhook('https://{}:443/{}'.format(ServerIP, Production_castle_token),
        #                                                   # certificate='./cert.pem')
    else:
        updater.start_polling(clean=False)

    ask_to_revoke_duty_link()

    updater.idle()
    file_globals.processing = False
    cwapi.stop()
    castles_stats_queue.put(None)
    save_user_data.join()
    conn.close()
    exit(0)