X Tutup
Skip to content

Commit 8f8b220

Browse files
committed
Get rid of requests requirement, adding sendVideo file test
1 parent d82b8bf commit 8f8b220

File tree

6 files changed

+113
-52
lines changed

6 files changed

+113
-52
lines changed

requirements.txt

Lines changed: 0 additions & 1 deletion
This file was deleted.

telegram/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from replykeyboardhide import ReplyKeyboardHide
2626
from forcereply import ForceReply
2727
from replymarkup import ReplyMarkup
28+
from inputfile import InputFile
2829
from error import TelegramError
2930
from emoji import Emoji
3031
from bot import Bot

telegram/bot.py

Lines changed: 35 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@
44
"""A library that provides a Python interface to the Telegram Bot API"""
55

66
import json
7-
import requests
7+
import urllib
8+
import urllib2
89

910
from telegram import (User, Message, Update, UserProfilePhotos, TelegramError,
10-
ReplyMarkup)
11+
ReplyMarkup, InputFile)
1112

1213

1314
class Bot(object):
@@ -66,7 +67,7 @@ def getMe(self):
6667
url = '%s/getMe' % (self.base_url)
6768

6869
json_data = self._requestUrl(url, 'GET')
69-
data = self._parseAndCheckTelegram(json_data.content)
70+
data = self._parseAndCheckTelegram(json_data)
7071

7172
return User.de_json(data)
7273

