Skip to content

Commit

Permalink
🔖 bump version 1.5.2
Browse files Browse the repository at this point in the history
  • Loading branch information
yanyongyu authored Sep 28, 2024
1 parent f9ab06c commit 880ff0d
Show file tree
Hide file tree
Showing 15 changed files with 456 additions and 438 deletions.
4 changes: 2 additions & 2 deletions nonebot/adapters/qq/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from .event import *
from .permission import *
from .bot import Bot as Bot
from .utils import log as log
from .event import * # noqa: F403
from .utils import escape as escape
from .adapter import Adapter as Adapter
from .message import Message as Message
from .permission import * # noqa: F403
from .utils import unescape as unescape
from .exception import ActionFailed as ActionFailed
from .exception import NetworkError as NetworkError
Expand Down
12 changes: 6 additions & 6 deletions nonebot/adapters/qq/adapter.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import sys
import asyncio
from typing_extensions import override
from typing import Any, List, Tuple, Literal, Optional
from typing import Any, Literal, Optional

from nonebot.utils import escape_tag
from nonebot.exception import WebSocketClosed
Expand Down Expand Up @@ -46,7 +46,7 @@ def __init__(self, driver: Driver, **kwargs: Any):

self.qq_config: Config = Config(**self.config.dict())

self.tasks: List["asyncio.Task"] = []
self.tasks: list["asyncio.Task"] = []
self.setup()

@classmethod
Expand Down Expand Up @@ -137,7 +137,7 @@ async def run_bot(self, bot_info: BotInfo) -> None:
# wait for session start concurrency limit
await asyncio.sleep(gateway_info.session_start_limit.max_concurrency or 1)

async def _forward_ws(self, bot: Bot, ws_url: URL, shard: Tuple[int, int]) -> None:
async def _forward_ws(self, bot: Bot, ws_url: URL, shard: tuple[int, int]) -> None:
# ws setup request
request = Request(
"GET",
Expand Down Expand Up @@ -236,7 +236,7 @@ async def _hello(self, bot: Bot, ws: WebSocket) -> Optional[int]:
)

async def _authenticate(
self, bot: Bot, ws: WebSocket, shard: Tuple[int, int]
self, bot: Bot, ws: WebSocket, shard: tuple[int, int]
) -> Optional[Literal[True]]:
"""鉴权连接"""
if not bot.ready:
Expand Down Expand Up @@ -318,7 +318,7 @@ async def _authenticate(
)

if ready_event:
asyncio.create_task(bot.handle_event(ready_event))
asyncio.create_task(bot.handle_event(ready_event)) # noqa: RUF006

return True

