Skip to content

Commit

Permalink
Format code with Black.
Browse files Browse the repository at this point in the history
  • Loading branch information
jarhill0 committed Jan 25, 2020
1 parent d250845 commit c0e2d1e
Show file tree
Hide file tree
Showing 149 changed files with 3,247 additions and 2,246 deletions.
27 changes: 21 additions & 6 deletions pawt/__init__.py
@@ -1,10 +1,25 @@
from .exceptions import *
from .models import inline_queries, input_message_content
from .models.message_specials import (Bold, BotCommand, Code, Email, Hashtag,
Italic, Mention, MessageEntity, Pre,
TextLink, TextMention, Url)
from .models.reply_markup import InlineKeyboardMarkupBuilder, \
ReplyKeyboardMarkupBuilder, force_reply, reply_keyboard_remove
from .models.message_specials import (
Bold,
BotCommand,
Code,
Email,
Hashtag,
Italic,
Mention,
MessageEntity,
Pre,
TextLink,
TextMention,
Url,
)
from .models.reply_markup import (
InlineKeyboardMarkupBuilder,
ReplyKeyboardMarkupBuilder,
force_reply,
reply_keyboard_remove,
)
from .telegram import Telegram

__version__ = '0.0.2a1'
__version__ = "0.0.2a1"
51 changes: 30 additions & 21 deletions pawt/bots/bot.py
@@ -1,9 +1,16 @@
from ..telegram import Telegram

CONTENT_TYPES = ('message', 'edited_message', 'channel_post',
'edited_channel_post', 'inline_query',
'chosen_inline_result', 'callback_query',
'shipping_query', 'pre_checkout_query')
CONTENT_TYPES = (
"message",
"edited_message",
"channel_post",
"edited_channel_post",
"inline_query",
"chosen_inline_result",
"callback_query",
"shipping_query",
"pre_checkout_query",
)


class TelegramBotInterface:
Expand All @@ -17,9 +24,12 @@ def __init__(self, token, *, url=None, session=None):
def run(self, timeout=60):
while self.go:
try:
updates = self.tg.get_updates(self.update_offset, limit=100,
timeout=timeout,
allowed_updates=CONTENT_TYPES)
updates = self.tg.get_updates(
self.update_offset,
limit=100,
timeout=timeout,
allowed_updates=CONTENT_TYPES,
)

if not updates:
self.perform_extra_task()
Expand All @@ -29,27 +39,26 @@ def run(self, timeout=60):
for update in updates:
try:
# it will only be one-- what a nice little elif chain!
if update.content_type == 'message':
if update.content_type == "message":
self.message_handler(update.message)
elif update.content_type == 'edited_message':
elif update.content_type == "edited_message":
self.edited_message_handler(update.edited_message)
elif update.content_type == 'channel_post':
elif update.content_type == "channel_post":
self.channel_post_handler(update.channel_post)
elif update.content_type == 'edited_channel_post':
self.edited_channel_post_handler(
update.edited_channel_post)
elif update.content_type == 'inline_query':
elif update.content_type == "edited_channel_post":
self.edited_channel_post_handler(update.edited_channel_post)
elif update.content_type == "inline_query":
self.inline_query_handler(update.inline_query)
elif update.content_type == 'chosen_inline_result':
elif update.content_type == "chosen_inline_result":
self.chosen_inline_result_handler(
update.chosen_inline_result)
elif update.content_type == 'callback_query':
update.chosen_inline_result
)
elif update.content_type == "callback_query":
self.callback_query_handler(update.callback_query)
elif update.content_type == 'shipping_query':
elif update.content_type == "shipping_query":
self.shipping_query_handler(update.shipping_query)
elif update.content_type == 'pre_checkout_query':
self.pre_checkout_query_handler(
update.pre_checkout_query)
elif update.content_type == "pre_checkout_query":
self.pre_checkout_query_handler(update.pre_checkout_query)
except Exception as e:
if not self.exception_handled(e):
raise
Expand Down
6 changes: 3 additions & 3 deletions pawt/bots/command_bot.py
Expand Up @@ -23,7 +23,7 @@ def edited_channel_post_handler(self, edited_channel_post):

@staticmethod
def next_cmd_ind(entities, entity):
for potential_e in entities[entities.index(entity) + 1:]:
for potential_e in entities[entities.index(entity) + 1 :]:
if isinstance(potential_e, BotCommand):
return potential_e.offset # next command found
return None # no other command
Expand All @@ -34,12 +34,12 @@ def _handle_message(self, message):
if isinstance(entity, BotCommand):
command = entity.command.lower()
end = self.next_cmd_ind(message.entities, entity)
cmd_text = message.text[entity.offset:end]
cmd_text = message.text[entity.offset : end]
self.text_command_handler(message, command, cmd_text)
elif message.caption_entities: # entities are caption-related
for entity in message.caption_entities:
if isinstance(entity, BotCommand):
command = entity.command.lower()
end = self.next_cmd_ind(message.caption_entities, entity)
cmd_text = message.caption[entity.offset:end]
cmd_text = message.caption[entity.offset : end]
self.caption_command_handler(message, command, cmd_text)
5 changes: 3 additions & 2 deletions pawt/bots/mapped_command_bot.py
Expand Up @@ -2,8 +2,9 @@


