This commit is contained in:
leandrotoledo 2016-04-22 21:33:37 -03:00
commit 203364d939
36 changed files with 628 additions and 226 deletions

View file

@ -108,6 +108,13 @@ getUserProfilePhotos Yes
getFile Yes
setWebhook Yes
answerInlineQuery Yes
kickChatMember Yes
unbanChatMember Yes
answerCallbackQuery Yes
editMessageText Yes
editMessageCaption Yes
editMessageReplyMarkup Yes
answerCallbackQuery Yes
========================= ============
-------------------------
@ -273,7 +280,8 @@ To tell the user that something is happening on bot's side::
To create `Custom Keyboards <https://core.telegram.org/bots#keyboards>`_::
>>> custom_keyboard = [[ telegram.Emoji.THUMBS_UP_SIGN, telegram.Emoji.THUMBS_DOWN_SIGN ]]
>>> custom_keyboard = [[ telegram.KeyboardButton(telegram.Emoji.THUMBS_UP_SIGN),
... telegram.KeyboardButton(telegram.Emoji.THUMBS_DOWN_SIGN) ]]
>>> reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard)
>>> bot.sendMessage(chat_id=chat_id, text="Stay here, I'll be back.", reply_markup=reply_markup)

View file

@ -1,7 +1,7 @@
telegram.jobqueue module
telegram.ext.jobqueue module
========================
.. automodule:: telegram.jobqueue
.. automodule:: telegram.ext.jobqueue
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinekeyboardbutton module
===========================
.. automodule:: telegram.inlinekeyboardbutton
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinekeyboardmarkup module
==========================
.. automodule:: telegram.inlinekeyboardmarkup
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultarticle module
=================================
.. automodule:: telegram.inlinequeryresultarticle
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultaudio module
=================================
.. automodule:: telegram.inlinequeryresultaudio
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultcachedaudio module
=================================
.. automodule:: telegram.inlinequeryresultcachedaudio
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultcacheddocument module
=================================
.. automodule:: telegram.inlinequeryresultcacheddocument
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultcachedgif module
=================================
.. automodule:: telegram.inlinequeryresultcachedgif
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultcachedmpeg4gif module
=================================
.. automodule:: telegram.inlinequeryresultcachedmpeg4gif
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultcachedphoto module
=================================
.. automodule:: telegram.inlinequeryresultcachedphoto
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultcachedsticker module
=================================
.. automodule:: telegram.inlinequeryresultcachedsticker
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultcachedvideo module
=================================
.. automodule:: telegram.inlinequeryresultcachedvideo
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultcachedvoice module
=================================
.. automodule:: telegram.inlinequeryresultcachedvoice
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultcontact module
=================================
.. automodule:: telegram.inlinequeryresultcontact
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultdocument module
=================================
.. automodule:: telegram.inlinequeryresultdocument
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultgif module
=================================
.. automodule:: telegram.inlinequeryresultgif
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultlocation module
=================================
.. automodule:: telegram.inlinequeryresultlocation
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultmpeg4gif module
=================================
.. automodule:: telegram.inlinequeryresultmpeg4gif
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultphoto module
=================================
.. automodule:: telegram.inlinequeryresultphoto
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultvenue module
=================================
.. automodule:: telegram.inlinequeryresultvenue
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultvideo module
=================================
.. automodule:: telegram.inlinequeryresultvideo
:members:
:undoc-members:
:show-inheritance:

View file

@ -0,0 +1,7 @@
telegram.inlinequeryresultvoice module
=================================
.. automodule:: telegram.inlinequeryresultvoice
:members:
:undoc-members:
:show-inheritance:

View file

@ -11,9 +11,30 @@ Submodules
telegram.bot
telegram.ext.updater
telegram.ext.dispatcher
telegram.jobqueue
telegram.ext.jobqueue
telegram.inlinequery
telegram.inlinequeryresult
telegram.inlinekeyboardbutton
telegram.inlinekeyboardmarkup
telegram.inlinequeryresultarticle
telegram.inlinequeryresultaudio
telegram.inlinequeryresultcachedaudio
telegram.inlinequeryresultcacheddocument
telegram.inlinequeryresultcachedgif
telegram.inlinequeryresultcachedmpeg4gif
telegram.inlinequeryresultcachedphoto
telegram.inlinequeryresultcachedsticker
telegram.inlinequeryresultcachedvideo
telegram.inlinequeryresultcachedvoice
telegram.inlinequeryresultcontact
telegram.inlinequeryresultdocument
telegram.inlinequeryresultgif
telegram.inlinequeryresultlocation
telegram.inlinequeryresultmpeg4gif
telegram.inlinequeryresultphoto
telegram.inlinequeryresultvenue
telegram.inlinequeryresultvideo
telegram.inlinequeryresultvoice
telegram.choseninlineresult
telegram.chataction
telegram.contact

