Beispiel #1
0
def draft_heart_button_click_handler(bot: telegram.Bot, _: telegram.Update,
                                     query: telegram.CallbackQuery,
                                     data) -> None:
    """
    Обработчик кнопки выбора сердечка
    """
    user_id = query.from_user.id

    draft: Optional[CardDraftSelectHeart] = cache.get(
        f'{CACHE_PREFIX}:draft:card:{user_id}')
    if draft is None or not isinstance(draft, CardDraftSelectHeart):
        query.answer(text='Черновик не найден')
        query.message.delete()
        return

    heart: str = data['heart']
    chat_names = {
        chat.chat_id: get_chat_title(bot, chat.chat_id)
        for chat in draft.from_user.chats
    }
    answer = draft.select_heart(heart, chat_names)
    answer.original_draft_message_id = draft.original_draft_message_id

    cache.set(f'{CACHE_PREFIX}:draft:card:{user_id}', answer, time=TWO_DAYS)
    query.edit_message_text(text=answer.get_message_text(), parse_mode=HTML)
    query.edit_message_reply_markup(
        reply_markup=get_reply_markup(answer.get_message_buttons()))
    query.answer()
Beispiel #2
0
def select_time(update: Update, context: CallbackContext,
                query: CallbackQuery):
    time_btns = [[
        InlineKeyboardButton(text=times[0].name,
                             callback_data=json.dumps([
                                 CallbackCommands.POPULARITY.SELECT_TIME,
                                 times[0].uid
                             ]))
    ]]
    for i in range(1, 24, 3):
        time_btns.append([
            InlineKeyboardButton(text=times[i].name,
                                 callback_data=json.dumps([
                                     CallbackCommands.POPULARITY.SELECT_TIME,
                                     times[i].uid
                                 ])),
            InlineKeyboardButton(text=times[i + 1].name,
                                 callback_data=json.dumps([
                                     CallbackCommands.POPULARITY.SELECT_TIME,
                                     times[i + 1].uid
                                 ])),
            InlineKeyboardButton(text=times[i + 2].name,
                                 callback_data=json.dumps([
                                     CallbackCommands.POPULARITY.SELECT_TIME,
                                     times[i + 2].uid
                                 ]))
        ])

    markup = InlineKeyboardMarkup(time_btns)
    query.edit_message_text(text='Zeit Auswählen')
    query.edit_message_reply_markup(reply_markup=markup)
Beispiel #3
0
    def buttonsetdec(self, query: CallbackQuery, args: List[str],
                     card1: Optional[GameCard]) -> bool:
        if not card1:
            return self.errorHandlerQ(query, "找不到卡。")

        dname = args[0][:args[0].find("dec")]
        if dname not in card1.data.alldatanames:
            self.sendtoAdmin("属性名错误,请检查代码")
            return self.errorHandlerQ(query, "属性名错误,请检查代码")
        if card1.data.datadec is None:
            return self.errorHandlerQ(query, "该卡无需设置属性降值。")

        decnames = card1.data.datadec[0].split('_')
        decval = int(args[2])

        assert (card1.data.__dict__[dname] - decval >= 1)
        assert (card1.data.datadec[1] + decval <= 0)

        if len(decnames) == 2:
            otherdec = decnames[0] if dname == decnames[1] else decnames[1]
            assert (card1.data.__dict__[otherdec] + card1.data.datadec[1] +
                    decval >= 1)

            card1.data.__dict__[dname] -= decval
            card1.data.__dict__[otherdec] += card1.data.datadec[1] + decval
            card1.data.datadec = None

            card1.generateOtherAttributes()

            query.edit_message_text(
                f"属性下降设置完成,现在基础属性:\n{str(card1.data)}\n请点击 /setjob 设置职业。")
            return True

        if len(decnames) == 3:
            decnames.pop(decnames.index(dname))

            card1.data.__dict__[dname] -= decval
            card1.data.datadec = ('_'.join(decnames),
                                  card1.data.datadec[1] + decval)
            card1.write()

            query.edit_message_text(f"请继续设置属性降值,目前全部数值如下:\n{str(card1.data)}")

            rtbuttons = [[]]
            for dname in decnames:
                rtbuttons[0].append(
                    InlineKeyboardButton(text=dname,
                                         callback_data="choosedec " + dname))

            rp_markup = InlineKeyboardMarkup(rtbuttons)
            query.edit_message_reply_markup(reply_markup=rp_markup)
            self.workingMethod[self.lastchat] = BUTTON_CHOOSEDEC
            return True

        self.sendtoAdmin("下降属性参数长度有误")
        return self.errorHandlerQ(query, "下降属性参数长度有误")
