Get rid of requests requirement, adding sendVideo file test

This commit is contained in:
Leandro Toledo 2015-07-10 13:43:35 -03:00
parent d82b8bfbe6
commit 8f8b220bff
6 changed files with 113 additions and 52 deletions

View file

@ -1 +0,0 @@
requests

View file

@ -25,6 +25,7 @@ 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

View file

@ -4,10 +4,11 @@
"""A library that provides a Python interface to the Telegram Bot API"""
import json
import requests
import urllib
import urllib2
from telegram import (User, Message, Update, UserProfilePhotos, TelegramError,
ReplyMarkup)
ReplyMarkup, InputFile)
class Bot(object):
@ -66,7 +67,7 @@ class Bot(object):
url = '%s/getMe' % (self.base_url)
json_data = self._requestUrl(url, 'GET')
data = self._parseAndCheckTelegram(json_data.content)
data = self._parseAndCheckTelegram(json_data)
return User.de_json(data)
@ -115,7 +116,7 @@ class Bot(object):
data['reply_markup'] = reply_markup
json_data = self._requestUrl(url, 'POST', data=data)
data = self._parseAndCheckTelegram(json_data.content)
data = self._parseAndCheckTelegram(json_data)
return Message.de_json(data)
@ -152,7 +153,7 @@ class Bot(object):
data['message_id'] = message_id
json_data = self._requestUrl(url, 'POST', data=data)
data = self._parseAndCheckTelegram(json_data.content)
data = self._parseAndCheckTelegram(json_data)
return Message.de_json(data)
@ -204,7 +205,7 @@ class Bot(object):
data['reply_markup'] = reply_markup
json_data = self._requestUrl(url, 'POST', data=data)
data = self._parseAndCheckTelegram(json_data.content)
data = self._parseAndCheckTelegram(json_data)
return Message.de_json(data)
@ -253,7 +254,7 @@ class Bot(object):
data['reply_markup'] = reply_markup
json_data = self._requestUrl(url, 'POST', data=data)
data = self._parseAndCheckTelegram(json_data.content)
data = self._parseAndCheckTelegram(json_data)
return Message.de_json(data)
@ -299,7 +300,7 @@ class Bot(object):
data['reply_markup'] = reply_markup
json_data = self._requestUrl(url, 'POST', data=data)
data = self._parseAndCheckTelegram(json_data.content)
data = self._parseAndCheckTelegram(json_data)
return Message.de_json(data)
@ -345,7 +346,7 @@ class Bot(object):
data['reply_markup'] = reply_markup
json_data = self._requestUrl(url, 'POST', data=data)
data = self._parseAndCheckTelegram(json_data.content)
data = self._parseAndCheckTelegram(json_data)
return Message.de_json(data)
@ -392,7 +393,7 @@ class Bot(object):
data['reply_markup'] = reply_markup
json_data = self._requestUrl(url, 'POST', data=data)
data = self._parseAndCheckTelegram(json_data.content)
data = self._parseAndCheckTelegram(json_data)
return Message.de_json(data)
@ -440,7 +441,7 @@ class Bot(object):
data['reply_markup'] = reply_markup
json_data = self._requestUrl(url, 'POST', data=data)
data = self._parseAndCheckTelegram(json_data.content)
data = self._parseAndCheckTelegram(json_data)
return Message.de_json(data)
@ -509,7 +510,7 @@ class Bot(object):
data['limit'] = limit
json_data = self._requestUrl(url, 'POST', data=data)
data = self._parseAndCheckTelegram(json_data.content)
data = self._parseAndCheckTelegram(json_data)
return UserProfilePhotos.de_json(data)
@ -551,9 +552,9 @@ class Bot(object):
data['timeout'] = timeout
json_data = self._requestUrl(url, 'POST', data=data)
data = self._parseAndCheckTelegram(json_data.content)
data = self._parseAndCheckTelegram(json_data)
return [Update.de_json(x) for x in data]
return [Update.de_json(x) for x in data] # TODO: error handling
def setWebhook(self, webhook_url=""):
"""Use this method to specify a url and receive incoming updates via an
@ -578,7 +579,7 @@ class Bot(object):
data = {'url': webhook_url}
json_data = self._requestUrl(url, 'POST', data=data)
data = self._parseAndCheckTelegram(json_data.content)
data = self._parseAndCheckTelegram(json_data)
return True
@ -601,51 +602,35 @@ class Bot(object):
"""
if method == 'POST':
if 'photo' in data and isinstance(data['photo'], file):
if 'audio' in data and isinstance(data['audio'], file) or \
'document' in data and isinstance(data['document'], file) or \
'photo' in data and isinstance(data['photo'], file) or \
'video' in data and isinstance(data['video'], file):
try:
photo = data.pop('photo')
return requests.post(
data = InputFile(data)
request = urllib2.Request(
url,
data=data,
files={'photo': photo}
data=data.to_form(),
headers=data.headers
)
except requests.RequestException as e:
raise TelegramError(str(e))
if 'audio' in data and isinstance(data['audio'], file):
try:
audio = data.pop('audio')
return requests.post(
url,
data=data,
files={'audio': audio}
)
except requests.RequestException as e:
raise TelegramError(str(e))
if 'document' in data and isinstance(data['document'], file):
try:
document = data.pop('document')
return requests.post(
url,
data=data,
files={'document': document}
)
except requests.RequestException as e:
return urllib2.urlopen(request).read()
except urllib2.URLError as e:
raise TelegramError(str(e))
else:
try:
return requests.post(
return urllib2.urlopen(
url,
data=data
)
except requests.RequestException as e:
urllib.urlencode(data)
).read()
except urllib.IOError as e:
raise TelegramError(str(e))
except urllib2.URLError as e:
raise TelegramError(str(e))
if method == 'GET':
try:
return requests.get(url)
except requests.RequestException as e:
return urllib2.urlopen(url).read()
except urllib2.URLError as e:
raise TelegramError(str(e))
return 0

69
telegram/inputfile.py Normal file
View file

@ -0,0 +1,69 @@
#!/usr/bin/env python
import mimetools
import mimetypes
import os
class InputFile(object):
def __init__(self,
data):
self.data = data
self.boundary = mimetools.choose_boundary()
if 'audio' in data and isinstance(data['audio'], file):
self.input_name = 'audio'
self.input_file = data.pop('audio')
if 'document' in data and isinstance(data['document'], file):
self.input_name = 'document'
self.input_file = data.pop('document')
if 'photo' in data and isinstance(data['photo'], file):
self.input_name = 'photo'
self.input_file = data.pop('photo')
if 'video' in data and isinstance(data['video'], file):
self.input_name = 'video'
self.input_file = data.pop('video')
self.input_file_content = self.input_file.read()
self.filename = os.path.basename(self.input_file.name)
self.mimetype = mimetypes.guess_type(self.filename)[0] or \
'application/octet-stream'
@property
def headers(self):
return {'User-agent': 'Python Telegram Bot (https://github.com/leandrotoledo/python-telegram-bot)',
'Content-type': self.content_type}
@property
def content_type(self):
return 'multipart/form-data; boundary=%s' % self.boundary
def to_form(self):
form = []
form_boundary = '--' + self.boundary
# Add data fields
for name, value in self.data.iteritems():
form.extend([
form_boundary,
'Content-Disposition: form-data; name="%s"' % name,
'',
str(value)
])
# Add input_file to upload
form.extend([
form_boundary,
'Content-Disposition: form-data; name="%s"; filename="%s"' % (
self.input_name, self.filename
),
'Content-Type: %s' % self.mimetype,
'',
self.input_file_content
])
form.append('--' + self.boundary + '--')
form.append('')
return '\r\n'.join(form)

BIN
tests/telegram.mp4 Normal file

Binary file not shown.

View file

@ -33,7 +33,7 @@ class BotTest(unittest.TestCase):
'''Test the telegram.Bot getUpdates method'''
print 'Testing getUpdates'
updates = self._bot.getUpdates()
self.assertEqual(129566562, updates[0].update_id)
self.assertEqual(129566572, updates[0].update_id)
def testForwardMessage(self):
'''Test the telegram.Bot forwardMessage method'''
@ -93,6 +93,13 @@ class BotTest(unittest.TestCase):
chat_id=12173560)
self.assertEqual(39518, message.sticker.file_size)
def testSendVideo(self):
'''Test the telegram.Bot sendVideo method'''
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'