View file

@ -65,7 +65,7 @@ class TelegramObject(object):
data = dict()
for key, value in self.__dict__.items():
if value:
if value or value == '':
if hasattr(value, 'to_dict'):
data[key] = value.to_dict()
else:

View file

@ -20,14 +20,13 @@
"""This module contains a object that represents a Telegram Bot."""
import functools
import logging
import functools
from telegram import (User, Message, Update, UserProfilePhotos, File,
ReplyMarkup, TelegramObject, NullHandler)
from telegram.error import InvalidToken
from telegram import User, Message, Update, UserProfilePhotos, File, \
ReplyMarkup, TelegramObject, NullHandler
from telegram.utils import request
from telegram.utils.validate import validate_string
from telegram.utils.validate import validate_token
logging.getLogger(__name__).addHandler(NullHandler())
@ -36,35 +35,36 @@ class Bot(TelegramObject):
"""This object represents a Telegram Bot.
Attributes:
id (int):
first_name (str):
last_name (str):
username (str):
name (str):
id (int): Unique identifier for this bot.
first_name (str): Bot's first name.
last_name (str): Bot's last name.
username (str): Bot's username.
name (str): Bot's @username.
Args:
token (str):
token (str): Bot's unique authentication.
**kwargs: Arbitrary keyword arguments.
Keyword Args:
base_url (Optional[str]):
base_url (Optional[str]): Telegram Bot API service URL.
base_file_url (Optional[str]): Telegram Bot API file URL.
"""
def __init__(self,
token,
base_url=None,
base_file_url=None):
self.token = self._valid_token(token)
self.token = validate_token(token)
if not base_url:
self.base_url = 'https://api.telegram.org/bot%s' % \
self.token
self.base_url = 'https://api.telegram.org/bot{0}'.format(
self.token)
else:
self.base_url = base_url + self.token
if not base_file_url:
self.base_file_url = 'https://api.telegram.org/file/bot%s' % \
self.token
self.base_file_url = 'https://api.telegram.org/file/bot{0}'.format(
self.token)
else:
self.base_file_url = base_file_url + self.token
@ -73,15 +73,8 @@ class Bot(TelegramObject):
self.logger = logging.getLogger(__name__)
def info(func):
"""
Returns:
"""
@functools.wraps(func)
def decorator(self, *args, **kwargs):
"""
decorator
"""
if not self.bot:
self.getMe()
@ -93,44 +86,32 @@ class Bot(TelegramObject):
@property
@info
def id(self):
"""int: """
return self.bot.id
@property
@info
def first_name(self):
"""str: """
return self.bot.first_name
@property
@info
def last_name(self):
"""str: """
return self.bot.last_name
@property
@info
def username(self):
"""str: """
return self.bot.username
@property
def name(self):
"""str: """
return '@%s' % self.username
return '@{0}'.format(self.username)
def log(func):
"""
Returns:
A telegram.Message instance representing the message posted.
"""
logger = logging.getLogger(func.__module__)
@functools.wraps(func)
def decorator(self, *args, **kwargs):
"""
decorator
"""
logger.debug('Entering: %s', func.__name__)
result = func(self, *args, **kwargs)
logger.debug(result)
@ -140,16 +121,8 @@ class Bot(TelegramObject):
return decorator
def message(func):
"""
Returns:
A telegram.Message instance representing the message posted.
"""
@functools.wraps(func)
def decorator(self, *args, **kwargs):
"""
decorator
"""
url, data = func(self, *args, **kwargs)
if kwargs.get('reply_to_message_id'):
@ -183,10 +156,16 @@ class Bot(TelegramObject):
"""A simple method for testing your bot's auth token.
Returns:
A telegram.User instance representing that bot if the
credentials are valid, None otherwise.
:class:`telegram.User`: A :class:`telegram.User` instance
representing that bot if the credentials are valid, `None`
otherwise.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/getMe' % self.base_url
url = '{0}/getMe'.format(self.base_url)
result = request.get(url)
@ -227,6 +206,12 @@ class Bot(TelegramObject):
interface options. A JSON-serialized object for an inline
keyboard, custom reply keyboard, instructions to hide reply
keyboard or to force a reply from the user.
timeout (Optional[float]): If this value is specified, use it as
the definitive timeout (in seconds) for urlopen() operations.
network_delay (Optional[float]): If using the timeout (which is
a `timeout` for the Telegram servers operation),
then `network_delay` as an extra delay (in seconds) to
compensate for network latency. Defaults to 2.
Returns:
:class:`telegram.Message`: On success, the sent message is
@ -237,7 +222,7 @@ class Bot(TelegramObject):
"""
url = '%s/sendMessage' % self.base_url
url = '{0}/sendMessage'.format(self.base_url)
data = {'chat_id': chat_id,
'text': text}
@ -254,7 +239,8 @@ class Bot(TelegramObject):
def forwardMessage(self,
chat_id,
from_chat_id,
message_id):
message_id,
**kwargs):
"""Use this method to forward messages of any kind.
Args:
@ -265,16 +251,28 @@ class Bot(TelegramObject):
- Chat id.
message_id:
Unique message identifier.
disable_notification:
Sends the message silently. iOS users will not receive
a notification, Android users will receive a notification
with no sound. Other apps coming soon. [Optional]
Keyword Args:
disable_notification (Optional[bool]): Sends the message silently.
iOS users will not receive a notification, Android users will
receive a notification with no sound.
timeout (Optional[float]): If this value is specified, use it as
the definitive timeout (in seconds) for urlopen() operations.
network_delay (Optional[float]): If using the timeout (which is
a `timeout` for the Telegram servers operation),
then `network_delay` as an extra delay (in seconds) to
compensate for network latency. Defaults to 2.
Returns:
A telegram.Message instance representing the message forwarded.
:class:`telegram.Message`: On success, instance representing the
message forwarded.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/forwardMessage' % self.base_url
url = '{0}/forwardMessage'.format(self.base_url)
data = {}
@ -306,22 +304,34 @@ class Bot(TelegramObject):
caption:
Photo caption (may also be used when resending photos by file_id).
[Optional]
disable_notification:
Sends the message silently. iOS users will not receive
a notification, Android users will receive a notification
with no sound. Other apps coming soon. [Optional]
reply_to_message_id:
If the message is a reply, ID of the original message. [Optional]
reply_markup:
Additional interface options. A JSON-serialized object for a custom
reply keyboard, instructions to hide keyboard or to force a reply
from the user. [Optional]
Keyword Args:
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. A JSON-serialized object for an inline
keyboard, custom reply keyboard, instructions to hide reply
keyboard or to force a reply from the user.
timeout (Optional[float]): If this value is specified, use it as
the definitive timeout (in seconds) for urlopen() operations.
network_delay (Optional[float]): If using the timeout (which is
a `timeout` for the Telegram servers operation),
then `network_delay` as an extra delay (in seconds) to
compensate for network latency. Defaults to 2.
Returns:
A telegram.Message instance representing the message posted.
:class:`telegram.Message`: On success, instance representing the
message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/sendPhoto' % self.base_url
url = '{0}/sendPhoto'.format(self.base_url)
data = {'chat_id': chat_id,
'photo': photo}
@ -364,22 +374,34 @@ class Bot(TelegramObject):
Performer of sent audio. [Optional]
title:
Title of sent audio. [Optional]
disable_notification:
Sends the message silently. iOS users will not receive
a notification, Android users will receive a notification
with no sound. Other apps coming soon. [Optional]
reply_to_message_id:
If the message is a reply, ID of the original message. [Optional]
reply_markup:
Additional interface options. A JSON-serialized object for a
custom reply keyboard, instructions to hide keyboard or to force a
reply from the user. [Optional]
Keyword Args:
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. A JSON-serialized object for an inline
keyboard, custom reply keyboard, instructions to hide reply
keyboard or to force a reply from the user.
timeout (Optional[float]): If this value is specified, use it as
the definitive timeout (in seconds) for urlopen() operations.
network_delay (Optional[float]): If using the timeout (which is
a `timeout` for the Telegram servers operation),
then `network_delay` as an extra delay (in seconds) to
compensate for network latency. Defaults to 2.
Returns:
A telegram.Message instance representing the message posted.
:class:`telegram.Message`: On success, instance representing the
message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/sendAudio' % self.base_url
url = '{0}/sendAudio'.format(self.base_url)
data = {'chat_id': chat_id,
'audio': audio}
@ -412,22 +434,34 @@ class Bot(TelegramObject):
filename:
File name that shows in telegram message (it is usefull when you
send file generated by temp module, for example). [Optional]
disable_notification:
Sends the message silently. iOS users will not receive
a notification, Android users will receive a notification
with no sound. Other apps coming soon. [Optional]
reply_to_message_id:
If the message is a reply, ID of the original message. [Optional]
reply_markup:
Additional interface options. A JSON-serialized object for a
custom reply keyboard, instructions to hide keyboard or to force a
reply from the user. [Optional]
Keyword Args:
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. A JSON-serialized object for an inline
keyboard, custom reply keyboard, instructions to hide reply
keyboard or to force a reply from the user.
timeout (Optional[float]): If this value is specified, use it as
the definitive timeout (in seconds) for urlopen() operations.
network_delay (Optional[float]): If using the timeout (which is
a `timeout` for the Telegram servers operation),
then `network_delay` as an extra delay (in seconds) to
compensate for network latency. Defaults to 2.
Returns:
A telegram.Message instance representing the message posted.
:class:`telegram.Message`: On success, instance representing the
message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/sendDocument' % self.base_url
url = '{0}/sendDocument'.format(self.base_url)
data = {'chat_id': chat_id,
'document': document}
@ -452,22 +486,34 @@ class Bot(TelegramObject):
Sticker to send. You can either pass a file_id as String to resend
a sticker that is already on the Telegram servers, or upload a new
sticker using multipart/form-data.
disable_notification:
Sends the message silently. iOS users will not receive
a notification, Android users will receive a notification
with no sound. Other apps coming soon. [Optional]
reply_to_message_id:
If the message is a reply, ID of the original message. [Optional]
reply_markup:
Additional interface options. A JSON-serialized object for a
custom reply keyboard, instructions to hide keyboard or to force a
reply from the user. [Optional]
Keyword Args:
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. A JSON-serialized object for an inline
keyboard, custom reply keyboard, instructions to hide reply
keyboard or to force a reply from the user.
timeout (Optional[float]): If this value is specified, use it as
the definitive timeout (in seconds) for urlopen() operations.
network_delay (Optional[float]): If using the timeout (which is
a `timeout` for the Telegram servers operation),
then `network_delay` as an extra delay (in seconds) to
compensate for network latency. Defaults to 2.
Returns:
A telegram.Message instance representing the message posted.
:class:`telegram.Message`: On success, instance representing the
message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/sendSticker' % self.base_url
url = '{0}/sendSticker'.format(self.base_url)
data = {'chat_id': chat_id,
'sticker': sticker}
@ -497,25 +543,34 @@ class Bot(TelegramObject):
caption:
Video caption (may also be used when resending videos by file_id).
[Optional]
timeout:
float. If this value is specified, use it as the definitive timeout
(in seconds) for urlopen() operations. [Optional]
disable_notification:
Sends the message silently. iOS users will not receive
a notification, Android users will receive a notification
with no sound. Other apps coming soon. [Optional]
reply_to_message_id:
If the message is a reply, ID of the original message. [Optional]
reply_markup:
Additional interface options. A JSON-serialized object for a
custom reply keyboard, instructions to hide keyboard or to force a
reply from the user. [Optional]
Keyword Args:
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. A JSON-serialized object for an inline
keyboard, custom reply keyboard, instructions to hide reply
keyboard or to force a reply from the user.
timeout (Optional[float]): If this value is specified, use it as
the definitive timeout (in seconds) for urlopen() operations.
network_delay (Optional[float]): If using the timeout (which is
a `timeout` for the Telegram servers operation),
then `network_delay` as an extra delay (in seconds) to
compensate for network latency. Defaults to 2.
Returns:
A telegram.Message instance representing the message posted.
:class:`telegram.Message`: On success, instance representing the
message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/sendVideo' % self.base_url
url = '{0}/sendVideo'.format(self.base_url)
data = {'chat_id': chat_id,
'video': video}
@ -550,22 +605,34 @@ class Bot(TelegramObject):
a new audio file using multipart/form-data.
duration:
Duration of sent audio in seconds. [Optional]
disable_notification:
Sends the message silently. iOS users will not receive
a notification, Android users will receive a notification
with no sound. Other apps coming soon. [Optional]
reply_to_message_id:
If the message is a reply, ID of the original message. [Optional]
reply_markup:
Additional interface options. A JSON-serialized object for a
custom reply keyboard, instructions to hide keyboard or to force a
reply from the user. [Optional]
Keyword Args:
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. A JSON-serialized object for an inline
keyboard, custom reply keyboard, instructions to hide reply
keyboard or to force a reply from the user.
timeout (Optional[float]): If this value is specified, use it as
the definitive timeout (in seconds) for urlopen() operations.
network_delay (Optional[float]): If using the timeout (which is
a `timeout` for the Telegram servers operation),
then `network_delay` as an extra delay (in seconds) to
compensate for network latency. Defaults to 2.
Returns:
A telegram.Message instance representing the message posted.
:class:`telegram.Message`: On success, instance representing the
message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/sendVoice' % self.base_url
url = '{0}/sendVoice'.format(self.base_url)
data = {'chat_id': chat_id,
'voice': voice}
@ -591,22 +658,34 @@ class Bot(TelegramObject):
Latitude of location.
longitude:
Longitude of location.
disable_notification:
Sends the message silently. iOS users will not receive
a notification, Android users will receive a notification
with no sound. Other apps coming soon. [Optional]
reply_to_message_id:
If the message is a reply, ID of the original message. [Optional]
reply_markup:
Additional interface options. A JSON-serialized object for a
custom reply keyboard, instructions to hide keyboard or to force a
reply from the user. [Optional]
Keyword Args:
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. A JSON-serialized object for an inline
keyboard, custom reply keyboard, instructions to hide reply
keyboard or to force a reply from the user.
timeout (Optional[float]): If this value is specified, use it as
the definitive timeout (in seconds) for urlopen() operations.
network_delay (Optional[float]): If using the timeout (which is
a `timeout` for the Telegram servers operation),
then `network_delay` as an extra delay (in seconds) to
compensate for network latency. Defaults to 2.
Returns:
A telegram.Message instance representing the message posted.
:class:`telegram.Message`: On success, instance representing the
message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/sendLocation' % self.base_url
url = '{0}/sendLocation'.format(self.base_url)
data = {'chat_id': chat_id,
'latitude': latitude,
@ -641,22 +720,34 @@ class Bot(TelegramObject):
Address of the venue.
foursquare_id:
Foursquare identifier of the venue.
disable_notification:
Sends the message silently. iOS users will not receive a
notification, Android users will receive a notification with no
sound.
reply_to_message_id:
If the message is a reply, ID of the original message.
reply_markup:
Additional interface options. A JSON-serialized object for an
inline keyboard, custom reply keyboard, instructions to hide
reply keyboard or to force a reply from the user.
Keyword Args:
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. A JSON-serialized object for an inline
keyboard, custom reply keyboard, instructions to hide reply
keyboard or to force a reply from the user.
timeout (Optional[float]): If this value is specified, use it as
the definitive timeout (in seconds) for urlopen() operations.
network_delay (Optional[float]): If using the timeout (which is
a `timeout` for the Telegram servers operation),
then `network_delay` as an extra delay (in seconds) to
compensate for network latency. Defaults to 2.
Returns:
A telegram.Message instance representing the message posted.
:class:`telegram.Message`: On success, instance representing the
message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/sendVenue' % self.base_url
url = '{0}/sendVenue'.format(self.base_url)
data = {'chat_id': chat_id,
'latitude': latitude,
@ -690,21 +781,34 @@ class Bot(TelegramObject):
Contact's first name.
last_name:
Contact's last name.
disable_notification:
Sends the message silently. iOS users will not receive a
notification, Android users will receive a notification with no
sound.
reply_to_message_id:
If the message is a reply, ID of the original message.
reply_markup:
Additional interface options. A JSON-serialized object for an
inline keyboard, custom reply keyboard, instructions to hide
reply keyboard or to force a reply from the user.
Keyword Args:
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. A JSON-serialized object for an inline
keyboard, custom reply keyboard, instructions to hide reply
keyboard or to force a reply from the user.
timeout (Optional[float]): If this value is specified, use it as
the definitive timeout (in seconds) for urlopen() operations.
network_delay (Optional[float]): If using the timeout (which is
a `timeout` for the Telegram servers operation),
then `network_delay` as an extra delay (in seconds) to
compensate for network latency. Defaults to 2.
Returns:
A telegram.Message instance representing the message posted.
:class:`telegram.Message`: On success, instance representing the
message posted.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/sendContact' % self.base_url
url = '{0}/sendContact'.format(self.base_url)
data = {'chat_id': chat_id,
'phone_number': phone_number,
@ -739,7 +843,7 @@ class Bot(TelegramObject):
- ChatAction.FIND_LOCATION for location data.
"""
url = '%s/sendChatAction' % self.base_url
url = '{0}/sendChatAction'.format(self.base_url)
data = {'chat_id': chat_id,
'action': action}
@ -788,10 +892,7 @@ class Bot(TelegramObject):
"""
validate_string(inline_query_id, 'inline_query_id')
validate_string(inline_query_id, 'next_offset')
url = '%s/answerInlineQuery' % self.base_url
url = '{0}/answerInlineQuery'.format(self.base_url)
results = [res.to_dict() for res in results]
@ -799,9 +900,9 @@ class Bot(TelegramObject):
'results': results}
if cache_time or cache_time == 0:
data['cache_time'] = int(cache_time)
data['cache_time'] = cache_time
if is_personal:
data['is_personal'] = bool(is_personal)
data['is_personal'] = is_personal
if next_offset or next_offset == '':
data['next_offset'] = next_offset
if switch_pm_text:
@ -831,10 +932,15 @@ class Bot(TelegramObject):
are accepted. Defaults to 100. [Optional]
Returns:
Returns a telegram.UserProfilePhotos object.
list[:class:`telegram.UserProfilePhotos`]: A list of
:class:`telegram.UserProfilePhotos` objects are returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/getUserProfilePhotos' % self.base_url
url = '{0}/getUserProfilePhotos'.format(self.base_url)
data = {'user_id': user_id}
@ -859,10 +965,15 @@ class Bot(TelegramObject):
File identifier to get info about.
Returns:
Returns a telegram.File object
:class:`telegram.File`: On success, a :class:`telegram.File`
object is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/getFile' % self.base_url
url = '{0}/getFile'.format(self.base_url)
data = {'file_id': file_id}
@ -891,10 +1002,14 @@ class Bot(TelegramObject):
Unique identifier of the target user.
Returns:
True on success.
bool: On success, `True` is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/kickChatMember' % self.base_url
url = '{0}/kickChatMember'.format(self.base_url)
data = {'chat_id': chat_id,
'user_id': user_id}
@ -920,10 +1035,14 @@ class Bot(TelegramObject):
Unique identifier of the target user.
Returns:
True on success.
bool: On success, `True` is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/unbanChatMember' % self.base_url
url = '{0}/unbanChatMember'.format(self.base_url)
data = {'chat_id': chat_id,
'user_id': user_id}
@ -958,7 +1077,7 @@ class Bot(TelegramObject):
"""
url = '%s/answerCallbackQuery' % self.base_url
url = '{0}/answerCallbackQuery'.format(self.base_url)
data = {'callback_query_id': callback_query_id}
@ -1005,10 +1124,16 @@ class Bot(TelegramObject):
A JSON-serialized object for an inline keyboard.
Returns:
Returns a telegram.Message object.
:class:`telegram.Message`: On success, if edited message is sent by
the bot, the edited message is returned, otherwise `True` is
returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/editMessageText' % self.base_url
url = '{0}/editMessageText'.format(self.base_url)
data = {'text': text}
@ -1057,11 +1182,16 @@ class Bot(TelegramObject):
Keyword Args:
reply_markup (Optional[:class:`telegram.InlineKeyboardMarkup`]):
A JSON-serialized object for an inline keyboard.
timeout (Optional[float]): If this value is specified, use it as
the definitive timeout (in seconds) for urlopen() operations.
network_delay (Optional[float]): If using the timeout (which is
a `timeout` for the Telegram servers operation),
then `network_delay` as an extra delay (in seconds) to
compensate for network latency. Defaults to 2.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by
the bot, the edited Message is returned, otherwise `True` is
the bot, the edited message is returned, otherwise `True` is
returned.
Raises:
@ -1069,7 +1199,7 @@ class Bot(TelegramObject):
"""
url = '%s/editMessageCaption' % self.base_url
url = '{0}/editMessageCaption'.format(self.base_url)
data = {}
@ -1107,6 +1237,12 @@ class Bot(TelegramObject):
Keyword Args:
reply_markup (Optional[:class:`telegram.InlineKeyboardMarkup`]):
A JSON-serialized object for an inline keyboard.
timeout (Optional[float]): If this value is specified, use it as
the definitive timeout (in seconds) for urlopen() operations.
network_delay (Optional[float]): If using the timeout (which is
a `timeout` for the Telegram servers operation),
then `network_delay` as an extra delay (in seconds) to
compensate for network latency. Defaults to 2.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by
@ -1118,7 +1254,7 @@ class Bot(TelegramObject):
"""
url = '%s/editMessageReplyMarkup' % self.base_url
url = '{0}/editMessageReplyMarkup'.format(self.base_url)
data = {}
@ -1159,10 +1295,15 @@ class Bot(TelegramObject):
long for data to be transmitted from and to the Telegram servers.
Returns:
A list of telegram.Update objects are returned.
list[:class:`telegram.Message`]: A list of :class:`telegram.Update`
objects are returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/getUpdates' % self.base_url
url = '{0}/getUpdates'.format(self.base_url)
data = {}
@ -1199,9 +1340,14 @@ class Bot(TelegramObject):
Use an empty string to remove webhook integration
Returns:
True if successful else TelegramError was raised
bool: On success, `True` is returned.
Raises:
:class:`telegram.TelegramError`
"""
url = '%s/setWebhook' % self.base_url
url = '{0}/setWebhook'.format(self.base_url)
data = {}
@ -1216,28 +1362,21 @@ class Bot(TelegramObject):
@staticmethod
def de_json(data):
pass
data = super(Bot, Bot).de_json(data)
return Bot(**data)
def to_dict(self):
"""
Returns:
dict:
"""
data = {'id': self.id,
'username': self.username,
'first_name': self.username}
if self.last_name:
data['last_name'] = self.last_name
return data
def __reduce__(self):
return (self.__class__, (self.token,
self.base_url.replace(self.token, '')))
@staticmethod
def _valid_token(token):
"""a very basic validation on token"""
left, sep, _right = token.partition(':')
if (not sep) or (not left.isdigit()) or (len(left) < 3):
raise InvalidToken()
return token
self.base_url.replace(self.token, ''),
self.base_file_url.replace(self.token, '')))

View file

@ -24,23 +24,40 @@ from telegram import TelegramObject
class InlineKeyboardButton(TelegramObject):
"""This object represents a Telegram InlineKeyboardButton."""
"""This object represents a Telegram InlineKeyboardButton.
Attributes:
text (str):
url (str):
callback_data (str):
switch_inline_query (str):
Args:
text (str):
**kwargs: Arbitrary keyword arguments.
Keyword Args:
url (Optional[str]):
callback_data (Optional[str]):
switch_inline_query (Optional[str]):
"""
def __init__(self,
text,
url=None,
callback_data=None,
switch_inline_query=None):
**kwargs):
# Required
self.text = text
# Optionals
self.url = url
self.callback_data = callback_data
self.switch_inline_query = switch_inline_query
self.url = kwargs.get('url')
self.callback_data = kwargs.get('callback_data')
self.switch_inline_query = kwargs.get('switch_inline_query')
@staticmethod
def de_json(data):
data = super(InlineKeyboardButton, InlineKeyboardButton).de_json(data)
if not data:
return None

View file

@ -24,7 +24,15 @@ from telegram import ReplyMarkup, InlineKeyboardButton
class InlineKeyboardMarkup(ReplyMarkup):
"""This object represents a Telegram InlineKeyboardMarkup."""
"""This object represents a Telegram InlineKeyboardMarkup.
Attributes:
inline_keyboard (List[List[:class:`telegram.InlineKeyboardMarkup`]]):
Args:
inline_keyboard (List[List[:class:`telegram.InlineKeyboardMarkup`]]):
"""
def __init__(self,
inline_keyboard):

View file

@ -62,6 +62,8 @@ class InlineQuery(TelegramObject):
Returns:
telegram.InlineQuery:
"""
data = super(InlineQuery, InlineQuery).de_json(data)
if not data:
return None

