mirror of
https://github.com/python-telegram-bot/python-telegram-bot.git
synced 2026-06-21 08:35:28 +00:00
Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 53f5911aad | |||
| d4870148c7 | |||
| 6e2881b31b | |||
| 686aecb914 | |||
| 35f31bf136 | |||
| 56f6845969 | |||
| 505df01ae1 | |||
| 3be58b759f | |||
| 5dc1e4cac1 | |||
| 2cecca8324 | |||
| 109439022f | |||
| 59ff1b68b5 | |||
| fda1843593 | |||
| 9b6ccaf94b | |||
| ea1614631e | |||
| 6bcc8cdcfd |
+20
-1
@@ -1 +1,20 @@
|
||||
* Leandro Toledo
|
||||
Credits
|
||||
=======
|
||||
|
||||
``python-telegram-bot`` is written and maintained by `Leandro Toledo <https://github.com/leandrotoledo>`_.
|
||||
|
||||
Contributors
|
||||
------------
|
||||
|
||||
The following wonderful people contributed directly or indirectly to this project:
|
||||
|
||||
- `Avanatiker <https://github.com/Avanatiker>`_
|
||||
- `bimmlerd <https://github.com/bimmlerd>`_
|
||||
- `franciscod <https://github.com/franciscod>`_
|
||||
- `JASON0916 <https://github.com/JASON0916>`_
|
||||
- `JRoot3D <https://github.com/JRoot3D>`_
|
||||
- `macrojames <https://github.com/macrojames>`_
|
||||
- `sooyhwang <https://github.com/sooyhwang>`_
|
||||
- `wjt <https://github.com/wjt>`_
|
||||
|
||||
Please add yourself here alphabetically when you submit your first pull request.
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
2015-08-15
|
||||
Released 2.6.1
|
||||
Fixed parsing image header issue on < Python 2.7.3
|
||||
|
||||
|
||||
2015-08-14
|
||||
Released 2.6.0
|
||||
Depreciation of require_authentication and clearCredentials methods
|
||||
Giving AUTHORS the proper credits for their contribution for this project
|
||||
Message.date and Message.forward_date are now datetime objects
|
||||
|
||||
|
||||
2015-08-12
|
||||
Released 2.5.3
|
||||
telegram.Bot now supports to be unpickled
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
How To Contribute
|
||||
=================
|
||||
|
||||
Every open source project lives from the generous help by contributors that sacrifice their time and ``python-telegram-bot`` is no different.
|
||||
|
||||
To make participation as pleasant as possible, this project adheres to the `Code of Conduct`_ by the Python Software Foundation.
|
||||
|
||||
Here are a few guidelines to get you started:
|
||||
|
||||
- Add yourself to the AUTHORS.rst_ file in an alphabetical fashion.
|
||||
Every contribution is valuable and shall be credited.
|
||||
- If your change is noteworthy, add an entry to the CHANGES_.
|
||||
- No contribution is too small; please submit as many fixes for typos and grammar bloopers as you can!
|
||||
- Don’t break backward compatibility.
|
||||
- *Always* add tests and docs for your code.
|
||||
This is a hard rule; patches with missing tests or documentation won’t be merged.
|
||||
If a feature is not tested or documented, it doesn’t exist.
|
||||
- Obey `PEP 8`_ and `PEP 257`_.
|
||||
- Follow `Google Python Style Guide`_ and `Google Python Style Docstrings`_.
|
||||
- Write `good commit messages`_.
|
||||
|
||||
.. note::
|
||||
If you have something great but aren’t sure whether it adheres -- or even can adhere -- to the rules above: **please submit a pull request anyway**!
|
||||
|
||||
In the best case, we can mold it into something, in the worst case the pull request gets politely closed.
|
||||
There’s absolutely nothing to fear.
|
||||
|
||||
Thank you for considering to contribute to ``python-telegram-bot``!
|
||||
If you have any question or concerns, feel free to reach out to me.
|
||||
|
||||
|
||||
.. _`PEP 8`: https://www.python.org/dev/peps/pep-0008/
|
||||
.. _`PEP 257`: https://www.python.org/dev/peps/pep-0257/
|
||||
.. _`good commit messages`: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html
|
||||
.. _`Code of Conduct`: https://www.python.org/psf/codeofconduct/
|
||||
.. _`Google Python Style Guide`: https://google-styleguide.googlecode.com/svn/trunk/pyguide.html
|
||||
.. _`Google Python Style Docstrings`: http://sphinx-doc.org/latest/ext/example_google.html
|
||||
.. _CHANGES: https://github.com/leandrotoledo/python-telegram-bot/blob/master/CHANGES
|
||||
.. _AUTHORS.rst: https://github.com/leandrotoledo/python-telegram-bot/blob/master/AUTHORS.rst
|
||||
+3
-2
@@ -89,6 +89,7 @@ sendAudio Yes
|
||||
sendDocument Yes
|
||||
sendSticker Yes
|
||||
sendVideo Yes
|
||||
sendVoice Yes
|
||||
sendLocation Yes
|
||||
sendChatAction Yes
|
||||
getUpdates Yes
|
||||
@@ -194,9 +195,9 @@ To post an image file via URL (right now only sendPhoto supports this)::
|
||||
|
||||
>>> bot.sendPhoto(chat_id=chat_id, photo='https://telegram.org/img/t_logo.png')
|
||||
|
||||
To post an audio file::
|
||||
To post a voice file::
|
||||
|
||||
>>> bot.sendAudio(chat_id=chat_id, audio=open('tests/telegram.ogg', 'rb'))
|
||||
>>> bot.sendVoice(chat_id=chat_id, voice=open('tests/telegram.ogg', 'rb'))
|
||||
|
||||
To tell the user that something is happening on bot's side::
|
||||
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
sphinx
|
||||
sphinx_rtd_theme
|
||||
sphinx-pypi-upload
|
||||
|
||||
@@ -29,6 +29,7 @@ Submodules
|
||||
telegram.user
|
||||
telegram.userprofilephotos
|
||||
telegram.video
|
||||
telegram.voice
|
||||
|
||||
Module contents
|
||||
---------------
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
telegram.voice module
|
||||
=====================
|
||||
|
||||
.. automodule:: telegram.voice
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
@@ -1,5 +1,10 @@
|
||||
[wheel]
|
||||
universal = 1
|
||||
|
||||
[upload_docs]
|
||||
[build_sphinx]
|
||||
source-dir = docs/source
|
||||
build-dir = docs/build
|
||||
all_files = 1
|
||||
|
||||
[upload_sphinx]
|
||||
upload-dir = docs/build/html
|
||||
|
||||
@@ -15,7 +15,7 @@ def read(*paths):
|
||||
|
||||
setup(
|
||||
name='python-telegram-bot',
|
||||
version='2.5.3',
|
||||
version='2.6.1',
|
||||
author='Leandro Toledo',
|
||||
author_email='leandrotoledodesouza@gmail.com',
|
||||
license='LGPLv3',
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
|
||||
|
||||
__author__ = 'leandrotoledodesouza@gmail.com'
|
||||
__version__ = '2.5.3'
|
||||
__version__ = '2.6.1'
|
||||
|
||||
from .base import TelegramObject
|
||||
from .user import User
|
||||
@@ -27,6 +27,7 @@ from .update import Update
|
||||
from .groupchat import GroupChat
|
||||
from .photosize import PhotoSize
|
||||
from .audio import Audio
|
||||
from .voice import Voice
|
||||
from .document import Document
|
||||
from .sticker import Sticker
|
||||
from .video import Video
|
||||
@@ -48,4 +49,5 @@ __all__ = ['Bot', 'Emoji', 'TelegramError', 'InputFile', 'ReplyMarkup',
|
||||
'ForceReply', 'ReplyKeyboardHide', 'ReplyKeyboardMarkup',
|
||||
'UserProfilePhotos', 'ChatAction', 'Location', 'Contact',
|
||||
'Video', 'Sticker', 'Document', 'Audio', 'PhotoSize', 'GroupChat',
|
||||
'Update', 'Message', 'User', 'TelegramObject', 'NullHandler']
|
||||
'Update', 'Message', 'User', 'TelegramObject', 'NullHandler',
|
||||
'Voice']
|
||||
|
||||
@@ -24,10 +24,14 @@ class Audio(TelegramObject):
|
||||
def __init__(self,
|
||||
file_id,
|
||||
duration,
|
||||
performer=None,
|
||||
title=None,
|
||||
mime_type=None,
|
||||
file_size=None):
|
||||
self.file_id = file_id
|
||||
self.duration = duration
|
||||
self.performer = performer
|
||||
self.title = title
|
||||
self.mime_type = mime_type
|
||||
self.file_size = file_size
|
||||
|
||||
@@ -35,12 +39,18 @@ class Audio(TelegramObject):
|
||||
def de_json(data):
|
||||
return Audio(file_id=data.get('file_id', None),
|
||||
duration=data.get('duration', None),
|
||||
performer=data.get('performer', None),
|
||||
title=data.get('title', None),
|
||||
mime_type=data.get('mime_type', None),
|
||||
file_size=data.get('file_size', None))
|
||||
|
||||
def to_dict(self):
|
||||
data = {'file_id': self.file_id,
|
||||
'duration': self.duration}
|
||||
if self.performer:
|
||||
data['performer'] = self.performer
|
||||
if self.title:
|
||||
data['title'] = self.title
|
||||
if self.mime_type:
|
||||
data['mime_type'] = self.mime_type
|
||||
if self.file_size:
|
||||
|
||||
+101
-42
@@ -48,21 +48,39 @@ class Bot(TelegramObject):
|
||||
else:
|
||||
self.base_url = base_url + self.token
|
||||
|
||||
self.bot = None
|
||||
|
||||
self.log = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
bot = self.getMe()
|
||||
def info(func):
|
||||
@functools.wraps(func)
|
||||
def decorator(self, *args, **kwargs):
|
||||
if not self.bot:
|
||||
self.getMe()
|
||||
|
||||
self.id = bot.id
|
||||
self.first_name = bot.first_name
|
||||
self.last_name = bot.last_name
|
||||
self.username = bot.username
|
||||
result = func(self, *args, **kwargs)
|
||||
return result
|
||||
return decorator
|
||||
|
||||
self.__auth = True
|
||||
@property
|
||||
@info
|
||||
def id(self):
|
||||
return self.bot.id
|
||||
|
||||
self.log.info('Starting bot %s' % self.name)
|
||||
except TelegramError:
|
||||
raise TelegramError({'message': 'Bad token'})
|
||||
@property
|
||||
@info
|
||||
def first_name(self):
|
||||
return self.bot.first_name
|
||||
|
||||
@property
|
||||
@info
|
||||
def last_name(self):
|
||||
return self.bot.last_name
|
||||
|
||||
@property
|
||||
@info
|
||||
def username(self):
|
||||
return self.bot.username
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
@@ -109,22 +127,6 @@ class Bot(TelegramObject):
|
||||
return Message.de_json(data)
|
||||
return decorator
|
||||
|
||||
def require_authentication(func):
|
||||
@functools.wraps(func)
|
||||
def decorator(self, *args, **kwargs):
|
||||
if not self.__auth:
|
||||
raise TelegramError({'message': "API must be authenticated."})
|
||||
|
||||
return func(self, *args, **kwargs)
|
||||
return decorator
|
||||
|
||||
@log
|
||||
@require_authentication
|
||||
def clearCredentials(self):
|
||||
"""Clear any credentials for this instance.
|
||||
"""
|
||||
self.__auth = False
|
||||
|
||||
@log
|
||||
def getMe(self):
|
||||
"""A simple method for testing your bot's auth token.
|
||||
@@ -138,11 +140,12 @@ class Bot(TelegramObject):
|
||||
json_data = self._requestUrl(url, 'GET')
|
||||
data = self._parseAndCheckTelegram(json_data)
|
||||
|
||||
return User.de_json(data)
|
||||
self.bot = User.de_json(data)
|
||||
|
||||
return self.bot
|
||||
|
||||
@log
|
||||
@message
|
||||
@require_authentication
|
||||
def sendMessage(self,
|
||||
chat_id,
|
||||
text,
|
||||
@@ -182,7 +185,6 @@ class Bot(TelegramObject):
|
||||
|
||||
@log
|
||||
@message
|
||||
@require_authentication
|
||||
def forwardMessage(self,
|
||||
chat_id,
|
||||
from_chat_id,
|
||||
@@ -216,7 +218,6 @@ class Bot(TelegramObject):
|
||||
|
||||
@log
|
||||
@message
|
||||
@require_authentication
|
||||
def sendPhoto(self,
|
||||
chat_id,
|
||||
photo,
|
||||
@@ -258,16 +259,24 @@ class Bot(TelegramObject):
|
||||
|
||||
@log
|
||||
@message
|
||||
@require_authentication
|
||||
def sendAudio(self,
|
||||
chat_id,
|
||||
audio,
|
||||
duration=None,
|
||||
performer=None,
|
||||
title=None,
|
||||
reply_to_message_id=None,
|
||||
reply_markup=None):
|
||||
"""Use this method to send audio files, if you want Telegram clients to
|
||||
display the file as a playable voice message. For this to work, your
|
||||
audio must be in an .ogg file encoded with OPUS (other formats may be
|
||||
sent as telegram.Document).
|
||||
display them in the music player. Your audio must be in an .mp3 format.
|
||||
On success, the sent Message is returned. Bots can currently send audio
|
||||
files of up to 50 MB in size, this limit may be changed in the future.
|
||||
|
||||
For backward compatibility, when both fields title and description are
|
||||
empty and mime-type of the sent file is not "audio/mpeg", file is sent
|
||||
as playable voice message. In this case, your audio must be in an .ogg
|
||||
file encoded with OPUS. This will be removed in the future. You need to
|
||||
use sendVoice method instead.
|
||||
|
||||
Args:
|
||||
chat_id:
|
||||
@@ -276,6 +285,12 @@ class Bot(TelegramObject):
|
||||
Audio file to send. You can either pass a file_id as String to
|
||||
resend an audio that is already on the Telegram servers, or upload
|
||||
a new audio file using multipart/form-data.
|
||||
duration:
|
||||
Duration of sent audio in seconds. [Optional]
|
||||
performer:
|
||||
Performer of sent audio. [Optional]
|
||||
title:
|
||||
Title of sent audio. [Optional]
|
||||
reply_to_message_id:
|
||||
If the message is a reply, ID of the original message. [Optional]
|
||||
reply_markup:
|
||||
@@ -292,11 +307,17 @@ class Bot(TelegramObject):
|
||||
data = {'chat_id': chat_id,
|
||||
'audio': audio}
|
||||
|
||||
if duration:
|
||||
data['duration'] = duration
|
||||
if performer:
|
||||
data['performer'] = performer
|
||||
if title:
|
||||
data['title'] = title
|
||||
|
||||
return url, data
|
||||
|
||||
@log
|
||||
@message
|
||||
@require_authentication
|
||||
def sendDocument(self,
|
||||
chat_id,
|
||||
document,
|
||||
@@ -331,7 +352,6 @@ class Bot(TelegramObject):
|
||||
|
||||
@log
|
||||
@message
|
||||
@require_authentication
|
||||
def sendSticker(self,
|
||||
chat_id,
|
||||
sticker,
|
||||
@@ -366,7 +386,6 @@ class Bot(TelegramObject):
|
||||
|
||||
@log
|
||||
@message
|
||||
@require_authentication
|
||||
def sendVideo(self,
|
||||
chat_id,
|
||||
video,
|
||||
@@ -414,7 +433,51 @@ class Bot(TelegramObject):
|
||||
|
||||
@log
|
||||
@message
|
||||
@require_authentication
|
||||
def sendVoice(self,
|
||||
chat_id,
|
||||
voice,
|
||||
duration=None,
|
||||
reply_to_message_id=None,
|
||||
reply_markup=None):
|
||||
"""Use this method to send audio files, if you want Telegram clients to
|
||||
display the file as a playable voice message. For this to work, your
|
||||
audio must be in an .ogg file encoded with OPUS (other formats may be
|
||||
sent as Audio or Document). On success, the sent Message is returned.
|
||||
Bots can currently send audio files of up to 50 MB in size, this limit
|
||||
may be changed in the future.
|
||||
|
||||
Args:
|
||||
chat_id:
|
||||
Unique identifier for the message recipient - User or GroupChat id.
|
||||
voice:
|
||||
Audio file to send. You can either pass a file_id as String to
|
||||
resend an audio that is already on the Telegram servers, or upload
|
||||
a new audio file using multipart/form-data.
|
||||
duration:
|
||||
Duration of sent audio in seconds. [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]
|
||||
|
||||
Returns:
|
||||
A telegram.Message instance representing the message posted.
|
||||
"""
|
||||
|
||||
url = '%s/sendVoice' % self.base_url
|
||||
|
||||
data = {'chat_id': chat_id,
|
||||
'voice': voice}
|
||||
|
||||
if duration:
|
||||
data['duration'] = duration
|
||||
|
||||
return url, data
|
||||
|
||||
@log
|
||||
@message
|
||||
def sendLocation(self,
|
||||
chat_id,
|
||||
latitude,
|
||||
@@ -451,7 +514,6 @@ class Bot(TelegramObject):
|
||||
|
||||
@log
|
||||
@message
|
||||
@require_authentication
|
||||
def sendChatAction(self,
|
||||
chat_id,
|
||||
action):
|
||||
@@ -482,7 +544,6 @@ class Bot(TelegramObject):
|
||||
return url, data
|
||||
|
||||
@log
|
||||
@require_authentication
|
||||
def getUserProfilePhotos(self,
|
||||
user_id,
|
||||
offset=None,
|
||||
@@ -518,7 +579,6 @@ class Bot(TelegramObject):
|
||||
return UserProfilePhotos.de_json(data)
|
||||
|
||||
@log
|
||||
@require_authentication
|
||||
def getUpdates(self,
|
||||
offset=None,
|
||||
limit=100,
|
||||
@@ -565,7 +625,6 @@ class Bot(TelegramObject):
|
||||
return [Update.de_json(x) for x in data]
|
||||
|
||||
@log
|
||||
@require_authentication
|
||||
def setWebhook(self,
|
||||
webhook_url):
|
||||
"""Use this method to specify a url and receive incoming updates via an
|
||||
|
||||
+10
-17
@@ -26,8 +26,8 @@ except ImportError:
|
||||
from urllib2 import urlopen
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import imghdr
|
||||
|
||||
from .error import TelegramError
|
||||
|
||||
@@ -54,6 +54,9 @@ class InputFile(object):
|
||||
if 'video' in data:
|
||||
self.input_name = 'video'
|
||||
self.input_file = data.pop('video')
|
||||
if 'voice' in data:
|
||||
self.input_name = 'voice'
|
||||
self.input_file = data.pop('voice')
|
||||
|
||||
if isinstance(self.input_file, file):
|
||||
self.input_file_content = self.input_file.read()
|
||||
@@ -128,26 +131,16 @@ class InputFile(object):
|
||||
Returns:
|
||||
The str mimetype of an image.
|
||||
"""
|
||||
try:
|
||||
header = stream[:10]
|
||||
|
||||
if re.match(b'GIF8', header):
|
||||
return 'image/gif'
|
||||
|
||||
if re.match(b'\x89PNG', header):
|
||||
return 'image/png'
|
||||
|
||||
if re.match(b'\xff\xd8\xff\xe0\x00\x10JFIF', header) or \
|
||||
re.match(b'\xff\xd8\xff\xe1(.*){2}Exif', header):
|
||||
return 'image/jpeg'
|
||||
except IndexError as e:
|
||||
raise TelegramError(str(e))
|
||||
image = imghdr.what(None, stream)
|
||||
if image:
|
||||
return 'image/%s' % image
|
||||
|
||||
raise TelegramError({'message': 'Could not parse file content'})
|
||||
|
||||
@staticmethod
|
||||
def is_inputfile(data):
|
||||
"""Check if the request is a file request
|
||||
"""Check if the request is a file request.
|
||||
|
||||
Args:
|
||||
data:
|
||||
A dict of (str, unicode) key/value pairs
|
||||
@@ -156,7 +149,7 @@ class InputFile(object):
|
||||
bool
|
||||
"""
|
||||
if data:
|
||||
file_types = ['audio', 'document', 'photo', 'video']
|
||||
file_types = ['audio', 'document', 'photo', 'video', 'voice']
|
||||
file_type = [i for i in list(data.keys()) if i in file_types]
|
||||
|
||||
if file_type:
|
||||
|
||||
+43
-6
@@ -18,6 +18,8 @@
|
||||
|
||||
|
||||
from telegram import TelegramObject
|
||||
from datetime import datetime
|
||||
from time import mktime
|
||||
|
||||
|
||||
class Message(TelegramObject):
|
||||
@@ -35,6 +37,7 @@ class Message(TelegramObject):
|
||||
photo=None,
|
||||
sticker=None,
|
||||
video=None,
|
||||
voice=None,
|
||||
caption=None,
|
||||
contact=None,
|
||||
location=None,
|
||||
@@ -57,6 +60,7 @@ class Message(TelegramObject):
|
||||
self.photo = photo
|
||||
self.sticker = sticker
|
||||
self.video = video
|
||||
self.voice = voice
|
||||
self.caption = caption
|
||||
self.contact = contact
|
||||
self.location = location
|
||||
@@ -79,6 +83,11 @@ class Message(TelegramObject):
|
||||
else:
|
||||
from_user = None
|
||||
|
||||
if 'date' in data:
|
||||
date = datetime.fromtimestamp(data['date'])
|
||||
else:
|
||||
date = None
|
||||
|
||||
if 'chat' in data:
|
||||
if 'first_name' in data['chat']:
|
||||
from telegram import User
|
||||
@@ -95,6 +104,11 @@ class Message(TelegramObject):
|
||||
else:
|
||||
forward_from = None
|
||||
|
||||
if 'forward_date' in data:
|
||||
forward_date = datetime.fromtimestamp(data['forward_date'])
|
||||
else:
|
||||
forward_date = None
|
||||
|
||||
if 'reply_to_message' in data:
|
||||
reply_to_message = Message.de_json(data['reply_to_message'])
|
||||
else:
|
||||
@@ -130,6 +144,12 @@ class Message(TelegramObject):
|
||||
else:
|
||||
video = None
|
||||
|
||||
if 'voice' in data:
|
||||
from telegram import Voice
|
||||
voice = Voice.de_json(data['voice'])
|
||||
else:
|
||||
voice = None
|
||||
|
||||
if 'contact' in data:
|
||||
from telegram import Contact
|
||||
contact = Contact.de_json(data['contact'])
|
||||
@@ -156,10 +176,10 @@ class Message(TelegramObject):
|
||||
|
||||
return Message(message_id=data.get('message_id', None),
|
||||
from_user=from_user,
|
||||
date=data.get('date', None),
|
||||
date=date,
|
||||
chat=chat,
|
||||
forward_from=forward_from,
|
||||
forward_date=data.get('forward_date', None),
|
||||
forward_date=forward_date,
|
||||
reply_to_message=reply_to_message,
|
||||
text=data.get('text', ''),
|
||||
audio=audio,
|
||||
@@ -167,6 +187,7 @@ class Message(TelegramObject):
|
||||
photo=photo,
|
||||
sticker=sticker,
|
||||
video=video,
|
||||
voice=voice,
|
||||
caption=data.get('caption', ''),
|
||||
contact=contact,
|
||||
location=location,
|
||||
@@ -180,12 +201,22 @@ class Message(TelegramObject):
|
||||
def to_dict(self):
|
||||
data = {'message_id': self.message_id,
|
||||
'from': self.from_user.to_dict(),
|
||||
'date': self.date,
|
||||
'chat': self.chat.to_dict()}
|
||||
try:
|
||||
# Python 3.3+ supports .timestamp()
|
||||
data['date'] = int(self.date.timestamp())
|
||||
|
||||
if self.forward_date:
|
||||
data['forward_date'] = int(self.forward_date.timestamp())
|
||||
except AttributeError:
|
||||
# _totimestamp() for Python 3 (< 3.3) and Python 2
|
||||
data['date'] = self._totimestamp(self.date)
|
||||
|
||||
if self.forward_date:
|
||||
data['forward_date'] = self._totimestamp(self.forward_date)
|
||||
|
||||
if self.forward_from:
|
||||
data['forward_from'] = self.forward_from
|
||||
if self.forward_date:
|
||||
data['forward_date'] = self.forward_date
|
||||
data['forward_from'] = self.forward_from.to_dict()
|
||||
if self.reply_to_message:
|
||||
data['reply_to_message'] = self.reply_to_message
|
||||
if self.text:
|
||||
@@ -200,6 +231,8 @@ class Message(TelegramObject):
|
||||
data['sticker'] = self.sticker.to_dict()
|
||||
if self.video:
|
||||
data['video'] = self.video.to_dict()
|
||||
if self.voice:
|
||||
data['voice'] = self.voice.to_dict()
|
||||
if self.caption:
|
||||
data['caption'] = self.caption
|
||||
if self.contact:
|
||||
@@ -219,3 +252,7 @@ class Message(TelegramObject):
|
||||
if self.group_chat_created:
|
||||
data['group_chat_created'] = self.group_chat_created
|
||||
return data
|
||||
|
||||
@staticmethod
|
||||
def _totimestamp(dt):
|
||||
return int(mktime(dt.timetuple()))
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
|
||||
#
|
||||
# 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/].
|
||||
|
||||
|
||||
from telegram import TelegramObject
|
||||
|
||||
|
||||
class Voice(TelegramObject):
|
||||
def __init__(self,
|
||||
file_id,
|
||||
duration=None,
|
||||
mime_type=None,
|
||||
file_size=None):
|
||||
self.file_id = file_id
|
||||
self.duration = duration
|
||||
self.mime_type = mime_type
|
||||
self.file_size = file_size
|
||||
|
||||
@staticmethod
|
||||
def de_json(data):
|
||||
return Voice(file_id=data.get('file_id', None),
|
||||
duration=data.get('duration', None),
|
||||
mime_type=data.get('mime_type', None),
|
||||
file_size=data.get('file_size', None))
|
||||
|
||||
def to_dict(self):
|
||||
data = {'file_id': self.file_id}
|
||||
if self.duration:
|
||||
data['duration'] = self.duration
|
||||
if self.mime_type:
|
||||
data['mime_type'] = self.mime_type
|
||||
if self.file_size:
|
||||
data['file_size'] = self.file_size
|
||||
return data
|
||||
Binary file not shown.
+86
-12
@@ -19,11 +19,21 @@
|
||||
|
||||
|
||||
import os
|
||||
import json
|
||||
import telegram
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class BotTest(unittest.TestCase):
|
||||
@staticmethod
|
||||
def is_json(string):
|
||||
try:
|
||||
json.loads(string)
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
def setUp(self):
|
||||
bot = telegram.Bot(token=os.environ.get('TOKEN'))
|
||||
self._bot = bot
|
||||
@@ -33,6 +43,7 @@ class BotTest(unittest.TestCase):
|
||||
'''Test the telegram.Bot getMe method'''
|
||||
print('Testing getMe')
|
||||
bot = self._bot.getMe()
|
||||
self.assertTrue(self.is_json(bot.to_json()))
|
||||
self.assertEqual(120405045, bot.id)
|
||||
self.assertEqual('Toledo\'s Palace Bot', bot.first_name)
|
||||
self.assertEqual(None, bot.last_name)
|
||||
@@ -43,12 +54,15 @@ class BotTest(unittest.TestCase):
|
||||
print('Testing sendMessage')
|
||||
message = self._bot.sendMessage(chat_id=12173560,
|
||||
text='Моё судно на воздушной подушке полно угрей')
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual(u'Моё судно на воздушной подушке полно угрей', message.text)
|
||||
self.assertIsInstance(message.date, datetime)
|
||||
|
||||
def testGetUpdates(self):
|
||||
'''Test the telegram.Bot getUpdates method'''
|
||||
print('Testing getUpdates')
|
||||
updates = self._bot.getUpdates()
|
||||
self.assertTrue(self.is_json(updates[0].to_json()))
|
||||
self.assertIsInstance(updates[0], telegram.Update)
|
||||
|
||||
def testForwardMessage(self):
|
||||
@@ -57,8 +71,10 @@ class BotTest(unittest.TestCase):
|
||||
message = self._bot.forwardMessage(chat_id=12173560,
|
||||
from_chat_id=12173560,
|
||||
message_id=138)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual('Oi', message.text)
|
||||
self.assertEqual('leandrotoledo', message.forward_from.username)
|
||||
self.assertIsInstance(message.forward_date, datetime)
|
||||
|
||||
def testSendPhoto(self):
|
||||
'''Test the telegram.Bot sendPhoto method'''
|
||||
@@ -66,49 +82,102 @@ class BotTest(unittest.TestCase):
|
||||
message = self._bot.sendPhoto(photo=open('tests/telegram.png', 'rb'),
|
||||
caption='testSendPhoto',
|
||||
chat_id=12173560)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual(1451, message.photo[0].file_size)
|
||||
self.assertEqual('testSendPhoto', message.caption)
|
||||
|
||||
def testResendPhoto(self):
|
||||
'''Test the telegram.Bot sendPhoto method'''
|
||||
print('Testing sendPhoto - Resend')
|
||||
message = self._bot.sendPhoto(photo=str('AgADAQADr6cxGzU8LQe6q0dMJD2rHYkP2ykABFymiQqJgjxRGGMAAgI'),
|
||||
message = self._bot.sendPhoto(photo='AgADAQADr6cxGzU8LQe6q0dMJD2rHYkP2ykABFymiQqJgjxRGGMAAgI',
|
||||
chat_id=12173560)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual('AgADAQADr6cxGzU8LQe6q0dMJD2rHYkP2ykABFymiQqJgjxRGGMAAgI', message.photo[0].file_id)
|
||||
|
||||
def testSendURLPhoto(self):
|
||||
def testSendJPGURLPhoto(self):
|
||||
'''Test the telegram.Bot sendPhoto method'''
|
||||
print('Testing sendPhoto - URL')
|
||||
message = self._bot.sendPhoto(photo=str('http://dummyimage.com/600x400/000/fff.jpg&text=telegram'),
|
||||
print('Testing testSendJPGURLPhoto - URL')
|
||||
message = self._bot.sendPhoto(photo='http://dummyimage.com/600x400/000/fff.jpg&text=telegram',
|
||||
chat_id=12173560)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual(822, message.photo[0].file_size)
|
||||
|
||||
def testSendPNGURLPhoto(self):
|
||||
'''Test the telegram.Bot sendPhoto method'''
|
||||
print('Testing testSendPNGURLPhoto - URL')
|
||||
message = self._bot.sendPhoto(photo='http://dummyimage.com/600x400/000/fff.png&text=telegram',
|
||||
chat_id=12173560)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual(684, message.photo[0].file_size)
|
||||
|
||||
def testSendGIFURLPhoto(self):
|
||||
'''Test the telegram.Bot sendPhoto method'''
|
||||
print('Testing testSendGIFURLPhoto - URL')
|
||||
message = self._bot.sendPhoto(photo='http://dummyimage.com/600x400/000/fff.gif&text=telegram',
|
||||
chat_id=12173560)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual(684, message.photo[0].file_size)
|
||||
|
||||
def testSendAudio(self):
|
||||
'''Test the telegram.Bot sendAudio method'''
|
||||
print('Testing sendAudio - File')
|
||||
message = self._bot.sendAudio(audio=open('tests/telegram.ogg', 'rb'),
|
||||
chat_id=12173560)
|
||||
self.assertEqual(9199, message.audio.file_size)
|
||||
message = self._bot.sendAudio(audio=open('tests/telegram.mp3', 'rb'),
|
||||
chat_id=12173560,
|
||||
performer='Leandro Toledo',
|
||||
title='Teste')
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual(28232, message.audio.file_size)
|
||||
self.assertEqual('Leandro Toledo', message.audio.performer)
|
||||
self.assertEqual('Teste', message.audio.title)
|
||||
|
||||
def testResendAudio(self):
|
||||
'''Test the telegram.Bot sendAudio method'''
|
||||
print('Testing sendAudio - Resend')
|
||||
message = self._bot.sendAudio(audio=str('AwADAQADIQEAAvjAuQABSAXg_GhkhZcC'),
|
||||
message = self._bot.sendAudio(audio='BQADAQADwwcAAjU8LQdBRsl3_qD2TAI',
|
||||
chat_id=12173560,
|
||||
performer='Leandro Toledo', # Bug #39
|
||||
title='Teste') # Bug #39
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual('BQADAQADwwcAAjU8LQdBRsl3_qD2TAI', message.audio.file_id)
|
||||
|
||||
def testSendVoice(self):
|
||||
'''Test the telegram.Bot sendVoice method'''
|
||||
print('Testing sendVoice - File')
|
||||
message = self._bot.sendVoice(voice=open('tests/telegram.ogg', 'rb'),
|
||||
chat_id=12173560)
|
||||
self.assertEqual('AwADAQADIQEAAvjAuQABSAXg_GhkhZcC', message.audio.file_id)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual(9199, message.voice.file_size)
|
||||
|
||||
def testResendVoice(self):
|
||||
'''Test the telegram.Bot sendVoice method'''
|
||||
print('Testing sendVoice - Resend')
|
||||
message = self._bot.sendVoice(voice='AwADAQADIQEAAvjAuQABSAXg_GhkhZcC',
|
||||
chat_id=12173560)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual('AwADAQADIQEAAvjAuQABSAXg_GhkhZcC', message.voice.file_id)
|
||||
|
||||
def testSendDocument(self):
|
||||
'''Test the telegram.Bot sendDocument method'''
|
||||
print('Testing sendDocument - File')
|
||||
message = self._bot.sendDocument(document=open('tests/telegram.png', 'rb'),
|
||||
chat_id=12173560)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual(12948, message.document.file_size)
|
||||
|
||||
def testSendGIFURLDocument(self):
|
||||
'''Test the telegram.Bot sendDocument method'''
|
||||
print('Testing sendDocument - File')
|
||||
message = self._bot.sendPhoto(photo='http://dummyimage.com/600x400/000/fff.gif&text=telegram',
|
||||
chat_id=12173560)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual(684, message.photo[0].file_size)
|
||||
|
||||
def testResendDocument(self):
|
||||
'''Test the telegram.Bot sendDocument method'''
|
||||
print('Testing sendDocument - Resend')
|
||||
message = self._bot.sendDocument(document=str('BQADAQADHAADNTwtBxZxUGKyxYbYAg'),
|
||||
message = self._bot.sendDocument(document='BQADAQADHAADNTwtBxZxUGKyxYbYAg',
|
||||
chat_id=12173560)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual('BQADAQADHAADNTwtBxZxUGKyxYbYAg', message.document.file_id)
|
||||
|
||||
def testSendVideo(self):
|
||||
@@ -117,21 +186,24 @@ class BotTest(unittest.TestCase):
|
||||
message = self._bot.sendVideo(video=open('tests/telegram.mp4', 'rb'),
|
||||
caption='testSendVideo',
|
||||
chat_id=12173560)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual(326534, message.video.file_size)
|
||||
self.assertEqual('testSendVideo', message.caption)
|
||||
|
||||
def testResendVideo(self):
|
||||
'''Test the telegram.Bot sendVideo method'''
|
||||
print('Testing sendVideo - Resend')
|
||||
message = self._bot.sendVideo(video=str('BAADAQADIgEAAvjAuQABOuTB937fPTgC'),
|
||||
message = self._bot.sendVideo(video='BAADAQADIgEAAvjAuQABOuTB937fPTgC',
|
||||
chat_id=12173560)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual(4, message.video.duration)
|
||||
|
||||
def testResendSticker(self):
|
||||
'''Test the telegram.Bot sendSticker method'''
|
||||
print('Testing sendSticker - Resend')
|
||||
message = self._bot.sendSticker(sticker=str('BQADAQADHAADyIsGAAFZfq1bphjqlgI'),
|
||||
message = self._bot.sendSticker(sticker='BQADAQADHAADyIsGAAFZfq1bphjqlgI',
|
||||
chat_id=12173560)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual(39518, message.sticker.file_size)
|
||||
|
||||
def testSendLocation(self):
|
||||
@@ -140,6 +212,7 @@ class BotTest(unittest.TestCase):
|
||||
message = self._bot.sendLocation(latitude=-23.558873,
|
||||
longitude=-46.659732,
|
||||
chat_id=12173560)
|
||||
self.assertTrue(self.is_json(message.to_json()))
|
||||
self.assertEqual(-23.558873, message.location.latitude)
|
||||
self.assertEqual(-46.659732, message.location.longitude)
|
||||
|
||||
@@ -153,4 +226,5 @@ class BotTest(unittest.TestCase):
|
||||
'''Test the telegram.Bot getUserProfilePhotos method'''
|
||||
print('Testing getUserProfilePhotos')
|
||||
upf = self._bot.getUserProfilePhotos(user_id=12173560)
|
||||
self.assertTrue(self.is_json(upf.to_json()))
|
||||
self.assertEqual(6547, upf.photos[0][0].file_size)
|
||||
|
||||
Reference in New Issue
Block a user