Beispiel #1
0
def answerBackQuery(update, context):
    query = update.callback_query
    CallbackQuery.answer(query)
    query.edit_message_text(
        text="*Available packages for your search query :*",
        parse_mode=ParseMode.MARKDOWN_V2,
        reply_markup=result_keyboard)
Beispiel #2
0
    def buttoncgintskill(self, query: CallbackQuery, args: List[str],
                         card1: Optional[GameCard]) -> bool:
        if not card1:
            return self.errorHandlerQ(query, "找不到卡。")
        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.group.write()
            if card1.skill.points or card1.interest.points:
                self.addskill0(card1)
            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] + ",当前技能点:" + str(card1.interest.get(args[1])),
            reply_markup=rp_markup)
        self.workingMethod[self.lastchat] = BUTTON_CGINTSKILL
        return True
def mig_button_click_handler(bot: telegram.Bot, _: telegram.Update,
                             query: telegram.CallbackQuery, __) -> None:
    """
    Обработчик кнопки подмигивания
    """
    store = Store(query)
    if not store.load():
        return
    store.card = cast(Card, store.card)

    button_name = 'mig_clicked'
    result = store.card.mig(store.user_id, store.is_already_clicked(button_name),
                            get_username_or_link(store.user_id))

    query.answer(result.text)
    if result.success:
        store.mark_as_already_clicked(button_name)
        with StatsRedis.lock:
            with StatsRedis() as stats:
                stats.add_mig(store.card, store.user_id)
        try:
            bot.send_message(store.card.from_user.user_id, result.notify_text, parse_mode=HTML,
                             reply_to_message_id=store.card.original_draft_message_id)
        except Exception:
            pass
        sleep(0.8)
        try:
            bot.edit_message_text(f'✅ Тебе подмигнули!', store.card.from_user.user_id, store.card.status_message_id)
        except Exception:
            pass
Beispiel #4
0
def get_false_update_fixture_decorator_params():
    message = Message(1, User(1, '', False), DATE, Chat(1, ''), text='test')
    params = [{
        'callback_query':
        CallbackQuery(1, User(1, '', False), 'chat', message=message)
    }, {
        'channel_post': message
    }, {
        'edited_channel_post': message
    }, {
        'inline_query': InlineQuery(1, User(1, '', False), '', '')
    }, {
        'chosen_inline_result':
        ChosenInlineResult('id', User(1, '', False), '')
    }, {
        'shipping_query':
        ShippingQuery('id', User(1, '', False), '', None)
    }, {
        'pre_checkout_query':
        PreCheckoutQuery('id', User(1, '', False), '', 0, '')
    }, {
        'callback_query': CallbackQuery(1, User(1, '', False), 'chat')
    }]
    ids = tuple(key for kwargs in params for key in kwargs)
    return {'params': params, 'ids': ids}
Beispiel #5
0
def subscribe(update: Update, query: CallbackQuery, location: str) -> None:
    """
    Inline command responsible for handling subscriptions

    :param update: Telegram Update Object for getting right user
    :param query: Telegram Query Object for inline functionality
    :param location: Location that should be toggled

    - Adds user to database
    - Toggles status of chosen location
    - Updates message
    - Saves new settings to db
    """

    # getting chat by using the writer.add method
    # it checks database and adds chat if not already existing
    # the users chat will be returned
    chat = writer.add(update.effective_chat)

    settings = chat.settings  # settings of that chat contain subscription status
    # if location is not subscribed - subscribing
    if not settings[location]:
        settings[location] = True
        query.edit_message_text(text=f'Sie haben {location} abonniert',
                                reply_markup=kb.inline_sub_soft)

    # location is subscribed - settings subscription to false
    else:
        settings[location] = False
        query.edit_message_text(text=f'Sie haben {location} deabonniert',
                                reply_markup=kb.inline_sub_soft)

    # writing db to store changes
    writer.write()
