コード例 #1
0
def matchmaking_start(bot, update, user_data):
    if user_data.get("status") != "In Location":
        bot.send_message(chat_id=update.message.chat_id,
                         text="Сейчас вы заняты чем-то ещё")
        return
    group = user_data.get("battle_group")
    if group is not None and group.creator != update.message.chat_id:
        bot.send_message(chat_id=update.message.chat_id,
                         text="Только лидер группы может начинать поиск")
        return
    user_data.update(matchmaking=[0, 0, 0])
    button_list = [
        InlineKeyboardButton("1 x 1", callback_data="mm 1x1"),
        InlineKeyboardButton("3 x 3", callback_data="mm 3x3"),
        InlineKeyboardButton("5 x 5", callback_data="mm 5x5")
    ]
    footer_buttons = [
        InlineKeyboardButton("Начать поиск", callback_data="mm start")
    ]
    reply_markup = InlineKeyboardMarkup(
        build_menu(button_list, n_cols=3, footer_buttons=footer_buttons))
    bot.send_message(chat_id=update.message.chat_id,
                     text="Выберите настройки битвы:\n\n{0}".format(
                         "Информация по группе: /group_info" if user_data.
                         get("battle_group") else ""),
                     reply_markup=reply_markup)
コード例 #2
0
def get_allies_buttons(battle, team):
    __ally_buttons = []
    ally_team = battle.teams[team]
    for i in ally_team:
        __ally_buttons.append(KeyboardButton(i.participant.nickname))
    __ally_buttons.append(KeyboardButton('Отмена'))
    return ReplyKeyboardMarkup(build_menu(__ally_buttons, 2),
                               resize_keyboard=True)
コード例 #3
0
def get_enemies_buttons(battle, team):
    enemy_team_n = (team + 1) % 2
    __enemies_buttons = []
    enemy_team = battle.teams[enemy_team_n]
    for i in enemy_team:
        __enemies_buttons.append(KeyboardButton(i.participant.nickname))
    __enemies_buttons.append(KeyboardButton('Отмена'))
    return ReplyKeyboardMarkup(build_menu(__enemies_buttons, 2),
                               resize_keyboard=True)
コード例 #4
0
ファイル: lvl_up_player.py プロジェクト: Cactiw/UText_bot
def choose_points(bot, update, user_data):
    id = update.message.from_user.id
    player = get_player(id)
    if(player is None):
        return
    free_points = player.free_points
    if(free_points < 0):
        player.free_points = 0
        free_points = 0
    if(free_points == 0):
        bot.send_message(chat_id = update.message.chat_id, text = "У вас нет свободных очков\n\n"
                                                                  "Выносливость - <b>{0}</b>\nБроня - <b>{1}</b>\n"
                                                                  "Сила - <b>{2}</b>\nСкорость - <b>{3}</b>\n"
                                                                  "Заряд - <b>{4}</b>".format(
            player.stats.get("endurance"), player.stats.get("armor"),
            player.stats.get("power"), player.stats.get("speed"),
            player.stats.get("charge")),
                         parse_mode = "HTML", reply_markup = ReplyKeyboardRemove())
        player.update_stats()
        players.update({id: player})
        players_need_update.put(player)
        update_status(user_data.get('saved_lvl_up_status'), player, user_data)
        user_data.pop('saved_lvl_up_status')
        player.update_stats()
        show_general_buttons(bot, update, user_data)
        return

    update_status("Lvl_up_points", player, user_data)
    button_list = [
        KeyboardButton("Выносливость"),
        KeyboardButton("Броня"),
        KeyboardButton("Сила"),
        KeyboardButton("Скорость"),
        KeyboardButton("Заряд"),
        KeyboardButton("Готово")
    ]
    buttons = ReplyKeyboardMarkup(build_menu(button_list, n_cols=2), resize_keyboard=True, one_time_keyboard=False)
    s = ''
    if free_points == 1:
        s = "характеристику"
    elif free_points >= 2 or free_points <= 4:
        s = "характеристики"
    elif free_points >= 5:
        s = "характеристик"
    bot.send_message(chat_id=update.message.chat_id,
                     text="Вы можете улучшить <b>{5}</b> {6}\n\nВыберите характеристику, которую хотите улучшить\n"
                          "Выносливость - <b>{0}</b>\nБроня - <b>{1}</b>\n"
                          "Сила - <b>{2}</b>\nСкорость - <b>{3}</b>\n"
                          "Заряд- <b>{4}</b>".format(player.stats.get("endurance"), player.stats.get("armor"),
                                                     player.stats.get("power"), player.stats.get("speed"),
                                                     player.stats.get("charge"), free_points, s),
                     parse_mode='HTML', reply_markup=buttons)
    players.update({id: player})
    players_need_update.put(player)
