X Tutup
Skip to content

Commit 3767d26

Browse files
jeffffcjh0ker
authored andcommitted
Add both handlers for queries from new Payment API (python-telegram-bot#630)
* add handlers for new payment API * fix typo * fix docstring mistakes * added missing 'from_user'
1 parent 01430a2 commit 3767d26

File tree

8 files changed

+219
-3
lines changed

8 files changed

+219
-3
lines changed

AUTHORS.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ The following wonderful people contributed directly or indirectly to this projec
2929
- `Hugo Damer <https://github.com/HakimusGIT>`_
3030
- `Jacob Bom <https://github.com/bomjacob>`_
3131
- `JASON0916 <https://github.com/JASON0916>`_
32+
- `jeffffc <https://github.com/jeffffc`_
3233
- `jh0ker <https://github.com/jh0ker>`_
3334
- `John Yong <https://github.com/whipermr5>`_
3435
- `jossalgon <https://github.com/jossalgon>`_

telegram/ext/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,11 @@
3333
from .stringregexhandler import StringRegexHandler
3434
from .typehandler import TypeHandler
3535
from .conversationhandler import ConversationHandler
36+
from .precheckoutqueryhandler import PreCheckoutQueryHandler
37+
from .shippingqueryhandler import ShippingQueryHandler
3638

3739
__all__ = ('Dispatcher', 'JobQueue', 'Job', 'Updater', 'CallbackQueryHandler',
3840
'ChosenInlineResultHandler', 'CommandHandler', 'Handler', 'InlineQueryHandler',
3941
'MessageHandler', 'BaseFilter', 'Filters', 'RegexHandler', 'StringCommandHandler',
40-
'StringRegexHandler', 'TypeHandler', 'ConversationHandler')
42+
'StringRegexHandler', 'TypeHandler', 'ConversationHandler',
43+
'PreCheckoutQueryHandler', 'ShippingQueryHandler')
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#!/usr/bin/env python
2+
#
3+
# A library that provides a Python interface to the Telegram Bot API
4+
# Copyright (C) 2015-2017
5+
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
6+
#
7+
# This program is free software: you can redistribute it and/or modify
8+
# it under the terms of the GNU Lesser Public License as published by
9+
# the Free Software Foundation, either version 3 of the License, or
10+
# (at your option) any later version.
11+
#
12+
# This program is distributed in the hope that it will be useful,
13+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15+
# GNU Lesser Public License for more details.
16+
#
17+
# You should have received a copy of the GNU Lesser Public License
18+
# along with this program. If not, see [http://www.gnu.org/licenses/].
19+
""" This module contains the PreCheckoutQueryHandler class """
20+
21+
from telegram import Update
22+
from .handler import Handler
23+
24+
25+
class PreCheckoutQueryHandler(Handler):
26+
"""
27+
Handler class to handle Telegram PreCheckout callback queries.
28+
29+
Args:
30+
callback (function): A function that takes ``bot, update`` as
31+
positional arguments. It will be called when the ``check_update``
32+
has determined that an update should be processed by this handler.
33+
pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called
34+
``update_queue`` will be passed to the callback function. It will be the ``Queue``
35+
instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can
36+
be used to insert updates. Default is ``False``.
37+
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
38+
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
39+
instance created by the ``Updater`` which can be used to schedule new jobs.
40+
Default is ``False``.
41+
pass_user_data (optional[bool]): If set to ``True``, a keyword argument called
42+
``user_data`` will be passed to the callback function. It will be a ``dict`` you
43+
can use to keep any data related to the user that sent the update. For each update of
44+
the same user, it will be the same ``dict``. Default is ``False``.
45+
pass_chat_data (optional[bool]): If set to ``True``, a keyword argument called
46+
``chat_data`` will be passed to the callback function. It will be a ``dict`` you
47+
can use to keep any data related to the chat that the update was sent in.
48+
For each update in the same chat, it will be the same ``dict``. Default is ``False``.
49+
"""
50+
51+
def __init__(self,
52+
callback,
53+
pass_update_queue=False,
54+
pass_job_queue=False,
55+
pass_user_data=False,
56+
pass_chat_data=False):
57+
super(PreCheckoutQueryHandler, self).__init__(
58+
callback,
59+
pass_update_queue=pass_update_queue,
60+
pass_job_queue=pass_job_queue,
61+
pass_user_data=pass_user_data,
62+
pass_chat_data=pass_chat_data)
63+
64+
def check_update(self, update):
65+
if isinstance(update, Update) and update.pre_checkout_query:
66+
return True
67+
68+
def handle_update(self, update, dispatcher):
69+
optional_args = self.collect_optional_args(dispatcher, update)
70+
return self.callback(dispatcher.bot, update, **optional_args)
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#!/usr/bin/env python
2+
#
3+
# A library that provides a Python interface to the Telegram Bot API
4+
# Copyright (C) 2015-2017
5+
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
6+
#
7+
# This program is free software: you can redistribute it and/or modify
8+
# it under the terms of the GNU Lesser Public License as published by
9+
# the Free Software Foundation, either version 3 of the License, or
10+
# (at your option) any later version.
11+
#
12+
# This program is distributed in the hope that it will be useful,
13+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15+
# GNU Lesser Public License for more details.
16+
#
17+
# You should have received a copy of the GNU Lesser Public License
18+
# along with this program. If not, see [http://www.gnu.org/licenses/].
19+
""" This module contains the ShippingQueryHandler class """
20+
21+
from telegram import Update
22+
from .handler import Handler
23+
24+
25+
class ShippingQueryHandler(Handler):
26+
"""
27+
Handler class to handle Telegram shipping callback queries.
28+
29+
Args:
30+
callback (function): A function that takes ``bot, update`` as
31+
positional arguments. It will be called when the ``check_update``
32+
has determined that an update should be processed by this handler.
33+
pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called
34+
``update_queue`` will be passed to the callback function. It will be the ``Queue``
35+
instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can
36+
be used to insert updates. Default is ``False``.
37+
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
38+
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
39+
instance created by the ``Updater`` which can be used to schedule new jobs.
40+
Default is ``False``.
41+
pass_user_data (optional[bool]): If set to ``True``, a keyword argument called
42+
``user_data`` will be passed to the callback function. It will be a ``dict`` you
43+
can use to keep any data related to the user that sent the update. For each update of
44+
the same user, it will be the same ``dict``. Default is ``False``.
45+
pass_chat_data (optional[bool]): If set to ``True``, a keyword argument called
46+
``chat_data`` will be passed to the callback function. It will be a ``dict`` you
47+
can use to keep any data related to the chat that the update was sent in.
48+
For each update in the same chat, it will be the same ``dict``. Default is ``False``.
49+
"""
50+
51+
def __init__(self,
52+
callback,
53+
pass_update_queue=False,
54+
pass_job_queue=False,
55+
pass_user_data=False,
56+
pass_chat_data=False):
57+
super(ShippingQueryHandler, self).__init__(
58+
callback,
59+
pass_update_queue=pass_update_queue,
60+
pass_job_queue=pass_job_queue,
61+
pass_user_data=pass_user_data,
62+
pass_chat_data=pass_chat_data)
63+
64+
def check_update(self, update):
65+
if isinstance(update, Update) and update.shipping_query:
66+
return True
67+
68+
def handle_update(self, update, dispatcher):
69+
optional_args = self.collect_optional_args(dispatcher, update)
70+
return self.callback(dispatcher.bot, update, **optional_args)