Beispiel #6
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)
    def test_chat_confirm(self):
        with self.subTest("Cancel"):
            self.master.chat_binding.link_chat_gen_list(1, 1)
            c = CallbackQuery(1, self.user, None, message=self.message, data=Flags.CANCEL_PROCESS)
            self.master.chat_binding.link_chat_confirm(self.bot, Update(0, callback_query=c))
            self.master.bot_manager.edit_message_text.assert_called()
            self.assertNotIn("reply_markup", self.master.bot_manager.edit_message_text.call_args[1])
            self.master.bot_manager.reset_mock()

        with self.subTest("Unknown command"):
            self.master.chat_binding.link_chat_gen_list(1, 1)
            c = CallbackQuery(1, self.user, None, message=self.message, data="__unknown_command__")
            self.master.chat_binding.link_chat_confirm(self.bot, Update(0, callback_query=c))
            self.master.bot_manager.edit_message_text.assert_called()
            self.assertNotIn("reply_markup", self.master.bot_manager.edit_message_text.call_args[1])
            self.master.bot_manager.reset_mock()

        with self.subTest("Chat choice: non-linked"):
            self.master.chat_binding.link_chat_gen_list(1, 1)
            c = CallbackQuery(1, self.user, None, message=self.message, data="chat 0")
            self.master.chat_binding.link_chat_confirm(self.bot, Update(0, callback_query=c))
            self.master.bot_manager.edit_message_text.assert_called()
            state_buttons = self.master.bot_manager.edit_message_text.call_args[1]['reply_markup'].inline_keyboard[0]
            self.assertEqual(len(state_buttons), 2)
            self.master.bot_manager.reset_mock()
def export_watchlist(query: CallbackQuery):
    """
    Wrapper for watchlist_to_csv() that handles the telegram part, edits message and sends file
    """
    path = watchlist_to_csv(query)
    with open(path, 'r') as f:
        query.edit_message_text("Here you go:")
        query.message.chat.send_document(f)
Beispiel #9
0
def ban_roadblock_author(_bot: Bot, query: CallbackQuery) -> None:
    if query.message.chat.id == mods_chat:
        nmaps_message = retrieve_roadblock(mods_id=query.message.message_id)
    else:
        nmaps_message = retrieve_roadblock(roads_id=query.message.message_id)
    query.edit_message_text(BOT_USER_BANNED.format(query.from_user.name,
                                                   query.from_user.id),
                            parse_mode='markdown')
    with db_session:
        U.get(user_id=nmaps_message.author).banned = True
Beispiel #10
0
def timer_next_callback(job_queue: JobQueue, query: telegram.CallbackQuery,
                        data: str):
    [_, timer, comment] = data.rsplit(':', 2)
    try:
        timer = int(timer)
        comment = base64.b64decode(comment).decode()
        if len(comment) > 128:
            raise ValueError()
    except ValueError:
        query.answer("wrong timer callback arguments")
    timer_message(job_queue, query.message.chat_id, timer, comment)
    query.answer()
def callback_query(bot, request):
    cbq = CallbackQuery(TestCallbackQuery.id,
                        TestCallbackQuery.from_user,
                        TestCallbackQuery.chat_instance,
                        data=TestCallbackQuery.data,
                        game_short_name=TestCallbackQuery.game_short_name,
                        bot=bot)
    if request.param == 'message':
        cbq.message = TestCallbackQuery.message
    else:
        cbq.inline_message_id = TestCallbackQuery.inline_message_id
    return cbq
def inlinebutton_tweet_time(update: Update, context: CallbackContext,
                            query: CallbackQuery, args: List[str]):
    try:
        tweet_time = datetime.strptime(':'.join(args),
                                       '%H:%M').strftime("%H:%M")
    except ValueError:
        query.edit_message_text(
            "Sorry, I didn't understand that time. Time must be in format %H:%M"
        )
        return
    redis.set(f'chat:{query.message.chat_id}:settings:tweet_time', tweet_time)
    query.edit_message_text(f'I will tweet at {tweet_time}')
def callback_query(bot, request):
    cbq = CallbackQuery(TestCallbackQuery.id_,
                        TestCallbackQuery.from_user,
                        TestCallbackQuery.chat_instance,
                        data=TestCallbackQuery.data,
                        game_short_name=TestCallbackQuery.game_short_name,
                        bot=bot)
    if request.param == 'message':
        cbq.message = TestCallbackQuery.message
    else:
        cbq.inline_message_id = TestCallbackQuery.inline_message_id
    return cbq
