More pydoc's in api module and rewrite Methods class (use Helper) and reorder methods in list.

This commit is contained in:
Alex Root Junior 2017-07-23 06:08:06 +03:00
parent 1fd3290514
commit a333216e25

View file

@ -5,14 +5,23 @@ import aiohttp
from ..exceptions import ValidationError, TelegramAPIError from ..exceptions import ValidationError, TelegramAPIError
from ..utils import json from ..utils import json
from ..utils.helper import Helper, HelperMode, Item
# Main aiogram logger
log = logging.getLogger('aiogram') log = logging.getLogger('aiogram')
# API Url's
API_URL = "https://api.telegram.org/bot{token}/{method}" API_URL = "https://api.telegram.org/bot{token}/{method}"
FILE_URL = "https://api.telegram.org/file/bot{token}/{path}" FILE_URL = "https://api.telegram.org/file/bot{token}/{path}"
def check_token(token): def check_token(token: str) -> bool:
"""
Validate BOT token
:param token:
:return:
"""
if any(x.isspace() for x in token): if any(x.isspace() for x in token):
raise ValidationError('Token is invalid!') raise ValidationError('Token is invalid!')
@ -54,22 +63,34 @@ async def _check_result(method_name, response):
def _guess_filename(obj): def _guess_filename(obj):
"""
Get file name from object
:param obj:
:return:
"""
name = getattr(obj, 'name', None) name = getattr(obj, 'name', None)
if name and isinstance(name, str) and name[0] != '<' and name[-1] != '>': if name and isinstance(name, str) and name[0] != '<' and name[-1] != '>':
return os.path.basename(name) return os.path.basename(name)
def _compose_data(params, files=None): def _compose_data(params=None, files=None):
"""
Prepare request data
:param params:
:param files:
:return:
"""
data = aiohttp.formdata.FormData() data = aiohttp.formdata.FormData()
if params: if params:
for key, value in params.items(): for key, value in params.items():
if isinstance(value, dict): # TODO: Normalize data in other place.
if value.__class__ is dict:
value = json.dumps(value) value = json.dumps(value)
elif hasattr(value, 'to_json'): elif hasattr(value, 'to_json'):
value = json.dumps(value.to_json()) value = json.dumps(value.to_json())
else:
value = str(value)
data.add_field(key, value) data.add_field(key, value)
if files: if files:
@ -87,7 +108,23 @@ def _compose_data(params, files=None):
return data return data
async def request(session, token, method, data=None, files=None): async def request(session, token, method, data=None, files=None) -> bool or dict:
"""
Make request to API
That make request with Content-Type:
application/x-www-form-urlencoded - For simple request
and multipart/form-data - for files uploading
https://core.telegram.org/bots/api#making-requests
:param session: :class:`aiohttp.ClientSession`
:param token: BOT token
:param method: API method
:param data: request payload
:param files: files
:return: bool or dict
"""
log.debug(f"Make request: '{method}' with data: {data or {}} and files {files or {}}") log.debug(f"Make request: '{method}' with data: {data or {}} and files {files or {}}")
data = _compose_data(data, files) data = _compose_data(data, files)
url = Methods.api_url(token=token, method=method) url = Methods.api_url(token=token, method=method)
@ -95,66 +132,100 @@ async def request(session, token, method, data=None, files=None):
return await _check_result(method, response) return await _check_result(method, response)
class Methods: class Methods(Helper):
GET_ME = 'getMe' """
GET_UPDATES = 'getUpdates' Helper for Telegram API Methods listed on https://core.telegram.org/bots/api
SET_WEBHOOK = 'setWebhook'
DELETE_WEBHOOK = 'deleteWebhook' List is updated to Bot API 3.2
GET_WEBHOOK_INFO = 'getWebhookInfo' """
SEND_MESSAGE = 'sendMessage' mode = HelperMode.camelCase
FORWARD_MESSAGE = 'forwardMessage'
SEND_PHOTO = 'sendPhoto' # Getting Updates
SEND_AUDIO = 'sendAudio' GET_UPDATES = Item() # getUpdates
SEND_DOCUMENT = 'sendDocument' SET_WEBHOOK = Item() # setWebhook
SEND_STICKER = 'sendSticker' DELETE_WEBHOOK = Item() # deleteWebhook
GET_STICKER_SET = 'getStickerSet' GET_WEBHOOK_INFO = Item() # getWebhookInfo
UPLOAD_STICKER_FILE = 'uploadStickerFile'
CREATE_NEW_STICKER_SET = 'createNewStickerSet' # Available methods
ADD_STICKER_TO_SET = 'addStickerToSet' GET_ME = Item() # getMe
SET_STICKER_POSITION_IN_SET = 'setStickerPositionInSet' SEND_MESSAGE = Item() # sendMessage
DELETE_STICKER_FROM_SET = 'deleteStickerFromSet' FORWARD_MESSAGE = Item() # forwardMessage
SEND_VIDEO = 'sendVideo' SEND_PHOTO = Item() # sendPhoto
SEND_VOICE = 'sendVoice' SEND_AUDIO = Item() # sendAudio
SEND_VIDEO_NOTE = 'sendVideoNote' SEND_DOCUMENT = Item() # sendDocument
SEND_LOCATION = 'sendLocation' SEND_VIDEO = Item() # sendVideo
SEND_VENUE = 'sendVenue' SEND_VOICE = Item() # sendVoice
SEND_CONTACT = 'sendContact' SEND_VIDEO_NOTE = Item() # sendVideoNote
SEND_CHAT_ACTION = 'sendChatAction' SEND_LOCATION = Item() # sendLocation
GET_USER_PROFILE_PHOTOS = 'getUserProfilePhotos' SEND_VENUE = Item() # sendVenue
GET_FILE = 'getFile' SEND_CONTACT = Item() # sendContact
KICK_CHAT_MEMBER = 'kickChatMember' SEND_CHAT_ACTION = Item() # sendChatAction
UNBAN_CHAT_MEMBER = 'unbanChatMember' GET_USER_PROFILE_PHOTOS = Item() # getUserProfilePhotos
LEAVE_CHAT = 'leaveChat' GET_FILE = Item() # getFile
GET_CHAT = 'getChat' KICK_CHAT_MEMBER = Item() # kickChatMember
GET_CHAT_ADMINISTRATORS = 'getChatAdministrators' UNBAN_CHAT_MEMBER = Item() # unbanChatMember
GET_CHAT_MEMBERS_COUNT = 'getChatMembersCount' RESTRICT_CHAT_MEMBER = Item() # restrictChatMember
GET_CHAT_MEMBER = 'getChatMember' PROMOTE_CHAT_MEMBER = Item() # promoteChatMember
RESTRICT_CHAT_MEMBER = 'restrictChatMember' EXPORT_CHAT_INVITE_LINK = Item() # exportChatInviteLink
PROMOTE_CHAT_MEMBER = 'promoteChatMember' SET_CHAT_PHOTO = Item() # setChatPhoto
EXPORT_CHAT_INVITE_LINK = 'exportChatInviteLink' DELETE_CHAT_PHOTO = Item() # deleteChatPhoto
SET_CHAT_PHOTO = 'setChatPhoto' SET_CHAT_TITLE = Item() # setChatTitle
DELETE_CHAT_PHOTO = 'deleteChatPhoto' SET_CHAT_DESCRIPTION = Item() # setChatDescription
SET_CHAT_TITLE = 'setChatTitle' PIN_CHAT_MESSAGE = Item() # pinChatMessage
SET_CHAT_DESCRIPTION = 'setChatDescription' UNPIN_CHAT_MESSAGE = Item() # unpinChatMessage
PIN_CHAT_MESSAGE = 'pinChatMessage' LEAVE_CHAT = Item() # leaveChat
UNPIN_CHAT_MESSAGE = 'unpinChatMessage' GET_CHAT = Item() # getChat
ANSWER_CALLBACK_QUERY = 'answerCallbackQuery' GET_CHAT_ADMINISTRATORS = Item() # getChatAdministrators
ANSWER_INLINE_QUERY = 'answerInlineQuery' GET_CHAT_MEMBERS_COUNT = Item() # getChatMembersCount
EDIT_MESSAGE_TEXT = 'editMessageText' GET_CHAT_MEMBER = Item() # getChatMember
EDIT_MESSAGE_CAPTION = 'editMessageCaption' ANSWER_CALLBACK_QUERY = Item() # answerCallbackQuery
EDIT_MESSAGE_REPLY_MARKUP = 'editMessageReplyMarkup'
DELETE_MESSAGE = 'deleteMessage' # Updating messages
SEND_INVOICE = 'sendInvoice' EDIT_MESSAGE_TEXT = Item() # editMessageText
ANSWER_SHIPPING_QUERY = 'answerShippingQuery' EDIT_MESSAGE_CAPTION = Item() # editMessageCaption
ANSWER_PRE_CHECKOUT_QUERY = 'answerPreCheckoutQuery' EDIT_MESSAGE_REPLY_MARKUP = Item() # editMessageReplyMarkup
SEND_GAME = 'sendGame' DELETE_MESSAGE = Item() # deleteMessage
SET_GAME_SCORE = 'setGameScore'
GET_GAME_HIGH_SCORES = 'getGameHighScores' # Stickers
SEND_STICKER = Item() # sendSticker
GET_STICKER_SET = Item() # getStickerSet
UPLOAD_STICKER_FILE = Item() # uploadStickerFile
CREATE_NEW_STICKER_SET = Item() # createNewStickerSet
ADD_STICKER_TO_SET = Item() # addStickerToSet
SET_STICKER_POSITION_IN_SET = Item() # setStickerPositionInSet
DELETE_STICKER_FROM_SET = Item() # deleteStickerFromSet
# Inline mode
ANSWER_INLINE_QUERY = Item() # answerInlineQuery
# Payments
SEND_INVOICE = Item() # sendInvoice
ANSWER_SHIPPING_QUERY = Item() # answerShippingQuery
ANSWER_PRE_CHECKOUT_QUERY = Item() # answerPreCheckoutQuery
# Games
SEND_GAME = Item() # sendGame
SET_GAME_SCORE = Item() # setGameScore
GET_GAME_HIGH_SCORES = Item() # getGameHighScores
@staticmethod @staticmethod
def api_url(token, method): def api_url(token, method):
"""
Generate API URL with included token and method name
:param token:
:param method:
:return:
"""
return API_URL.format(token=token, method=method) return API_URL.format(token=token, method=method)
@staticmethod @staticmethod
def file_url(token, path): def file_url(token, path):
"""
Generate File URL with included token and file path
:param token:
:param path:
:return:
"""
return FILE_URL.format(token=token, path=path) return FILE_URL.format(token=token, path=path)