コード例 #5
0
ファイル: battle_group.py プロジェクト: Cactiw/UText_bot
def group_invite(bot, update, user_data):
    mes = update.message
    group = user_data.get("battle_group")
    if group is None:
        group = BattleGroup(mes.from_user.id)
        user_data.update({"battle_group": group})
    elif group.creator != mes.from_user.id:
        bot.send_message(
            chat_id=mes.from_user.id,
            text=
            "Вы не являетесь создателем группы и не можете приглашать в неё новых игроков"
        )
        return
    id = mes.text.partition(" ")[2]
    if not id.isdigit():
        request = "select id from players where nickname = %s"
        cursor.execute(request, (id, ))
        row = cursor.fetchone()
        if row is None:
            bot.send_message(
                chat_id=mes.from_user.id,
                text="Игрок не найден. Проверьте правильность ввода.")
            return
        id = row[0]
    creator = get_player(mes.from_user.id)
    invited_player = get_player(id, notify_not_found=False)
    if invited_player is None:
        bot.send_message(chat_id=mes.from_user.id,
                         text="Игрок не найден. Проверьте правильность ввода.")
        return
    if dispatcher.user_data.get(id).get("battle_group") is not None:
        bot.send_message(chat_id=mes.from_user.id,
                         text="Данный игрок уже находится в группе.")
        return
    group.invitations.append(id)
    buttons = [
        InlineKeyboardButton("Да",
                             callback_data="bgiy {0}".format(
                                 mes.from_user.id)),
        InlineKeyboardButton("Нет",
                             callback_data="bgin {0}".format(mes.from_user.id))
    ]
    reply_markup = InlineKeyboardMarkup(build_menu(buttons, 2))
    bot.send_message(
        chat_id=id,
        text="<b>{0}</b> пригласил вас в свою группу. Вы примете приглашение?".
        format(creator.nickname),
        parse_mode='HTML',
        reply_markup=reply_markup)
    bot.send_message(chat_id=mes.from_user.id,
                     text="Приглашение игроку <b>{0}</b> отправлено!".format(
                         invited_player.nickname),
                     parse_mode='HTML')
コード例 #6
0
ファイル: pult.py プロジェクト: Cactiw/Dark-Desire-Damage-Bot
def build_pult(pult):
    castles = pult.castles
    twinks = pult.twinks
    __pult_buttons = []
    __castle_buttons = [
        [
            InlineKeyboardButton(castles[0], callback_data="pc0"),
            InlineKeyboardButton(castles[1], callback_data="pc1"),
            InlineKeyboardButton(castles[2], callback_data="pc2"),
        ],
        [
            InlineKeyboardButton(castles[3], callback_data="pc3"),
            InlineKeyboardButton(castles[4], callback_data="pc4"),
            InlineKeyboardButton(castles[5], callback_data="pc5"),
        ],
        [
            InlineKeyboardButton(castles[6], callback_data="pc6"),
        ],
        [
            InlineKeyboardButton("🆗 Подтвердить", callback_data="pok"),
        ]
    ]
    print(pult.real_account)
    print(twinks)
    if not pult.real_account:
        for id in list(twinks):
            twink = twinks.get(id)
            if twink.real_account:
                continue
            print(twink.current_castle)
            __pult_buttons.append(InlineKeyboardButton(twink.current_castle + twink.username, callback_data='ptn {0}'.format(id)))
        menu = build_menu(__pult_buttons, 3)
        for castle_row in __castle_buttons:
            menu.append(castle_row)
    else:
        menu = __castle_buttons
    reply_markup = InlineKeyboardMarkup(menu)
    return reply_markup
