Merge pull request #622 from python-telegram-bot/payment

Payment stuff

refs #617
This commit is contained in:
Noam Meltzer 2017-06-02 11:14:18 +03:00 committed by GitHub
commit 90e9e32632
24 changed files with 1598 additions and 80 deletions

0
examples/paymentbot.py Normal file
View file

View file

@ -50,6 +50,10 @@ from .parsemode import ParseMode
from .messageentity import MessageEntity
from .animation import Animation
from .game import Game
from .shippingaddress import ShippingAddress
from .orderinfo import OrderInfo
from .successfulpayment import SuccessfulPayment
from .invoice import Invoice
from .message import Message
from .inputmessagecontent import InputMessageContent
from .callbackquery import CallbackQuery
@ -82,6 +86,10 @@ from .inputtextmessagecontent import InputTextMessageContent
from .inputlocationmessagecontent import InputLocationMessageContent
from .inputvenuemessagecontent import InputVenueMessageContent
from .inputcontactmessagecontent import InputContactMessageContent
from .labeledprice import LabeledPrice
from .shippingoption import ShippingOption
from .precheckoutquery import PreCheckoutQuery
from .shippingquery import ShippingQuery
from .webhookinfo import WebhookInfo
from .gamehighscore import GameHighScore
from .videonote import VideoNote
@ -114,5 +122,6 @@ __all__ = [
'Video', 'Voice', 'MAX_MESSAGE_LENGTH', 'MAX_CAPTION_LENGTH', 'SUPPORTED_WEBHOOK_PORTS',
'MAX_FILESIZE_DOWNLOAD', 'MAX_FILESIZE_UPLOAD', 'MAX_MESSAGES_PER_SECOND_PER_CHAT',
'MAX_MESSAGES_PER_SECOND', 'MAX_MESSAGES_PER_MINUTE_PER_GROUP', 'WebhookInfo', 'Animation',
'Game', 'GameHighScore', 'VideoNote'
'Game', 'GameHighScore', 'VideoNote', 'LabeledPrice', 'SuccessfulPayment', 'ShippingOption',
'ShippingAddress', 'PreCheckoutQuery', 'OrderInfo', 'Invoice', 'ShippingQuery'
]

View file

@ -1818,6 +1818,182 @@ class Bot(TelegramObject):
return [GameHighScore.de_json(hs, self) for hs in result]
@log
@message
def send_invoice(self,
chat_id,
title,
description,
payload,
provider_token,
start_parameter,
currency,
prices,
photo_url=None,
photo_size=None,
photo_width=None,
photo_height=None,
need_name=None,
need_phone_number=None,
need_shipping_address=None,
is_flexible=None,
disable_notification=False,
reply_to_message_id=None,
reply_markup=None,
timeout=None,
**kwargs):
"""
Use this method to send invoices.
Args:
chat_id (int|str): Unique identifier for the target private chat
title (str): Product name
description (str): Product description
payload (str): Bot-defined invoice payload, 1-128 bytes. This will not be displayed
to the user, use for your internal processes.
provider_token (str): Payments provider token, obtained via Botfather
start_parameter (str): Unique deep-linking parameter that can be used to generate
this invoice when used as a start parameter
currency (str): Three-letter ISO 4217 currency code
prices (List[:class:`telegram.LabeledPrice`]): Price breakdown, a list of components
(e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
photo_url (Optional[str]): URL of the product photo for the invoice. Can be a photo of
the goods or a marketing image for a service. People like it better when they
see what they are paying for.
photo_size (Optional[str]): Photo size
photo_width (Optional[int]): Photo width
photo_height (Optional[int]): Photo height
need_name (Optional[bool]): Pass True, if you require the user's full name to complete
the order
need_phone_number (Optional[bool]): Pass True, if you require the user's phone number
to complete the order
need_shipping_address (Optional[bool]): Pass True, if you require the user's shipping
address to complete the order
is_flexible (Optional[bool]): Pass True, if the final price depends on the shipping
method
disable_notification (Optional[bool]): Sends the message silently. iOS users will not
receive a notification, Android users will receive a notification with no sound.
reply_to_message_id (Optional[int]): If the message is a reply, ID of the original
message.
reply_markup (Optional[:class:`telegram.ReplyMarkup`]): Additional interface options.
An inlinekeyboard. If empty, one 'Pay total price' button will be shown. If not
empty, the first button must be a Pay button.
timeout (Optional[int|float]): If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection
pool).
**kwargs (dict): Arbitrary keyword arguments.
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0}/sendInvoice'.format(self.base_url)
data = {
'chat_id': chat_id,
'title': title,
'description': description,
'payload': payload,
'provider_token': provider_token,
'start_parameter': start_parameter,
'currency': currency,
'prices': [p.to_dict() for p in prices]
}
if photo_url is not None:
data['photo_url'] = photo_url
if photo_size is not None:
data['photo_size'] = photo_size
if photo_width is not None:
data['photo_width'] = photo_width
if photo_height is not None:
data['photo_height'] = photo_height
if need_name is not None:
data['need_name'] = need_name
if need_phone_number is not None:
data['need_phone_number'] = need_phone_number
if need_shipping_address is not None:
data['need_shipping_address'] = need_shipping_address
if is_flexible is not None:
data['is_flexible'] = is_flexible
return url, data
def answer_shipping_query(self,
shipping_query_id,
ok,
shipping_options=None,
error_message=None):
"""
If you sent an invoice requesting a shipping address and the parameter is_flexible was
specified, the Bot API will send an Update with a shipping_query field to the bot. Use
this method to reply to shipping queries.
Args:
shipping_query_id (str): Unique identifier for the query to be answered
ok (bool): Specify True if delivery to the specified address is possible and False if
there are any problems (for example, if delivery to the specified address
is not possible)
shipping_options (Optional[List[:class:`telegram.ShippingOption`]]): Required if ok is
True. A list of available shipping options.
error_message (Optional[str]): Required if ok is False. Error message in human readable
form that explains why it is impossible to complete the order (e.g. "Sorry,
delivery to your desired address is unavailable'). Telegram will display this
message to the user.
Returns:
bool: On success, `True` is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0]/answerShippingQuery'.format(self.base_url)
data = {'shipping_query_id': shipping_query_id, 'ok': ok}
if shipping_options is not None:
data['shipping_options'] = shipping_options
if error_message is not None:
data['error_message'] = error_message
return url, data
def answer_pre_checkout_query(self, pre_checkout_query_id, ok, error_message=None):
"""
If you sent an invoice requesting a shipping address and the parameter is_flexible was
specified, the Bot API will send an Update with a shipping_query field to the bot.
Use this method to reply to shipping queries.
Args:
pre_checkout_query_id (str): Unique identifier for the query to be answered
ok (bool): Specify True if everything is alright (goods are available, etc.) and the
bot is ready to proceed with the order. Use False if there are any problems.
error_message (Optional[str]): Required if ok is False. Error message in human readable
form that explains the reason for failure to proceed with the checkout (e.g.
"Sorry, somebody just bought the last of our amazing black T-shirts while you were
busy filling out your payment details. Please choose a different color or
garment!"). Telegram will display this message to the user.
Returns:
bool: On success, `True` is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '{0]/answerPreCheckoutQuery'.format(self.base_url)
data = {'pre_checkout_query_id': pre_checkout_query_id, 'ok': ok}
if error_message is not None:
data['error_message'] = error_message
return url, data
@staticmethod
def de_json(data, bot):
data = super(Bot, Bot).de_json(data, bot)
@ -1873,3 +2049,6 @@ class Bot(TelegramObject):
getWebhookInfo = get_webhook_info
setGameScore = set_game_score
getGameHighScores = get_game_high_scores
sendInvoice = send_invoice
answerShippingQuery = answer_shipping_query
answerPreCheckoutQuery = answer_pre_checkout_query

View file

@ -324,6 +324,20 @@ class Filters(object):
group = _Group()
class _Invoice(BaseFilter):
def filter(self, message):
return bool(message.invoice)
invoice = _Invoice()
class _SuccessfulPayment(BaseFilter):
def filter(self, message):
return bool(message.successful_payment)
successful_payment = _SuccessfulPayment()
class language(BaseFilter):
"""
Filters messages to only allow those which are from users with a certain language code.

