From 354c296fedbcbbfea005d4aa8d86dad3b23ee746 Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 25 Jul 2025 00:52:16 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20=D0=BF?= =?UTF-8?q?=D0=BE=20ruff=20+=20mypy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- maxapi/connection/base.py | 6 ++++-- maxapi/dispatcher.py | 20 ++++++++++++------- maxapi/methods/add_admin_chat.py | 3 ++- maxapi/methods/add_members_chat.py | 3 ++- maxapi/methods/change_info.py | 15 +++++++++----- maxapi/methods/delete_bot_from_chat.py | 3 ++- maxapi/methods/delete_chat.py | 4 +++- maxapi/methods/delete_message.py | 4 +++- maxapi/methods/delete_pin_message.py | 5 ++++- maxapi/methods/download_media.py | 6 ------ maxapi/methods/edit_chat.py | 15 +++++++++----- maxapi/methods/edit_message.py | 16 ++++++++++----- maxapi/methods/get_chat_by_id.py | 4 +++- maxapi/methods/get_chat_by_link.py | 4 +++- maxapi/methods/get_chats.py | 5 ++++- maxapi/methods/get_list_admin_chat.py | 5 ++++- maxapi/methods/get_me.py | 5 ++++- maxapi/methods/get_me_from_chat.py | 5 ++++- maxapi/methods/get_members_chat.py | 11 +++++++--- maxapi/methods/get_messages.py | 8 ++++++-- maxapi/methods/get_pinned_message.py | 5 ++++- maxapi/methods/get_updates.py | 7 ++++--- maxapi/methods/get_upload_url.py | 5 ++++- maxapi/methods/get_video.py | 5 ++++- maxapi/methods/pin_message.py | 5 ++++- maxapi/methods/remove_admin.py | 5 ++++- maxapi/methods/remove_member_chat.py | 4 +++- maxapi/methods/send_action.py | 4 +++- maxapi/methods/send_callback.py | 10 +++++++--- maxapi/methods/send_message.py | 18 ++++++++++++----- maxapi/methods/types/sended_callback.py | 2 +- maxapi/types/attachments/attachment.py | 2 -- .../types/attachments/buttons/chat_button.py | 3 +-- .../attachments/buttons/message_button.py | 2 -- .../attachments/buttons/request_contact.py | 2 -- maxapi/types/attachments/video.py | 2 +- maxapi/types/input_media.py | 6 ------ maxapi/types/updates/message_callback.py | 14 +++++-------- maxapi/types/updates/message_created.py | 2 +- maxapi/types/updates/update.py | 6 +++--- maxapi/utils/message.py | 6 ++++-- 41 files changed, 166 insertions(+), 96 deletions(-) diff --git a/maxapi/connection/base.py b/maxapi/connection/base.py index 662f459..c604c68 100644 --- a/maxapi/connection/base.py +++ b/maxapi/connection/base.py @@ -70,7 +70,8 @@ class BaseConnection: - dict (если is_return_raw=True) """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') if not self.bot.session: self.bot.session = ClientSession( @@ -100,7 +101,8 @@ class BaseConnection: raw = await r.json() - if is_return_raw: return raw + if is_return_raw: + return raw model = model(**raw) # type: ignore diff --git a/maxapi/dispatcher.py b/maxapi/dispatcher.py index ff01c56..12a0cec 100644 --- a/maxapi/dispatcher.py +++ b/maxapi/dispatcher.py @@ -220,7 +220,7 @@ class Dispatcher: continue for key in kwargs.copy().keys(): - if not key in func_args: + if key not in func_args: del kwargs[key] await handler.func_event(event_object, **kwargs) @@ -247,9 +247,12 @@ class Dispatcher: await self.__ready(bot) while True: + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') try: - events: Dict = await self.bot.get_updates() # type: ignore + events: Dict = await self.bot.get_updates() except AsyncioTimeoutError: continue @@ -260,11 +263,11 @@ class Dispatcher: await asyncio.sleep(GET_UPDATES_RETRY_DELAY) continue - self.bot.marker_updates = events.get('marker') # type: ignore + self.bot.marker_updates = events.get('marker') processed_events = await process_update_request( events=events, - bot=self.bot # type: ignore + bot=self.bot ) for event in processed_events: @@ -276,7 +279,7 @@ class Dispatcher: except Exception as e: logger_dp.error(f'Общая ошибка при обработке событий: {e.__class__} - {e}') - async def handle_webhook(self, bot: Bot, host: str = '0.0.0.0', port: int = 8080): + async def handle_webhook(self, bot: Bot, host: str = '127.0.0.1', port: int = 8080): """ Запускает FastAPI-приложение для приёма обновлений через вебхук. @@ -288,12 +291,15 @@ class Dispatcher: @webhook_app.post('/') async def _(request: Request): + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + try: event_json = await request.json() event_object = await process_update_webhook( event_json=event_json, - bot=self.bot # type: ignore + bot=self.bot ) await self.handle(event_object) @@ -308,7 +314,7 @@ class Dispatcher: port=port ) - async def init_serve(self, bot: Bot, host: str = '0.0.0.0', port: int = 8080, **kwargs): + async def init_serve(self, bot: Bot, host: str = '127.0.0.1', port: int = 8080, **kwargs): """ Запускает сервер для обработки входящих вебхуков. diff --git a/maxapi/methods/add_admin_chat.py b/maxapi/methods/add_admin_chat.py index bde3f98..a7358f1 100644 --- a/maxapi/methods/add_admin_chat.py +++ b/maxapi/methods/add_admin_chat.py @@ -48,7 +48,8 @@ class AddAdminChat(BaseConnection): AddedListAdminChat: Результат операции с информацией об успешности. """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') json: Dict[str, Any] = {} diff --git a/maxapi/methods/add_members_chat.py b/maxapi/methods/add_members_chat.py index 7e76b64..732950d 100644 --- a/maxapi/methods/add_members_chat.py +++ b/maxapi/methods/add_members_chat.py @@ -45,7 +45,8 @@ class AddMembersChat(BaseConnection): AddedMembersChat: Результат операции с информацией об успешности добавления. """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') json: Dict[str, Any] = {} diff --git a/maxapi/methods/change_info.py b/maxapi/methods/change_info.py index d8076f5..18cf3a9 100644 --- a/maxapi/methods/change_info.py +++ b/maxapi/methods/change_info.py @@ -48,14 +48,19 @@ class ChangeInfo(BaseConnection): User: Объект с обновленными данными бота """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') json: Dict[str, Any] = {} - if self.name: json['name'] = self.name - if self.description: json['description'] = self.description - if self.commands: json['commands'] = [command.model_dump() for command in self.commands] - if self.photo: json['photo'] = self.photo + if self.name: + json['name'] = self.name + if self.description: + json['description'] = self.description + if self.commands: + json['commands'] = [command.model_dump() for command in self.commands] + if self.photo: + json['photo'] = self.photo return await super().request( method=HTTPMethod.PATCH, diff --git a/maxapi/methods/delete_bot_from_chat.py b/maxapi/methods/delete_bot_from_chat.py index 8cfe2f9..d391f8b 100644 --- a/maxapi/methods/delete_bot_from_chat.py +++ b/maxapi/methods/delete_bot_from_chat.py @@ -39,7 +39,8 @@ class DeleteMeFromMessage(BaseConnection): DeletedBotFromChat: Результат операции удаления. """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') return await super().request( method=HTTPMethod.DELETE, path=ApiPath.CHATS + '/' + str(self.chat_id) + ApiPath.MEMBERS + ApiPath.ME, diff --git a/maxapi/methods/delete_chat.py b/maxapi/methods/delete_chat.py index 017241c..7e23544 100644 --- a/maxapi/methods/delete_chat.py +++ b/maxapi/methods/delete_chat.py @@ -38,7 +38,9 @@ class DeleteChat(BaseConnection): DeletedChat: Результат операции удаления чата. """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + return await super().request( method=HTTPMethod.DELETE, path=ApiPath.CHATS.value + '/' + str(self.chat_id), diff --git a/maxapi/methods/delete_message.py b/maxapi/methods/delete_message.py index b5ac682..a14495e 100644 --- a/maxapi/methods/delete_message.py +++ b/maxapi/methods/delete_message.py @@ -40,7 +40,9 @@ class DeleteMessage(BaseConnection): DeletedMessage: Результат операции удаления сообщения. """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + params = self.bot.params.copy() params['message_id'] = self.message_id diff --git a/maxapi/methods/delete_pin_message.py b/maxapi/methods/delete_pin_message.py index 6c88331..5319498 100644 --- a/maxapi/methods/delete_pin_message.py +++ b/maxapi/methods/delete_pin_message.py @@ -38,7 +38,10 @@ class DeletePinMessage(BaseConnection): Returns: DeletedPinMessage: Результат операции удаления закреплённого сообщения. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + return await super().request( method=HTTPMethod.DELETE, path=ApiPath.CHATS + '/' + str(self.chat_id) + ApiPath.PIN, diff --git a/maxapi/methods/download_media.py b/maxapi/methods/download_media.py index 2a5d5f3..7b9edc6 100644 --- a/maxapi/methods/download_media.py +++ b/maxapi/methods/download_media.py @@ -1,11 +1,5 @@ from typing import TYPE_CHECKING -from ..methods.types.deleted_pin_message import DeletedPinMessage - -from ..enums.http_method import HTTPMethod -from ..enums.api_path import ApiPath -from ..enums.upload_type import UploadType - from ..connection.base import BaseConnection diff --git a/maxapi/methods/edit_chat.py b/maxapi/methods/edit_chat.py index 118966a..ae7c7c0 100644 --- a/maxapi/methods/edit_chat.py +++ b/maxapi/methods/edit_chat.py @@ -64,14 +64,16 @@ class EditChat(BaseConnection): Chat: Обновлённый объект чата. """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + json: Dict[str, Any] = {} if self.icon: dump = self.icon.model_dump() counter = Counter(dump.values()) - if not None in counter or \ + if None not in counter or \ not counter[None] == 2: raise MaxIconParamsException( @@ -81,9 +83,12 @@ class EditChat(BaseConnection): json['icon'] = dump - if self.title: json['title'] = self.title - if self.pin: json['pin'] = self.pin - if self.notify: json['notify'] = self.notify + if self.title: + json['title'] = self.title + if self.pin: + json['pin'] = self.pin + if self.notify: + json['notify'] = self.notify return await super().request( method=HTTPMethod.PATCH, diff --git a/maxapi/methods/edit_message.py b/maxapi/methods/edit_message.py index bd0feb3..a37ec40 100644 --- a/maxapi/methods/edit_message.py +++ b/maxapi/methods/edit_message.py @@ -66,14 +66,17 @@ class EditMessage(BaseConnection): EditedMessage: Обновлённое сообщение. """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + params = self.bot.params.copy() json: Dict[str, Any] = {'attachments': []} params['message_id'] = self.message_id - if not self.text is None: json['text'] = self.text + if self.text is not None: + json['text'] = self.text if self.attachments: @@ -91,9 +94,12 @@ class EditMessage(BaseConnection): else: json['attachments'].append(att.model_dump()) - if not self.link is None: json['link'] = self.link.model_dump() - if not self.notify is None: json['notify'] = self.notify - if not self.parse_mode is None: json['format'] = self.parse_mode.value + if self.link is not None: + json['link'] = self.link.model_dump() + if self.notify is not None: + json['notify'] = self.notify + if self.parse_mode is not None: + json['format'] = self.parse_mode.value await asyncio.sleep(self.bot.after_input_media_delay) diff --git a/maxapi/methods/get_chat_by_id.py b/maxapi/methods/get_chat_by_id.py index b67b7b0..c0a7fbc 100644 --- a/maxapi/methods/get_chat_by_id.py +++ b/maxapi/methods/get_chat_by_id.py @@ -39,7 +39,9 @@ class GetChatById(BaseConnection): Chat: Объект чата с полной информацией. """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + return await super().request( method=HTTPMethod.GET, path=ApiPath.CHATS.value + '/' + str(self.id), diff --git a/maxapi/methods/get_chat_by_link.py b/maxapi/methods/get_chat_by_link.py index b9d6f40..384297a 100644 --- a/maxapi/methods/get_chat_by_link.py +++ b/maxapi/methods/get_chat_by_link.py @@ -49,7 +49,9 @@ class GetChatByLink(BaseConnection): Chat: Объект с информацией о чате. """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + return await super().request( method=HTTPMethod.GET, path=ApiPath.CHATS.value + '/' + self.link[-1], diff --git a/maxapi/methods/get_chats.py b/maxapi/methods/get_chats.py index be2dacd..12bf77d 100644 --- a/maxapi/methods/get_chats.py +++ b/maxapi/methods/get_chats.py @@ -46,7 +46,10 @@ class GetChats(BaseConnection): Returns: Chats: Объект с данными по списку чатов. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + params = self.bot.params.copy() params['count'] = self.count diff --git a/maxapi/methods/get_list_admin_chat.py b/maxapi/methods/get_list_admin_chat.py index 38e0732..f0b64d5 100644 --- a/maxapi/methods/get_list_admin_chat.py +++ b/maxapi/methods/get_list_admin_chat.py @@ -42,7 +42,10 @@ class GetListAdminChat(BaseConnection): Returns: GettedListAdminChat: Объект с информацией о администраторах чата. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + return await super().request( method=HTTPMethod.GET, path=ApiPath.CHATS.value + '/' + str(self.chat_id) + ApiPath.MEMBERS + ApiPath.ADMINS, diff --git a/maxapi/methods/get_me.py b/maxapi/methods/get_me.py index d113042..b8ad5dc 100644 --- a/maxapi/methods/get_me.py +++ b/maxapi/methods/get_me.py @@ -32,7 +32,10 @@ class GetMe(BaseConnection): Returns: User: Объект пользователя с полной информацией. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + return await super().request( method=HTTPMethod.GET, path=ApiPath.ME, diff --git a/maxapi/methods/get_me_from_chat.py b/maxapi/methods/get_me_from_chat.py index 5b6a822..5dbd610 100644 --- a/maxapi/methods/get_me_from_chat.py +++ b/maxapi/methods/get_me_from_chat.py @@ -42,7 +42,10 @@ class GetMeFromChat(BaseConnection): Returns: ChatMember: Информация о боте как участнике чата. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + return await super().request( method=HTTPMethod.GET, path=ApiPath.CHATS + '/' + str(self.chat_id) + ApiPath.MEMBERS + ApiPath.ME, diff --git a/maxapi/methods/get_members_chat.py b/maxapi/methods/get_members_chat.py index d980da0..a40cd5d 100644 --- a/maxapi/methods/get_members_chat.py +++ b/maxapi/methods/get_members_chat.py @@ -57,14 +57,19 @@ class GetMembersChat(BaseConnection): Returns: GettedMembersChat: Объект с данными по участникам чата. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + params = self.bot.params.copy() if self.user_ids: params['user_ids'] = ','.join([str(user_id) for user_id in self.user_ids]) - if self.marker: params['marker'] = self.marker - if self.count: params['marker'] = self.count + if self.marker: + params['marker'] = self.marker + if self.count: + params['marker'] = self.count return await super().request( method=HTTPMethod.GET, diff --git a/maxapi/methods/get_messages.py b/maxapi/methods/get_messages.py index e30f814..a30ddd6 100644 --- a/maxapi/methods/get_messages.py +++ b/maxapi/methods/get_messages.py @@ -59,10 +59,14 @@ class GetMessages(BaseConnection): Returns: Messages: Объект с полученными сообщениями. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + params = self.bot.params.copy() - if self.chat_id: params['chat_id'] = self.chat_id + if self.chat_id: + params['chat_id'] = self.chat_id if self.message_ids: params['message_ids'] = ','.join(self.message_ids) diff --git a/maxapi/methods/get_pinned_message.py b/maxapi/methods/get_pinned_message.py index fb4d0b3..07b67a1 100644 --- a/maxapi/methods/get_pinned_message.py +++ b/maxapi/methods/get_pinned_message.py @@ -37,7 +37,10 @@ class GetPinnedMessage(BaseConnection): Returns: GettedPin: Объект с информацией о закреплённом сообщении. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + return await super().request( method=HTTPMethod.GET, path=ApiPath.CHATS + '/' + str(self.chat_id) + ApiPath.PIN, diff --git a/maxapi/methods/get_updates.py b/maxapi/methods/get_updates.py index a27b169..dd62086 100644 --- a/maxapi/methods/get_updates.py +++ b/maxapi/methods/get_updates.py @@ -1,8 +1,6 @@ from __future__ import annotations from typing import TYPE_CHECKING, Dict -from ..types.updates import UpdateUnion - from ..enums.http_method import HTTPMethod from ..enums.api_path import ApiPath @@ -45,7 +43,10 @@ class GetUpdates(BaseConnection): Returns: UpdateUnion: Объединённый тип данных обновлений. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + params = self.bot.params.copy() params['limit'] = self.limit diff --git a/maxapi/methods/get_upload_url.py b/maxapi/methods/get_upload_url.py index 423c35a..c13ec86 100644 --- a/maxapi/methods/get_upload_url.py +++ b/maxapi/methods/get_upload_url.py @@ -43,7 +43,10 @@ class GetUploadURL(BaseConnection): Returns: GettedUploadUrl: Результат с URL для загрузки. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + params = self.bot.params.copy() params['type'] = self.type.value diff --git a/maxapi/methods/get_video.py b/maxapi/methods/get_video.py index ab10cd1..4a31324 100644 --- a/maxapi/methods/get_video.py +++ b/maxapi/methods/get_video.py @@ -38,7 +38,10 @@ class GetVideo(BaseConnection): Returns: Video: Объект с информацией о видео. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + return await super().request( method=HTTPMethod.GET, path=ApiPath.VIDEOS.value + '/' + self.video_token, diff --git a/maxapi/methods/pin_message.py b/maxapi/methods/pin_message.py index feb7551..274c028 100644 --- a/maxapi/methods/pin_message.py +++ b/maxapi/methods/pin_message.py @@ -52,7 +52,10 @@ class PinMessage(BaseConnection): Returns: PinnedMessage: Объект с информацией о закреплённом сообщении. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + json: Dict[str, Any] = {} json['message_id'] = self.message_id diff --git a/maxapi/methods/remove_admin.py b/maxapi/methods/remove_admin.py index fad99a7..c4d7cc2 100644 --- a/maxapi/methods/remove_admin.py +++ b/maxapi/methods/remove_admin.py @@ -46,7 +46,10 @@ class RemoveAdmin(BaseConnection): Returns: RemovedAdmin: Объект с результатом отмены прав администратора. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + return await super().request( method=HTTPMethod.DELETE, path=ApiPath.CHATS + '/' + str(self.chat_id) + \ diff --git a/maxapi/methods/remove_member_chat.py b/maxapi/methods/remove_member_chat.py index bb567cf..79ca422 100644 --- a/maxapi/methods/remove_member_chat.py +++ b/maxapi/methods/remove_member_chat.py @@ -54,7 +54,9 @@ class RemoveMemberChat(BaseConnection): RemovedMemberChat: Результат удаления участника. """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + params = self.bot.params.copy() params['chat_id'] = self.chat_id diff --git a/maxapi/methods/send_action.py b/maxapi/methods/send_action.py index 9397de5..04f8d98 100644 --- a/maxapi/methods/send_action.py +++ b/maxapi/methods/send_action.py @@ -49,7 +49,9 @@ class SendAction(BaseConnection): Returns: SendedAction: Результат выполнения запроса. """ - assert self.bot is not None + + if self.bot is None: + raise RuntimeError('Bot не инициализирован') json: Dict[str, Any] = {} diff --git a/maxapi/methods/send_callback.py b/maxapi/methods/send_callback.py index 9e3f657..4c76366 100644 --- a/maxapi/methods/send_callback.py +++ b/maxapi/methods/send_callback.py @@ -55,15 +55,19 @@ class SendCallback(BaseConnection): SendedCallback: Объект с результатом отправки callback. """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + params = self.bot.params.copy() params['callback_id'] = self.callback_id json: Dict[str, Any] = {} - if self.message: json['message'] = self.message.model_dump() - if self.notification: json['notification'] = self.notification + if self.message: + json['message'] = self.message.model_dump() + if self.notification: + json['notification'] = self.notification return await super().request( method=HTTPMethod.POST, diff --git a/maxapi/methods/send_message.py b/maxapi/methods/send_message.py index 3d453e2..135a103 100644 --- a/maxapi/methods/send_message.py +++ b/maxapi/methods/send_message.py @@ -70,13 +70,17 @@ class SendMessage(BaseConnection): SendedMessage или Error """ - assert self.bot is not None + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + params = self.bot.params.copy() json: Dict[str, Any] = {'attachments': []} - if self.chat_id: params['chat_id'] = self.chat_id - elif self.user_id: params['user_id'] = self.user_id + if self.chat_id: + params['chat_id'] = self.chat_id + elif self.user_id: + params['user_id'] = self.user_id json['text'] = self.text @@ -96,9 +100,13 @@ class SendMessage(BaseConnection): else: json['attachments'].append(att.model_dump()) - if not self.link is None: json['link'] = self.link.model_dump() + if self.link is not None: + json['link'] = self.link.model_dump() + json['notify'] = self.notify - if not self.parse_mode is None: json['format'] = self.parse_mode.value + + if self.parse_mode is not None: + json['format'] = self.parse_mode.value await asyncio.sleep(self.bot.after_input_media_delay) diff --git a/maxapi/methods/types/sended_callback.py b/maxapi/methods/types/sended_callback.py index 5dd940e..c51c7e1 100644 --- a/maxapi/methods/types/sended_callback.py +++ b/maxapi/methods/types/sended_callback.py @@ -21,4 +21,4 @@ class SendedCallback(BaseModel): bot: Optional[Any] = Field(default=None, exclude=True) if TYPE_CHECKING: - bot: Optional[Bot] + bot: Optional[Bot] # type: ignore diff --git a/maxapi/types/attachments/attachment.py b/maxapi/types/attachments/attachment.py index 20f9d97..499fc3a 100644 --- a/maxapi/types/attachments/attachment.py +++ b/maxapi/types/attachments/attachment.py @@ -1,8 +1,6 @@ from typing import TYPE_CHECKING, Any, List, Optional, Union from pydantic import BaseModel, Field -from ...exceptions.download_file import NotAvailableForDownload - from ...types.attachments.upload import AttachmentUpload from ...types.attachments.buttons import InlineButtonUnion from ...types.users import User diff --git a/maxapi/types/attachments/buttons/chat_button.py b/maxapi/types/attachments/buttons/chat_button.py index d65452e..a0ea681 100644 --- a/maxapi/types/attachments/buttons/chat_button.py +++ b/maxapi/types/attachments/buttons/chat_button.py @@ -20,5 +20,4 @@ class ChatButton(Button): chat_title: Optional[str] = None chat_description: Optional[str] = None start_payload: Optional[str] = None - chat_title: Optional[str] = None - uuid: Optional[int] = None \ No newline at end of file + uuid: Optional[int] = None \ No newline at end of file diff --git a/maxapi/types/attachments/buttons/message_button.py b/maxapi/types/attachments/buttons/message_button.py index 3ea01eb..1daef58 100644 --- a/maxapi/types/attachments/buttons/message_button.py +++ b/maxapi/types/attachments/buttons/message_button.py @@ -1,5 +1,3 @@ -from pydantic import BaseModel - from ....enums.button_type import ButtonType from .button import Button diff --git a/maxapi/types/attachments/buttons/request_contact.py b/maxapi/types/attachments/buttons/request_contact.py index d1565fc..c040629 100644 --- a/maxapi/types/attachments/buttons/request_contact.py +++ b/maxapi/types/attachments/buttons/request_contact.py @@ -1,5 +1,3 @@ -from typing import Optional - from ....enums.button_type import ButtonType from .button import Button diff --git a/maxapi/types/attachments/video.py b/maxapi/types/attachments/video.py index c72bd05..b0e00ee 100644 --- a/maxapi/types/attachments/video.py +++ b/maxapi/types/attachments/video.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Any, Literal, Optional +from typing import TYPE_CHECKING, Any, Optional from pydantic import BaseModel, Field from ...enums.attachment import AttachmentType diff --git a/maxapi/types/input_media.py b/maxapi/types/input_media.py index 3e2e539..5ec9b26 100644 --- a/maxapi/types/input_media.py +++ b/maxapi/types/input_media.py @@ -1,16 +1,10 @@ from __future__ import annotations -from typing import TYPE_CHECKING - import puremagic from ..enums.upload_type import UploadType -if TYPE_CHECKING: - from io import BytesIO - - class InputMedia: """ Класс для представления медиафайла. diff --git a/maxapi/types/updates/message_callback.py b/maxapi/types/updates/message_callback.py index 6d990ef..63c24c8 100644 --- a/maxapi/types/updates/message_callback.py +++ b/maxapi/types/updates/message_callback.py @@ -1,4 +1,4 @@ -from typing import List, Optional, TYPE_CHECKING, Union +from typing import List, Optional, Union from pydantic import BaseModel, Field @@ -21,12 +21,6 @@ from ..attachments.video import Video from ..attachments.audio import Audio -if TYPE_CHECKING: - from ...bot import Bot - from ...types.chats import Chat - from ...types.users import User - - class MessageForCallback(BaseModel): """ @@ -110,6 +104,9 @@ class MessageCallback(Update): Результат вызова send_callback бота. """ + if self.bot is None: + raise RuntimeError('Bot не инициализирован') + message = MessageForCallback() message.text = new_text @@ -117,8 +114,7 @@ class MessageCallback(Update): message.link = link message.notify = notify message.format = format - - assert self.bot is not None + return await self.bot.send_callback( callback_id=self.callback.callback_id, message=message, diff --git a/maxapi/types/updates/message_created.py b/maxapi/types/updates/message_created.py index 64a77ee..f335732 100644 --- a/maxapi/types/updates/message_created.py +++ b/maxapi/types/updates/message_created.py @@ -1,5 +1,5 @@ from __future__ import annotations -from typing import Optional, TYPE_CHECKING +from typing import Optional from .update import Update diff --git a/maxapi/types/updates/update.py b/maxapi/types/updates/update.py index 1952252..aba244e 100644 --- a/maxapi/types/updates/update.py +++ b/maxapi/types/updates/update.py @@ -28,9 +28,9 @@ class Update(BaseModel): chat: Optional[Any] = Field(default=None, exclude=True) if TYPE_CHECKING: - bot: Optional[Bot] - from_user: Optional[User] - chat: Optional[Chat] + bot: Optional[Bot] # type: ignore + from_user: Optional[User] # type: ignore + chat: Optional[Chat] # type: ignore class Config: arbitrary_types_allowed=True \ No newline at end of file diff --git a/maxapi/utils/message.py b/maxapi/utils/message.py index df49ae0..aa0de48 100644 --- a/maxapi/utils/message.py +++ b/maxapi/utils/message.py @@ -53,8 +53,10 @@ async def process_input_media( if att.type in (UploadType.VIDEO, UploadType.AUDIO): if upload.token is None: - assert bot.session is not None - await bot.session.close() + + if bot.session is not None: + await bot.session.close() + raise MaxUploadFileFailed('По неизвестной причине token не был получен') token = upload.token