コード例 #7
0
def get_general_battle_buttons(player):
    user_data = dispatcher.user_data.get(player.id)
    if user_data and user_data.get('status') == "Battle_dead":
        return ReplyKeyboardRemove()
    stun = dispatcher.user_data.get(player.id).get('stunned')
    if stun is not None and stun > 0:
        #return ReplyKeyboardRemove()
        return None
    __general_battle_buttons = []
    n_cols = 3
    class_skills = skills.get(player.game_class)
    for i in class_skills.values():
        if i.priority == 0:
            continue
        if i.priority == 10:
            __general_battle_buttons.append(KeyboardButton(i.name))
            n_cols += 1
            continue
        if player.skill_lvl.get(i.name) > 0:
            __general_battle_buttons.append(KeyboardButton(i.name))
            n_cols += 1
    __general_battle_buttons.append(
        KeyboardButton('Использовать предмет')
    )  #TODO Сделать использование предметов в сообщении по /use_
    __general_battle_buttons.append(KeyboardButton('Голосование ((флекс))'))
    __general_battle_buttons.append(KeyboardButton('Пропуск хода'))
    if n_cols % 2 == 0:
        n_cols = 2
    elif n_cols % 3 == 0:
        n_cols = 3
    elif n_cols == 5:
        n_cols = 2
    elif n_cols == 7:
        n_cols = 3
    else:
        n_cols = 2
    return ReplyKeyboardMarkup(build_menu(__general_battle_buttons, n_cols),
                               resize_keyboard=True)
コード例 #8
0
ファイル: location_buttons.py プロジェクト: Cactiw/UText_bot
from telegram import KeyboardButton, ReplyKeyboardMarkup
from work_materials.globals import build_menu

__capital_button_list = [
    KeyboardButton('Инфо'),
    KeyboardButton('Доска объявлений'),
    KeyboardButton('Аукцион'),
    KeyboardButton('Торговец'),
    KeyboardButton('Таверна'),
    KeyboardButton('Битва'),
    KeyboardButton('Отправиться')
]
capital_buttons = ReplyKeyboardMarkup(build_menu(__capital_button_list, n_cols=2), resize_keyboard=True)

__guild_button_list = [
    KeyboardButton('Доска объявлений'),
    KeyboardButton('Кузнец'),
    KeyboardButton('Алхимическая станция'),
    KeyboardButton('Стол зачарования'),  #Может стоить объеденить в какую-нибудь кнопку, придумай название
    KeyboardButton('Инфо'),
    KeyboardButton('Отправиться')
]
guild_buttons = ReplyKeyboardMarkup(build_menu(__guild_button_list, n_cols=2), resize_keyboard=True)

__location_button_list = [
    KeyboardButton('Инфо'),
    KeyboardButton('Исследовать'),  #фарм
    KeyboardButton('Отправиться')  #TODO Добавить еще кнопок
]
farmLocation_buttons = ReplyKeyboardMarkup(build_menu(__location_button_list, n_cols=2), resize_keyboard=True)
コード例 #9
0
ファイル: lvl_up_player.py プロジェクト: Cactiw/UText_bot
def choose_skill(bot, update, user_data):
    id = update.message.from_user.id
    player = get_player(id)
    if player is None:
        return
    free_skill = player.free_skill_points
    if free_skill < 0:
        player.free_skill_points = 0
        free_skill = 0
    if free_skill == 0:
        button_list = [
            KeyboardButton("Выносливость"),
            KeyboardButton("Броня"),
            KeyboardButton("Сила"),
            KeyboardButton("Скорость"),
            KeyboardButton("Заряд"),
            KeyboardButton("Готово")
        ]
        buttons = ReplyKeyboardMarkup(build_menu(button_list, n_cols=2), resize_keyboard=True, one_time_keyboard=False)
        bot.send_message(chat_id = update.message.chat_id,
                         text = "У вас нет очков навыков\n\n"
                                 "{5} - {0}-го уровня\n{6} - {1}-го уровня\n"
                                 "{7} - {2}-го уровня\n{8} - {3}-го уровня\n"
                                 "{9} - {4}-го уровня".format(list(player.skill_lvl.values())[0], list(player.skill_lvl.values())[1],
                                                              list(player.skill_lvl.values())[2], list(player.skill_lvl.values())[3],
                                                              list(player.skill_lvl.values())[4], list(player.skill_lvl)[0],
                                                              list(player.skill_lvl)[1], list(player.skill_lvl)[2],
                                                              list(player.skill_lvl)[3], list(player.skill_lvl)[4]),
                         reply_markup = buttons)
        update_status("Lvl_up_points", player, user_data)
        player.update_skills()
        players.update({id: player})
        players_need_update.put(player)
        choose_points(bot, update, user_data)
        show_general_buttons(bot, update, user_data)
        player.lvl_check()
        return

    update_status("Lvl_up_skill", player, user_data)
    button_list = [
        KeyboardButton("1"),
        KeyboardButton("2"),
        KeyboardButton("3"),
        KeyboardButton("4"),
        KeyboardButton("5"),
        KeyboardButton("Готово")
    ]
    buttons = ReplyKeyboardMarkup(build_menu(button_list, n_cols=2), resize_keyboard=True, one_time_keyboard = False)
    s = ''
    if free_skill == 1:
        s = "навык"
    elif free_skill >= 2 and free_skill <= 4:
        s = "навыка"
    elif free_skill >= 5:
        s = "навыков"
    bot.send_message(chat_id=update.message.chat_id,
                     text="Вы можете улучшить <b>{5}</b> {6}\n\nВыберите навык, который хотите улучшить\n\n"
                          "{7} - {0}-го уровня\n{8} - {1}-го уровня\n"
                          "{9} - {2}-го уровня\n{10} - {3}-го уровня\n"
                          "{11} - {4}-го уровня".format(list(player.skill_lvl.values())[0], list(player.skill_lvl.values())[1], list(player.skill_lvl.values())[2],
                                                        list(player.skill_lvl.values())[3], list(player.skill_lvl.values())[4],  free_skill, s,
                                                        list(player.skill_lvl)[0], list(player.skill_lvl)[1], list(player.skill_lvl)[2], list(player.skill_lvl)[3], list(player.skill_lvl)[4]),
                     parse_mode='HTML', reply_markup=buttons)
    players.update({id: player})
    players_need_update.put(player)
