Skip to content

Commit

Permalink
🚨 make linters happy
Browse files Browse the repository at this point in the history
  • Loading branch information
j1g5awi committed Aug 5, 2024
1 parent bd7dd3c commit 601600a
Show file tree
Hide file tree
Showing 11 changed files with 248 additions and 533 deletions.
1 change: 1 addition & 0 deletions .envrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
source .venv/bin/activate
11 changes: 6 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ ci:
autoupdate_schedule: monthly
autoupdate_commit_msg: ":arrow_up: auto update by pre-commit hooks"
repos:
- repo: https://github.com/hadialqattan/pycln
rev: v2.4.0
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.5.0
hooks:
- id: pycln
args: [--config, pyproject.toml]
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
stages: [commit]

- repo: https://github.com/pycqa/isort
rev: 5.13.2
Expand All @@ -28,4 +29,4 @@ repos:
rev: v0.1.4
hooks:
- id: nonemoji
stages: [prepare-commit-msg]
stages: [prepare-commit-msg]
7 changes: 6 additions & 1 deletion example/sendxxx.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
from nonebot import on_command
from nonebot.adapters.telegram import Bot
from nonebot.adapters.telegram.event import MessageEvent
from nonebot.adapters.telegram.message import Message, MessageSegment
from nonebot.adapters.telegram.message import Entity, MessageSegment


@on_command("test_emoji").handle()
async def _(bot: Bot, event: MessageEvent):
await bot.send(event, "🧑‍💻" + Entity.bold("🧑‍💻") + "🧑‍💻")


@on_command("location").handle()
Expand Down
13 changes: 6 additions & 7 deletions nonebot/adapters/telegram/adapter.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import json
import asyncio
from collections.abc import Iterable
from typing_extensions import override
from typing import Any, Union, Iterable, Optional, cast
from typing import Any, Union, Optional, cast

