Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ The following wonderful people contributed directly or indirectly to this projec
- `Hugo Damer <https://github.com/HakimusGIT>`_
- `Jacob Bom <https://github.com/bomjacob>`_
- `JASON0916 <https://github.com/JASON0916>`_
- `jeffffc <https://github.com/jeffffc`_
- `jh0ker <https://github.com/jh0ker>`_
- `John Yong <https://github.com/whipermr5>`_
- `jossalgon <https://github.com/jossalgon>`_
Expand Down
5 changes: 4 additions & 1 deletion telegram/ext/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,11 @@
from .stringregexhandler import StringRegexHandler
from .typehandler import TypeHandler
from .conversationhandler import ConversationHandler
from .precheckoutqueryhandler import PreCheckoutQueryHandler
from .shippingqueryhandler import ShippingQueryHandler

__all__ = ('Dispatcher', 'JobQueue', 'Job', 'Updater', 'CallbackQueryHandler',
'ChosenInlineResultHandler', 'CommandHandler', 'Handler', 'InlineQueryHandler',
'MessageHandler', 'BaseFilter', 'Filters', 'RegexHandler', 'StringCommandHandler',
'StringRegexHandler', 'TypeHandler', 'ConversationHandler')
'StringRegexHandler', 'TypeHandler', 'ConversationHandler',
'PreCheckoutQueryHandler', 'ShippingQueryHandler')
70 changes: 70 additions & 0 deletions telegram/ext/precheckoutqueryhandler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the PreCheckoutQueryHandler class """

from telegram import Update
from .handler import Handler


class PreCheckoutQueryHandler(Handler):
"""
Handler class to handle Telegram PreCheckout callback queries.

Args:
callback (function): A function that takes ``bot, update`` as
positional arguments. It will be called when the ``check_update``
has determined that an update should be processed by this handler.
pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
Default is ``False``.
pass_user_data (optional[bool]): If set to ``True``, a keyword argument called
``user_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the user that sent the update. For each update of
the same user, it will be the same ``dict``. Default is ``False``.
pass_chat_data (optional[bool]): If set to ``True``, a keyword argument called
``chat_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the chat that the update was sent in.
For each update in the same chat, it will be the same ``dict``. Default is ``False``.
"""

def __init__(self,
callback,
pass_update_queue=False,
pass_job_queue=False,
pass_user_data=False,
pass_chat_data=False):
super(PreCheckoutQueryHandler, self).__init__(
callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue,
pass_user_data=pass_user_data,
pass_chat_data=pass_chat_data)

def check_update(self, update):
if isinstance(update, Update) and update.pre_checkout_query:
return True

def handle_update(self, update, dispatcher):
optional_args = self.collect_optional_args(dispatcher, update)
return self.callback(dispatcher.bot, update, **optional_args)
70 changes: 70 additions & 0 deletions telegram/ext/shippingqueryhandler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the ShippingQueryHandler class """

from telegram import Update
from .handler import Handler


class ShippingQueryHandler(Handler):
"""
Handler class to handle Telegram shipping callback queries.

Args:
callback (function): A function that takes ``bot, update`` as
positional arguments. It will be called when the ``check_update``
has determined that an update should be processed by this handler.
pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
Default is ``False``.
pass_user_data (optional[bool]): If set to ``True``, a keyword argument called
``user_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the user that sent the update. For each update of
the same user, it will be the same ``dict``. Default is ``False``.
pass_chat_data (optional[bool]): If set to ``True``, a keyword argument called
``chat_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the chat that the update was sent in.
For each update in the same chat, it will be the same ``dict``. Default is ``False``.
"""

def __init__(self,
callback,
pass_update_queue=False,
pass_job_queue=False,
pass_user_data=False,
pass_chat_data=False):
super(ShippingQueryHandler, self).__init__(
callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue,
pass_user_data=pass_user_data,
pass_chat_data=pass_chat_data)

def check_update(self, update):
if isinstance(update, Update) and update.shipping_query:
return True

def handle_update(self, update, dispatcher):
optional_args = self.collect_optional_args(dispatcher, update)
return self.callback(dispatcher.bot, update, **optional_args)
4 changes: 4 additions & 0 deletions telegram/precheckoutquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,7 @@ def to_dict(self):
data['from'] = data.pop('from_user', None)

return data

def answer(self, *args, **kwargs):
"""Shortcut for ``bot.answerPreCheckoutQuery(update.pre_checkout_query.id, *args, **kwargs)``"""
return self.bot.answerPreCheckoutQuery(self.id, *args, **kwargs)
4 changes: 4 additions & 0 deletions telegram/shippingquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,7 @@ def to_dict(self):
data['from'] = data.pop('from_user', None)

return data