コード例 #10
0
ファイル: merchant_buttons.py プロジェクト: Cactiw/UText_bot
from telegram import KeyboardButton, ReplyKeyboardMarkup
from work_materials.globals import build_menu

__merchant_buttons_list = [
    KeyboardButton('Оружие'),
    KeyboardButton('Голова'),
    KeyboardButton('Тело'),
    KeyboardButton('Перчатки'),
    KeyboardButton('Ноги'),
    KeyboardButton('Средства передвижения'),
    KeyboardButton('Импланты'),
    KeyboardButton('Продать'),
    KeyboardButton('Назад')
]

merchant_buttons = ReplyKeyboardMarkup(build_menu(__merchant_buttons_list,
                                                  n_cols=3),
                                       resize_keyboard=True)
コード例 #11
0
def matchmaking_callback(bot, update, user_data):
    mes = update.callback_query.message
    matchmaking = user_data.get("matchmaking")
    if update.callback_query.data == "mm start" or update.callback_query.data == "mm cancel":
        group = user_data.get("battle_group")
        player = get_player(update.callback_query.from_user.id)

        if update.callback_query.data == "mm cancel":
            if user_data.get("status") != "Matchmaking" and user_data.get(
                    "status"
            ) != "Battle":  # TODO Как битвы будут готовы, удалить проверку на статус "Battle", сейчас используется для отладки
                bot.send_message(chat_id=update.callback_query.from_user.id,
                                 text="Вы не находитесь в поиске битвы")
                return
            player_matchmaking = Player_matchmaking(player,
                                                    0,
                                                    matchmaking,
                                                    group=group)
            matchmaking_players.put(player_matchmaking)
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                    text="Подбор игроков успешно отменён",
                                    show_alert=False)
            try:
                bot.deleteMessage(chat_id=update.callback_query.from_user.id,
                                  message_id=mes.message_id)
            except Unauthorized:
                pass
            except BadRequest:
                pass
            new_status = user_data.get('saved_battle_status')
            update_status(new_status, player, user_data)
            matchmaking_start(bot, update.callback_query, user_data)
            return

        #   Начало подбора игроков
        flag = 0
        for i in matchmaking:
            if i == 1:
                flag = 1
                break
        if flag == 0:
            bot.send_message(chat_id=update.callback_query.from_user.id,
                             text="Необходимо выбрать хотя бы один режим")
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id)
            return
        if group is not None and (
                matchmaking[0] or
            (group.num_players() > 3 and matchmaking[1]) or
            (group.num_players() > 5 and matchmaking[2])):
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id)
            bot.send_message(
                chat_id=update.callback_query.from_user.id,
                text=
                "Игроков в группе больше, чем разрешено в выбранных режимах! (Хотя бы одном)"
            )
            return

        status = user_data.get("status")
        player.saved_battle_status = status
        player_matchmaking = Player_matchmaking(player,
                                                1,
                                                matchmaking,
                                                group=group)
        # bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text = "Подбор игроков успешно запущен!", show_alert = False)
        button_list = [
            InlineKeyboardButton("Отменить подбор игроков",
                                 callback_data="mm cancel")
        ]
        reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=1))
        try:
            bot.deleteMessage(chat_id=update.callback_query.from_user.id,
                              message_id=mes.message_id)
        except TelegramError:
            pass
        bot.send_message(chat_id=update.callback_query.from_user.id,
                         text="Подбор игроков запущен!",
                         reply_markup=reply_markup)
        user_data.update(
            saved_battle_status=status) if status != 'Matchmaking' else 0
        update_status('Matchmaking', player, user_data)
        matchmaking_players.put(player_matchmaking)
        return

    # Настройки матчмейкинга битв
    callback_data = update.callback_query.data
    if callback_data == "mm 1x1":
        matchmaking[0] = (matchmaking[0] + 1) % 2
    elif callback_data == "mm 3x3":
        matchmaking[1] = (matchmaking[1] + 1) % 2
    elif callback_data == "mm 5x5":
        matchmaking[2] = (matchmaking[2] + 1) % 2
    first_button_text = "{0}1 x 1".format('✅' if matchmaking[0] else "")
    second_button_text = "{0}3 x 3".format('✅' if matchmaking[1] else "")
    third_button_text = "{0}5 x 5".format('✅' if matchmaking[2] else "")
    button_list = [
        InlineKeyboardButton(first_button_text, callback_data="mm 1x1"),
        InlineKeyboardButton(second_button_text, callback_data="mm 3x3"),
        InlineKeyboardButton(third_button_text, callback_data="mm 5x5")
    ]
    footer_buttons = [
        InlineKeyboardButton("Начать поиск", callback_data="mm start")
    ]
    reply_markup = InlineKeyboardMarkup(
        build_menu(button_list, n_cols=3, footer_buttons=footer_buttons))
    try:
        bot.editMessageReplyMarkup(chat_id=mes.chat_id,
                                   message_id=mes.message_id,
                                   reply_markup=reply_markup)
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id)
    except TelegramError:
        logging.error(traceback.format_exc)
        pass