Expand Down Expand Up @@ -354,7 +354,7 @@ async def _loop(self, bot: Bot, ws: WebSocket):
else:
if isinstance(event, MessageAuditEvent):
audit_result.add_result(event)
asyncio.create_task(bot.handle_event(event))
asyncio.create_task(bot.handle_event(event)) # noqa: RUF006
elif isinstance(payload, HeartbeatAck):
log("TRACE", "Heartbeat ACK")
continue
Expand Down
54 changes: 26 additions & 28 deletions nonebot/adapters/qq/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
IO,
TYPE_CHECKING,
Any,
Dict,
List,
Union,
Literal,
NoReturn,
Expand Down Expand Up @@ -111,7 +109,7 @@ async def _check_reply(
if event.reply.author.id == bot.self_info.id:
event.to_me = True
except Exception as e:
log("WARNING", f"Error when getting message reply info: {repr(e)}", e)
log("WARNING", f"Error when getting message reply info: {e!r}", e)


def _check_at_me(
Expand Down Expand Up @@ -265,7 +263,7 @@ async def _get_authorization_header(self) -> str:
return f"QQBot {await self.get_access_token()}"
return f"Bot {self.bot_info.id}.{self.bot_info.token}"

async def get_authorization_header(self) -> Dict[str, str]:
async def get_authorization_header(self) -> dict[str, str]:
"""获取当前 Bot 的鉴权信息"""
headers = {"Authorization": await self._get_authorization_header()}
if self.bot_info.is_group_bot:
Expand All @@ -285,7 +283,7 @@ def _prepare_message(message: Union[str, Message, MessageSegment]) -> Message:
return _message

@staticmethod
def _extract_send_message(message: Message) -> Dict[str, Any]:
def _extract_send_message(message: Message) -> dict[str, Any]:
kwargs = {}
content = message.extract_content() or None
kwargs["content"] = content
Expand All @@ -302,7 +300,7 @@ def _extract_send_message(message: Message) -> Dict[str, Any]:
return kwargs

@staticmethod
def _extract_guild_image(message: Message) -> Dict[str, Any]:
def _extract_guild_image(message: Message) -> dict[str, Any]:
kwargs = {}
if image := (message["image"] or None):
kwargs["image"] = image[-1].data["url"]
Expand All @@ -311,7 +309,7 @@ def _extract_guild_image(message: Message) -> Dict[str, Any]:
return kwargs

@staticmethod
def _extract_qq_media(message: Message) -> Dict[str, Any]:
def _extract_qq_media(message: Message) -> dict[str, Any]:
kwargs = {}
if image := message["image"]:
kwargs["file_type"] = 1
Expand Down Expand Up @@ -607,13 +605,13 @@ async def guilds(
before: Optional[str] = None,
after: Optional[str] = None,
limit: Optional[float] = None,
) -> List[Guild]:
) -> list[Guild]:
request = Request(
"GET",
self.adapter.get_api_base().joinpath("users", "@me", "guilds"),
params=exclude_none({"before": before, "after": after, "limit": limit}),
)
return type_validate_python(List[Guild], await self._request(request))
return type_validate_python(list[Guild], await self._request(request))

# Guild API
@API
Expand All @@ -626,12 +624,12 @@ async def get_guild(self, *, guild_id: str) -> Guild:

# Channel API
@API
async def get_channels(self, *, guild_id: str) -> List[Channel]:
async def get_channels(self, *, guild_id: str) -> list[Channel]:
request = Request(
"GET",
self.adapter.get_api_base().joinpath("guilds", guild_id, "channels"),
)
return type_validate_python(List[Channel], await self._request(request))
return type_validate_python(list[Channel], await self._request(request))

@API
async def get_channel(self, *, channel_id: str) -> Channel:
Expand All @@ -652,10 +650,10 @@ async def post_channels(
position: Optional[int] = None,
parent_id: Optional[int] = None,
private_type: Optional[Union[PrivateType, int]] = None,
private_user_ids: Optional[List[str]] = None,
private_user_ids: Optional[list[str]] = None,
speak_permission: Optional[Union[SpeakPermission, int]] = None,
application_id: Optional[str] = None,
) -> List[Channel]:
) -> list[Channel]:
request = Request(
"POST",
self.adapter.get_api_base().joinpath("guilds", guild_id, "channels"),
Expand All @@ -673,7 +671,7 @@ async def post_channels(
}
),
)
return type_validate_python(List[Channel], await self._request(request))
return type_validate_python(list[Channel], await self._request(request))

@API
async def patch_channel(
Expand Down Expand Up @@ -723,13 +721,13 @@ async def get_members(
guild_id: str,
after: Optional[str] = None,
limit: Optional[float] = None,
) -> List[Member]:
) -> list[Member]:
request = Request(
"GET",
self.adapter.get_api_base().joinpath("guilds", guild_id, "members"),
params=exclude_none({"after": after, "limit": limit}),
)
return type_validate_python(List[Member], await self._request(request))
return type_validate_python(list[Member], await self._request(request))