View file

@ -46,7 +46,10 @@ class InlineKeyboardButton(TelegramObject):
the bot's username and the specified inline query in the current chat's input field.
Can be empty, in which case only the bot's username will be inserted.
callback_game (Optional[:class:`telegram.CallbackGame`]): Description of the game that will
be launched when the user presses the button.
be launched when the user presses the button. NOTE: This type of button must always be
the first button in the first row.
pay (Optional[bool]): Specify True, to send a Pay button. NOTE: This type of button must
always be the first button in the first row.
**kwargs (dict): Arbitrary keyword arguments.
"""
@ -58,6 +61,7 @@ class InlineKeyboardButton(TelegramObject):
switch_inline_query=None,
switch_inline_query_current_chat=None,
callback_game=None,
pay=None,
**kwargs):
# Required
self.text = text
@ -68,6 +72,7 @@ class InlineKeyboardButton(TelegramObject):
self.switch_inline_query = switch_inline_query
self.switch_inline_query_current_chat = switch_inline_query_current_chat
self.callback_game = callback_game
self.pay = pay
@staticmethod
def de_json(data, bot):

58
telegram/invoice.py Normal file
View file

@ -0,0 +1,58 @@
#!/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 an object that represents a Telegram Invoice."""
from telegram import TelegramObject
class Invoice(TelegramObject):
"""This object contains basic information about an invoice.
Attributes:
title (str): Product name
description (str): Product description
start_parameter (str): Unique bot deep-linking parameter that can
be used to generate this invoice
currency (str): Three-letter ISO 4217 currency code
total_amount (int): Total price in the smallest units of the currency (integer)
**kwargs (dict): Arbitrary keyword arguments.
"""
def __init__(self, title, description, start_parameter, currency, total_amount, **kwargs):
self.title = title
self.description = description
self.start_parameter = start_parameter
self.currency = currency
self.total_amount = total_amount
@staticmethod
def de_json(data, bot):
"""
Args:
data (dict):
bot (telegram.Bot):
Returns:
telegram.Invoice:
"""
if not data:
return None
return Invoice(**data)

70
telegram/labeledprice.py Normal file
View file