class MappedCommandBot(CommandBot):
def __init__(self, token, text_command_map, caption_command_map, *,
url=None, session=None):
def __init__(
self, token, text_command_map, caption_command_map, *, url=None, session=None
):
super().__init__(token, url=url, session=session)
self.text_command_map = text_command_map or dict()
self.caption_command_map = caption_command_map or dict()
Expand Down
3 changes: 1 addition & 2 deletions pawt/bots/simple_text_reply_bot.py
Expand Up @@ -3,8 +3,7 @@


class SimpleTextReplyBot(TelegramBotInterface):
def __init__(self, token, mapping, ignore_case=True, *, url=None,
session=None):
def __init__(self, token, mapping, ignore_case=True, *, url=None, session=None):
super().__init__(token, url=url, session=session)

self.ignore_case = ignore_case
Expand Down
119 changes: 60 additions & 59 deletions pawt/const.py
@@ -1,61 +1,62 @@
BASE_PATH = 'https://api.telegram.org/bot{token}/'
BASE_PATH = "https://api.telegram.org/bot{token}/"

API_PATH = {'get_updates': 'getUpdates',
'get_me': 'getMe',
'send_message': 'sendMessage',
'forward_message': 'forwardMessage',
'send_photo': 'sendPhoto',
'send_audio': 'sendAudio',
'send_document': 'sendDocument',
'send_video': 'sendVideo',
'send_voice': 'sendVoice',
'send_video_note': 'sendVideoNote',
'send_media_group': 'sendMediaGroup',
'send_location': 'sendLocation',
'edit_message_live_location': 'editMessageLiveLocation',
'stop_message_live_location': 'stopMessageLiveLocation',
'send_venue': 'sendVenue',
'send_contact': 'sendContact',
'send_chat_action': 'sendChatAction',
'get_user_profile_photos': 'getUserProfilePhotos',
'get_file': 'getFile',
'kick_chat_member': 'kickChatMember',
'unban_chat_member': 'unbanChatMember',
'restrict_chat_member': 'restrictChatMember',
'promote_chat_member': 'promoteChatMember',
'export_chat_invite_link': 'exportChatInviteLink',
'set_chat_photo': 'setChatPhoto',
'delete_chat_photo': 'deleteChatPhoto',
'set_chat_title': 'setChatTitle',
'set_chat_description': 'setChatDescription',
'pin_chat_message': 'pinChatMessage',
'unpin_chat_message': 'unpinChatMessage',
'leave_chat': 'leaveChat',
'get_chat': 'getChat',
'get_chat_administrators': 'getChatAdministrators',
'get_chat_members_count': 'getChatMembersCount',
'get_chat_member': 'getChatMember',
'set_chat_sticker_set': 'setChatStickerSet',
'delete_chat_sticker_set': 'deleteChatStickerSet',
'answer_callback_query': 'answerCallbackQuery',
'edit_message_text': 'editMessageText',
'edit_message_caption': 'editMessageCaption',
'edit_message_reply_markup': 'editMessageReplyMarkup',
'delete_message': 'deleteMessage',
'send_sticker': 'sendSticker',
'get_sticker_set': 'getStickerSet',
'upload_sticker_file': 'uploadStickerFile',
'create_new_sticker_set': 'createNewStickerSet',
'add_sticker_to_set': 'addStickerToSet',
'set_sticker_position_in_set': 'setStickerPositionInSet',
'delete_sticker_from_set': 'deleteStickerFromSet',
'answer_inline_query': 'answerInlineQuery',
'send_invoice': 'sendInvoice',
'answer_shipping_query': 'answerShippingQuery',
'answer_pre_checkout_query': 'answerPreCheckoutQuery',
'send_game': 'sendGame',
'set_game_score': 'setGameScore',
'get_game_high_scores': 'getGameHighScores'}
API_PATH = {
"get_updates": "getUpdates",
"get_me": "getMe",
"send_message": "sendMessage",
"forward_message": "forwardMessage",
"send_photo": "sendPhoto",
"send_audio": "sendAudio",
"send_document": "sendDocument",
"send_video": "sendVideo",
"send_voice": "sendVoice",
"send_video_note": "sendVideoNote",
"send_media_group": "sendMediaGroup",
"send_location": "sendLocation",
"edit_message_live_location": "editMessageLiveLocation",
"stop_message_live_location": "stopMessageLiveLocation",
"send_venue": "sendVenue",
"send_contact": "sendContact",
"send_chat_action": "sendChatAction",
"get_user_profile_photos": "getUserProfilePhotos",
"get_file": "getFile",
"kick_chat_member": "kickChatMember",
"unban_chat_member": "unbanChatMember",
"restrict_chat_member": "restrictChatMember",
"promote_chat_member": "promoteChatMember",
"export_chat_invite_link": "exportChatInviteLink",
"set_chat_photo": "setChatPhoto",
"delete_chat_photo": "deleteChatPhoto",
"set_chat_title": "setChatTitle",
"set_chat_description": "setChatDescription",
"pin_chat_message": "pinChatMessage",
"unpin_chat_message": "unpinChatMessage",
"leave_chat": "leaveChat",
"get_chat": "getChat",
"get_chat_administrators": "getChatAdministrators",
"get_chat_members_count": "getChatMembersCount",
"get_chat_member": "getChatMember",
"set_chat_sticker_set": "setChatStickerSet",
"delete_chat_sticker_set": "deleteChatStickerSet",
"answer_callback_query": "answerCallbackQuery",
"edit_message_text": "editMessageText",
"edit_message_caption": "editMessageCaption",
"edit_message_reply_markup": "editMessageReplyMarkup",
"delete_message": "deleteMessage",
"send_sticker": "sendSticker",
"get_sticker_set": "getStickerSet",
"upload_sticker_file": "uploadStickerFile",
"create_new_sticker_set": "createNewStickerSet",
"add_sticker_to_set": "addStickerToSet",
"set_sticker_position_in_set": "setStickerPositionInSet",
"delete_sticker_from_set": "deleteStickerFromSet",
"answer_inline_query": "answerInlineQuery",
"send_invoice": "sendInvoice",
"answer_shipping_query": "answerShippingQuery",
"answer_pre_checkout_query": "answerPreCheckoutQuery",
"send_game": "sendGame",
"set_game_score": "setGameScore",
"get_game_high_scores": "getGameHighScores",
}