telegram/precheckoutquery.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,3 +88,7 @@ def to_dict(self):
8888
data['from'] = data.pop('from_user', None)
8989

9090
return data
91+
92+
def answer(self, *args, **kwargs):
93+
"""Shortcut for ``bot.answerPreCheckoutQuery(update.pre_checkout_query.id, *args, **kwargs)``"""
94+
return self.bot.answerPreCheckoutQuery(self.id, *args, **kwargs)

telegram/shippingquery.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,7 @@ def to_dict(self):
7373
data['from'] = data.pop('from_user', None)
7474

7575
return data
76+
77+
def answer(self, *args, **kwargs):
78+
"""Shortcut for ``bot.answerShippingQuery(update.shipping_query.id, *args, **kwargs)``"""
79+
return self.bot.answerShippingQuery(self.id, *args, **kwargs)

telegram/update.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
# along with this program. If not, see [http://www.gnu.org/licenses/].
1919
"""This module contains an object that represents a Telegram Update."""
2020

21-
from telegram import (Message, TelegramObject, InlineQuery, ChosenInlineResult, CallbackQuery)
21+
from telegram import (Message, TelegramObject, InlineQuery, ChosenInlineResult,
22+
CallbackQuery, ShippingQuery, PreCheckoutQuery)
2223

2324