Beispiel #14
0
    def buttonswitch(self, query: CallbackQuery, args: List[str]) -> bool:
        pl = self.forcegetplayer(self.lastchat)
        cdid = int(args[1])

        if cdid not in pl.cards:
            return self.errorHandlerQ(query, "没有找到这个id的卡。")

        pl.controlling = pl.cards[cdid]
        pl.write()

        query.edit_message_text("修改成功,现在操作的卡是:" + pl.controlling.getname())
        return True
Beispiel #15
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
    def test_conversation_handler_per_message(self, dp, bot, user1, user2):
        def entry(bot, update):
            return 1

        def one(bot, update):
            return 2

        def two(bot, update):
            return ConversationHandler.END

        handler = ConversationHandler(
            entry_points=[CallbackQueryHandler(entry)],
            states={
                1: [CallbackQueryHandler(one)],
                2: [CallbackQueryHandler(two)]
            },
            fallbacks=[],
            per_message=True)
        dp.add_handler(handler)

        # User one, starts the state machine.
        message = Message(0,
                          user1,
                          None,
                          self.group,
                          text='msg w/ inlinekeyboard',
                          bot=bot)

        cbq = CallbackQuery(0,
                            user1,
                            None,
                            message=message,
                            data='data',
                            bot=bot)
        dp.process_update(Update(update_id=0, callback_query=cbq))

        assert handler.conversations[(self.group.id, user1.id,
                                      message.message_id)] == 1

        dp.process_update(Update(update_id=0, callback_query=cbq))

        assert handler.conversations[(self.group.id, user1.id,
                                      message.message_id)] == 2

        # Let's now verify that for a different user in the same group, the state will not be
        # updated
        cbq.from_user = user2
        dp.process_update(Update(update_id=0, callback_query=cbq))

        assert handler.conversations[(self.group.id, user1.id,
                                      message.message_id)] == 2
Beispiel #17
0
def cancel_roadblock(bot: Bot, query: CallbackQuery) -> None:
    if query.message.chat.id == mods_chat:
        nmaps_message = retrieve_roadblock(mods_id=query.message.message_id)
    else:
        if query.from_user.last_name not in roads_staff:
            query.answer(BOT_NOT_ROAD_STAFF)
            return
        nmaps_message = retrieve_roadblock(roads_id=query.message.message_id)
    bot.send_message(nmaps_message.chat_id,
                     BOT_REQUEST_CANCELLED_USR,
                     reply_to_message_id=nmaps_message.chat_message_id)
    query.edit_message_text(BOT_REQUEST_CANCELLED.format(
        query.from_user.name, query.from_user.id),
                            parse_mode='markdown')
Beispiel #18
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 #19
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 #20
0
def round_inline_callback(bot: telegram.Bot, query: telegram.CallbackQuery,
                          gm: bool):
    game_round = Round.objects.filter(chat_id=query.message.chat_id).first()

    def _(t: Text):
        get_by_user(t, query.from_user)

    if not isinstance(game_round, Round):
        query.answer(show_alert=True, text=_(Text.GAME_NOT_IN_ROUND))
        return
    try:
        with transaction.atomic():
            round_inline_handle(bot, query, gm, game_round)
    except NotGm:
        query.answer(show_alert=True, text=_(Text.NOT_GM), cache_time=0)
Beispiel #21
0
def show_post_statistics(query: CallbackQuery, post_id: ObjectId) -> None:
    try:
        post = db.models.find_post(post_id)
    except:
        LOGGER.error(
            f"Could not find post {post_id} on statistics button click")
        query.answer(text="Post has not been found. "
                     "Approach the developer.",
                     show_alert=False)
        return

    clicks_count, correct_clicks_count = db.models.count_post_clicks(post)
    query.answer(
        text=f"Правильных ответов: {correct_clicks_count} / {clicks_count}",
        show_alert=True)