@ -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 an object that represents a Telegram LabeledPrice."""
from telegram import TelegramObject
class LabeledPrice(TelegramObject):
"""This object represents a portion of the price for goods or services.
Attributes:
label (str): Portion label
amount (int): Price of the product in the smallest units of the currency (integer)
**kwargs (dict): Arbitrary keyword arguments.
"""
def __init__(self, label, amount, **kwargs):
self.label = label
self.amount = amount
@staticmethod
def de_json(data, bot):
"""
Args:
data (dict):
bot (telegram.Bot):
Returns:
telegram.LabeledPrice:
"""
if not data:
return None
return LabeledPrice(**data)
@staticmethod
def de_list(data, bot):
"""
Args:
data (list):
bot (telegram.Bot):
Returns:
List<telegram.PhotoSize>:
"""
if not data:
return []
labeled_prices = list()
for labeled_price in data:
labeled_prices.append(LabeledPrice.de_json(labeled_price, bot))
return labeled_prices

View file

@ -23,7 +23,7 @@ from datetime import datetime
from time import mktime
from telegram import (Audio, Contact, Document, Chat, Location, PhotoSize, Sticker, TelegramObject,
User, Video, Voice, Venue, MessageEntity, Game)
User, Video, Voice, Venue, MessageEntity, Game, Invoice, SuccessfulPayment)
from telegram.utils.deprecate import warn_deprecate_obj
from telegram.utils.helpers import escape_html, escape_markdown
from telegram.videonote import VideoNote
@ -36,38 +36,69 @@ class Message(TelegramObject):
* In Python `from` is a reserved word, use `from_user` instead.
Attributes:
message_id (int):
from_user (:class:`telegram.User`):
date (:class:`datetime.datetime`):
forward_from (:class:`telegram.User`):
forward_from_chat (:class:`telegram.Chat`):
forward_from_message_id (int):
forward_date (:class:`datetime.datetime`):
reply_to_message (:class:`telegram.Message`):
edit_date (:class:`datetime.datetime`):
text (str):
audio (:class:`telegram.Audio`):
document (:class:`telegram.Document`):
game (:class:`telegram.Game`):
photo (List[:class:`telegram.PhotoSize`]):
sticker (:class:`telegram.Sticker`):
video (:class:`telegram.Video`):
voice (:class:`telegram.Voice`):
message_id (int): Unique message identifier inside this chat
from_user (:class:`telegram.User`): Sender, can be empty for messages sent to channels
date (:class:`datetime.datetime`): Date the message was sent in Unix time
chat (:class:`telegram.Chat`): Conversation the message belongs to
forward_from (:class:`telegram.User`): For forwarded messages, sender of the original
message
forward_from_chat (:class:`telegram.Chat`): For messages forwarded from a channel,
information about the original channel
forward_from_message_id (int): For forwarded channel posts, identifier of the original
message in the channel
forward_date (:class:`datetime.datetime`): For forwarded messages, date the original
message was sent in Unix time
reply_to_message (:class:`telegram.Message`): For replies, the original message. Note
that the Message object in this field will not contain further reply_to_message
fields even if it itself is a reply.
edit_date (:class:`datetime.datetime`): Date the message was last edited in Unix time
text (str): For text messages, the actual UTF-8 text of the message, 0-4096 characters.
entities (List[:class:`telegram.MessageEntity`]): For text messages, special entities
like usernames, URLs, bot commands, etc. that appear in the text. See
parse_entity and parse_entities methods for how to use properly
video_note (:class:`telegram.VideoNote`): Message is a video note, information about the
video message
caption (str):
contact (:class:`telegram.Contact`):
location (:class:`telegram.Location`):
new_chat_member (:class:`telegram.User`):
left_chat_member (:class:`telegram.User`):
new_chat_title (str):
new_chat_photo (List[:class:`telegram.PhotoSize`]):
delete_chat_photo (bool):
group_chat_created (bool):
supergroup_chat_created (bool):
migrate_to_chat_id (int):
migrate_from_chat_id (int):
channel_chat_created (bool):
audio (:class:`telegram.Audio`): Message is an audio file, information about the file
document (:class:`telegram.Document`): Message is a general file, information about the
file
game (:class:`telegram.Game`):Message is a game, information about the game
photo (List[:class:`telegram.PhotoSize`]): Message is a photo, available sizes of the photo
sticker (:class:`telegram.Sticker`): Message is a sticker, information about the sticker
video (:class:`telegram.Video`): Message is a video, information about the video
voice (:class:`telegram.Voice`): Message is a voice message, information about the file
caption (str): Caption for the document, photo or video, 0-200 characters
contact (:class:`telegram.Contact`): Message is a shared contact, information about the
contact
location (:class:`telegram.Location`): Message is a shared location, information about the
location
new_chat_member (:class:`telegram.User`): A new member was added to the group,
information about them (this member may be the bot itself)
left_chat_member (:class:`telegram.User`): A member was removed from the group,
information about them (this member may be the bot itself)
new_chat_title (str): A chat title was changed to this value
new_chat_photo (List[:class:`telegram.PhotoSize`]): A chat photo was change to this value
delete_chat_photo (bool): Service message: the chat photo was deleted
group_chat_created (bool): Service message: the group has been created
supergroup_chat_created (bool): Service message: the supergroup has been created. This
field can't be received in a message coming through updates, because bot can't be a
member of a supergroup when it is created. It can only be found in reply_to_message
if someone replies to a very first message in a directly created supergroup.
migrate_to_chat_id (int): The group has been migrated to a supergroup with the specified
identifier.
migrate_from_chat_id (int): The supergroup has been migrated from a group with the
specified identifier.
channel_chat_created (bool): Service message: the channel has been created. This field
can't be received in a message coming through updates, because bot can't be a member
of a channel when it is created. It can only be found in reply_to_message if someone
replies to a very first message in a channel.
pinned_message (:class:`telegram.message`): Specified message was pinned. Note that the
Message object in this field will not contain further reply_to_message fields even if
it is itself a reply.
invoice (:class:`telegram.Invoice`): Message is an invoice for a payment, information
about the invoice.
successful_payment (:class:`telegram.SuccessfulPayment`): Message is a service message
about a successful payment, information about the payment.
bot (Optional[Bot]): The Bot to use for instance methods
Deprecated: 4.0
new_chat_participant (:class:`telegram.User`): Use `new_chat_member`
@ -76,40 +107,6 @@ class Message(TelegramObject):
left_chat_participant (:class:`telegram.User`): Use `left_chat_member`
instead.
Args:
message_id (int):
from_user (:class:`telegram.User`):
date (:class:`datetime.datetime`):
chat (:class:`telegram.Chat`):
forward_from (Optional[:class:`telegram.User`]):
forward_from_chat (Optional[:class:`telegram.Chat`]):
forward_from_message_id (Optional[int]):
forward_date (Optional[:class:`datetime.datetime`]):
reply_to_message (Optional[:class:`telegram.Message`]):
edit_date (Optional[:class:`datetime.datetime`]):
text (Optional[str]):
audio (Optional[:class:`telegram.Audio`]):
document (Optional[:class:`telegram.Document`]):
game (Optional[:class:`telegram.Game`]):
photo (Optional[List[:class:`telegram.PhotoSize`]]):
sticker (Optional[:class:`telegram.Sticker`]):
video (Optional[:class:`telegram.Video`]):
voice (Optional[:class:`telegram.Voice`]):
video_note (Optional[:class:`telegram.VideoNote`]):
caption (Optional[str]):
contact (Optional[:class:`telegram.Contact`]):
location (Optional[:class:`telegram.Location`]):
new_chat_member (Optional[:class:`telegram.User`]):
left_chat_member (Optional[:class:`telegram.User`]):
new_chat_title (Optional[str]):
new_chat_photo (Optional[List[:class:`telegram.PhotoSize`]):
delete_chat_photo (Optional[bool]):
group_chat_created (Optional[bool]):
supergroup_chat_created (Optional[bool]):
migrate_to_chat_id (Optional[int]):
migrate_from_chat_id (Optional[int]):
channel_chat_created (Optional[bool]):
bot (Optional[Bot]): The Bot to use for instance methods
"""
def __init__(self,
@ -147,6 +144,8 @@ class Message(TelegramObject):
channel_chat_created=False,
pinned_message=None,
forward_from_message_id=None,
invoice=None,
successful_payment=None,
bot=None,
video_note=None,
**kwargs):
@ -188,6 +187,8 @@ class Message(TelegramObject):
self.channel_chat_created = bool(channel_chat_created)
self.pinned_message = pinned_message
self.forward_from_message_id = forward_from_message_id
self.invoice = invoice
self.successful_payment = successful_payment
self.bot = bot
@ -238,6 +239,8 @@ class Message(TelegramObject):
data['left_chat_member'] = User.de_json(data.get('left_chat_member'), bot)
data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'), bot)
data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)
data['invoice'] = Invoice.de_json(data.get('invoice'), bot)
data['successful_payment'] = SuccessfulPayment.de_json(data.get('successful_payment'), bot)
return Message(bot=bot, **data)

