Skip to content

Commit

Permalink
[OneBot] Improve source related features
Browse files Browse the repository at this point in the history
  • Loading branch information
aicorein committed Dec 10, 2024
1 parent 0defb1b commit 88eeb85
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 24 deletions.
4 changes: 2 additions & 2 deletions src/melobot/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ class BotError(BotException):
"""melobot bot 异常"""


class IOError(BotException):
"""melobot 输入输出源异常"""
class SourceError(BotException):
"""melobot 源异常"""


class PluginError(BotException):
Expand Down
8 changes: 4 additions & 4 deletions src/melobot/io/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@
from ..utils import get_id


@dataclass(frozen=True)
@dataclass
class _Packet:
time: float = field(default_factory=lambda: time.time_ns() / 1e9)
id: str = field(default_factory=get_id)
protocol: LiteralString | None = None
data: Any = None


@dataclass(frozen=True)
@dataclass
class InPacket(_Packet):
"""输入包基类(数据类)
Expand All @@ -30,7 +30,7 @@ class InPacket(_Packet):
"""


@dataclass(frozen=True)
@dataclass
class OutPacket(_Packet):
"""输出包基类(数据类)
Expand All @@ -41,7 +41,7 @@ class OutPacket(_Packet):
"""


@dataclass(frozen=True)
@dataclass
class EchoPacket(_Packet):
"""回应包基类(数据类)
Expand Down
2 changes: 1 addition & 1 deletion src/melobot/protocols/onebot/v11/io/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class BaseIO(AbstractIOSource[InPacket, OutPacket, EchoPacket]):
# pylint: disable=duplicate-code
def __init__(self, cd_time: float) -> None:
super().__init__(PROTOCOL_IDENTIFIER)
self.cd_time = cd_time
self.cd_time = cd_time if cd_time > 0 else 0.01

@property
def logger(self) -> GenericLogger:
Expand Down
21 changes: 9 additions & 12 deletions src/melobot/protocols/onebot/v11/io/forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from websockets.asyncio.client import ClientConnection
from websockets.exceptions import ConnectionClosed

from melobot.exceptions import IOError
from melobot.exceptions import SourceError
from melobot.io import SourceLifeSpan
from melobot.log import LogLevel

Expand All @@ -31,7 +31,7 @@ def __init__(
self.conn: ClientConnection
self.access_token = access_token
self.max_retry: int = max_retry
self.retry_delay: float = retry_delay if retry_delay > 0 else 0
self.retry_delay: float = retry_delay if retry_delay > 0 else 0.5

self._in_buf: asyncio.Queue[InPacket] = asyncio.Queue()
self._out_buf: asyncio.Queue[OutPacket] = asyncio.Queue()
Expand Down Expand Up @@ -124,18 +124,11 @@ async def open(self) -> None:
headers = {"Authorization": f"Bearer {self.access_token}"}

retry_iter = count(0) if self.max_retry < 0 else range(self.max_retry + 1)
first_try, ok_flag = True, False
for _ in retry_iter: # type: ignore[union-attr]
if first_try:
first_try = False
else:
await asyncio.sleep(self.retry_delay)

for _ in retry_iter:
try:
self.conn = await websockets.connect(
self.url, additional_headers=headers
)
ok_flag = True
break

except BaseException as e:
Expand All @@ -145,8 +138,12 @@ async def open(self) -> None:
if "403" in str(e):
self.logger.warning("403 错误可能是 access_token 未配置或无效")

if not ok_flag:
raise IOError("重试已达最大次数,已放弃建立连接")
await asyncio.sleep(self.retry_delay)

else:
raise SourceError(
"OneBot v11 正向 WebSocket IO 源重试已达最大次数,已放弃建立连接"
)

self._tasks.append(asyncio.create_task(self._input_loop()))
self._tasks.append(asyncio.create_task(self._output_loop()))
Expand Down
10 changes: 5 additions & 5 deletions src/melobot/protocols/onebot/v11/io/packet.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
from dataclasses import dataclass, field

from melobot.io import EchoPacket as RootEchoPak
from melobot.io import InPacket as RootInPack
from melobot.io import InPacket as RootInPak
from melobot.io import OutPacket as RootOutPak

from ..const import PROTOCOL_IDENTIFIER


@dataclass(frozen=True, kw_only=True)
class InPacket(RootInPack):
@dataclass(kw_only=True)
class InPacket(RootInPak):
data: dict
protocol: str = PROTOCOL_IDENTIFIER


@dataclass(frozen=True, kw_only=True)
@dataclass(kw_only=True)
class OutPacket(RootOutPak):
data: str
action_type: str
Expand All @@ -22,7 +22,7 @@ class OutPacket(RootOutPak):
protocol: str = PROTOCOL_IDENTIFIER


@dataclass(frozen=True, kw_only=True)
@dataclass(kw_only=True)
class EchoPacket(RootEchoPak):
action_type: str = ""
data: dict = field(default_factory=dict)
Expand Down

0 comments on commit 88eeb85

Please sign in to comment.