def pult_callback(bot, update): update.callback_query.data = update.callback_query.data.partition("_")[0] data = update.callback_query.data try: fill_mid_players(other_process=True) # TODO сделать нормально except Exception: logging.error(traceback.format_exc()) if not check_access(update.callback_query.from_user.id): return if data == "ps": pult_send(bot, update) return if data.find("pdv") == 0: pult_divisions_callback(bot, update) return if data.find("pc") == 0: pult_castles_callback(bot, update) return if data.find("pt") == 0: pult_time_callback(bot, update) return if data.find("pds") == 0: pult_defense_callback(bot, update) return if data.find("pdt") == 0: pult_tactics_callback(bot, update) return if data.find("pp") == 0: pult_potions_callback(bot, update) return
def battle_equip(bot, update): mes = update.message if not check_access(mes.from_user.id): return battle_id = re.search("\\d+", mes.text) if battle_id is None: battle_id = count_battle_id(mes) else: battle_id = int(battle_id.group(0)) full = 'full' in mes.text request = "select player_id, equip from reports where battle_id = %s and equip is not null " \ "order by equip ->> 'status'" cursor.execute(request, (battle_id, )) rows = cursor.fetchall() response = "Дроп с битвы {} - {} :\n".format( battle_id, count_battle_time(battle_id).strftime("%d/%m/%y %H:%M:%S")) for row in rows: name, found_from = row[1].get("name"), row[1].get("from") player = Player.get_player(row[0]) response += "{}<b>{}</b> {}\n".format( "{} ".format((player.castle + player.nickname) if full else ""), name, "(От {})".format(found_from) if found_from is not None else "") bot.send_message(chat_id=mes.chat_id, text=response, parse_mode='HTML')
def remove_trigger(bot, update): mes = update.message if filter_is_pm(mes): return if mes.from_user.id not in get_admin_ids(bot=bot, chat_id=mes.chat_id): bot.send_message(chat_id=mes.chat_id, text="Доступ только у админов.", reply_to_message_id=mes.message_id) return text = mes.text.partition(" ")[2].lower() chat_id = mes.chat_id trigger_list = triggers_in.get(mes.chat_id) if trigger_list is None or text not in trigger_list: chat_id = 0 if text in global_triggers_in: if not check_access(mes.from_user.id): bot.send_message( chat_id=mes.chat_id, text="Недостаточно прав для удаления глобального триггера", reply_to_message_id=mes.message_id) return else: bot.send_message(chat_id=mes.chat_id, text="Триггер не найден", reply_to_message_id=mes.message_id) return trigger_list = global_triggers_in trigger_list.remove(text) request = "delete from triggers where text_in = %s and chat_id = %s" cursor.execute(request, (text, chat_id)) bot.send_message(chat_id=mes.chat_id, text="Триггер успешно удалён!", reply_to_message_id=mes.message_id)
def send_variant(bot, update): data = update.callback_query.data try: fill_mid_players(other_process=True) # TODO сделать нормально except Exception: logging.error(traceback.format_exc()) if not check_access(update.callback_query.from_user.id): return variant_id = re.search("_(\\d+)", data) if variant_id is None: bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text="Ошибка поиска варианта", show_alert=True) return variant_id = int(variant_id.group(1)) order = Pult.variants.get(variant_id) if order is None: bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text="Ошибка поиска варианта", show_alert=True) return send_order(bot=bot, chat_callback_id=update.callback_query.message.chat_id, divisions=order.divisions, castle_target=order.target, defense=order.defense, tactics=order.tactics, potions=order.potions, time=None) bot.answerCallbackQuery(callback_query_id=update.callback_query.id)
def view_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)) request = "select name, text, variants, started, duration, classes from votes where id = %s" cursor.execute(request, (vote_id,)) row = cursor.fetchone() if row is None: bot.send_message(chat_id=mes.chat_id, text="Голосование не найдено.") return response = "Голосование <b>{}</b>\n".format(row[0]) response += row[1] + "\n\n" response += "Начало: <code>{}</code>\n".format(row[3].strftime("%d/%m/%y %H:%M:%S") if row[3] is not None else "Не началось.") response += "Длительность: <code>{}</code>\n".format(row[4] if row[4] is not None else "Не задано.") cl_text = "" if all(row[5]) or not row[5]: cl_text = "ВСЕ" else: for i, b in enumerate(row[5]): cl_text += classes_list[i] if b else "" response += "Классы: <code>{}</code>\n".format(cl_text) if row[3] is None: response += "Изменить длительность: /change_vote_duration_{}\n".format(vote_id) response += "Начать голосование: /start_vote_{}\n".format(vote_id) response += "\nИзменить классы для голосований: /set_vote_classes_{} [Классы, которые ПРИНИМАЮТ участие " \ "в голосовании]\n\n<em>Классы ТОЛЬКО как в списке: {}</em>".format(vote_id, classes_list) print(response) bot.send_message(chat_id=mes.chat_id, text=response, parse_mode='HTML')
def set_status(bot, update): mes = update.message if not check_access(mes.from_user.id): return parse = re.search("set_status (\\d+) (.*)", mes.text) if parse is None: bot.send_message(chat_id=mes.chat_id, text="Неверный синтаксис", reply_to_message_id=mes.message_id) return player_id = int(parse.group(1)) new_status = parse.group(2) player = Player.get_player(player_id, notify_on_error=False) if player is None: bot.send_message(chat_id=mes.chat_id, text="Игрок не найден.", reply_to_message_id=mes.message_id) return if new_status == "": player.status = None else: player.status = new_status player.update() bot.send_message(chat_id=mes.chat_id, text="Обновление статуса успешно!", reply_to_message_id=mes.message_id)
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()
def finish_vote(bot, update, user_data): mes = update.message if not check_access(mes.from_user.id): return name, variants, text = user_data.get("vote_name"), user_data.get("vote_variants"), user_data.get("vote_text") if not all([name, variants, text]): bot.send_message(chat_id=mes.chat_id, text="Все этапы должны быть заполнены перед запуском голосования") choices = {} for i in range(len(variants)): choices.update({i: []}) choices = json.dumps(choices) request = "insert into votes(name, text, variants, choices) VALUES (%s, %s, %s, %s) returning id" cursor.execute(request, (name, text, variants, choices)) row = cursor.fetchone() if row is None: bot.send_message(chat_id=mes.chat_id, text="Произошла ошибка. Возможно, голосование всё же создалось, " "проверьте: /vote") return bot.send_message(chat_id=mes.chat_id, text="Голосование <b>{}</b> успешно создано.\n" "Просмотреть голосование: /view_vote_{}".format(name, row[0]), parse_mode='HTML') user_data.pop("vote_name") user_data.pop("vote_variants") user_data.pop("vote_text") user_data.pop("status")
def notify_guild_to_battle(bot, update): mes = update.message chat_dict = ping_by_chat_id.get(mes.chat_id) if chat_dict is None: return if mes.from_user.id not in get_admin_ids( bot, chat_id=mes.chat_id) and not check_access(mes.from_user.id): bot.send_message(chat_id=mes.chat_id, text="Доступ только у админов", parse_mode='HTML') return if mes.text.partition("@")[0].split("_")[2] == "sleeping": target_list = chat_dict.get("sleeping") else: target_list = chat_dict.get("do not ready") i = 0 response = "" for username in target_list: if i >= 4: response += "\n БИТВА!" bot.send_message(chat_id=mes.chat_id, text=response) response = "" i = 0 response += "@{0} ".format(username) i += 1 response += "\n БИТВА!" bot.send_message(chat_id=mes.chat_id, text=response)
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')
def reward_read_only(player, reward, cost, *args, **kwargs): mute_player = Player.get_player(reward) if mute_player is None: player.reputation += cost player.update() dispatcher.bot.send_message(player.id, text="Игрок не найден. Жетоны возвращены.") return if check_access(mute_player.id): # Хотят забанить чела из мида muted_players.update( {mute_player.id: time.time() + FORBID_MUTED_MINUTES * 60}) dispatcher.bot.send_message( chat_id=mute_player.id, text= "Ты протягиваешь кошель с жетонами стражнику, шепча на ухо имя бедолаги.\n" "-\"ШО, ПРЯМ СОВЕТНИКА КОРОЛЯ, ЗА ТАКИЕ-ТО ДЕНЬГИ?!\"\n" "Стражники скручивают тебя и кидают в темницу. Пять минуток " "посидишь - поумнеешь.") else: muted_players.update( {mute_player.id: time.time() + MUTED_MINUTES * 60}) dispatcher.bot.send_message( chat_id=mute_player.id, text= "\"Стражу подкупили!\" - кричишь ты, пока тебя утаскивают в одиночку " "на ближайшие пол часа.\nОтличное время подумать, где и когда ты умудрился " "нажить себе врагов, что аж жетонов не пожалели, чтобы тебе насолить.\n" "<em>30 минут вы не можете ничего писать в чатах с ботом.</em>", parse_mode='HTML')
def revoke_all_class_links(bot, update): if not check_access(update.message.from_user.id): return barracks = Location.get_location(1) barracks.special_info.update({"class_links": {}}) barracks.update_location_to_database() bot.send_message(chat_id=update.message.chat_id, text="Все ссылки сброшены!")
def del_quest(bot, update, guild=None): mes = update.message guild = mes.text.replace('/del_quest ', '').strip() if not check_access(mes.from_user.id): return if guild: quest = GuildQuest() quest.del_quest(guild) bot.send_message(chat_id=mes.chat_id, text="Квест удален.")
def add_vote_variant(bot, update, user_data): mes = update.message if not check_access(mes.from_user.id): return variants = user_data.get("vote_variants") if variants is None: variants = [] user_data.update({"vote_variants": variants}) variants.append(mes.text) bot.send_message(chat_id=mes.chat_id, text="Вариант добавлен. Введите ещё один, или нажмите /finish_vote")
def create_vote(bot, update, user_data): mes = update.message if not check_access(mes.from_user.id): return vote_name = mes.text.partition(" ")[2] if vote_name is None or len(vote_name) <= 1: bot.send_message(chat_id=mes.chat_id, text="Необходимо задать имя голосования в аргументах.") return user_data.update({"status": "creating_vote_text", "vote_name": vote_name, "vote_variants": [], "vote_text": ""}) bot.send_message(chat_id=mes.chat_id, text="Голосование создаётся. Введите текст голосования.")
def class_chat_check(mes): if mes.from_user.id in [CASTLE_BOT_ID, SUPER_ADMIN_ID, king_id ] or check_access(mes.from_user.id): return False if mes.new_chat_members is not None: users = mes.new_chat_members else: users = [mes.from_user] for user in users: player = Player.get_player(user.id) if player is None or player.game_class is None or class_chats.get(player.game_class) != mes.chat_id or \ player.castle != '🖤': return True return False
def castle_chat_check(message): if message.new_chat_members: users = message.new_chat_members else: users = [message.from_user] for user in users: player = Player.get_player(user.id) if message.from_user.id in [CASTLE_BOT_ID, SUPER_ADMIN_ID, king_id ] or check_access(message.from_user.id): return False if player is None: return True if player is None or player.castle != '🖤': return True return False
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')
def change_reputation(bot, update): mes = update.message if not check_access(mes.from_user.id): bot.send_message(chat_id=mes.chat_id, text="Доступ запрещен.") return parse = re.search(" (\\d+) (-?\\d+)", mes.text) if parse is None: bot.send_message( chat_id=mes.chat_id, text= "Неверный синтаксис. Пример: /change_reputation 205356091 10000") return player_id, add_reputation = int(parse.group(1)), int(parse.group(2)) if change_player_reputation(player_id, add_reputation) == 1: bot.send_message(chat_id=mes.chat_id, text="Игрок не найден") else: bot.send_message(chat_id=mes.chat_id, text="🔘Жетоны изменены.")
def check_ban_in_duty_chat(bot, update): """ Функция, которая проверяет, можно ли игроку зайти (и писать) в чат стражи """ gates = Location.get_location(3) players_on_duty = gates.special_info.get("players_on_duty") user_id = update.message.from_user.id player = Player.get_player(user_id) if player is not None and player.game_class == 'Sentinel': # Временно разрешено находиться в чате всем стражам return if user_id not in players_on_duty and not check_access( user_id) and user_id != CASTLE_BOT_ID: bot.kickChatMember(chat_id=SENTINELS_DUTY_CHAT_ID, user_id=update.message.from_user.id) bot.send_message( chat_id=SENTINELS_DUTY_CHAT_ID, text="Только стражам на службе разрешён вход в этот чат")
def guild_quests(bot, update): mes = update.message if not check_access(mes.from_user.id): return quests = GuildQuest.all_quests() text = '' for quest in quests: date = datetime.datetime.fromtimestamp( quest.last_update).strftime('%Y-%m-%d %H:%S') text += '<code>{}</code> {} <code>{}</code> {}\n'.format( quest.guild.ljust(3, ' '), quest.castle, quest.percent.rjust(5, ' '), date) if text: bot.send_message(chat_id=mes.chat_id, text=text, parse_mode='HTML') return bot.send_message(chat_id=mes.chat_id, text='Квестов нет', parse_mode='HTML')
def change_guilds_reputation(bot, update): mes = update.message if not check_access(mes.from_user.id): bot.send_message(chat_id=mes.chat_id, text="Доступ запрещен.") return parse = re.search("( (.+))* (-?\\d+)", mes.text) tags = parse.group(2).split() add_reputation = int(parse.group(3)) success, failed = "", "" for tag in tags: if change_guild_reputation(tag, add_reputation) == 0: success += "{} ".format(tag) else: failed += "{} ".format(tag) bot.send_message(chat_id=mes.chat_id, text="Успешно: <b>{}</b>\n" "Неудачно (не найдены гильдии): <b>{}</b>".format( success, failed), parse_mode='HTML')
def remove_players_from_chat(bot, update): message = update.message if message.new_chat_members: users = message.new_chat_members else: users = [message.from_user] for user in users: user_id = user.id player = Player.get_player(user.id) if message.from_user.id in [CASTLE_BOT_ID, SUPER_ADMIN_ID, king_id ] or check_access(message.from_user.id): return if player is None or player.castle != '🖤': try: text = "Этот чат только для игроков 🖤Скалы" bot.kickChatMember(chat_id=message.chat_id, user_id=user_id) bot.send_message(chat_id=message.chat_id, text=text, parse_mode='HTML') except TelegramError: pass
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')
def set_castle_chat(bot, update): mes = update.message if mes.from_user.id != SUPER_ADMIN_ID and not check_access( mes.from_user.id): return if mes.chat_id == mes.from_user.id: bot.send_message(chat_id=mes.chat_id, text="Команда запрещена в ЛС") return on = 'on' in update.message.text if on: if mes.chat_id in castle_chats: bot.send_message(chat_id=mes.chat_id, text="Чат уже установлен как замковый") return castle_chats.append(mes.chat_id) text = "Чат отмечен как замковый. Бот будет удалять любых участников не из Скалы, " \ "или с отсутствующими профилями" else: if mes.chat_id not in castle_chats: bot.send_message(chat_id=mes.chat_id, text="Чат и так не замковый") return castle_chats.remove(mes.chat_id) text = "Теперь чат разрешён для всех участников." bot.send_message(chat_id=mes.chat_id, text=text)
def filter(self, message): fill_mid_players(other_process=True) return check_access(message.from_user.id)
def notify_guild_attack(bot, update): mes = update.message remaining_time = get_time_remaining_to_battle() forward_message_date = utc.localize( mes.forward_date).astimezone(tz=moscow_tz).replace(tzinfo=None) if forward_message_date - datetime.datetime.now() > datetime.timedelta( minutes=2): return 0 if remaining_time > datetime.timedelta(minutes=30): pass return 0 ready_to_battle = mes.text.count("[⚔]") + mes.text.count("[🛡]") sleeping = mes.text.count("[🛌]") + mes.text.count("[⚒]") response = "<b>{0}</b>\nГотово к битве: <b>{1}</b>\nНе готово к битве, но занято <b>{2}</b>\n" \ "Спит: <b>{3}</b>\n\nВремя до битвы: {4}\n".format(mes.text.splitlines()[0], ready_to_battle, mes.text.count("\n") - ready_to_battle - sleeping, sleeping, ":".join(str(remaining_time).partition(".")[0].split(":")[0:3])) request = "select guild_id from guilds where chat_id = %s" cursor.execute(request, (mes.chat_id, )) row = cursor.fetchone() if row is None: return guild = Guild.get_guild(guild_id=row[0]) set = guild.settings.get( "battle_notify") if guild.settings is not None else True if guild is None or set is False: return if mes.chat_id != guild.chat_id: return if mes.from_user.id not in get_admin_ids( bot, chat_id=mes.chat_id) and not check_access(mes.from_user.id): bot.send_message(chat_id=mes.chat_id, text="Доступ только у админов", parse_mode='HTML', reply_to_message_id=mes.message_id) return do_not_ready = [] sleeping = [] for string in mes.text.splitlines()[1:]: if not ("[⚔]" in string or "[🛡]" in string): nickname = string.partition("]")[2][1:] do_not_ready.append(nickname) if "[🛌]" in string or "[⚒]" in string: sleeping.append(nickname) in_dict_do_not_ready = [] in_dict_sleeping = [] ping_dict = { "do not ready": in_dict_do_not_ready, "sleeping": in_dict_sleeping } for player_id in guild.members: player = Player.get_player(player_id, notify_on_error=False) if player is None: continue db_nickname = player.nickname.partition("]")[2] if db_nickname in do_not_ready: in_dict_do_not_ready.append(player.username) if db_nickname in sleeping: in_dict_sleeping.append(player.username) ping_by_chat_id.update({mes.chat_id: ping_dict}) response += "Пингануть тех, кто спит: /notify_guild_sleeping\n" \ "Пингануть всех, кто не готов: /notify_guild_not_ready" bot.send_message(chat_id=mes.chat_id, text=response, parse_mode='HTML')
def filter(self, message): if isinstance(message, Update): message = message.message if message is None: return False return check_access(message.from_user.id)
def get_general_buttons(user_data, player=None, only_buttons=False): status = user_data.get("status") rp_off = user_data.get("rp_off") buttons = None if rp_off and status in ["central_square", "rp_off"]: buttons = [[ KeyboardButton("👀 Профиль"), KeyboardButton("👥 Гильдия"), KeyboardButton("📈Топы"), ], [ KeyboardButton("🔖Связь с МИД"), KeyboardButton("🗂Обновления"), KeyboardButton("📰Инструкция"), ]] if player is not None: if player.guild is not None: guild = Guild.get_guild(player.guild) if guild is not None: if guild.check_high_access(player.id): pass # buttons[0].append(KeyboardButton("📜Список гильдий")) elif status is None or status in ["default", "central_square"]: status = "central_square" user_data.update({"status": status}) buttons = [ [ KeyboardButton(Location.get_location(1).name), KeyboardButton(Location.get_location(2).name), KeyboardButton("⛩ Врата замка"), ], [ KeyboardButton("🔭 Башня ТехМаг наук"), # ❗ KeyboardButton("🏤Мандапа Славы"), # KeyboardButton("📈Топы"), # KeyboardButton("🏚 Не построено"), ], [ KeyboardButton("↔️ Подойти к указателям"), KeyboardButton("🏚 Стройплощадка"), # KeyboardButton("↩️ Назад"), ] ] # Стройка Мандапы Славы окончена # hall = Location.get_location(8) # if hall is not None and hall.is_constructed(): # buttons[1].insert(1, KeyboardButton("🏤Мандапа Славы")) tea_party = Location.get_location(9) if tea_party is not None and tea_party.is_constructed(): buttons[1].insert(2, KeyboardButton("🍵Чайная лига")) elif status == 'barracks': buttons = [[ KeyboardButton("👀 Посмотреть в зеркало"), KeyboardButton("👥 Посмотреть ведомость гильдии"), ], [ KeyboardButton("↩️ Назад"), ]] if player is not None: if player.guild is not None: guild = Guild.get_guild(player.guild) if guild is not None: if guild.alliance_id is not None: buttons.insert(1, [KeyboardButton(" 🤝Альянс")]) if guild.check_high_access(player.id): pass # buttons.insert(1, [KeyboardButton("📜Изучить список гильдий")]) elif status == 'throne_room': buttons = [ [ KeyboardButton("Обратиться к командному составу"), KeyboardButton("Попросить аудиенции у 👑Короля"), ], [ KeyboardButton("🎇Посмотреть на портреты"), # KeyboardButton("💰Сокровищница"), ], [ KeyboardButton("↩️ Назад"), ] ] if player is not None and check_access(player.id): buttons[1].append(KeyboardButton("Штаб")) if player is not None and player.id in [king_id, SUPER_ADMIN_ID]: buttons[1].append(KeyboardButton("Кабинет Короля")) elif status in [ 'mid_feedback', 'duty_feedback', 'sending_guild_message', 'editing_debrief', 'changing_castle_message', 'sending_bot_guild_message', 'editing_update_message', "treasury", "awaiting_roulette_bet" ]: buttons = [[ KeyboardButton("↩️ Назад"), ]] elif status in ["sawmill", "quarry", "construction", "exploration", "pit"]: buttons = [[ KeyboardButton("👀 Профиль"), ], [ KeyboardButton("↩️ Отмена"), ]] elif status == 'castle_gates': on_duty = user_data.get("on_duty") print(on_duty, user_data) if on_duty: buttons = [ [ KeyboardButton("Покинуть вахту"), ], ] else: buttons = [[ KeyboardButton("🌲Лесопилка"), KeyboardButton("⛰Каменоломня"), ], [ KeyboardButton("Обратиться к 💂♂Стражам"), ], [ KeyboardButton("↩️ Назад"), ]] print(player, player.game_class if player is not None else "") if player is not None and player.game_class == "Sentinel": # Только для стражей, захардкожено buttons[0].append(KeyboardButton("Заступить на вахту")) elif status == 'king_cabinet': buttons = [[ KeyboardButton("Добавить генерала"), KeyboardButton("Изменить сообщение"), ], [ KeyboardButton("Начать стройку"), ], [ KeyboardButton("↩️ Назад"), ]] elif status == 'headquarters': buttons = [[ KeyboardButton("📜Выкатить дебриф"), KeyboardButton("📣Рассылка по гильдиям"), ], [ KeyboardButton("↩️ Назад"), ]] elif status == 'technical_tower': buttons = [ [ # KeyboardButton("🔖Обратиться к магу"), KeyboardButton("📰Манускрипт"), KeyboardButton("🗂Архив объявлений"), ], [ KeyboardButton("🧾История коммитов"), ], [ KeyboardButton("↩️ Назад"), ] ] if player is not None and player.id == SUPER_ADMIN_ID: buttons[1].insert(1, KeyboardButton("💻Кабинет ботодела")) elif status == 'my_cabinet': buttons = [[ KeyboardButton("📈Выкатить обнову"), KeyboardButton("📣Рассылка по гильдиям"), ], [ KeyboardButton("↩️ Назад"), ]] elif status == 'construction_plate': location = Location.get_location(status_to_location.get(status)) buttons = location.buttons elif status == 'hall_of_fame': buttons = [ [ KeyboardButton("📈Топы"), # KeyboardButton("📣Ещё кнопка, хз что"), ], [ KeyboardButton("↩️ Назад"), ] ] elif status == 'tops': buttons = [[ KeyboardButton("⚔️Атака"), KeyboardButton("🛡Защита"), KeyboardButton("🔥Опыт"), ], [ KeyboardButton("↩️ Назад"), ]] if not rp_off: buttons.insert(1, [ KeyboardButton("🌲Дерево"), KeyboardButton("⛰Камень"), KeyboardButton("🏚Стройка"), ]) elif status == 'manuscript': buttons = [ [ KeyboardButton("👤Игроки"), KeyboardButton("👥Гильдии"), KeyboardButton("📓Гайды"), ], [ KeyboardButton("🖋Триггеры"), KeyboardButton("📦Сток"), # KeyboardButton("🏠Профсоюзы"), ], [ KeyboardButton("↩️ Назад"), ] ] if not rp_off: buttons[1].insert(0, KeyboardButton("↔️Указатели")) elif status == 'guides': buttons = [[ KeyboardButton("⚗️Алхимик"), KeyboardButton("⚒Кузнец"), KeyboardButton("📦Добытчик"), ], [ KeyboardButton("🏹Лучник"), KeyboardButton("⚔Рыцарь"), KeyboardButton("🛡Защитник"), ], [ KeyboardButton("↩️ Назад"), ]] elif status == 'tea_party': buttons = [ # [ # KeyboardButton("Разведка"), # KeyboardButton("Рыть котлован"), # ], [ KeyboardButton("🎰Рулетка"), KeyboardButton("💲Магазин статусов"), ], [ KeyboardButton("🧳Контрабандист"), ], [ KeyboardButton("↩️ Назад"), ], ] elif status == 'roulette': buttons = [ [ KeyboardButton("🔸Сделать ставку"), KeyboardButton("📈Топы в рулетке"), ], [KeyboardButton("↩️ Назад")], ] if only_buttons or buttons is None: return buttons return ReplyKeyboardMarkup(buttons, resize_keyboard=True)
def check_whois_access(user_id): try: return check_access(user_id) or user_id == MERC_ID or user_id in trade_divisions_access_list or \ Guild.get_guild(guild_tag="АКАДЕМИЯ").check_high_access(user_id) except Exception: return False