59
telegram/orderinfo.py Normal file
View file

@ -0,0 +1,59 @@
#!/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 an object that represents a Telegram OrderInfo."""
from telegram import TelegramObject, ShippingAddress
class OrderInfo(TelegramObject):
"""This object represents information about an order.
Attributes:
name (Optional[str]): User name
phone_number (Optional[str]): User's phone number
email (Optional[str]): User email
shipping_address (Optional[:class:`telegram.ShippingAddress`]): User shipping address
**kwargs (dict): Arbitrary keyword arguments.
"""
def __init__(self, name=None, phone_number=None, email=None, shipping_address=None, **kwargs):
self.name = name
self.phone_number = phone_number
self.email = email
self.shipping_address = shipping_address
@staticmethod
def de_json(data, bot):
"""
Args:
data (dict):
bot (telegram.Bot):
Returns:
telegram.OrderInfo:
"""
if not data:
return OrderInfo()
data = super(OrderInfo, OrderInfo).de_json(data, bot)
data['shipping_address'] = ShippingAddress.de_json(data.get('shipping_address'), bot)
return OrderInfo(**data)

View file

@ -0,0 +1,90 @@
#!/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 an object that represents a Telegram PreCheckoutQuery."""
from telegram import TelegramObject, User, OrderInfo
class PreCheckoutQuery(TelegramObject):
"""This object contains information about an incoming pre-checkout query.
Note:
* In Python `from` is a reserved word, use `from_user` instead.
Attributes:
id (str): Unique query identifier
from_user (:class:`telegram.User`): User who sent the query
currency (str): Three-letter ISO 4217 currency code
total_amount (int): Total price in the smallest units of the currency (integer)
invoice_payload (str): Bot specified invoice payload
shipping_option_id (Optional[str]): Identifier of the shipping option chosen by the user
order_info (Optional[:class:`telegram.OrderInfo`]): Order info provided by the user
**kwargs (dict): Arbitrary keyword arguments.
"""
def __init__(self,
id,
from_user,
currency,
total_amount,
invoice_payload,
shipping_option_id=None,
order_info=None,
**kwargs):
self.id = id
self.from_user = from_user
self.currency = currency
self.total_amount = total_amount
self.invoice_payload = invoice_payload
self.shipping_option_id = shipping_option_id
self.order_info = order_info
self._id_attrs = (self.id,)
@staticmethod
def de_json(data, bot):
"""
Args:
data (dict):
bot (telegram.Bot):
Returns:
telegram.PreCheckoutQuery:
"""
if not data:
return None
data = super(PreCheckoutQuery, PreCheckoutQuery).de_json(data, bot)
data['from_user'] = User.de_json(data.pop('from'), bot)
data['order_info'] = OrderInfo.de_json(data.get('order_info'), bot)
return PreCheckoutQuery(**data)
def to_dict(self):
"""
Returns:
dict:
"""
data = super(PreCheckoutQuery, self).to_dict()
data['from'] = data.pop('from_user', None)
return data

View file

@ -0,0 +1,62 @@
#!/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 an object that represents a Telegram ShippingAddress."""
from telegram import TelegramObject
class ShippingAddress(TelegramObject):
"""This object represents a Telegram ShippingAddress.
Attributes:
country_code (str): ISO 3166-1 alpha-2 country code
state (str): State, if applicable
city (str): City
street_line1 (str): First line for the address
street_line2 (str): Second line for the address
post_code (str): Address post code
**kwargs (dict): Arbitrary keyword arguments.
"""
def __init__(self, country_code, state, city, street_line1, street_line2, post_code, **kwargs):
self.country_code = country_code
self.state = state
self.city = city
self.street_line1 = street_line1
self.street_line2 = street_line2
self.post_code = post_code
self._id_attrs = (self.country_code, self.state, self.city, self.street_line1,
self.street_line2, self.post_code)
@staticmethod
def de_json(data, bot):
"""
Args:
data (dict):
bot (telegram.Bot):
Returns:
telegram.ShippingAddress:
"""
if not data:
return None
return ShippingAddress(**data)

View file

