Правки по ruff + mypy

This commit is contained in:
Денис Семёнов 2025-07-25 00:52:16 +03:00
parent 8f93cf36e4
commit 354c296fed
41 changed files with 166 additions and 96 deletions

View File

@ -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

View File

@ -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):
"""
Запускает сервер для обработки входящих вебхуков.

View File

@ -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] = {}

View File

@ -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] = {}

View File

@ -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,

View File

@ -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,

View File

@ -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),

View File

@ -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

View File

@ -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,

View File

@ -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

View File

@ -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,

View File

@ -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)

View File

@ -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),

View File

@ -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],

View File

@ -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

View File

@ -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,

View File

@ -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,

View File

@ -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,

View File

@ -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,

View File

@ -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)

View File

@ -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,

View File

@ -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

View File

@ -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

View File

@ -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,

View File

@ -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

View File

@ -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) + \

View File

@ -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

View File

@ -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] = {}

View File

@ -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,

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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
uuid: Optional[int] = None

View File

@ -1,5 +1,3 @@
from pydantic import BaseModel
from ....enums.button_type import ButtonType
from .button import Button

View File

@ -1,5 +1,3 @@
from typing import Optional
from ....enums.button_type import ButtonType
from .button import Button

View File

@ -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

View File

@ -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:
"""
Класс для представления медиафайла.

View File

@ -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,

View File

@ -1,5 +1,5 @@
from __future__ import annotations
from typing import Optional, TYPE_CHECKING
from typing import Optional
from .update import Update

View File

@ -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

View File

@ -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