2425
class Update(TelegramObject):
@@ -31,6 +32,8 @@ class Update(TelegramObject):
3132
edited_message (:class:`telegram.Message`): New version of a message that is known to the
3233
bot and was edited
3334
inline_query (:class:`telegram.InlineQuery`): New incoming inline query.
35+
shipping_query (:class:`telegram.ShippingQuery`): New incoming shipping query.
36+
pre_checkout_query (:class:`telegram.PreCheckoutQuery`): New incoming pre-checkout query.
3437
chosen_inline_result (:class:`telegram.ChosenInlineResult`): The result of an inline query
3538
that was chosen by a user and sent to their chat partner.
3639
callback_query (:class:`telegram.CallbackQuery`): New incoming callback query.
@@ -46,6 +49,8 @@ class Update(TelegramObject):
4649
inline_query (Optional[:class:`telegram.InlineQuery`]):
4750
chosen_inline_result (Optional[:class:`telegram.ChosenInlineResult`])
4851
callback_query (Optional[:class:`telegram.CallbackQuery`]):
52+
shipping_query (Optional[:class:`telegram.ShippingQuery`]):
53+
pre_checkout_query (Optional[:class:`telegram.PreCheckoutQuery`]):
4954
channel_post (Optional[:class:`telegram.Message`]):
5055
edited_channel_post (Optional[:class:`telegram.Message`]):
5156
**kwargs: Arbitrary keyword arguments.
@@ -59,6 +64,8 @@ def __init__(self,
5964
inline_query=None,
6065
chosen_inline_result=None,
6166
callback_query=None,
67+
shipping_query=None,
68+
pre_checkout_query=None,
6269
channel_post=None,
6370
edited_channel_post=None,
6471
**kwargs):
@@ -70,6 +77,8 @@ def __init__(self,
7077
self.inline_query = inline_query
7178
self.chosen_inline_result = chosen_inline_result
7279
self.callback_query = callback_query
80+
self.shipping_query = shipping_query
81+
self.pre_checkout_query = pre_checkout_query
7382
self.channel_post = channel_post
7483
self.edited_channel_post = edited_channel_post
7584

@@ -100,6 +109,8 @@ def de_json(data, bot):
100109
data['chosen_inline_result'] = ChosenInlineResult.de_json(
101110
data.get('chosen_inline_result'), bot)
102111
data['callback_query'] = CallbackQuery.de_json(data.get('callback_query'), bot)
112+
data['shipping_query'] = ShippingQuery.de_json(data.get('shipping_query'), bot)
113+
data['pre_checkout_query'] = PreCheckoutQuery.de_json(data.get('pre_checkout_query'), bot)
103114
data['channel_post'] = Message.de_json(data.get('channel_post'), bot)
104115
data['edited_channel_post'] = Message.de_json(data.get('edited_channel_post'), bot)
105116

@@ -132,6 +143,12 @@ def effective_user(self):
132143
elif self.callback_query:
133144
user = self.callback_query.from_user
134145

146+
elif self.shipping_query:
147+
user = self.shipping_query.from_user
148+
149+
elif self.pre_checkout_query:
150+
user = self.pre_checkout_query.from_user
151+
135152
self._effective_user = user
136153
return user
137154

tests/test_updater.py

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,8 @@
4646

4747
sys.path.append('.')
4848

49-
from telegram import Update, Message, TelegramError, User, Chat, Bot, InlineQuery, CallbackQuery
49+
from telegram import (Update, Message, TelegramError, User, Chat, Bot,
50+
InlineQuery, CallbackQuery, ShippingQuery, PreCheckoutQuery)
5051
from telegram.ext import *
5152
from telegram.ext.dispatcher import run_async
5253
from telegram.error import Unauthorized, InvalidToken
@@ -119,6 +120,14 @@ def telegramCallbackHandlerTest(self, bot, update):
119120
self.received_message = update.callback_query
120121
self.message_count += 1
121122

123+
def telegramShippingHandlerTest(self, bot, update):
124+
self.received_message = update.shipping_query
125+
self.message_count += 1
126+
127+
def telegramPreCheckoutHandlerTest(self, bot, update):
128+
self.received_message = update.pre_checkout_query
129+
self.message_count += 1
130+
122131
@run_async
123132
def asyncHandlerTest(self, bot, update):
124133
sleep(1)
@@ -488,6 +497,44 @@ def test_addRemoveCallbackQueryHandler(self):
488497
sleep(.1)
489498
self.assertTrue(None is self.received_message)
490499

500+
def test_addRemoveShippingQueryHandler(self):
501+
self._setup_updater('', messages=0)
502+
d = self.updater.dispatcher
503+
handler = ShippingQueryHandler(self.telegramShippingHandlerTest)
504+
d.add_handler(handler)
505+
queue = self.updater.start_polling(0.01)
506+
update = Update(update_id=0, shipping_query="testshipping")
507+
queue.put(update)
508+
sleep(.1)
509+
self.assertEqual(self.received_message, "testshipping")
510+
511+
# Remove handler
512+
d.remove_handler(handler)
513+
self.reset()
514+
515+
queue.put(update)
516+
sleep(.1)
517+
self.assertTrue(None is self.received_message)
518+
519+
def test_addRemovePreCheckoutQueryHandler(self):
520+
self._setup_updater('', messages=0)
521+
d = self.updater.dispatcher
522+
handler = PreCheckoutQueryHandler(self.telegramPreCheckoutHandlerTest)
523+
d.add_handler(handler)
524+
queue = self.updater.start_polling(0.01)
525+
update = Update(update_id=0, pre_checkout_query="testprecheckout")
526+
queue.put(update)
527+
sleep(.1)
528+
self.assertEqual(self.received_message, "testprecheckout")
529+
530+
# Remove handler
531+
d.remove_handler(handler)
532+
self.reset()
533+
534+
queue.put(update)
535+
sleep(.1)
536+
self.assertTrue(None is self.received_message)
537+
491538
def test_runAsync(self):
492539
self._setup_updater('Test5', messages=2)
493540
d = self.updater.dispatcher

0 commit comments

Comments
 (0)
X Tutup