@API
async def get_role_members(
Expand Down Expand Up @@ -958,16 +956,16 @@ async def get_message_of_id(
return type_validate_python(GuildMessage, result)

@staticmethod
def _parse_send_message(data: Dict[str, Any]) -> Dict[str, Any]:
def _parse_send_message(data: dict[str, Any]) -> dict[str, Any]:
data = exclude_none(data)
data = {
k: v.dict(exclude_none=True) if isinstance(v, BaseModel) else v
for k, v in data.items()
}
if file_image := data.pop("file_image", None):
# 使用 multipart/form-data
multipart_files: Dict[str, Any] = {"file_image": ("file_image", file_image)}
multipart_data: Dict[str, Any] = {}
multipart_files: dict[str, Any] = {"file_image": ("file_image", file_image)}
multipart_data: dict[str, Any] = {}
for k, v in data.items():
if isinstance(v, (dict, list)):
# 当字段类型为对象或数组时需要将字段序列化为 JSON 字符串后进行调用
Expand Down Expand Up @@ -1172,10 +1170,10 @@ async def patch_guild_mute_multi_member(
self,
*,
guild_id: str,
user_ids: List[str],
user_ids: list[str],
mute_end_timestamp: Optional[Union[int, datetime]] = None,
mute_seconds: Optional[Union[int, timedelta]] = None,
) -> List[int]:
) -> list[int]:
if isinstance(mute_end_timestamp, datetime):
mute_end_timestamp = int(mute_end_timestamp.timestamp())

Expand All @@ -1193,7 +1191,7 @@ async def patch_guild_mute_multi_member(
}
),
)
return type_validate_python(List[int], await self._request(request))
return type_validate_python(list[int], await self._request(request))

# Announce API
@API
Expand All @@ -1204,7 +1202,7 @@ async def post_guild_announces(
message_id: Optional[str] = None,
channel_id: Optional[str] = None,
announces_type: Optional[int] = None,
recommend_channels: Optional[List[RecommendChannel]] = None,
recommend_channels: Optional[list[RecommendChannel]] = None,
) -> None:
request = Request(
"POST",
Expand Down Expand Up @@ -1269,7 +1267,7 @@ async def get_pins_message(self, *, channel_id: str) -> PinsMessage:
@API
async def get_schedules(
self, *, channel_id: str, since: Optional[Union[int, datetime]] = None
) -> List[Schedule]:
) -> list[Schedule]:
if isinstance(since, datetime):
since = int(since.timestamp() * 1000)

Expand All @@ -1278,7 +1276,7 @@ async def get_schedules(
self.adapter.get_api_base() / f"channels/{channel_id}/schedules",
json=exclude_none({"since": since}),
)
return type_validate_python(List[Schedule], await self._request(request))
return type_validate_python(list[Schedule], await self._request(request))