@ -0,0 +1,73 @@
#!/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 an object that represents a Telegram ShippingOption."""
from telegram import TelegramObject, LabeledPrice
class ShippingOption(TelegramObject):
"""This object represents one shipping option.
Note:
* In Python `from` is a reserved word, use `from_user` instead.
Attributes:
id (str): Shipping option identifier
title (str): Option title
prices (List[:class:`telegram.LabeledPrice`]): List of price portions
**kwargs (dict): Arbitrary keyword arguments.
"""
def __init__(self, id, title, prices, **kwargs):
self.id = id
self.title = title
self.prices = prices
self._id_attrs = (self.id,)
@staticmethod
def de_json(data, bot):
"""
Args:
data (dict):
bot (telegram.Bot):
Returns:
telegram.ShippingOption:
"""
if not data:
return None
data = super(ShippingOption, ShippingOption).de_json(data, bot)
data['prices'] = LabeledPrice.de_list(data.get('prices'), bot)
return ShippingOption(**data)
def to_dict(self):
"""
Returns:
dict:
"""
data = super(ShippingOption, self).to_dict()
data['prices'] = [p.to_dict() for p in self.prices]
return data

76
telegram/shippingquery.py Normal file
View file

@ -0,0 +1,76 @@
#!/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 an object that represents a Telegram ShippingQuery."""
from telegram import TelegramObject, User, ShippingAddress
class ShippingQuery(TelegramObject):
"""This object contains information about an incoming shipping query.
Note:
* In Python `from` is a reserved word, use `from_user` instead.
Attributes:
id (str): Unique query identifier
from_user (:class:`telegram.User`): User who sent the query
invoice_payload (str): Bot specified invoice payload
shipping_address (:class:`telegram.ShippingQuery`): User specified shipping address
**kwargs (dict): Arbitrary keyword arguments.
"""
def __init__(self, id, from_user, invoice_payload, shipping_address, **kwargs):
self.id = id
self.from_user = from_user
self.invoice_payload = invoice_payload
self.shipping_address = shipping_address
self._id_attrs = (self.id,)
@staticmethod
def de_json(data, bot):
"""
Args:
data (dict):
bot (telegram.Bot):
Returns:
telegram.ShippingQuery:
"""
if not data:
return None
data = super(ShippingQuery, ShippingQuery).de_json(data, bot)
data['from_user'] = User.de_json(data.pop('from'), bot)
data['shipping_address'] = ShippingAddress.de_json(data.get('shipping_address'), bot)
return ShippingQuery(**data)
def to_dict(self):
"""
Returns:
dict:
"""
data = super(ShippingQuery, self).to_dict()
data['from'] = data.pop('from_user', None)
return data

View file

@ -0,0 +1,77 @@
#!/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 an object that represents a Telegram SuccessfulPayment."""
from telegram import TelegramObject, OrderInfo
class SuccessfulPayment(TelegramObject):
"""This object contains basic information about a successful payment.
Note:
* In Python `from` is a reserved word, use `from_user` instead.
Attributes:
currency (str): Three-letter ISO 4217 currency code
total_amount (int): Total price in the smallest units of the currency (integer)
invoice_payload (str): Bot specified invoice payload
telegram_payment_charge_id (str): Telegram payment identifier
provider_payment_charge_id (str): Provider payment identifier
shipping_option_id (Optional[str]): Identifier of the shipping option chosen by the user
order_info (Optional[:class:`telegram.OrderInfo`]): Order info provided by the user
**kwargs (dict): Arbitrary keyword arguments.
"""
def __init__(self,
currency,
total_amount,
invoice_payload,
telegram_payment_charge_id,
provider_payment_charge_id,
shipping_option_id=None,
order_info=None,
**kwargs):
self.currency = currency
self.total_amount = total_amount
self.invoice_payload = invoice_payload
self.shipping_option_id = shipping_option_id
self.order_info = order_info
self.telegram_payment_charge_id = telegram_payment_charge_id
self.provider_payment_charge_id = provider_payment_charge_id
self._id_attrs = (self.telegram_payment_charge_id, self.provider_payment_charge_id)
@staticmethod
def de_json(data, bot):
"""
Args:
data (dict):
bot (telegram.Bot):
Returns:
telegram.SuccessfulPayment:
"""
if not data:
return None
data = super(SuccessfulPayment, SuccessfulPayment).de_json(data, bot)
data['order_info'] = OrderInfo.de_json(data.get('order_info'), bot)
return SuccessfulPayment(**data)

View file

@ -44,6 +44,8 @@ class BaseTest(object):
self._channel_id = os.environ.get('CHANNEL_ID', '@pythontelegrambottests')
self._bot = bot
self._chat_id = chat_id
self._payment_provider_token = os.environ.get('PAYMENT_PROVIDER_TOKEN',
'284685063:TEST:ZGJlMmQxZDI3ZTc3')
@staticmethod
def is_json(string):

121
tests/test_invoice.py Normal file
View file

