1
0
mirror of https://github.com/eternnoir/pyTelegramBotAPI.git synced 2023-08-10 21:12:57 +03:00

Merge pull request #60 from pevdh/better-error-description

Better error description
This commit is contained in:
FrankWang 2015-08-20 15:07:17 +08:00
commit b7a4d3f0b3
3 changed files with 182 additions and 170 deletions

View File

@ -2,14 +2,14 @@
from setuptools import setup from setuptools import setup
setup(name='pyTelegramBotAPI', setup(name='pyTelegramBotAPI',
version='0.3.0', version='0.3.1',
description='Python Telegram bot api. ', description='Python Telegram bot api. ',
author='eternnoir', author='eternnoir',
author_email='eternnoir@gmail.com', author_email='eternnoir@gmail.com',
url='https://github.com/eternnoir/pyTelegramBotAPI', url='https://github.com/eternnoir/pyTelegramBotAPI',
packages=['telebot'], packages=['telebot'],
license='GPL2', license='GPL2',
keywords='tools', keywords='telegram bot api tools',
install_requires=['pytest', 'requests', 'six'], install_requires=['pytest', 'requests', 'six'],
classifiers=[ classifiers=[
'Development Status :: 5 - Production/Stable', 'Development Status :: 5 - Production/Stable',

View File

@ -16,20 +16,44 @@ def _make_request(token, method_name, method='get', params=None, files=None):
:param method: HTTP method to be used. Defaults to 'get'. :param method: HTTP method to be used. Defaults to 'get'.
:param params: Optional parameters. Should be a dictionary with key-value pairs. :param params: Optional parameters. Should be a dictionary with key-value pairs.
:param files: Optional files. :param files: Optional files.
:return: :return: The result parsed to a JSON dictionary.
""" """
request_url = telebot.API_URL + 'bot' + token + '/' + method_name request_url = telebot.API_URL + 'bot' + token + '/' + method_name
result = requests.request(method, request_url, params=params, files=files) result = requests.request(method, request_url, params=params, files=files)
logger.debug(result.text) logger.debug(result.text)
return _check_result(method_name, result)['result']
def _check_result(method_name, result):
"""
Checks whether `result` is a valid API response.
A result is considered invalid if:
- The server returned an HTTP response code other than 200
- The content of the result is invalid JSON.
- The method call was unsuccessful (The JSON 'ok' field equals False)
:raises ApiException: if one of the above listed cases is applicable
:param method_name: The name of the method called
:param result: The returned result of the method request
:return: The result parsed to a JSON dictionary.
"""
if result.status_code != 200: if result.status_code != 200:
raise ApiException(method_name, result) msg = 'The server returned HTTP {0} {1}. Response body:\n[{2}]'\
.format(result.status_code, result.reason, result.text)
raise ApiException(msg, method_name, result)
try: try:
result_json = result.json() result_json = result.json()
if not result_json['ok']:
raise Exception()
except: except:
raise ApiException(method_name, result) msg = 'The server returned an invalid JSON response. Response body:\n[{0}]'\
return result_json['result'] .format(result.text)
raise ApiException(msg, method_name, result)
if not result_json['ok']:
msg = 'Error code: {0} Description: {1}'\
.format(result_json['error_code'], result_json['description'])
raise ApiException(msg, method_name, result)
return result_json
def get_me(token): def get_me(token):
@ -251,9 +275,12 @@ def split_string(text, chars_per_string):
class ApiException(Exception): class ApiException(Exception):
""" """
This class represents an Exception thrown when a call to the Telegram API fails. This class represents an Exception thrown when a call to the Telegram API fails.
In addition to an informative message, it has a `function_name` and a `result` attribute, which respectively
contain the name of the failed function and the returned result that made the function to be considered as
failed.
""" """
def __init__(self, function_name, result): def __init__(self, msg, function_name, result):
super(ApiException, self).__init__('{0} failed. Returned result: {1}'.format(function_name, result)) super(ApiException, self).__init__("A request to the Telegram API was unsuccessful. {0}".format(msg))
self.function_name = function_name self.function_name = function_name
self.result = result self.result = result

View File

@ -1,200 +1,185 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import sys import sys
import time
sys.path.append('../') sys.path.append('../')
from telebot import types
from telebot import apihelper import time
import telebot import pytest
import os import os
TOKEN = os.environ['TOKEN'] import telebot
CHAT_ID = os.environ['CHAT_ID'] from telebot import types
from telebot import apihelper
should_skip = 'TOKEN' and 'CHAT_ID' not in os.environ
if not should_skip:
TOKEN = os.environ['TOKEN']
CHAT_ID = os.environ['CHAT_ID']
def test_message_listener(): @pytest.mark.skipif(should_skip, reason="No environment variables configured")
msg_list = [] class TestTeleBot:
for x in range(100):
msg_list.append(create_text_message('Message ' + str(x)))
def listener(messages): def test_message_listener(self):
assert len(messages) == 100 msg_list = []
for x in range(100):
msg_list.append(self.create_text_message('Message ' + str(x)))
tb = telebot.TeleBot('') def listener(messages):
tb.set_update_listener(listener) assert len(messages) == 100
tb = telebot.TeleBot('')
tb.set_update_listener(listener)
def test_message_handler(): def test_message_handler(self):
tb = telebot.TeleBot('') tb = telebot.TeleBot('')
msg = create_text_message('/help') msg = self.create_text_message('/help')
@tb.message_handler(commands=['help', 'start']) @tb.message_handler(commands=['help', 'start'])
def command_handler(message): def command_handler(message):
message.text = 'got' message.text = 'got'
tb.process_new_messages([msg]) tb.process_new_messages([msg])
time.sleep(1) time.sleep(1)
assert msg.text == 'got' assert msg.text == 'got'
def test_message_handler_reg(self):
bot = telebot.TeleBot('')
msg = self.create_text_message(r'https://web.telegram.org/')
def test_message_handler_reg(): @bot.message_handler(regexp='((https?):((//)|(\\\\))+([\w\d:#@%/;$()~_?\+-=\\\.&](#!)?)*)')
bot = telebot.TeleBot('') def command_url(message):
msg = create_text_message(r'https://web.telegram.org/') msg.text = 'got'
@bot.message_handler(regexp='((https?):((//)|(\\\\))+([\w\d:#@%/;$()~_?\+-=\\\.&](#!)?)*)') bot.process_new_messages([msg])
def command_url(message): time.sleep(1)
msg.text = 'got' assert msg.text == 'got'
bot.process_new_messages([msg]) def test_message_handler_reg_fail(self):
time.sleep(1) bot = telebot.TeleBot('')
assert msg.text == 'got' msg = self.create_text_message(r'web.telegram.org/')
@bot.message_handler(regexp='((https?):((//)|(\\\\))+([\w\d:#@%/;$()~_?\+-=\\\.&](#!)?)*)')
def command_url(message):
msg.text = 'got'
def test_message_handler_reg_fail(): bot.process_new_messages([msg])
bot = telebot.TeleBot('') time.sleep(1)
msg = create_text_message(r'web.telegram.org/') assert not msg.text == 'got'
@bot.message_handler(regexp='((https?):((//)|(\\\\))+([\w\d:#@%/;$()~_?\+-=\\\.&](#!)?)*)') def test_send_file_by_id(self):
def command_url(message): file_id = 'BQADBQADjAIAAsYifgbvqwq1he9REAI'
msg.text = 'got' tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_document(CHAT_ID, file_id)
assert ret_msg.message_id
bot.process_new_messages([msg]) def test_send_file(self):
time.sleep(1) file_data = open('../examples/detailed_example/kitten.jpg', 'rb')
assert not msg.text == 'got' tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_document(CHAT_ID, file_data)
assert ret_msg.message_id
def test_send_video(self):
file_data = open('./test_data/test_video.mp4', 'rb')
tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_video(CHAT_ID, file_data)
assert ret_msg.message_id
def test_send_file_by_id(): def test_send_video_more_params(self):
file_id = 'BQADBQADjAIAAsYifgbvqwq1he9REAI' file_data = open('./test_data/test_video.mp4', 'rb')
tb = telebot.TeleBot(TOKEN) tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_document(CHAT_ID, file_id) ret_msg = tb.send_video(CHAT_ID, file_data, 1)
assert ret_msg.message_id assert ret_msg.message_id
def test_send_file_exception(self):
tb = telebot.TeleBot(TOKEN)
try:
tb.send_document(CHAT_ID, None)
assert False
except Exception as e:
print(e)
assert True
def test_send_file(): def test_send_photo_by_id(self):
file_data = open('../examples/detailed_example/kitten.jpg', 'rb') photo_id = 'AgADBQADTKgxG8YifgbcWQAB7Da9yYIx1rEyAAT-HYJ3CrJEqdA2AQABAg'
tb = telebot.TeleBot(TOKEN) tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_document(CHAT_ID, file_data) ret_msg = tb.send_photo(CHAT_ID, photo_id)
assert ret_msg.message_id assert ret_msg.message_id
def test_send_photo(self):
file_data = open('../examples/detailed_example/kitten.jpg', 'rb')
tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_photo(CHAT_ID, file_data)
assert ret_msg.message_id
def test_send_video(): def test_send_audio(self):
file_data = open('./test_data/test_video.mp4', 'rb') file_data = open('./test_data/record.mp3', 'rb')
tb = telebot.TeleBot(TOKEN) tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_video(CHAT_ID, file_data) ret_msg = tb.send_audio(CHAT_ID, file_data, 1, 'eternnoir', 'pyTelegram')
assert ret_msg.message_id assert ret_msg.content_type == 'audio'
assert ret_msg.audio.performer == 'eternnoir'
assert ret_msg.audio.title == 'pyTelegram'
def test_send_voice(self):
file_data = open('./test_data/record.ogg', 'rb')
tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_voice(CHAT_ID, file_data)
assert ret_msg.voice.mime_type == 'audio/ogg'
def test_send_video_more_params(): def test_send_message(self):
file_data = open('./test_data/test_video.mp4', 'rb') text = 'CI Test Message'
tb = telebot.TeleBot(TOKEN) tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_video(CHAT_ID, file_data, 1) ret_msg = tb.send_message(CHAT_ID, text)
assert ret_msg.message_id assert ret_msg.message_id
def test_forward_message(self):
text = 'CI forward_message Test Message'
tb = telebot.TeleBot(TOKEN)
msg = tb.send_message(CHAT_ID, text)
ret_msg = tb.forward_message(CHAT_ID, CHAT_ID, msg.message_id)
assert ret_msg.forward_from
def test_send_file_exception(): def test_reply_to(self):
tb = telebot.TeleBot(TOKEN) text = 'CI reply_to Test Message'
try: tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_document(CHAT_ID, None) msg = tb.send_message(CHAT_ID, text)
assert False ret_msg = tb.reply_to(msg, text + ' REPLY')
except Exception as e: assert ret_msg.reply_to_message.message_id == msg.message_id
print(e)
assert True
def test_register_for_reply(self):
text = 'CI reply_to Test Message'
tb = telebot.TeleBot(TOKEN)
msg = tb.send_message(CHAT_ID, text, reply_markup=types.ForceReply())
reply_msg = tb.reply_to(msg, text + ' REPLY')
def test_send_photo_by_id(): def process_reply(message):
photo_id = 'AgADBQADTKgxG8YifgbcWQAB7Da9yYIx1rEyAAT-HYJ3CrJEqdA2AQABAg' assert msg.message_id == message.reply_to_message.message_id
tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_photo(CHAT_ID, photo_id)
assert ret_msg.message_id
tb.register_for_reply(msg, process_reply)
def test_send_photo(): tb.process_new_messages([reply_msg])
file_data = open('../examples/detailed_example/kitten.jpg', 'rb')
tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_photo(CHAT_ID, file_data)
assert ret_msg.message_id
def test_send_location(self):
tb = telebot.TeleBot(TOKEN)
lat = 26.3875591
lon = -161.2901042
ret_msg = tb.send_location(CHAT_ID, lat, lon)
assert int(ret_msg.location.longitude) == int(lon)
assert int(ret_msg.location.latitude) == int(lat)
def test_send_audio(): def create_text_message(self, text):
file_data = open('./test_data/record.mp3', 'rb') params = {'text': text}
tb = telebot.TeleBot(TOKEN) chat = types.User(11, 'test')
ret_msg = tb.send_audio(CHAT_ID, file_data, 1, 'eternnoir', 'pyTelegram') return types.Message(1, None, None, chat, 'text', params)
assert ret_msg.content_type == 'audio'
assert ret_msg.audio.performer == 'eternnoir'
assert ret_msg.audio.title == 'pyTelegram'
def test_is_string_unicode(self):
s1 = u'string'
assert apihelper.is_string(s1)
def test_send_voice(): def test_is_string_string(self):
file_data = open('./test_data/record.ogg', 'rb') s1 = 'string'
tb = telebot.TeleBot(TOKEN) assert apihelper.is_string(s1)
ret_msg = tb.send_voice(CHAT_ID, file_data)
assert ret_msg.voice.mime_type == 'audio/ogg'
def test_not_string(self):
def test_send_message(): i1 = 10
text = 'CI Test Message' assert not apihelper.is_string(i1)
tb = telebot.TeleBot(TOKEN)
ret_msg = tb.send_message(CHAT_ID, text)
assert ret_msg.message_id
def test_forward_message():
text = 'CI forward_message Test Message'
tb = telebot.TeleBot(TOKEN)
msg = tb.send_message(CHAT_ID, text)
ret_msg = tb.forward_message(CHAT_ID, CHAT_ID, msg.message_id)
assert ret_msg.forward_from
def test_reply_to():
text = 'CI reply_to Test Message'
tb = telebot.TeleBot(TOKEN)
msg = tb.send_message(CHAT_ID, text)
ret_msg = tb.reply_to(msg, text + ' REPLY')
assert ret_msg.reply_to_message.message_id == msg.message_id
def test_register_for_reply():
text = 'CI reply_to Test Message'
tb = telebot.TeleBot(TOKEN)
msg = tb.send_message(CHAT_ID, text, reply_markup=types.ForceReply())
reply_msg = tb.reply_to(msg, text + ' REPLY')
def process_reply(message):
assert msg.message_id == message.reply_to_message.message_id
tb.register_for_reply(msg, process_reply)
tb.process_new_messages([reply_msg])
def test_send_location():
tb = telebot.TeleBot(TOKEN)
lat = 26.3875591
lon = -161.2901042
ret_msg = tb.send_location(CHAT_ID, lat, lon)
assert int(ret_msg.location.longitude) == int(lon)
assert int(ret_msg.location.latitude) == int(lat)
def create_text_message(text):
params = {'text': text}
chat = types.User(11, 'test')
return types.Message(1, None, None, chat, 'text', params)
def test_is_string_unicode():
s1 = u'string'
assert apihelper.is_string(s1)
def test_is_string_string():
s1 = 'string'
assert apihelper.is_string(s1)
def test_not_string():
i1 = 10
assert not apihelper.is_string(i1)
test_send_voice()