MAX_LENGTH = {'text': 4096,
'caption': 200}
MAX_LENGTH = {"text": 4096, "caption": 200}
14 changes: 7 additions & 7 deletions pawt/exceptions.py
Expand Up @@ -11,8 +11,8 @@ class APIException(TelegramException):
"""Class for all exceptions caused serverside."""

def __init__(self, data):
message = '{}: {}'.format(data['error_code'], data['description'])
self.response_parameters = data.get('parameters')
message = "{}: {}".format(data["error_code"], data["description"])
self.response_parameters = data.get("parameters")
super().__init__(message)


Expand All @@ -32,17 +32,17 @@ def __init__(self, tg, api_path, data, *args, files=None) -> None:

def send_chunked(self):
"""Method to automatically re-send a message in chunks."""
param_name = 'text' if self._data.get('text') else 'caption'
param_name = "text" if self._data.get("text") else "caption"
# this method won't work on a long amount of text separated by
# non-space whitespace.
original = self._data[param_name].split(' ')
original = self._data[param_name].split(" ")
if any(len(part) > MAX_LENGTH[param_name] for part in original):
# we can't do it gracefully
return self._dummy_mode()

# helper -- better than copy-paste!
def send():
message = ' '.join(this_chunk)
message = " ".join(this_chunk)
self._data[param_name] = message
resp = self._tg.post(self._path, data=self._data, files=self._files)
return self._tg.message(resp)
Expand All @@ -64,14 +64,14 @@ def send():

def _dummy_mode(self):
"""Mangle the text in perfect chunks."""
param_name = 'text' if self._data.get('text') else 'caption'
param_name = "text" if self._data.get("text") else "caption"
text = self._data[param_name]
size = MAX_LENGTH[param_name]

sent_messages = []

for i in range(0, len(text), size):
chunk = text[i:i + size]
chunk = text[i : i + size]
self._data[param_name] = chunk
resp = self._tg.post(self._path, data=self._data, files=self._files)
mess = self._tg.message(resp)
Expand Down
11 changes: 6 additions & 5 deletions pawt/models/base.py
Expand Up @@ -13,18 +13,19 @@ def __getattr__(self, item):
self._load()
self._fetched = True
return getattr(self, item)
raise AttributeError('{} does not have attribute {!r}'.format(
self.__class__.__name__, item))
raise AttributeError(
"{} does not have attribute {!r}".format(self.__class__.__name__, item)
)

def _load(self):
raise NotImplementedError('Should be implemented by subclass.')
raise NotImplementedError("Should be implemented by subclass.")


class Sendable(PAWTBase):
def send(self, chat, *args, **kwargs):
raise NotImplementedError('Should be implemented by subclass')
raise NotImplementedError("Should be implemented by subclass")

def _chat_parser(self, chat):
if isinstance(chat, (str, int)):
chat = self._tg.chat(chat)
return chat
return chat
3 changes: 1 addition & 2 deletions pawt/models/inline_queries/__init__.py
Expand Up @@ -5,8 +5,7 @@
from .inline_query_result_cached_audio import InlineQueryResultCachedAudio
from .inline_query_result_cached_document import InlineQueryResultCachedDocument
from .inline_query_result_cached_gif import InlineQueryResultCachedGif
from .inline_query_result_cached_mpeg4_gif import \
InlineQueryResultCachedMpeg4Gif
from .inline_query_result_cached_mpeg4_gif import InlineQueryResultCachedMpeg4Gif
from .inline_query_result_cached_photo import InlineQueryResultCachedPhoto
from .inline_query_result_cached_sticker import InlineQueryResultCachedSticker
from .inline_query_result_cached_video import InlineQueryResultCachedVideo
Expand Down

0 comments on commit c0e2d1e

Please sign in to comment.