Beispiel #22
0
    def buttondiscard(self, query: CallbackQuery, args: List[str]) -> bool:
        cdid = int(args[1])

        card = self.getcard(cdid)
        if card is None:
            return self.errorHandlerQ(query, "找不到这个id的卡。")

        pl = self.forcegetplayer(self.lastchat)
        if not self.checkaccess(pl, card) & CANDISCARD:
            return self.errorHandlerQ(query, "该卡不可删除。")

        self.cardpop(cdid)

        query.edit_message_text(f"删除了:{card.getname()}。\n该删除操作不可逆。")
        return True
Beispiel #23
0
 def test_per_chat_message_without_chat(self, bot, user1):
     handler = ConversationHandler(
         entry_points=[CommandHandler('start', self.start_end)], states={},
         fallbacks=[])
     cbq = CallbackQuery(0, user1, None, None, bot=bot)
     update = Update(0, callback_query=cbq)
     assert not handler.check_update(update)
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.Update:
        """
        if not data:
            return None

        data = super(Update, Update).de_json(data, bot)

        data['message'] = Message.de_json(data.get('message'), bot)
        data['edited_message'] = Message.de_json(data.get('edited_message'), bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'), bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        data['callback_query'] = CallbackQuery.de_json(data.get('callback_query'), bot)
        data['shipping_query'] = ShippingQuery.de_json(data.get('shipping_query'), bot)
        data['pre_checkout_query'] = PreCheckoutQuery.de_json(data.get('pre_checkout_query'), bot)
        data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
        data['edited_channel_post'] = Message.de_json(data.get('edited_channel_post'), bot)

        return Update(**data)
    def test_clear_all(self, callback_data_cache, method):
        changing_button_1 = InlineKeyboardButton('changing',
                                                 callback_data='some data 1')
        changing_button_2 = InlineKeyboardButton('changing',
                                                 callback_data='some data 2')
        reply_markup = InlineKeyboardMarkup.from_row(
            [changing_button_1, changing_button_2])

        for i in range(100):
            out = callback_data_cache.process_keyboard(reply_markup)
            callback_query = CallbackQuery(
                str(i),
                from_user=None,
                chat_instance=None,
                data=out.inline_keyboard[0][1].callback_data,
            )
            callback_data_cache.process_callback_query(callback_query)

        if method == 'callback_data':
            callback_data_cache.clear_callback_data()
            # callback_data was cleared, callback_queries weren't
            assert len(callback_data_cache.persistence_data[0]) == 0
            assert len(callback_data_cache.persistence_data[1]) == 100
        else:
            callback_data_cache.clear_callback_queries()
            # callback_queries were cleared, callback_data wasn't
            assert len(callback_data_cache.persistence_data[0]) == 100
            assert len(callback_data_cache.persistence_data[1]) == 0
Beispiel #26
0
    def de_json(cls, data: Optional[JSONDict],
                bot: 'Bot') -> Optional['Update']:
        """See :meth:`telegram.TelegramObject.de_json`."""
        data = cls._parse_data(data)

        if not data:
            return None

        data['message'] = Message.de_json(data.get('message'), bot)
        data['edited_message'] = Message.de_json(data.get('edited_message'),
                                                 bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'),
                                                   bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        data['callback_query'] = CallbackQuery.de_json(
            data.get('callback_query'), bot)
        data['shipping_query'] = ShippingQuery.de_json(
            data.get('shipping_query'), bot)
        data['pre_checkout_query'] = PreCheckoutQuery.de_json(
            data.get('pre_checkout_query'), bot)
        data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
        data['edited_channel_post'] = Message.de_json(
            data.get('edited_channel_post'), bot)
        data['poll'] = Poll.de_json(data.get('poll'), bot)
        data['poll_answer'] = PollAnswer.de_json(data.get('poll_answer'), bot)
        data['my_chat_member'] = ChatMemberUpdated.de_json(
            data.get('my_chat_member'), bot)
        data['chat_member'] = ChatMemberUpdated.de_json(
            data.get('chat_member'), bot)
        data['chat_join_request'] = ChatJoinRequest.de_json(
            data.get('chat_join_request'), bot)

        return cls(**data)
Beispiel #27
0
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.Update:
        """
        if not data:
            return None

        data = super(Update, Update).de_json(data, bot)

        data['message'] = Message.de_json(data.get('message'), bot)
        data['edited_message'] = Message.de_json(data.get('edited_message'),
                                                 bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'),
                                                   bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        data['callback_query'] = CallbackQuery.de_json(
            data.get('callback_query'), bot)
        data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
        data['edited_channel_post'] = Message.de_json(
            data.get('edited_channel_post'), bot)

        return Update(**data)
Beispiel #28
0
 def test_perChatMessageWithoutChat(self):
     handler = ConversationHandler(
         entry_points=[CommandHandler('start', self.start_end)], states={}, fallbacks=[])
     user = User(first_name="Misses Test", id=123)
     cbq = CallbackQuery(0, user, None, None)
     update = Update(0, callback_query=cbq)
     handler.check_update(update)
Beispiel #29
0
    def de_json(cls, data: Optional[JSONDict],
                bot: 'Bot') -> Optional['Update']:
        data = cls.parse_data(data)

        if not data:
            return None

        data['message'] = Message.de_json(data.get('message'), bot)
        data['edited_message'] = Message.de_json(data.get('edited_message'),
                                                 bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'),
                                                   bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        data['callback_query'] = CallbackQuery.de_json(
            data.get('callback_query'), bot)
        data['shipping_query'] = ShippingQuery.de_json(
            data.get('shipping_query'), bot)
        data['pre_checkout_query'] = PreCheckoutQuery.de_json(
            data.get('pre_checkout_query'), bot)
        data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
        data['edited_channel_post'] = Message.de_json(
            data.get('edited_channel_post'), bot)
        data['poll'] = Poll.de_json(data.get('poll'), bot)
        data['poll_answer'] = PollAnswer.de_json(data.get('poll_answer'), bot)

        return cls(**data)
Beispiel #30
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(Update, cls).de_json(data, bot)

        data['message'] = Message.de_json(data.get('message'), bot)
        data['edited_message'] = Message.de_json(data.get('edited_message'),
                                                 bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'),
                                                   bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        data['callback_query'] = CallbackQuery.de_json(
            data.get('callback_query'), bot)
        data['shipping_query'] = ShippingQuery.de_json(
            data.get('shipping_query'), bot)
        data['pre_checkout_query'] = PreCheckoutQuery.de_json(
            data.get('pre_checkout_query'), bot)
        data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
        data['edited_channel_post'] = Message.de_json(
            data.get('edited_channel_post'), bot)
        data['poll'] = Poll.de_json(data.get('poll'), bot)

        return cls(**data)
Beispiel #31
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(Update, cls).de_json(data, bot)

        message = data.get('message')
        if message:
            message['default_quote'] = data.get('default_quote')
        data['message'] = Message.de_json(message, bot)
        edited_message = data.get('edited_message')
        if edited_message:
            edited_message['default_quote'] = data.get('default_quote')
        data['edited_message'] = Message.de_json(edited_message, bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'), bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        callback_query = data.get('callback_query')
        if callback_query:
            callback_query['default_quote'] = data.get('default_quote')
        data['callback_query'] = CallbackQuery.de_json(callback_query, bot)
        data['shipping_query'] = ShippingQuery.de_json(data.get('shipping_query'), bot)
        data['pre_checkout_query'] = PreCheckoutQuery.de_json(data.get('pre_checkout_query'), bot)
        channel_post = data.get('channel_post')
        if channel_post:
            channel_post['default_quote'] = data.get('default_quote')
        data['channel_post'] = Message.de_json(channel_post, bot)
        edited_channel_post = data.get('edited_channel_post')
        if edited_channel_post:
            edited_channel_post['default_quote'] = data.get('default_quote')
        data['edited_channel_post'] = Message.de_json(edited_channel_post, bot)
        data['poll'] = Poll.de_json(data.get('poll'), bot)

        return cls(**data)
 def test_all_update_types(self, dp, bot, user1):
     handler = ConversationHandler(
         entry_points=[CommandHandler('start', self.start_end)],
         states={},
         fallbacks=[])
     message = Message(0, user1, None, self.group, text='ignore', bot=bot)
     callback_query = CallbackQuery(0,
                                    user1,
                                    None,
                                    message=message,
                                    data='data',
                                    bot=bot)
     chosen_inline_result = ChosenInlineResult(0, user1, 'query', bot=bot)
     inline_query = InlineQuery(0, user1, 'query', 0, bot=bot)
     pre_checkout_query = PreCheckoutQuery(0,
                                           user1,
                                           'USD',
                                           100, [],
                                           bot=bot)
     shipping_query = ShippingQuery(0, user1, [], None, bot=bot)
     assert not handler.check_update(
         Update(0, callback_query=callback_query))
     assert not handler.check_update(
         Update(0, chosen_inline_result=chosen_inline_result))
     assert not handler.check_update(Update(0, inline_query=inline_query))
     assert not handler.check_update(Update(0, message=message))
     assert not handler.check_update(
         Update(0, pre_checkout_query=pre_checkout_query))
     assert not handler.check_update(
         Update(0, shipping_query=shipping_query))
    def test_conversation_handler_per_message(self, dp, bot, user1, user2):
        def entry(bot, update):
            return 1

        def one(bot, update):
            return 2

        def two(bot, update):
            return ConversationHandler.END

        handler = ConversationHandler(
            entry_points=[CallbackQueryHandler(entry)],
            states={1: [CallbackQueryHandler(one)],
                    2: [CallbackQueryHandler(two)]},
            fallbacks=[],
            per_message=True)
        dp.add_handler(handler)

        # User one, starts the state machine.
        message = Message(0, user1, None, self.group, text='msg w/ inlinekeyboard', bot=bot)

        cbq = CallbackQuery(0, user1, None, message=message, data='data', bot=bot)
        dp.process_update(Update(update_id=0, callback_query=cbq))

        assert handler.conversations[(self.group.id, user1.id, message.message_id)] == 1

        dp.process_update(Update(update_id=0, callback_query=cbq))

        assert handler.conversations[(self.group.id, user1.id, message.message_id)] == 2

        # Let's now verify that for a different user in the same group, the state will not be
        # updated
        cbq.from_user = user2
        dp.process_update(Update(update_id=0, callback_query=cbq))

        assert handler.conversations[(self.group.id, user1.id, message.message_id)] == 2
    def test_de_json(self, bot):
        json_dict = {'id': self.id,
                     'from': self.from_user.to_dict(),
                     'chat_instance': self.chat_instance,
                     'message': self.message.to_dict(),
                     'data': self.data,
                     'inline_message_id': self.inline_message_id,
                     'game_short_name': self.game_short_name}
        callback_query = CallbackQuery.de_json(json_dict, bot)

        assert callback_query.id == self.id
        assert callback_query.from_user == self.from_user
        assert callback_query.chat_instance == self.chat_instance
        assert callback_query.message == self.message
        assert callback_query.data == self.data
        assert callback_query.inline_message_id == self.inline_message_id
        assert callback_query.game_short_name == self.game_short_name
Beispiel #35
0
    def de_json(data):
        """
        Args:
            data (dict):

        Returns:
            telegram.Update:
        """
        if not data:
            return None

        data['message'] = Message.de_json(data.get('message'))
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'))
        data['chosen_inline_result'] = ChosenInlineResult.de_json(data.get('chosen_inline_result'))
        data['callback_query'] = CallbackQuery.de_json(data.get('callback_query'))

        return Update(**data)
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(Update, cls).de_json(data, bot)

        data['message'] = Message.de_json(data.get('message'), bot)
        data['edited_message'] = Message.de_json(data.get('edited_message'), bot)
        data['inline_query'] = InlineQuery.de_json(data.get('inline_query'), bot)
        data['chosen_inline_result'] = ChosenInlineResult.de_json(
            data.get('chosen_inline_result'), bot)
        data['callback_query'] = CallbackQuery.de_json(data.get('callback_query'), bot)
        data['shipping_query'] = ShippingQuery.de_json(data.get('shipping_query'), bot)
        data['pre_checkout_query'] = PreCheckoutQuery.de_json(data.get('pre_checkout_query'), bot)
        data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
        data['edited_channel_post'] = Message.de_json(data.get('edited_channel_post'), bot)

        return cls(**data)