@ -0,0 +1,121 @@
#!/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 General 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
Invoice"""
import sys
import unittest
from flaky import flaky
sys.path.append('.')
import telegram
from tests.base import BaseTest, timeout
class InvoiceTest(BaseTest, unittest.TestCase):
"""This object represents Tests for Telegram Invoice."""
def setUp(self):
self.payload = 'payload'
self.provider_token = self._payment_provider_token
self.prices = [telegram.LabeledPrice('Fish', 100), telegram.LabeledPrice('Fish Tax', 1000)]
self.title = 'title'
self.description = 'description'
self.start_parameter = 'start_parameter'
self.currency = 'EUR'
self.total_amount = sum([p.amount for p in self.prices])
self.json_dict = {
'title': self.title,
'description': self.description,
'start_parameter': self.start_parameter,
'currency': self.currency,
'total_amount': self.total_amount
}
def test_invoice_de_json(self):
invoice = telegram.Invoice.de_json(self.json_dict, self._bot)
self.assertEqual(invoice.title, self.title)
self.assertEqual(invoice.description, self.description)
self.assertEqual(invoice.start_parameter, self.start_parameter)
self.assertEqual(invoice.currency, self.currency)
self.assertEqual(invoice.total_amount, self.total_amount)
def test_invoice_to_json(self):
invoice = telegram.Invoice.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(invoice.to_json()))
def test_invoice_to_dict(self):
invoice = telegram.Invoice.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(invoice))
self.assertDictEqual(self.json_dict, invoice)
@flaky(3, 1)
@timeout(10)
def test_send_invoice_required_args_only(self):
message = self._bot.send_invoice(self._chat_id, self.title, self.description, self.payload,
self.provider_token, self.start_parameter, self.currency,
self.prices)
invoice = message.invoice
self.assertEqual(invoice.currency, self.currency)
self.assertEqual(invoice.start_parameter, self.start_parameter)
self.assertEqual(invoice.description, self.description)
self.assertEqual(invoice.title, self.title)
self.assertEqual(invoice.total_amount, self.total_amount)
@flaky(3, 1)
@timeout(10)
def test_send_invoice_all_args(self):
message = self._bot.send_invoice(
self._chat_id,
self.title,
self.description,
self.payload,
self.provider_token,
self.start_parameter,
self.currency,
self.prices,
photo_url='https://raw.githubusercontent.com/'
'python-telegram-bot/logos/master/'
'logo/png/ptb-logo_240.png',
photo_size=240,
photo_width=240,
photo_height=240,
need_name=True,
need_phone_number=True,
need_shipping_address=True,
is_flexible=True)
invoice = message.invoice
self.assertEqual(invoice.currency, self.currency)
self.assertEqual(invoice.start_parameter, self.start_parameter)
self.assertEqual(invoice.description, self.description)
self.assertEqual(invoice.title, self.title)
self.assertEqual(invoice.total_amount, self.total_amount)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,59 @@
#!/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 General 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
LabeledPrice"""
import sys
import unittest
sys.path.append('.')
import telegram
from tests.base import BaseTest
class LabeledPriceTest(BaseTest, unittest.TestCase):
"""This object represents Tests for Telegram LabeledPrice."""
def setUp(self):
self.label = 'label'
self.amount = 100
self.json_dict = {'label': self.label, 'amount': self.amount}
def test_labeledprice_de_json(self):
labeledprice = telegram.LabeledPrice.de_json(self.json_dict, self._bot)
self.assertEqual(labeledprice.label, self.label)
self.assertEqual(labeledprice.amount, self.amount)
def test_labeledprice_to_json(self):
labeledprice = telegram.LabeledPrice.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(labeledprice.to_json()))
def test_labeledprice_to_dict(self):
labeledprice = telegram.LabeledPrice.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(labeledprice))
self.assertDictEqual(self.json_dict, labeledprice)
if __name__ == '__main__':
unittest.main()

View file

@ -44,24 +44,24 @@ class MessageEntityTest(BaseTest, unittest.TestCase):
'url': self.url
}
def test_sticker_de_json(self):
sticker = telegram.MessageEntity.de_json(self.json_dict, self._bot)
def test_messageentity_de_json(self):
entity = telegram.MessageEntity.de_json(self.json_dict, self._bot)
self.assertEqual(sticker.type, self.type)
self.assertEqual(sticker.offset, self.offset)
self.assertEqual(sticker.length, self.length)
self.assertEqual(sticker.url, self.url)
self.assertEqual(entity.type, self.type)
self.assertEqual(entity.offset, self.offset)
self.assertEqual(entity.length, self.length)
self.assertEqual(entity.url, self.url)
def test_sticker_to_json(self):
sticker = telegram.MessageEntity.de_json(self.json_dict, self._bot)
def test_messageentity_to_json(self):
entity = telegram.MessageEntity.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(sticker.to_json()))
self.assertTrue(self.is_json(entity.to_json()))
def test_sticker_to_dict(self):
sticker = telegram.MessageEntity.de_json(self.json_dict, self._bot).to_dict()
def test_messageentity_to_dict(self):
entity = telegram.MessageEntity.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(sticker))
self.assertDictEqual(self.json_dict, sticker)
self.assertTrue(self.is_dict(entity))
self.assertDictEqual(self.json_dict, entity)
if __name__ == '__main__':

69
tests/test_orderinfo.py Normal file
View file