@@ -115,7 +116,7 @@ def sendMessage(self,
115116
data['reply_markup'] = reply_markup
116117

117118
json_data = self._requestUrl(url, 'POST', data=data)
118-
data = self._parseAndCheckTelegram(json_data.content)
119+
data = self._parseAndCheckTelegram(json_data)
119120

120121
return Message.de_json(data)
121122

@@ -152,7 +153,7 @@ def forwardMessage(self,
152153
data['message_id'] = message_id
153154

154155
json_data = self._requestUrl(url, 'POST', data=data)
155-
data = self._parseAndCheckTelegram(json_data.content)
156+
data = self._parseAndCheckTelegram(json_data)
156157

157158
return Message.de_json(data)
158159

@@ -204,7 +205,7 @@ def sendPhoto(self,
204205
data['reply_markup'] = reply_markup
205206

206207
json_data = self._requestUrl(url, 'POST', data=data)
207-
data = self._parseAndCheckTelegram(json_data.content)
208+
data = self._parseAndCheckTelegram(json_data)
208209

209210
return Message.de_json(data)
210211

@@ -253,7 +254,7 @@ def sendAudio(self,
253254
data['reply_markup'] = reply_markup
254255

255256
json_data = self._requestUrl(url, 'POST', data=data)
256-
data = self._parseAndCheckTelegram(json_data.content)
257+
data = self._parseAndCheckTelegram(json_data)
257258

258259
return Message.de_json(data)
259260

@@ -299,7 +300,7 @@ def sendDocument(self,
299300
data['reply_markup'] = reply_markup
300301

301302
json_data = self._requestUrl(url, 'POST', data=data)
302-
data = self._parseAndCheckTelegram(json_data.content)
303+
data = self._parseAndCheckTelegram(json_data)
303304

304305
return Message.de_json(data)
305306

@@ -345,7 +346,7 @@ def sendSticker(self,
345346
data['reply_markup'] = reply_markup
346347

347348
json_data = self._requestUrl(url, 'POST', data=data)
348-
data = self._parseAndCheckTelegram(json_data.content)
349+
data = self._parseAndCheckTelegram(json_data)
349350

350351
return Message.de_json(data)
351352

@@ -392,7 +393,7 @@ def sendVideo(self,
392393
data['reply_markup'] = reply_markup
393394

394395
json_data = self._requestUrl(url, 'POST', data=data)
395-
data = self._parseAndCheckTelegram(json_data.content)
396+
data = self._parseAndCheckTelegram(json_data)
396397

397398
return Message.de_json(data)
398399

@@ -440,7 +441,7 @@ def sendLocation(self,
440441
data['reply_markup'] = reply_markup
441442

442443
json_data = self._requestUrl(url, 'POST', data=data)
443-
data = self._parseAndCheckTelegram(json_data.content)
444+
data = self._parseAndCheckTelegram(json_data)
444445

445446
return Message.de_json(data)
446447

@@ -509,7 +510,7 @@ def getUserProfilePhotos(self,
509510
data['limit'] = limit
510511

511512
json_data = self._requestUrl(url, 'POST', data=data)
512-
data = self._parseAndCheckTelegram(json_data.content)
513+
data = self._parseAndCheckTelegram(json_data)
513514

514515
return UserProfilePhotos.de_json(data)
515516

@@ -551,9 +552,9 @@ def getUpdates(self,
551552
data['timeout'] = timeout
552553

553554
json_data = self._requestUrl(url, 'POST', data=data)
554-
data = self._parseAndCheckTelegram(json_data.content)
555+
data = self._parseAndCheckTelegram(json_data)
555556

556-
return [Update.de_json(x) for x in data]
557+
return [Update.de_json(x) for x in data] # TODO: error handling
557558

558559
def setWebhook(self, webhook_url=""):
559560
"""Use this method to specify a url and receive incoming updates via an
@@ -578,7 +579,7 @@ def setWebhook(self, webhook_url=""):
578579
data = {'url': webhook_url}
579580

580581
json_data = self._requestUrl(url, 'POST', data=data)
581-
data = self._parseAndCheckTelegram(json_data.content)
582+
data = self._parseAndCheckTelegram(json_data)
582583

583584
return True
584585

@@ -601,51 +602,35 @@ def _requestUrl(self,
601602
"""
602603

603604
if method == 'POST':
604-
if 'photo' in data and isinstance(data['photo'], file):
605+
if 'audio' in data and isinstance(data['audio'], file) or \
606+
'document' in data and isinstance(data['document'], file) or \
607+
'photo' in data and isinstance(data['photo'], file) or \
608+
'video' in data and isinstance(data['video'], file):
605609
try:
606-
photo = data.pop('photo')
607-
608-
return requests.post(
609-
url,
610-
data=data,
611-
files={'photo': photo}
612-
)
613-
except requests.RequestException as e:
614-
raise TelegramError(str(e))
615-
if 'audio' in data and isinstance(data['audio'], file):
616-
try:
617-
audio = data.pop('audio')
618-
619-
return requests.post(
620-
url,
621-
data=data,
622-
files={'audio': audio}
623-
)
624-
except requests.RequestException as e:
625-
raise TelegramError(str(e))
626-
if 'document' in data and isinstance(data['document'], file):
627-
try:
628-
document = data.pop('document')
629-
630-
return requests.post(
610+
data = InputFile(data)
611+
request = urllib2.Request(
631612
url,
632-
data=data,
633-
files={'document': document}
613+
data=data.to_form(),
614+
headers=data.headers
634615
)
635-
except requests.RequestException as e:
616+
return urllib2.urlopen(request).read()
617+
except urllib2.URLError as e:
636618
raise TelegramError(str(e))
637619
else:
638620
try:
639-
return requests.post(
621+
return urllib2.urlopen(
640622
url,
641-
data=data
642-
)
643-
except requests.RequestException as e:
623+
urllib.urlencode(data)
624+
).read()
625+
except urllib.IOError as e:
626+
raise TelegramError(str(e))
627+
except urllib2.URLError as e:
644628
raise TelegramError(str(e))
629+
645630
if method == 'GET':
646631
try:
647-
return requests.get(url)
648-
except requests.RequestException as e:
632+
return urllib2.urlopen(url).read()
633+
except urllib2.URLError as e:
649634
raise TelegramError(str(e))
650635
return 0
651636

telegram/inputfile.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#!/usr/bin/env python
2+
3+
4+
import mimetools
5+
import mimetypes
6+
import os
7+
8+
9+
class InputFile(object):
10+
def __init__(self,
11+
data):
12+
self.data = data
13+
self.boundary = mimetools.choose_boundary()
14+
15+
if 'audio' in data and isinstance(data['audio'], file):
16+
self.input_name = 'audio'
17+
self.input_file = data.pop('audio')
18+
if 'document' in data and isinstance(data['document'], file):
19+
self.input_name = 'document'
20+
self.input_file = data.pop('document')
21+
if 'photo' in data and isinstance(data['photo'], file):
22+
self.input_name = 'photo'
23+
self.input_file = data.pop('photo')
24+
if 'video' in data and isinstance(data['video'], file):
25+
self.input_name = 'video'
26+
self.input_file = data.pop('video')
27+
28+
self.input_file_content = self.input_file.read()
29+
self.filename = os.path.basename(self.input_file.name)
30+
self.mimetype = mimetypes.guess_type(self.filename)[0] or \
31+
'application/octet-stream'
32+
33+
@property
34+
def headers(self):
35+
return {'User-agent': 'Python Telegram Bot (https://github.com/leandrotoledo/python-telegram-bot)',
36+
'Content-type': self.content_type}
37+
38+
@property
39+
def content_type(self):
40+
return 'multipart/form-data; boundary=%s' % self.boundary
41+
42+
def to_form(self):
43+
form = []
44+
form_boundary = '--' + self.boundary
45+
46+
# Add data fields
47+
for name, value in self.data.iteritems():
48+
form.extend([
49+
form_boundary,
50+
'Content-Disposition: form-data; name="%s"' % name,
51+
'',
52+
str(value)
53+
])
54+
55+
# Add input_file to upload
56+
form.extend([
57+
form_boundary,
58+
'Content-Disposition: form-data; name="%s"; filename="%s"' % (
59+
self.input_name, self.filename
60+
),
61+
'Content-Type: %s' % self.mimetype,
62+
'',
63+
self.input_file_content
64+
])
65+
66+
form.append('--' + self.boundary + '--')
67+
form.append('')
68+
69+
return '\r\n'.join(form)

tests/telegram.mp4

319 KB
Binary file not shown.

tests/test_bot.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def testGetUpdates(self):
3333
'''Test the telegram.Bot getUpdates method'''
3434
print 'Testing getUpdates'
3535
updates = self._bot.getUpdates()
36-
self.assertEqual(129566562, updates[0].update_id)
36+
self.assertEqual(129566572, updates[0].update_id)
3737

3838
def testForwardMessage(self):
3939
'''Test the telegram.Bot forwardMessage method'''
@@ -93,6 +93,13 @@ def testResendSticker(self):
9393
chat_id=12173560)
9494
self.assertEqual(39518, message.sticker.file_size)
9595

96+
def testSendVideo(self):
97+
'''Test the telegram.Bot sendVideo method'''
98+
print 'Testing sendVideo - File'
99+
message = self._bot.sendVideo(video=open('tests/telegram.mp4', 'rb'),
100+
chat_id=12173560)
101+
self.assertEqual(326534, message.video.file_size)
102+
96103
def testResendVideo(self):
97104
'''Test the telegram.Bot sendVideo method'''
98105
print 'Testing sendVideo - Resend'

0 commit comments

Comments
 (0)
X Tutup