View file

@ -30,8 +30,8 @@ class InlineQueryResultArticle(InlineQueryResult):
Attributes:
id (str):
title (str):
input_message_content (telegram.InputMessageContent):
reply_markup (telegram.ReplyMarkup):
input_message_content (:class:`telegram.InputMessageContent`):
reply_markup (:class:`telegram.ReplyMarkup`):
url (str):
hide_url (bool):
description (str):
@ -39,10 +39,18 @@ class InlineQueryResultArticle(InlineQueryResult):
thumb_width (int):
thumb_height (int):
Deprecated: 4.0
message_text (str): Use :class:`InputTextMessageContent` instead.
parse_mode (str): Use :class:`InputTextMessageContent` instead.
disable_web_page_preview (bool): Use :class:`InputTextMessageContent`
instead.
Args:
id (str): Unique identifier for this result, 1-64 Bytes
title (str):
reply_markup (telegram.ReplyMarkup):
reply_markup (:class:`telegram.ReplyMarkup`):
Keyword Args:
url (Optional[str]):

View file

@ -25,6 +25,40 @@ from telegram import InlineQueryResult, InlineKeyboardMarkup, \
class InlineQueryResultAudio(InlineQueryResult):
"""Represents a link to an mp3 audio file. By default, this audio file will
be sent by the user. Alternatively, you can use input_message_content to
send a message with the specified content instead of the audio.
Attributes:
id (str):
audio_url (str):
title (str):
performer (Optional[str]):
audio_duration (Optional[str]):
reply_markup (Optional[:class:`telegram.InlineKeyboardMarkup`]):
input_message_content (Optional[
:class:`telegram.input_message_content`]):
Deprecated: 4.0
message_text (str): Use :class:`InputTextMessageContent` instead.
parse_mode (str): Use :class:`InputTextMessageContent` instead.
disable_web_page_preview (bool): Use :class:`InputTextMessageContent`
instead.
Args:
audio_url (str):
title (str):
**kwargs: Arbitrary keyword arguments.
Keyword Args:
performer (Optional[str]):
audio_duration (Optional[str]):
reply_markup (Optional[:class:`telegram.InlineKeyboardMarkup`]):
input_message_content (Optional[
:class:`telegram.input_message_content`]):
"""
def __init__(self,
id,
audio_url,

View file

@ -62,6 +62,13 @@ class Message(TelegramObject):
migrate_from_chat_id (int):
channel_chat_created (bool):
Deprecated: 4.0
new_chat_participant (:class:`telegram.User`): Use `new_chat_member`
instead.
left_chat_participant (:class:`telegram.User`): Use `left_chat_member`
instead.
Args:
message_id (int):
from_user (:class:`telegram.User`):

View file

@ -19,6 +19,8 @@
"""This module contains functions to validate function arguments"""
from telegram.error import InvalidToken
try:
type(basestring)
except NameError:
@ -36,3 +38,11 @@ def validate_string(arg, name):
"""
if not isinstance(arg, basestring) and arg is not None:
raise ValueError(name + ' is not a string')
def validate_token(token):
"""a very basic validation on token"""
left, sep, _right = token.partition(':')
if (not sep) or (not left.isdigit()) or (len(left) < 3):
raise InvalidToken()
return token

View file

@ -186,8 +186,9 @@ class BotTest(BaseTest, unittest.TestCase):
def testInvalidSrvResp(self):
with self.assertRaisesRegexp(telegram.TelegramError, 'Invalid server response'):
# bypass the valid token check
bot_cls = type('bot_cls', (telegram.Bot, ), {'_valid_token': lambda self, token: token})
bot = bot_cls('12')
bot = telegram.Bot.__new__(telegram.Bot)
bot.base_url = 'https://api.telegram.org/bot{0}'.format('12')
bot.getMe()

View file

@ -70,7 +70,7 @@ class InlineQueryTest(BaseTest, unittest.TestCase):
inlinequery = telegram.InlineQuery.de_json(self.json_dict).to_dict()
self.assertTrue(self.is_dict(inlinequery))
# self.assertDictEqual(inlinequery, self.json_dict)
self.assertDictEqual(inlinequery, self.json_dict)
if __name__ == '__main__':