コード例 #12
0
        __enemies_buttons.append(KeyboardButton(i.participant.nickname))
    __enemies_buttons.append(KeyboardButton('Отмена'))
    return ReplyKeyboardMarkup(build_menu(__enemies_buttons, 2),
                               resize_keyboard=True)


def get_allies_buttons(battle, team):
    __ally_buttons = []
    ally_team = battle.teams[team]
    for i in ally_team:
        __ally_buttons.append(KeyboardButton(i.participant.nickname))
    __ally_buttons.append(KeyboardButton('Отмена'))
    return ReplyKeyboardMarkup(build_menu(__ally_buttons, 2),
                               resize_keyboard=True)


def get_all_targets_buttons(battle, team):
    __all_buttons = []
    all_team = battle.teams[team]
    all_team += battle.teams[(team + 1) % 2]
    for i in all_team:
        __all_buttons.append(KeyboardButton(i.participant.nickname))
    __all_buttons.append(KeyboardButton('Отмена'))
    return ReplyKeyboardMarkup(build_menu(__all_buttons, 2),
                               resize_keyboard=True)


__cancel = [KeyboardButton('Отмена')]
cancel_button = ReplyKeyboardMarkup(build_menu(__cancel, 1),
                                    resize_keyboard=True)
コード例 #13
0
ファイル: farming_buttons.py プロジェクト: Cactiw/UText_bot
from telegram import KeyboardButton, ReplyKeyboardMarkup
from work_materials.globals import build_menu

__farming_buttons = [
    KeyboardButton("Вернуться в локацию"),
]

farming_buttons = ReplyKeyboardMarkup(build_menu(__farming_buttons, n_cols=2),
                                      resize_keyboard=True)