@ -0,0 +1,69 @@
#!/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 General 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
OrderInfo"""
import sys
import unittest
sys.path.append('.')
import telegram
from tests.base import BaseTest
class OrderInfoTest(BaseTest, unittest.TestCase):
"""This object represents Tests for Telegram OrderInfo."""
def setUp(self):
self.name = 'name'
self.phone_number = 'phone_number'
self.email = 'email'
self.shipping_address = telegram.ShippingAddress('GB', '', 'London', '12 Grimmauld Place',
'', 'WC1')
self.json_dict = {
'name': self.name,
'phone_number': self.phone_number,
'email': self.email,
'shipping_address': self.shipping_address.to_dict()
}
def test_orderinfo_de_json(self):
orderinfo = telegram.OrderInfo.de_json(self.json_dict, self._bot)
self.assertEqual(orderinfo.name, self.name)
self.assertEqual(orderinfo.phone_number, self.phone_number)
self.assertEqual(orderinfo.email, self.email)
self.assertEqual(orderinfo.shipping_address, self.shipping_address)
def test_orderinfo_to_json(self):
orderinfo = telegram.OrderInfo.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(orderinfo.to_json()))
def test_orderinfo_to_dict(self):
orderinfo = telegram.OrderInfo.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(orderinfo))
self.assertDictEqual(self.json_dict, orderinfo)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,99 @@
#!/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 General 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
PreCheckoutQuery"""
import sys
import unittest
sys.path.append('.')
import telegram
from tests.base import BaseTest
class PreCheckoutQueryTest(BaseTest, unittest.TestCase):
"""This object represents Tests for Telegram PreCheckoutQuery."""
def setUp(self):
self.id = 5
self.invoice_payload = 'invoice_payload'
self.shipping_option_id = 'shipping_option_id'
self.currency = 'EUR'
self.total_amount = 100
self.from_user = telegram.User(0, '')
self.order_info = telegram.OrderInfo()
self.json_dict = {
'id': self.id,
'invoice_payload': self.invoice_payload,
'shipping_option_id': self.shipping_option_id,
'currency': self.currency,
'total_amount': self.total_amount,
'from': self.from_user.to_dict(),
'order_info': self.order_info.to_dict()
}
def test_precheckoutquery_de_json(self):
precheckoutquery = telegram.PreCheckoutQuery.de_json(self.json_dict, self._bot)
self.assertEqual(precheckoutquery.id, self.id)
self.assertEqual(precheckoutquery.invoice_payload, self.invoice_payload)
self.assertEqual(precheckoutquery.shipping_option_id, self.shipping_option_id)
self.assertEqual(precheckoutquery.currency, self.currency)
self.assertEqual(precheckoutquery.from_user, self.from_user)
self.assertEqual(precheckoutquery.order_info, self.order_info)
def test_precheckoutquery_to_json(self):
precheckoutquery = telegram.PreCheckoutQuery.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(precheckoutquery.to_json()))
def test_precheckoutquery_to_dict(self):
precheckoutquery = telegram.PreCheckoutQuery.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(precheckoutquery))
self.assertDictEqual(self.json_dict, precheckoutquery)
def test_equality(self):
a = telegram.PreCheckoutQuery(self.id, self.from_user, self.currency, self.total_amount,
self.invoice_payload)
b = telegram.PreCheckoutQuery(self.id, self.from_user, self.currency, self.total_amount,
self.invoice_payload)
c = telegram.PreCheckoutQuery(self.id, None, '', 0, '')
d = telegram.PreCheckoutQuery(0, self.from_user, self.currency, self.total_amount,
self.invoice_payload)
e = telegram.Update(self.id)
self.assertEqual(a, b)
self.assertEqual(hash(a), hash(b))
self.assertIsNot(a, b)
self.assertEqual(a, c)
self.assertEqual(hash(a), hash(c))
self.assertNotEqual(a, d)
self.assertNotEqual(hash(a), hash(d))
self.assertNotEqual(a, e)
self.assertNotEqual(hash(a), hash(e))
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,114 @@
#!/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 General 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
ShippingAddress"""
import sys
import unittest
sys.path.append('.')
import telegram
from tests.base import BaseTest
class ShippingAddressTest(BaseTest, unittest.TestCase):
"""This object represents Tests for Telegram ShippingAddress."""
def setUp(self):
self.country_code = 'GB'
self.state = 'state'
self.city = 'London'
self.street_line1 = '12 Grimmauld Place'
self.street_line2 = 'street_line2'
self.post_code = 'WC1'
self.json_dict = {
'country_code': self.country_code,
'state': self.state,
'city': self.city,
'street_line1': self.street_line1,
'street_line2': self.street_line2,
'post_code': self.post_code
}
def test_shippingaddress_de_json(self):
shippingaddress = telegram.ShippingAddress.de_json(self.json_dict, self._bot)
self.assertEqual(shippingaddress.country_code, self.country_code)
self.assertEqual(shippingaddress.state, self.state)
self.assertEqual(shippingaddress.city, self.city)
self.assertEqual(shippingaddress.street_line1, self.street_line1)
self.assertEqual(shippingaddress.street_line2, self.street_line2)
self.assertEqual(shippingaddress.post_code, self.post_code)
def test_shippingaddress_to_json(self):
shippingaddress = telegram.ShippingAddress.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(shippingaddress.to_json()))
def test_shippingaddress_to_dict(self):
shippingaddress = telegram.ShippingAddress.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(shippingaddress))
self.assertDictEqual(self.json_dict, shippingaddress)
def test_equality(self):
a = telegram.ShippingAddress(self.country_code, self.state, self.city, self.street_line1,
self.street_line2, self.post_code)
b = telegram.ShippingAddress(self.country_code, self.state, self.city, self.street_line1,
self.street_line2, self.post_code)
d = telegram.ShippingAddress('', self.state, self.city, self.street_line1,
self.street_line2, self.post_code)
d2 = telegram.ShippingAddress(self.country_code, '', self.city, self.street_line1,
self.street_line2, self.post_code)
d3 = telegram.ShippingAddress(self.country_code, self.state, '', self.street_line1,
self.street_line2, self.post_code)
d4 = telegram.ShippingAddress(self.country_code, self.state, self.city, '',
self.street_line2, self.post_code)
d5 = telegram.ShippingAddress(self.country_code, self.state, self.city, self.street_line1,
'', self.post_code)
d6 = telegram.ShippingAddress(self.country_code, self.state, self.city, self.street_line1,
self.street_line2, '')
self.assertEqual(a, b)
self.assertEqual(hash(a), hash(b))
self.assertIsNot(a, b)
self.assertNotEqual(a, d)
self.assertNotEqual(hash(a), hash(d))
self.assertNotEqual(a, d2)
self.assertNotEqual(hash(a), hash(d2))
self.assertNotEqual(a, d3)
self.assertNotEqual(hash(a), hash(d3))
self.assertNotEqual(a, d4)
self.assertNotEqual(hash(a), hash(d4))
self.assertNotEqual(a, d5)
self.assertNotEqual(hash(a), hash(d5))
self.assertNotEqual(a, d6)
self.assertNotEqual(hash(6), hash(d6))
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,88 @@
#!/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 General 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
ShippingOption"""
import sys
import unittest
sys.path.append('.')
import telegram
from tests.base import BaseTest
class ShippingOptionTest(BaseTest, unittest.TestCase):
"""This object represents Tests for Telegram ShippingOption."""
def setUp(self):
self.id = 'id'
self.title = 'title'
self.prices = [
telegram.LabeledPrice('Fish Container', 100),
telegram.LabeledPrice('Premium Fish Container', 1000)
]
self.json_dict = {
'id': self.id,
'title': self.title,
'prices': [x.to_dict() for x in self.prices]
}
def test_shippingoption_de_json(self):
shippingoption = telegram.ShippingOption.de_json(self.json_dict, self._bot)
self.assertEqual(shippingoption.id, self.id)
self.assertEqual(shippingoption.title, self.title)
self.assertEqual(shippingoption.prices, self.prices)
def test_shippingoption_to_json(self):
shippingoption = telegram.ShippingOption.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(shippingoption.to_json()))
def test_shippingoption_to_dict(self):
shippingoption = telegram.ShippingOption.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(shippingoption))
self.assertDictEqual(self.json_dict, shippingoption)
def test_equality(self):
a = telegram.ShippingOption(self.id, self.title, self.prices)
b = telegram.ShippingOption(self.id, self.title, self.prices)
c = telegram.ShippingOption(self.id, '', [])
d = telegram.ShippingOption(0, self.title, self.prices)
e = telegram.Voice(self.id, 0)
self.assertEqual(a, b)
self.assertEqual(hash(a), hash(b))
self.assertIsNot(a, b)
self.assertEqual(a, c)
self.assertEqual(hash(a), hash(c))
self.assertNotEqual(a, d)
self.assertNotEqual(hash(a), hash(d))
self.assertNotEqual(a, e)
self.assertNotEqual(hash(a), hash(e))
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,91 @@
#!/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 General 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
ShippingQuery"""
import sys
import unittest
sys.path.append('.')
import telegram
from tests.base import BaseTest
class ShippingQueryTest(BaseTest, unittest.TestCase):
"""This object represents Tests for Telegram ShippingQuery."""
def setUp(self):
self.id = 5
self.invoice_payload = 'invoice_payload'
self.from_user = telegram.User(0, '')
self.shipping_address = telegram.ShippingAddress('GB', '', 'London', '12 Grimmauld Place',
'', 'WC1')
self.json_dict = {
'id': self.id,
'invoice_payload': self.invoice_payload,
'from': self.from_user.to_dict(),
'shipping_address': self.shipping_address.to_dict()
}
def test_shippingquery_de_json(self):
shippingquery = telegram.ShippingQuery.de_json(self.json_dict, self._bot)
self.assertEqual(shippingquery.id, self.id)
self.assertEqual(shippingquery.invoice_payload, self.invoice_payload)
self.assertEqual(shippingquery.from_user, self.from_user)
self.assertEqual(shippingquery.shipping_address, self.shipping_address)
def test_shippingquery_to_json(self):
shippingquery = telegram.ShippingQuery.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(shippingquery.to_json()))
def test_shippingquery_to_dict(self):
shippingquery = telegram.ShippingQuery.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(shippingquery))
self.assertDictEqual(self.json_dict, shippingquery)
def test_equality(self):
a = telegram.ShippingQuery(self.id, self.from_user, self.invoice_payload,
self.shipping_address)
b = telegram.ShippingQuery(self.id, self.from_user, self.invoice_payload,
self.shipping_address)
c = telegram.ShippingQuery(self.id, None, '', None)
d = telegram.ShippingQuery(0, self.from_user, self.invoice_payload, self.shipping_address)
e = telegram.Update(self.id)
self.assertEqual(a, b)
self.assertEqual(hash(a), hash(b))
self.assertIsNot(a, b)
self.assertEqual(a, c)
self.assertEqual(hash(a), hash(c))
self.assertNotEqual(a, d)
self.assertNotEqual(hash(a), hash(d))
self.assertNotEqual(a, e)
self.assertNotEqual(hash(a), hash(e))
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,100 @@
#!/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 General 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
SuccessfulPayment"""
import sys
import unittest
sys.path.append('.')
import telegram
from tests.base import BaseTest
class SuccessfulPaymentTest(BaseTest, unittest.TestCase):
"""This object represents Tests for Telegram SuccessfulPayment."""
def setUp(self):
self.invoice_payload = 'invoice_payload'
self.shipping_option_id = 'shipping_option_id'
self.currency = 'EUR'
self.total_amount = 100
self.order_info = telegram.OrderInfo()
self.telegram_payment_charge_id = 'telegram_payment_charge_id'
self.provider_payment_charge_id = 'provider_payment_charge_id'
self.json_dict = {
'invoice_payload': self.invoice_payload,
'shipping_option_id': self.shipping_option_id,
'currency': self.currency,
'total_amount': self.total_amount,
'order_info': self.order_info.to_dict(),
'telegram_payment_charge_id': self.telegram_payment_charge_id,
'provider_payment_charge_id': self.provider_payment_charge_id
}
def test_successfulpayment_de_json(self):
successfulpayment = telegram.SuccessfulPayment.de_json(self.json_dict, self._bot)
self.assertEqual(successfulpayment.invoice_payload, self.invoice_payload)
self.assertEqual(successfulpayment.shipping_option_id, self.shipping_option_id)
self.assertEqual(successfulpayment.currency, self.currency)
self.assertEqual(successfulpayment.order_info, self.order_info)
self.assertEqual(successfulpayment.telegram_payment_charge_id,
self.telegram_payment_charge_id)
self.assertEqual(successfulpayment.provider_payment_charge_id,
self.provider_payment_charge_id)
def test_successfulpayment_to_json(self):
successfulpayment = telegram.SuccessfulPayment.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(successfulpayment.to_json()))
def test_successfulpayment_to_dict(self):
successfulpayment = telegram.SuccessfulPayment.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(successfulpayment))
self.assertDictEqual(self.json_dict, successfulpayment)
def test_equality(self):
a = telegram.SuccessfulPayment(self.currency, self.total_amount, self.invoice_payload,
self.telegram_payment_charge_id,
self.provider_payment_charge_id)
b = telegram.SuccessfulPayment(self.currency, self.total_amount, self.invoice_payload,
self.telegram_payment_charge_id,
self.provider_payment_charge_id)
c = telegram.SuccessfulPayment('', 0, '', self.telegram_payment_charge_id,
self.provider_payment_charge_id)
d = telegram.SuccessfulPayment(self.currency, self.total_amount, self.invoice_payload,
self.telegram_payment_charge_id, '')
self.assertEqual(a, b)
self.assertEqual(hash(a), hash(b))
self.assertIsNot(a, b)
self.assertEqual(a, c)
self.assertEqual(hash(a), hash(c))
self.assertNotEqual(a, d)
self.assertNotEqual(hash(a), hash(d))
if __name__ == '__main__':
unittest.main()