def answer(self, *args, **kwargs):
"""Shortcut for ``bot.answerShippingQuery(update.shipping_query.id, *args, **kwargs)``"""
return self.bot.answerShippingQuery(self.id, *args, **kwargs)
19 changes: 18 additions & 1 deletion telegram/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Update."""

from telegram import (Message, TelegramObject, InlineQuery, ChosenInlineResult, CallbackQuery)
from telegram import (Message, TelegramObject, InlineQuery, ChosenInlineResult,
CallbackQuery, ShippingQuery, PreCheckoutQuery)


class Update(TelegramObject):
Expand All @@ -31,6 +32,8 @@ class Update(TelegramObject):
edited_message (:class:`telegram.Message`): New version of a message that is known to the
bot and was edited
inline_query (:class:`telegram.InlineQuery`): New incoming inline query.
shipping_query (:class:`telegram.ShippingQuery`): New incoming shipping query.
pre_checkout_query (:class:`telegram.PreCheckoutQuery`): New incoming pre-checkout query.
chosen_inline_result (:class:`telegram.ChosenInlineResult`): The result of an inline query
that was chosen by a user and sent to their chat partner.
callback_query (:class:`telegram.CallbackQuery`): New incoming callback query.
Expand All @@ -46,6 +49,8 @@ class Update(TelegramObject):
inline_query (Optional[:class:`telegram.InlineQuery`]):
chosen_inline_result (Optional[:class:`telegram.ChosenInlineResult`])
callback_query (Optional[:class:`telegram.CallbackQuery`]):
shipping_query (Optional[:class:`telegram.ShippingQuery`]):
pre_checkout_query (Optional[:class:`telegram.PreCheckoutQuery`]):
channel_post (Optional[:class:`telegram.Message`]):
edited_channel_post (Optional[:class:`telegram.Message`]):
**kwargs: Arbitrary keyword arguments.
Expand All @@ -59,6 +64,8 @@ def __init__(self,
inline_query=None,
chosen_inline_result=None,
callback_query=None,
shipping_query=None,
pre_checkout_query=None,
channel_post=None,
edited_channel_post=None,
**kwargs):
Expand All @@ -70,6 +77,8 @@ def __init__(self,
self.inline_query = inline_query
self.chosen_inline_result = chosen_inline_result
self.callback_query = callback_query
self.shipping_query = shipping_query
self.pre_checkout_query = pre_checkout_query
self.channel_post = channel_post
self.edited_channel_post = edited_channel_post

Expand Down Expand Up @@ -100,6 +109,8 @@ def de_json(data, 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)

Expand Down Expand Up @@ -132,6 +143,12 @@ def effective_user(self):
elif self.callback_query:
user = self.callback_query.from_user

elif self.shipping_query:
user = self.shipping_query.from_user

elif self.pre_checkout_query:
user = self.pre_checkout_query.from_user

self._effective_user = user
return user

Expand Down
49 changes: 48 additions & 1 deletion tests/test_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@

sys.path.append('.')

from telegram import Update, Message, TelegramError, User, Chat, Bot, InlineQuery, CallbackQuery
from telegram import (Update, Message, TelegramError, User, Chat, Bot,
InlineQuery, CallbackQuery, ShippingQuery, PreCheckoutQuery)
from telegram.ext import *
from telegram.ext.dispatcher import run_async
from telegram.error import Unauthorized, InvalidToken
Expand Down Expand Up @@ -119,6 +120,14 @@ def telegramCallbackHandlerTest(self, bot, update):
self.received_message = update.callback_query
self.message_count += 1

def telegramShippingHandlerTest(self, bot, update):
self.received_message = update.shipping_query
self.message_count += 1

def telegramPreCheckoutHandlerTest(self, bot, update):
self.received_message = update.pre_checkout_query
self.message_count += 1

@run_async
def asyncHandlerTest(self, bot, update):
sleep(1)
Expand Down Expand Up @@ -488,6 +497,44 @@ def test_addRemoveCallbackQueryHandler(self):
sleep(.1)
self.assertTrue(None is self.received_message)

def test_addRemoveShippingQueryHandler(self):
self._setup_updater('', messages=0)
d = self.updater.dispatcher
handler = ShippingQueryHandler(self.telegramShippingHandlerTest)
d.add_handler(handler)
queue = self.updater.start_polling(0.01)
update = Update(update_id=0, shipping_query="testshipping")
queue.put(update)
sleep(.1)
self.assertEqual(self.received_message, "testshipping")

# Remove handler
d.remove_handler(handler)
self.reset()

queue.put(update)
sleep(.1)
self.assertTrue(None is self.received_message)

def test_addRemovePreCheckoutQueryHandler(self):
self._setup_updater('', messages=0)
d = self.updater.dispatcher
handler = PreCheckoutQueryHandler(self.telegramPreCheckoutHandlerTest)
d.add_handler(handler)
queue = self.updater.start_polling(0.01)
update = Update(update_id=0, pre_checkout_query="testprecheckout")
queue.put(update)
sleep(.1)
self.assertEqual(self.received_message, "testprecheckout")

# Remove handler
d.remove_handler(handler)
self.reset()

queue.put(update)
sleep(.1)
self.assertTrue(None is self.received_message)

def test_runAsync(self):
self._setup_updater('Test5', messages=2)
d = self.updater.dispatcher
Expand Down