@API
async def get_schedule(self, *, channel_id: str, schedule_id: str) -> Schedule:
Expand Down Expand Up @@ -1460,7 +1458,7 @@ async def audio_control(
audio_url: Optional[str] = None,
text: Optional[str] = None,
status: Union[AudioStatus, int],
) -> Dict[Never, Never]:
) -> dict[Never, Never]:
request = Request(
"POST",
self.adapter.get_api_base().joinpath("channels", channel_id, "audio"),
Expand All @@ -1471,15 +1469,15 @@ async def audio_control(
return await self._request(request)

@API
async def put_mic(self, *, channel_id: str) -> Dict[Never, Never]:
async def put_mic(self, *, channel_id: str) -> dict[Never, Never]:
request = Request(
"PUT",
self.adapter.get_api_base().joinpath("channels", channel_id, "mic"),
)
return await self._request(request)

@API
async def delete_mic(self, *, channel_id: str) -> Dict[Never, Never]:
async def delete_mic(self, *, channel_id: str) -> dict[Never, Never]:
request = Request(
"DELETE",
self.adapter.get_api_base().joinpath("channels", channel_id, "mic"),
Expand Down
6 changes: 3 additions & 3 deletions nonebot/adapters/qq/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List, Tuple, Optional
from typing import Optional

from pydantic import Field, HttpUrl, BaseModel
from nonebot.compat import PYDANTIC_V2, ConfigDict
Expand Down Expand Up @@ -53,7 +53,7 @@ class BotInfo(BaseModel):
id: str = Field(alias="id")
token: str = Field(alias="token")
secret: str = Field(alias="secret")
shard: Optional[Tuple[int, int]] = None
shard: Optional[tuple[int, int]] = None
intent: Intents = Field(default_factory=Intents)

@property
Expand All @@ -67,4 +67,4 @@ class Config(BaseModel):
qq_api_base: HttpUrl = Field("https://api.sgroup.qq.com/")
qq_sandbox_api_base: HttpUrl = Field("https://sandbox.api.sgroup.qq.com")
qq_auth_base: HttpUrl = Field("https://bots.qq.com/app/getAppAccessToken")
qq_bots: List[BotInfo] = Field(default_factory=list)
qq_bots: list[BotInfo] = Field(default_factory=list)
8 changes: 4 additions & 4 deletions nonebot/adapters/qq/event.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from enum import Enum
from datetime import datetime
from typing_extensions import override
from typing import Dict, Type, Tuple, TypeVar, Optional, cast
from typing import TypeVar, Optional, cast

from nonebot.utils import escape_tag

Expand Down Expand Up @@ -145,10 +145,10 @@ def is_tome(self) -> bool:
return False


EVENT_CLASSES: Dict[str, Type[Event]] = {}
EVENT_CLASSES: dict[str, type[Event]] = {}


def register_event_class(event_class: Type[E]) -> Type[E]:
def register_event_class(event_class: type[E]) -> type[E]:
EVENT_CLASSES[event_class.__type__.value] = event_class
return event_class

Expand All @@ -166,7 +166,7 @@ class ReadyEvent(MetaEvent):
version: int
session_id: str
user: User
shard: Tuple[int, int]
shard: tuple[int, int]


@register_event_class
Expand Down
18 changes: 5 additions & 13 deletions nonebot/adapters/qq/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,9 @@
from io import BytesIO
from pathlib import Path
from dataclasses import dataclass
from collections.abc import Iterable
from typing_extensions import Self, override
from typing import (
TYPE_CHECKING,
Dict,
Type,
Union,
Iterable,
Optional,
TypedDict,
overload,
)
from typing import TYPE_CHECKING, Union, Optional, TypedDict, overload

from nonebot.compat import type_validate_python

Expand All @@ -35,7 +27,7 @@
class MessageSegment(BaseMessageSegment["Message"]):
@classmethod
@override
def get_message_class(cls) -> Type["Message"]:
def get_message_class(cls) -> type["Message"]:
return Message

@staticmethod
Expand Down Expand Up @@ -432,7 +424,7 @@ def _validate(cls, value) -> Self:
return instance


SEGMENT_TYPE_MAP: Dict[str, Type[MessageSegment]] = {
SEGMENT_TYPE_MAP: dict[str, type[MessageSegment]] = {
"text": Text,
"emoji": Emoji,
"mention_user": MentionUser,
Expand All @@ -457,7 +449,7 @@ def _validate(cls, value) -> Self:
class Message(BaseMessage[MessageSegment]):
@classmethod
@override
def get_segment_class(cls) -> Type[MessageSegment]:
def get_segment_class(cls) -> type[MessageSegment]:
return MessageSegment

@override
Expand Down
6 changes: 3 additions & 3 deletions nonebot/adapters/qq/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .qq import *
from .guild import *
from .common import *
from .qq import * # noqa: F403
from .guild import * # noqa: F403
from .common import * # noqa: F403
from .payload import Hello as Hello
from .payload import Opcode as Opcode
from .payload import Resume as Resume
Expand Down
Loading

0 comments on commit 880ff0d

Please sign in to comment.