diff --git a/telegram/__init__.py b/telegram/__init__.py index 4368078b55a..abcaa3b0649 100644 --- a/telegram/__init__.py +++ b/telegram/__init__.py @@ -6,26 +6,30 @@ __author__ = 'leandrotoledodesouza@gmail.com' __version__ = '1.1' -import json +from .user import User +from .message import Message +from .update import Update +from .groupchat import GroupChat +from .photosize import PhotoSize +from .audio import Audio +from .document import Document +from .sticker import Sticker +from .video import Video +from .contact import Contact +from .location import Location +from .chataction import ChatAction +from .userprofilephotos import UserProfilePhotos +from .replykeyboardmarkup import ReplyKeyboardMarkup +from .replykeyboardhide import ReplyKeyboardHide +from .forcereply import ForceReply +from .replymarkup import ReplyMarkup +from .inputfile import InputFile +from .error import TelegramError +from .emoji import Emoji +from .bot import Bot -from user import User -from message import Message -from update import Update -from groupchat import GroupChat -from photosize import PhotoSize -from audio import Audio -from document import Document -from sticker import Sticker -from video import Video -from contact import Contact -from location import Location -from chataction import ChatAction -from userprofilephotos import UserProfilePhotos -from replykeyboardmarkup import ReplyKeyboardMarkup -from replykeyboardhide import ReplyKeyboardHide -from forcereply import ForceReply -from replymarkup import ReplyMarkup -from inputfile import InputFile -from error import TelegramError -from emoji import Emoji -from bot import Bot +__all__ = ['Bot', 'Emoji', 'TelegramError', 'InputFile', 'ReplyMarkup', + 'ForceReply', 'ReplyKeyboardHide', 'ReplyKeyboardMarkup', + 'UserProfilePhotos', 'ChatAction', 'Location', 'Contact', + 'Video', 'Sticker', 'Document', 'Audio', 'PhotoSize', 'GroupChat', + 'Update', 'Message', 'User'] diff --git a/telegram/bot.py b/telegram/bot.py index 12e333c794b..86fb83f71ce 100644 --- a/telegram/bot.py +++ b/telegram/bot.py @@ -4,11 +4,12 @@ """A library that provides a Python interface to the Telegram Bot API""" import json -import urllib -import urllib2 +# import urllib +from six.moves import urllib from telegram import (User, Message, Update, UserProfilePhotos, TelegramError, ReplyMarkup, InputFile) +from telegram.inputfile import is_file class Bot(object): @@ -67,7 +68,7 @@ def getMe(self): url = '%s/getMe' % (self.base_url) json_data = self._requestUrl(url, 'GET') - data = self._parseAndCheckTelegram(json_data) + data = self._parseAndCheckTelegram(json_data.decode()) return User.de_json(data) @@ -116,7 +117,7 @@ def sendMessage(self, data['reply_markup'] = reply_markup json_data = self._requestUrl(url, 'POST', data=data) - data = self._parseAndCheckTelegram(json_data) + data = self._parseAndCheckTelegram(json_data.decode()) return Message.de_json(data) @@ -153,7 +154,7 @@ def forwardMessage(self, data['message_id'] = message_id json_data = self._requestUrl(url, 'POST', data=data) - data = self._parseAndCheckTelegram(json_data) + data = self._parseAndCheckTelegram(json_data.decode()) return Message.de_json(data) @@ -205,7 +206,7 @@ def sendPhoto(self, data['reply_markup'] = reply_markup json_data = self._requestUrl(url, 'POST', data=data) - data = self._parseAndCheckTelegram(json_data) + data = self._parseAndCheckTelegram(json_data.decode()) return Message.de_json(data) @@ -254,7 +255,7 @@ def sendAudio(self, data['reply_markup'] = reply_markup json_data = self._requestUrl(url, 'POST', data=data) - data = self._parseAndCheckTelegram(json_data) + data = self._parseAndCheckTelegram(json_data.decode()) return Message.de_json(data) @@ -300,7 +301,7 @@ def sendDocument(self, data['reply_markup'] = reply_markup json_data = self._requestUrl(url, 'POST', data=data) - data = self._parseAndCheckTelegram(json_data) + data = self._parseAndCheckTelegram(json_data.decode()) return Message.de_json(data) @@ -346,7 +347,7 @@ def sendSticker(self, data['reply_markup'] = reply_markup json_data = self._requestUrl(url, 'POST', data=data) - data = self._parseAndCheckTelegram(json_data) + data = self._parseAndCheckTelegram(json_data.decode()) return Message.de_json(data) @@ -393,7 +394,7 @@ def sendVideo(self, data['reply_markup'] = reply_markup json_data = self._requestUrl(url, 'POST', data=data) - data = self._parseAndCheckTelegram(json_data) + data = self._parseAndCheckTelegram(json_data.decode()) return Message.de_json(data) @@ -441,7 +442,7 @@ def sendLocation(self, data['reply_markup'] = reply_markup json_data = self._requestUrl(url, 'POST', data=data) - data = self._parseAndCheckTelegram(json_data) + data = self._parseAndCheckTelegram(json_data.decode()) return Message.de_json(data) @@ -510,7 +511,7 @@ def getUserProfilePhotos(self, data['limit'] = limit json_data = self._requestUrl(url, 'POST', data=data) - data = self._parseAndCheckTelegram(json_data) + data = self._parseAndCheckTelegram(json_data.decode()) return UserProfilePhotos.de_json(data) @@ -552,7 +553,7 @@ def getUpdates(self, data['timeout'] = timeout json_data = self._requestUrl(url, 'POST', data=data) - data = self._parseAndCheckTelegram(json_data) + data = self._parseAndCheckTelegram(json_data.decode()) return [Update.de_json(x) for x in data] @@ -579,7 +580,7 @@ def setWebhook(self, webhook_url=""): data = {'url': webhook_url} json_data = self._requestUrl(url, 'POST', data=data) - data = self._parseAndCheckTelegram(json_data) + data = self._parseAndCheckTelegram(json_data.decode()) return True @@ -602,35 +603,33 @@ def _requestUrl(self, """ if method == 'POST': - if 'audio' in data and (isinstance(data['audio'], file) or 'http' in data['audio']) or \ - 'document' in data and (isinstance(data['document'], file) or 'http' in data['document']) or \ - 'photo' in data and (isinstance(data['photo'], file) or 'http' in data['photo']) or \ - 'video' in data and (isinstance(data['video'], file) or 'http' in data['video']): + if 'audio' in data and is_file(data['audio']) or \ + 'document' in data and is_file(data['document']) or \ + 'photo' in data and is_file(data['photo']) or \ + 'video' in data and is_file(data['video']): try: data = InputFile(data) - request = urllib2.Request( + request = urllib.request( url, data=data.to_form(), headers=data.headers ) - return urllib2.urlopen(request).read() - except urllib2.URLError as e: + return urllib.request.urlopen(request).read() + except urllib.error.URLError as e: raise TelegramError(str(e)) else: try: - return urllib2.urlopen( + return urllib.request.urlopen( url, - urllib.urlencode(data) + urllib.parse.urlencode(data).encode() ).read() - except urllib.IOError as e: - raise TelegramError(str(e)) - except urllib2.URLError as e: + except urllib.error.URLError as e: raise TelegramError(str(e)) if method == 'GET': try: - return urllib2.urlopen(url).read() - except urllib2.URLError as e: + return urllib.request.urlopen(url).read() + except urllib.error.URLError as e: raise TelegramError(str(e)) return 0 diff --git a/telegram/forcereply.py b/telegram/forcereply.py index 6cb5a149d0a..0dca6fb4dc4 100644 --- a/telegram/forcereply.py +++ b/telegram/forcereply.py @@ -2,7 +2,7 @@ import json -from replymarkup import ReplyMarkup +from .replymarkup import ReplyMarkup class ForceReply(ReplyMarkup): diff --git a/telegram/inputfile.py b/telegram/inputfile.py index f33045dd85f..86edc6d425e 100644 --- a/telegram/inputfile.py +++ b/telegram/inputfile.py @@ -1,45 +1,54 @@ #!/usr/bin/env python - -import mimetools -import mimetypes +try: + from mimetools import choose_boundary +except: + from email.generator import _make_boundary as choose_boundary +from mimetypes import guess_type +import six import os -import urllib2 + + +DEFAULT_MIME_TYPE = 'application/octet-stream' +USER_AGENT = 'Python Telegram Bot'\ + ' (https://github.com/leandrotoledo/python-telegram-bot)' + +if six.PY3: + import io + + def is_file(item): + return isinstance(item, io.TextIOWrapper) +else: + def is_file(item): + return isinstance(item, file) class InputFile(object): def __init__(self, data): self.data = data - self.boundary = mimetools.choose_boundary() + self.boundary = choose_boundary() - if 'audio' in data: + if 'audio' in data and is_file(data['audio']): self.input_name = 'audio' self.input_file = data.pop('audio') - if 'document' in data: + if 'document' in data and is_file(data['document']): self.input_name = 'document' self.input_file = data.pop('document') - if 'photo' in data: + if 'photo' in data and is_file(data['photo']): self.input_name = 'photo' self.input_file = data.pop('photo') - if 'video' in data: + if 'video' in data and is_file(data['video']): self.input_name = 'video' self.input_file = data.pop('video') - if isinstance(self.input_file, file): - self.filename = os.path.basename(self.input_file.name) - self.input_file_content = self.input_file.read() - if 'http' in self.input_file: - self.filename = os.path.basename(self.input_file) - self.input_file_content = urllib2.urlopen(self.input_file).read() - - self.mimetype = mimetypes.guess_type(self.filename)[0] or \ - 'application/octet-stream' + self.input_file_content = self.input_file.read() + self.filename = os.path.basename(self.input_file.name) + self.mimetype = guess_type(self.filename)[0] or DEFAULT_MIME_TYPE @property def headers(self): - return {'User-agent': 'Python Telegram Bot (https://github.com/leandrotoledo/python-telegram-bot)', - 'Content-type': self.content_type} + return {'User-agent': USER_AGENT, 'Content-type': self.content_type} @property def content_type(self): @@ -63,7 +72,7 @@ def to_form(self): form_boundary, str('Content-Disposition: form-data; name="%s"; filename="%s"' % ( self.input_name, self.filename - )), + )), 'Content-Type: %s' % self.mimetype, '', self.input_file_content diff --git a/telegram/message.py b/telegram/message.py index 8c5f74daf9b..2634c8abf2f 100644 --- a/telegram/message.py +++ b/telegram/message.py @@ -61,15 +61,14 @@ def de_json(data): else: from_user = None + chat = None if 'chat' in data: - if 'username' in data['chat']: + if 'username' in data['chat'] or 'first_name' in data['chat']: from telegram import User chat = User.de_json(data['chat']) if 'title' in data['chat']: from telegram import GroupChat chat = GroupChat.de_json(data['chat']) - else: - chat = None if 'forward_from' in data: from telegram import User @@ -186,9 +185,9 @@ def to_json(self): if self.location: json_data['location'] = self.location.to_json() if self.new_chat_participant: - json_data['new_chat_participant'] = self.new_chat_participant + json_data['new_chat_participant'] = self.new_chat_participant.__dict__ if self.left_chat_participant: - json_data['left_chat_participant'] = self.left_chat_participant + json_data['left_chat_participant'] = self.left_chat_participant.__dict__ if self.new_chat_title: json_data['new_chat_title'] = self.new_chat_title if self.new_chat_photo: diff --git a/telegram/replykeyboardhide.py b/telegram/replykeyboardhide.py index 2f4830e5dd6..bba71149b64 100644 --- a/telegram/replykeyboardhide.py +++ b/telegram/replykeyboardhide.py @@ -2,7 +2,7 @@ import json -from replymarkup import ReplyMarkup +from .replymarkup import ReplyMarkup class ReplyKeyboardHide(ReplyMarkup): diff --git a/telegram/replykeyboardmarkup.py b/telegram/replykeyboardmarkup.py index b217fb5d625..e3c273c002c 100644 --- a/telegram/replykeyboardmarkup.py +++ b/telegram/replykeyboardmarkup.py @@ -2,7 +2,7 @@ import json -from replymarkup import ReplyMarkup +from .replymarkup import ReplyMarkup class ReplyKeyboardMarkup(ReplyMarkup): diff --git a/telegram/user.py b/telegram/user.py index 50f3e98ef7a..8ba22326c84 100644 --- a/telegram/user.py +++ b/telegram/user.py @@ -31,5 +31,12 @@ def to_json(self): json_data['username'] = self.username return json.dumps(json_data) + def name(self): + if self.username: + return self.username + if self.last_name: + return '{} {}'.format(self.first_name, self.last_name) + return self.first_name + def __str__(self): return self.to_json() diff --git a/tests/test_bot.py b/tests/test_bot.py index 794e98ac435..8115da1a5c9 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -11,11 +11,11 @@ class BotTest(unittest.TestCase): def setUp(self): bot = telegram.Bot(token=os.environ.get('TOKEN')) self._bot = bot - print 'Testing the Bot API class' + print('Testing the Bot API class') def testGetMe(self): '''Test the telegram.Bot getMe method''' - print 'Testing getMe' + print('Testing getMe') user = self._bot.getMe() self.assertEqual(120405045, user.id) self.assertEqual('Toledo\'s Palace Bot', user.first_name) @@ -24,92 +24,92 @@ def testGetMe(self): def testSendMessage(self): '''Test the telegram.Bot sendMessage method''' - print 'Testing sendMessage' + print('Testing sendMessage') message = self._bot.sendMessage(chat_id=12173560, - text=u'Моё судно на воздушной подушке полно угрей'.encode('utf8')) - self.assertEqual(u'Моё судно на воздушной подушке полно угрей', message.text) + text='Моё судно на воздушной подушке полно угрей'.encode('utf8')) + self.assertEqual('Моё судно на воздушной подушке полно угрей', message.text) def testGetUpdates(self): '''Test the telegram.Bot getUpdates method''' - print 'Testing getUpdates' + print('Testing getUpdates') updates = self._bot.getUpdates() self.assertEqual(129566590, updates[0].update_id) def testForwardMessage(self): '''Test the telegram.Bot forwardMessage method''' - print 'Testing forwardMessage' + print('Testing forwardMessage') message = self._bot.forwardMessage(chat_id=12173560, from_chat_id=12173560, message_id=138) - self.assertEqual(u'Oi', message.text) - self.assertEqual(u'leandrotoledo', message.forward_from.username) + self.assertEqual('Oi', message.text) + self.assertEqual('leandrotoledo', message.forward_from.username) def testSendPhoto(self): '''Test the telegram.Bot sendPhoto method''' - print 'Testing sendPhoto - File' + print('Testing sendPhoto - File') message = self._bot.sendPhoto(photo=open('tests/telegram.png', 'rb'), chat_id=12173560) self.assertEqual(12948, message.photo[2].file_size) def testResendPhoto(self): '''Test the telegram.Bot sendPhoto method''' - print 'Testing sendPhoto - Resend' + print('Testing sendPhoto - Resend') message = self._bot.sendPhoto(photo=str('AgAD_v___6-nMRs1PC0HuqtHTCQ9qx0AFAI'), chat_id=12173560) - self.assertEqual(u'AgAD_v___6-nMRs1PC0HuqtHTCQ9qx0AFAI', message.photo[2].file_id) + self.assertEqual('AgAD_v___6-nMRs1PC0HuqtHTCQ9qx0AFAI', message.photo[2].file_id) def testSendAudio(self): '''Test the telegram.Bot sendAudio method''' - print 'Testing sendAudio - File' + print('Testing sendAudio - File') message = self._bot.sendAudio(audio=open('tests/telegram.ogg', 'rb'), chat_id=12173560) self.assertEqual(9199, message.audio.file_size) def testResendAudio(self): '''Test the telegram.Bot sendAudio method''' - print 'Testing sendAudio - Resend' + print('Testing sendAudio - Resend') message = self._bot.sendAudio(audio=str('AwADAQADIQEAAvjAuQABSAXg_GhkhZcC'), chat_id=12173560) - self.assertEqual(u'AwADAQADIQEAAvjAuQABSAXg_GhkhZcC', message.audio.file_id) + self.assertEqual('AwADAQADIQEAAvjAuQABSAXg_GhkhZcC', message.audio.file_id) def testSendDocument(self): '''Test the telegram.Bot sendDocument method''' - print 'Testing sendDocument - File' + print('Testing sendDocument - File') message = self._bot.sendDocument(document=open('tests/telegram.png', 'rb'), chat_id=12173560) self.assertEqual(12948, message.document.file_size) def testResendDocument(self): '''Test the telegram.Bot sendDocument method''' - print 'Testing sendDocument - Resend' + print('Testing sendDocument - Resend') message = self._bot.sendDocument(document=str('BQADAQADHAADNTwtBxZxUGKyxYbYAg'), chat_id=12173560) - self.assertEqual(u'BQADAQADHAADNTwtBxZxUGKyxYbYAg', message.document.file_id) + self.assertEqual('BQADAQADHAADNTwtBxZxUGKyxYbYAg', message.document.file_id) def testResendSticker(self): '''Test the telegram.Bot sendSticker method''' - print 'Testing sendSticker - Resend' + print('Testing sendSticker - Resend') message = self._bot.sendSticker(sticker=str('BQADAQADHAADyIsGAAFZfq1bphjqlgI'), chat_id=12173560) self.assertEqual(39518, message.sticker.file_size) def testSendVideo(self): '''Test the telegram.Bot sendVideo method''' - print 'Testing sendVideo - File' + print('Testing sendVideo - File') message = self._bot.sendVideo(video=open('tests/telegram.mp4', 'rb'), chat_id=12173560) self.assertEqual(326534, message.video.file_size) def testResendVideo(self): '''Test the telegram.Bot sendVideo method''' - print 'Testing sendVideo - Resend' + print('Testing sendVideo - Resend') message = self._bot.sendVideo(video=str('BAADAQADIgEAAvjAuQABOuTB937fPTgC'), chat_id=12173560) self.assertEqual(4, message.video.duration) def testSendLocation(self): '''Test the telegram.Bot sendLocation method''' - print 'Testing sendLocation' + print('Testing sendLocation') message = self._bot.sendLocation(latitude=-23.558873, longitude=-46.659732, chat_id=12173560) @@ -118,12 +118,12 @@ def testSendLocation(self): def testSendChatAction(self): '''Test the telegram.Bot sendChatAction method''' - print 'Testing sendChatAction - ChatAction.TYPING' + print('Testing sendChatAction - ChatAction.TYPING') self._bot.sendChatAction(action=telegram.ChatAction.TYPING, chat_id=12173560) def testGetUserProfilePhotos(self): '''Test the telegram.Bot getUserProfilePhotos method''' - print 'Testing getUserProfilePhotos' + print('Testing getUserProfilePhotos') upf = self._bot.getUserProfilePhotos(user_id=12173560) self.assertEqual(8314, upf.photos[0][0].file_size)