import anyio
from pydantic.main import BaseModel
Expand Down Expand Up @@ -89,10 +90,8 @@ async def poll(self, bot: Bot):
if update_offset is not None:
for update in updates:
update_offset = update.update_id + 1
asyncio.create_task(
self.__handle_update(
bot, update.model_dump(by_alias=True, exclude_none=True)
)
await self.__handle_update(
bot, update.model_dump(by_alias=True, exclude_none=True)
)
elif updates:
update_offset = updates[0].update_id
Expand All @@ -118,7 +117,7 @@ async def handle_http(self, request: Request) -> Response:
if bot.secret_token == token:
if request.content:
update: dict = json.loads(request.content)
asyncio.create_task(self.__handle_update(bot, update))
await self.__handle_update(bot, update)
return Response(204)
return Response(401)

Expand Down Expand Up @@ -247,5 +246,5 @@ async def process_input_file(file: Union[InputFile, str]) -> Optional[str]:
if response.status_code == 404:
raise ApiNotAvailable
raise NetworkError(
f"HTTP request received unexpected {response.status_code} {response.content}",
f"Received unexpected {response.status_code} {response.content}"
)
1 change: 0 additions & 1 deletion nonebot/adapters/telegram/api.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from typing import Union, Literal, Optional

from .model import (
Chat,
File,
Poll,
User,
Expand Down
3 changes: 2 additions & 1 deletion nonebot/adapters/telegram/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ async def send_to(
**kwargs,
):
"""
由于 Telegram 对于不同类型的消息有不同的 API,如果需要使用同一方法发送不同类型的消息请使用此方法。
由于 Telegram 对于不同类型的消息有不同的 API,
如果需要使用同一方法发送不同类型的消息请使用此方法。
- `File` 或 `Entity` 可随意组合
- 非 `File` 非 `Entity` 的 `MessageSegment` 无法组合
Expand Down
57 changes: 45 additions & 12 deletions nonebot/adapters/telegram/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def _parse_event(cls, obj: dict, failed: set = set()) -> "Event":
if subclass not in failed:
try:
return subclass.parse_event(obj)
except:
except Exception:
pass
return cls.model_validate(obj)

Expand Down Expand Up @@ -183,7 +183,10 @@ def is_tome(self) -> bool:

@override
def get_event_description(self) -> str:
return f"Message {self.message_id} @[Chat {self.chat.id}]: {self.get_message_description()}"
return (
f"Message {self.message_id} @[Chat {self.chat.id}]: "
+ self.get_message_description()
)


class PrivateMessageEvent(MessageEvent):
Expand All @@ -207,7 +210,10 @@ def is_tome(self) -> bool:

@override
def get_event_description(self) -> str:
return f"Message {self.message_id} from {self.from_.id}: {self.get_message_description()}"
return (
f"Message {self.message_id} from {self.from_.id}: "
+ self.get_message_description()
)


class GroupMessageEvent(MessageEvent):
Expand Down Expand Up @@ -237,7 +243,10 @@ def get_session_id(self) -> str:

@override
def get_event_description(self) -> str:
return f"Message {self.message_id} from {self.from_.id}@[Chat {self.chat.id}]: {self.get_message_description()}"
return (
f"Message {self.message_id} from {self.from_.id}@[Chat {self.chat.id}]: "
+ self.get_message_description()
)


class ForumTopicMessageEvent(GroupMessageEvent):
Expand All @@ -253,7 +262,10 @@ def get_session_id(self) -> str:

@override
def get_event_description(self) -> str:
return f"Message {self.message_id} from {self.from_.id}@[Chat {self.chat.id} Thread {self.message_thread_id}]: {self.get_message_description()}"
return (
f"Message {self.message_id} from {self.from_.id}@[Chat {self.chat.id} "
f"Thread {self.message_thread_id}]: {self.get_message_description()}"
)


class ChannelPostEvent(MessageEvent):
Expand Down Expand Up @@ -315,7 +327,10 @@ def get_plaintext(self) -> str:

@override
def get_event_description(self) -> str:
return f"EditedMessage {self.message_id} @[Chat {self.chat.id}]: {self.get_message_description()}"
return (
f"EditedMessage {self.message_id} @[Chat {self.chat.id}]: "
+ self.get_message_description()
)


class PrivateEditedMessageEvent(EditedMessageEvent):
Expand All @@ -340,7 +355,10 @@ def is_tome(self) -> bool:

@override
def get_event_description(self) -> str:
return f"EditedMessage {self.message_id} from {self.from_.id}: {self.get_message_description()}"
return (
f"EditedMessage {self.message_id} from {self.from_.id}: "
+ self.get_message_description()
)


class GroupEditedMessageEvent(EditedMessageEvent):
Expand Down Expand Up @@ -370,7 +388,10 @@ def get_session_id(self) -> str:

@override
def get_event_description(self) -> str:
return f"EditedMessage {self.message_id} from {self.from_.id}@[Chat {self.chat.id}]: {self.get_message_description()}"
return (
f"EditedMessage {self.message_id} from {self.from_.id}"
f"@[Chat {self.chat.id}]: {self.get_message_description()}"
)


class ForumTopicEditedMessageEvent(GroupEditedMessageEvent):
Expand All @@ -386,7 +407,10 @@ def get_session_id(self) -> str:

@override
def get_event_description(self) -> str:
return f"EditedMessage {self.message_id} from {self.from_.id}@[Chat {self.chat.id} Thread {self.message_thread_id}]: {self.get_message_description()}"
return (
f"EditedMessage {self.message_id} from {self.from_.id}@[Chat {self.chat.id}"
f" Thread {self.message_thread_id}]: {self.get_message_description()}"
)


class EditedChannelPostEvent(EditedMessageEvent):
Expand Down Expand Up @@ -465,7 +489,10 @@ def get_message(self) -> Message:

@override
def get_event_description(self) -> str:
return f"PinnedMessage {self.pinned_message.message_id} @[Chat {self.pinned_message.chat.id}]: {self.get_message_description()}"
return (
f"PinnedMessage {self.pinned_message.message_id} "
f"@[Chat {self.pinned_message.chat.id}]: {self.get_message_description()}"
)


class NewChatMemberEvent(NoticeEvent):
Expand Down Expand Up @@ -658,7 +685,10 @@ def is_tome(self) -> bool:

@override
def get_event_description(self) -> str:
return f"InlineQuery {self.id} from {self.from_.id}: {self.get_message_description()}"
return (
f"InlineQuery {self.id} from {self.from_.id}: "
+ self.get_message_description()
)


class ChosenInlineResultEvent(InlineEvent, ChosenInlineResult):
Expand All @@ -668,7 +698,10 @@ def get_event_name(self) -> str:

@override
def get_event_description(self) -> str:
return f"ChosenInlineResult {self.result_id} from {self.from_.id} for Query {self.query}"
return (
f"ChosenInlineResult {self.result_id} from {self.from_.id} "
+ f"for Query {self.query}"
)


class CallbackQueryEvent(InlineEvent, CallbackQuery):
Expand Down
13 changes: 9 additions & 4 deletions nonebot/adapters/telegram/message.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections.abc import Iterable
from typing_extensions import override
from typing import Any, Union, Literal, TypeVar, Iterable, Optional
from typing import Any, Union, Literal, TypeVar, Optional

from nonebot.adapters import Message as BaseMessage
from nonebot.adapters import MessageSegment as BaseMessageSegment
Expand Down Expand Up @@ -30,7 +31,11 @@ def __repr__(self) -> str:
return self.data.get("text", "")
params = ", ".join(
[
f"{k}={f'<file {v[0]}>' if isinstance(v, tuple) else ('<bytes>' if isinstance(v, bytes) else v)}"
(
f"{k}=" + f"<file {v[0]}>"
if isinstance(v, tuple)
else ("<bytes>" if isinstance(v, bytes) else v)
)
for k, v in self.data.items()
if v is not None
]
Expand Down Expand Up @@ -328,7 +333,7 @@ def build_telegram_entities(entities: list["Entity"]) -> list[MessageEntity]:
[
MessageEntity(
type=entity.type, # type: ignore
offset=sum(map(lambda _: _._length, entities[:i])),
offset=sum(_._length for _ in entities[:i]),
length=entity._length,
url=entity.data.get("url"),
user=entity.data.get("user"),
Expand Down Expand Up @@ -433,7 +438,7 @@ def model_validate(cls, obj: dict[str, Any]) -> "Message":
else ("caption", "caption_entities")
)
msg.extend(
Entity.from_telegram_entities(obj[key], obj.get(entities_key, ()))
Entity.from_telegram_entities(obj[key], obj.get(entities_key, []))
)
del obj[key]
obj.pop(entities_key, None)
Expand Down
Loading

0 comments on commit 601600a

Please sign in to comment.