Beispiel #4
0
def send_response(query: CallbackQuery, text):
    # display message to user
    try:
        query.edit_message_text(text=text)
        query.edit_message_reply_markup(
            reply_markup=InlineKeyboardMarkup([[]]))
    except BadRequest as e:
        # filter out weird "Message is not modified" error
        if 'Message is not modified' in e.message:
            pass
        else:
            raise e
Beispiel #5
0
def select_day(update: Update, context: CallbackContext, query: CallbackQuery):
    day_btns = []
    for day in days:
        day_btns.append([
            InlineKeyboardButton(text=day.name,
                                 callback_data=json.dumps([
                                     CallbackCommands.POPULARITY.SELECT_DAY,
                                     day.uid
                                 ]))
        ])

    markup = InlineKeyboardMarkup(day_btns)
    query.edit_message_text(text="Tag auswählen")
    query.edit_message_reply_markup(reply_markup=markup)
Beispiel #6
0
    def buttonaddintskill(self, query: CallbackQuery, args: List[str],
                          card1: Optional[GameCard]) -> bool:
        """响应KeyboardButton的addintskill请求。

        因为使用的是能翻页的列表,所以有可能位置1的参数是`page`,
        且位置2的参数是页码。"""
        if args[1] == "page":
            rttext, rtbuttons = self.showskillpages(int(args[2]), card1)
            query.edit_message_text(rttext)
            query.edit_message_reply_markup(InlineKeyboardMarkup(rtbuttons))
            self.workingMethod[self.lastchat] = BUTTON_ADDINTSKILL
            return True

        if len(args) == 3:
            skvalue = int(args[2])
            needpt = self.evalskillcost(args[1], skvalue, card1, False)
            card1.interest.set(args[1], skvalue, needpt)
            query.edit_message_text(text="兴趣技能:" + args[1] + "的值现在是" +
                                    str(skvalue) + "。剩余技能点:" +
                                    str(card1.interest.points))
            card1.write()
            if card1.skill.points or card1.interest.points:
                self.addskill0(card1)
            else:
                self.sendto(
                    card1.player,
                    "接下来,如果没有设置过的话,请使用 /setname 设置姓名、 /setsex 设置性别、 /setbkg 设置背景信息。"
                )
                self.reply(
                    card1.player.id,
                    "背景设定中必要的部分有:故事、信仰、重要之人、意义非凡之地、珍视之物、性格特质。如果需要帮助,请点击`/help setbkg`并发送给我。",
                    parse_mode="MarkdownV2")
            return True

        m = self.getskilllevelfromdict(card1, args[1])
        mm = self.skillmaxval(args[1], card1, False)
        rtbuttons = self.makeIntButtons(m, mm, args[0], args[1])
        rp_markup = InlineKeyboardMarkup(rtbuttons)
        query.edit_message_text("添加兴趣技能。剩余技能点:" + str(card1.interest.points) +
                                " 技能名称:" + args[1],
                                reply_markup=rp_markup)
        self.workingMethod[self.lastchat] = BUTTON_ADDINTSKILL
        return True
def inlinebutton_timezone(update: Update, context: CallbackContext,
                          query: CallbackQuery, args: List[str]):
    continents = sorted(
        set([x.partition('/')[0] for x in pytz.common_timezones]))
    location = args[0]
    if location == 'region_selection':
        reply = get_timezone_region_markup(continents)
        query.edit_message_text('Choose your region')
        query.edit_message_reply_markup(reply)
    elif location in pytz.all_timezones:
        redis.set(f'chat:{query.message.chat_id}:settings:timezone', location)
        tz = timezone(location)
        local_time = query.message.date.astimezone(tz).strftime('%X')
        reply = InlineKeyboardMarkup([[
            (InlineKeyboardButton('Change timezone',
                                  callback_data='timezone:region_selection'))
        ]])
        query.edit_message_text(
            f'Timezone of this chat was set to {location}. '
            f'Looks like it was {local_time} when you sent the last /timezone command. '
            'If this is incorrect, please execute /timezone again or click the button below.'
        )
        query.edit_message_reply_markup(reply)
    elif location in continents:
        zones = [x for x in pytz.all_timezones if x.startswith(location)]
        reply = InlineKeyboardMarkup([[
            InlineKeyboardButton(x.partition('/')[2],
                                 callback_data=':'.join(['timezone', x]))
        ] for x in zones] + [[(InlineKeyboardButton(
            '« Back', callback_data='timezone:region_selection'))]], )
        query.edit_message_text('Choose your timezone')
        query.edit_message_reply_markup(reply)