Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[bug] 无法建立 Websocket 连接 #18

Closed
Autuamn opened this issue Mar 10, 2024 · 14 comments
Closed

[bug] 无法建立 Websocket 连接 #18

Autuamn opened this issue Mar 10, 2024 · 14 comments

Comments

@Autuamn
Copy link
Contributor

Autuamn commented Mar 10, 2024

版本

  • nonebot2 2.2.1
  • nonebot-adapter-discord 0.1.4
  • pydantic 2.6.3
  • pydantic_core 2.16.3

log

ubuntu@ip-114-514-1919-810:~/test$ nb run
Using python: /home/ubuntu/test/.venv/bin/python
/home/ubuntu/test/.venv/lib/python3.10/site-packages/pydantic/_migration.py:283: UserWarning: `pydantic.generics:GenericModel` has been moved to `pydantic.BaseModel`.
  warnings.warn(f'`{import_path}` has been moved to `{new_location}`.')
03-09 15:15:12 [SUCCESS] nonebot | NoneBot is initializing...
03-09 15:15:13 [INFO] nonebot | Current Env: prod
03-09 15:15:13 [DEBUG] nonebot | Loaded Config: {'driver': '~aiohttp', 'host': IPv4Address('127.0.0.1'), 'port': 8080, 'log_level': 'TRACE', 'api_timeout': 30.0, 'superusers': set(), 'nickname': set(), 'command_start': {'/'}, 'command_sep': {'.'}, 'session_expire_timeout': datetime.timedelta(seconds=120), 'discord_bots': [{'token': 'xxx', 'intent': {'guild_messages': True, 'direct_messages': True}, 'application_commands': {'echo': ['*'], 'test': [123]}}]}
03-09 15:15:13 [TRACE] nonebot | Detected driver <class 'abc.CombinedDriver'> with no mixins.
03-09 15:15:13 [DEBUG] nonebot | Succeeded to load adapter "Discord"
03-09 15:15:13 [SUCCESS] nonebot | Running NoneBot...
03-09 15:15:13 [DEBUG] nonebot | Loaded adapters: Discord
03-09 15:15:13 [INFO] nonebot | Discord | Discord Adapter is starting up...
03-09 15:15:13 [DEBUG] nonebot | Discord | Discord api base url: https://discord.com/api/v10
03-09 15:15:13 [INFO] nonebot | Application startup completed.
03-09 15:15:13 [DEBUG] nonebot | Discord | Forwarding WebSocket Connection to wss://gateway.discord.gg...
03-09 15:15:13 [DEBUG] nonebot | Discord | WebSocket Connection to wss://gateway.discord.gg established
03-09 15:15:13 [DEBUG] nonebot | Discord | Received hello: opcode=<Opcode.HELLO: 10> data=Hello(heartbeat_interval=41250) t=None s=None
03-09 15:15:13 [DEBUG] nonebot | Discord | Waiting for first heartbeat to be send...
03-09 15:15:18 [TRACE] nonebot | Discord | Heartbeat
03-09 15:16:08 [ERROR] nonebot | Discord | WebSocket Closed
Traceback (most recent call last):
  File "<string>", line 15, in <module>
  File "/home/ubuntu/test/.venv/lib/python3.10/site-packages/nonebot/__init__.py", line 334, in run
    get_driver().run(*args, **kwargs)
  File "/home/ubuntu/test/.venv/lib/python3.10/site-packages/nonebot/drivers/none.py", line 56, in run
    loop.run_until_complete(self._serve())
  File "/usr/lib/python3.10/asyncio/base_events.py", line 636, in run_until_complete
    self.run_forever()
  File "/usr/lib/python3.10/asyncio/base_events.py", line 603, in run_forever
    self._run_once()
  File "/usr/lib/python3.10/asyncio/base_events.py", line 1909, in _run_once
    handle._run()
  File "/usr/lib/python3.10/asyncio/events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
> File "/home/ubuntu/test/.venv/lib/python3.10/site-packages/nonebot/adapters/discord/adapter.py", line 199, in _forward_ws
    await self._heartbeat_ack(ws)
  File "/home/ubuntu/test/.venv/lib/python3.10/site-packages/nonebot/adapters/discord/adapter.py", line 269, in _heartbeat_ack
    payload = await self.receive_payload(ws)
  File "/home/ubuntu/test/.venv/lib/python3.10/site-packages/nonebot/adapters/discord/adapter.py", line 430, in receive_payload
    data = await ws.receive()
  File "/home/ubuntu/test/.venv/lib/python3.10/site-packages/nonebot/drivers/aiohttp.py", line 146, in receive
    msg = await self._receive()
  File "/home/ubuntu/test/.venv/lib/python3.10/site-packages/nonebot/drivers/aiohttp.py", line 141, in _receive
    raise WebSocketClosed(self.websocket.close_code or 1006)
nonebot.exception.WebSocketClosed: WebSocketClosed(code=1000)
03-09 15:16:08 [ERROR] nonebot | Discord | Error while setup websocket to wss://gateway.discord.gg. Trying to reconnect...
Traceback (most recent call last):
  File "<string>", line 15, in <module>
  File "/home/ubuntu/test/.venv/lib/python3.10/site-packages/nonebot/__init__.py", line 334, in run
    get_driver().run(*args, **kwargs)
  File "/home/ubuntu/test/.venv/lib/python3.10/site-packages/nonebot/drivers/none.py", line 56, in run
    loop.run_until_complete(self._serve())
  File "/usr/lib/python3.10/asyncio/base_events.py", line 636, in run_until_complete
    self.run_forever()
  File "/usr/lib/python3.10/asyncio/base_events.py", line 603, in run_forever
    self._run_once()
  File "/usr/lib/python3.10/asyncio/base_events.py", line 1909, in _run_once
    handle._run()
  File "/usr/lib/python3.10/asyncio/events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
> File "/home/ubuntu/test/.venv/lib/python3.10/site-packages/nonebot/adapters/discord/adapter.py", line 232, in _forward_ws
    self.bot_disconnect(bot)
  File "/home/ubuntu/test/.venv/lib/python3.10/site-packages/nonebot/internal/adapter/adapter.py", line 72, in bot_disconnect
    raise RuntimeError(f"{bot} not found in adapter {self.get_name()}")
RuntimeError: Bot(type='Discord', self_id='123') not found in adapter Discord

详细描述

log来源一台在美西的aws服务器,不可能是网络问题


在此处

payload = type_validate_python(
Heartbeat,
{"data": bot.sequence if bot.has_sequence else None},
)
with contextlib.suppress(Exception):
await ws.send(json.dumps(model_dump(payload)))

如果单独运行

model_dump(payload)

就会报

>>> model_dump(payload)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".venv\Lib\site-packages\nonebot\compat.py", line 204, in model_dump
    return model.model_dump(
           ^^^^^^^^^^^^^^^^^
TypeError: Payload.model_dump() got an unexpected keyword argument 'by_alias'
@CMHopeSunshine
Copy link
Member

尝试用httpx+websockets的驱动器组合

@Autuamn Autuamn changed the title [but] 无法建立 Websocket 连接 [bug] 无法建立 Websocket 连接 Mar 10, 2024
@Autuamn
Copy link
Contributor Author

Autuamn commented Mar 10, 2024

改用 httpx+websockets 后卡在 Waiting for first heartbeat to be send... 很久不动


ubuntu@ip-114-514-1919-810:~/test$ nb run
Using python: /home/ubuntu/test/.venv/bin/python
/home/ubuntu/test/.venv/lib/python3.10/site-packages/pydantic/_migration.py:283: UserWarning: `pydantic.generics:GenericModel` has been moved to `pydantic.BaseModel`.
  warnings.warn(f'`{import_path}` has been moved to `{new_location}`.')
03-10 07:03:26 [SUCCESS] nonebot | NoneBot is initializing...
03-10 07:03:26 [INFO] nonebot | Current Env: prod
03-10 07:03:26 [DEBUG] nonebot | Loaded Config: {'driver': '~httpx+~websockets', 'host': IPv4Address('127.0.0.1'), 'port': 8080, 'log_level': 'TRACE', 'api_timeout': 30.0, 'superusers': set(), 'nickname': set(), 'command_start': {'/'}, 'command_sep': {'.'}, 'session_expire_timeout': datetime.timedelta(seconds=120), 'discord_bots': [{'token': 'xxx', 'intent': {'guild_messages': True, 'direct_messages': True}}]}
03-10 07:03:27 [TRACE] nonebot | Detected driver <class 'abc.CombinedDriver'> with mixins [<class 'nonebot.drivers.websockets.Mixin'>].
03-10 07:03:27 [DEBUG] nonebot | Succeeded to load adapter "Discord"
03-10 07:03:27 [SUCCESS] nonebot | Running NoneBot...
03-10 07:03:27 [DEBUG] nonebot | Loaded adapters: Discord
03-10 07:03:27 [INFO] nonebot | Discord | Discord Adapter is starting up...
03-10 07:03:27 [DEBUG] nonebot | Discord | Discord api base url: https://discord.com/api/v10
03-10 07:03:27 [INFO] nonebot | Application startup completed.
03-10 07:03:27 [DEBUG] nonebot | Discord | Forwarding WebSocket Connection to wss://gateway.discord.gg...
03-10 07:03:28 [DEBUG] nonebot | Discord | WebSocket Connection to wss://gateway.discord.gg established
03-10 07:03:28 [DEBUG] nonebot | Discord | Received hello: opcode=<Opcode.HELLO: 10> data=Hello(heartbeat_interval=41250) t=None s=None
03-10 07:03:28 [DEBUG] nonebot | Discord | Waiting for first heartbeat to be send...
03-10 07:03:33 [TRACE] nonebot | Discord | Heartbeat
^C03-10 07:46:09 [INFO] nonebot | Shutting down
03-10 07:46:09 [INFO] nonebot | Waiting for application shutdown.
03-10 07:46:09 [INFO] nonebot | Application shutdown complete.

@CMHopeSunshine
Copy link
Member

几十秒一般是正常的,由discord提供的建议等待时间

@Autuamn
Copy link
Contributor Author

Autuamn commented Mar 10, 2024

长达43分钟正常吗

@CMHopeSunshine
Copy link
Member

啊那不正常。bot_token填写正确了吗,我看提供的日志里token是xxx

@Autuamn
Copy link
Contributor Author

Autuamn commented Mar 10, 2024

token是对的,xxx是代指

@CMHopeSunshine
Copy link
Member

日志显示在给dc服务器发送心跳后,dc没有回应心跳并以1000代码正常关闭了ws连接。你方便在本地或者另一台服务器试试同样token吗

@Autuamn
Copy link
Contributor Author

Autuamn commented Mar 10, 2024

经过漫长的等待,有一个新的错误

换了一台服务器,位于国内,用 DISCORD_PROXY 设置代理一直连不上心跳,就直接用 proxychains4 代理了

这个错误在上一台服务器也出现过

[root@iZwz9j2r2wvt2zn42zbhkkZ test]# proxychains4 nb run
[28/1591][proxychains] config file found: /etc/proxychains.conf
[proxychains] preloading /usr/local/lib/libproxychains4.so
[proxychains] DLL init: proxychains-ng 4.16-git-15-g0c79508
Using python: /root/NoneBot/test/.venv/bin/python
[proxychains] DLL init: proxychains-ng 4.16-git-15-g0c79508
[proxychains] DLL init: proxychains-ng 4.16-git-15-g0c79508
[proxychains] DLL init: proxychains-ng 4.16-git-15-g0c79508
/root/NoneBot/test/.venv/lib/python3.12/site-packages/pydantic/_migration.py:283: UserWarning: `pydantic.generics:GenericModel` has been moved to `pydantic.BaseModel`.
  warnings.warn(f'`{import_path}` has been moved to `{new_location}`.')
03-10 18:23:57 [SUCCESS] nonebot | NoneBot is initializing...
03-10 18:23:57 [INFO] nonebot | Current Env: prod
03-10 18:23:57 [DEBUG] nonebot | Loaded Config: {'driver': '~httpx+~websockets', 'host': IPv4Address('127.0.0.1'), 'port': 8080, 'log_level': 'TRACE', 'api_timeout': 30.0, 'superusers': set(), 'nickname': set(), 'command_start': {'/'}, 'command_sep': {'.'}, 'session_expire_timeout': datetime.timedelta(seconds=120), 'discord_bots': [{'token': 'MTIxNjI5OTcwMDIxOTY3ODc2Mg.GfmWBJ.jYSBbwZ-krQPaD2xGctglP55CAaWCAcYR6hWTQ', 'intent': {'guild_messages': True, 'direct_messages': True}}]}
03-10 18:23:57 [TRACE] nonebot | Detected driver <class 'abc.CombinedDriver'> with mixins [<class 'nonebot.drivers.websockets.Mixin'>].
03-10 18:23:57 [DEBUG] nonebot | Succeeded to load adapter "Discord"
03-10 18:23:57 [SUCCESS] nonebot | Running NoneBot...
03-10 18:23:57 [DEBUG] nonebot | Loaded adapters: Discord
03-10 18:23:57 [INFO] nonebot | Discord | Discord Adapter is starting up...
03-10 18:23:57 [DEBUG] nonebot | Discord | Discord api base url: https://discord.com/api/v10
03-10 18:23:57 [INFO] nonebot | Application startup completed.
[proxychains] Dynamic chain  ...  127.0.0.1:7891  ...  2a03:2880:f12d:83:face:b00c:0:25de:443  ...  OK
03-10 18:23:58 [DEBUG] nonebot | Discord | Forwarding WebSocket Connection to wss://gateway.discord.gg...
[proxychains] Dynamic chain  ...  127.0.0.1:7891  ...  2a03:2880:f12d:83:face:b00c:0:25de:443  ...  OK
[proxychains] Dynamic chain  ...  127.0.0.1:7891  ...  xxx.xxx.167.30:443  ...  OK
03-10 18:23:58 [DEBUG] nonebot | Discord | WebSocket Connection to wss://gateway.discord.gg established
03-10 18:23:58 [DEBUG] nonebot | Discord | Received hello: opcode=<Opcode.HELLO: 10> data=Hello(heartbeat_interval=41250) t=None s=None
03-10 18:23:58 [DEBUG] nonebot | Discord | Waiting for first heartbeat to be send...
03-10 18:24:03 [TRACE] nonebot | Discord | Heartbeat
03-10 20:44:54 [ERROR] nonebot | Discord | Error while sending Identify event
Traceback (most recent call last):
  File "<string>", line 15, in <module>
  File "/root/NoneBot/test/.venv/lib/python3.12/site-packages/nonebot/__init__.py", line 334, in run
    get_driver().run(*args, **kwargs)
  File "/root/NoneBot/test/.venv/lib/python3.12/site-packages/nonebot/drivers/none.py", line 56, in run
    loop.run_until_complete(self._serve())
  File "/usr/local/python3/lib/python3.12/asyncio/base_events.py", line 651, in run_until_complete
    self.run_forever()
  File "/usr/local/python3/lib/python3.12/asyncio/base_events.py", line 618, in run_forever
    self._run_once()
  File "/usr/local/python3/lib/python3.12/asyncio/base_events.py", line 1951, in _run_once
    handle._run()
  File "/usr/local/python3/lib/python3.12/asyncio/events.py", line 84, in _run
    self._context.run(self._callback, *self._args)
  File "/root/NoneBot/test/.venv/lib/python3.12/site-packages/nonebot/adapters/discord/adapter.py", line 207, in _forward_ws
    result = await self._authenticate(bot, ws, shard)
> File "/root/NoneBot/test/.venv/lib/python3.12/site-packages/nonebot/adapters/discord/adapter.py", line 322, in _authenticate
    await ws.send(json.dumps(model_dump(payload, exclude_none=True)))
  File "/root/NoneBot/test/.venv/lib/python3.12/site-packages/nonebot/compat.py", line 204, in model_dump
    return model.model_dump(
TypeError: Payload.model_dump() got an unexpected keyword argument 'by_alias'

用了 httpx+websockets 之后,我本地就一直出现 ConnectionRefusedError: [WinError 1225] 远程计算机拒绝网络连接。`,用的 clash for windows 的 http 代理

PS C:\Users\autua\Desktop\NoneBot\test> nb run
使用 Python: C:\Users\autua\Desktop\NoneBot\test\.venv\Scripts\python.exe
C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\pydantic\_migration.py:283: UserWarning: `pydantic.generics:GenericModel` has been moved to `pydantic.BaseModel`.
  warnings.warn(f'`{import_path}` has been moved to `{new_location}`.')
03-10 21:20:02 [SUCCESS] nonebot | NoneBot is initializing...
03-10 21:20:02 [INFO] nonebot | Current Env: prod
03-10 21:20:02 [DEBUG] nonebot | Loaded Config: {'driver': '~httpx+~websockets', 'host': IPv4Address('127.0.0.1'), 'port': 8080, 'log_level': 'TRACE', 'api_timeout': 30.0, 'superusers': set(), 'nickname': set(), 'command_start': {'/'}, 'command_sep': {'.'}, 'session_expire_timeout': datetime.timedelta(seconds=120), 'discord_bots': [{'token': 'MTIxNjI5OTcwMDIxOTY3ODc2Mg.GfmWBJ.jYSBbwZ-krQPaD2xGctglP55CAaWCAcYR6hWTQ', 'intent': {'guild_messages': True, 'direct_messages': True}}], 'discord_proxy': 'http://127.0.0.1:7890'}
03-10 21:20:02 [TRACE] nonebot | Detected driver <class 'abc.CombinedDriver'> with mixins [<class 'nonebot.drivers.websockets.Mixin'>].
03-10 21:20:02 [DEBUG] nonebot | Succeeded to load adapter "Discord"
03-10 21:20:02 [SUCCESS] nonebot | Running NoneBot...
03-10 21:20:02 [DEBUG] nonebot | Loaded adapters: Discord
03-10 21:20:02 [INFO] nonebot | Discord | Discord Adapter is starting up...
03-10 21:20:02 [DEBUG] nonebot | Discord | Discord api base url: https://discord.com/api/v10
03-10 21:20:02 [INFO] nonebot | Application startup completed.
03-10 21:20:03 [DEBUG] nonebot | Discord | Forwarding WebSocket Connection to wss://gateway.discord.gg...
03-10 21:20:06 [ERROR] nonebot | Discord | Error while setup websocket to wss://gateway.discord.gg. Trying to reconnect...
Traceback (most recent call last):
  File "C:\Users\autua\Desktop\NoneBot\test\bot.py", line 15, in <module>
    nonebot.run()
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\__init__.py", line 334, in run
    get_driver().run(*args, **kwargs)
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\drivers\none.py", line 56, in run
    loop.run_until_complete(self._serve())
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 651, in run_until_complete
    self.run_forever()
  File "C:\Program Files\Python312\Lib\asyncio\windows_events.py", line 321, in run_forever
    super().run_forever()
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 618, in run_forever
    self._run_once()
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 1951, in _run_once
    handle._run()
  File "C:\Program Files\Python312\Lib\asyncio\events.py", line 84, in _run
    self._context.run(self._callback, *self._args)
> File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\adapters\discord\adapter.py", line 179, in _forward_ws
    async with self.websocket(request) as ws:
  File "C:\Program Files\Python312\Lib\contextlib.py", line 204, in __aenter__
    return await anext(self.gen)
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\internal\adapter\adapter.py", line 98, in websocket
    async with self.driver.websocket(setup) as ws:
  File "C:\Program Files\Python312\Lib\contextlib.py", line 204, in __aenter__
    return await anext(self.gen)
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\drivers\websockets.py", line 74, in websocket
    async with connection as ws:
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\websockets\legacy\client.py", line 629, in __aenter__
    return await self
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\websockets\legacy\client.py", line 647, in __await_impl_timeout__
    return await self.__await_impl__()
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\websockets\legacy\client.py", line 651, in __await_impl__
    _transport, _protocol = await self._create_connection()
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 1099, in create_connection
    raise exceptions[0]
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 1081, in create_connection
    sock = await self._connect_sock(
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 984, in _connect_sock
    await self.sock_connect(sock, address)
  File "C:\Program Files\Python312\Lib\asyncio\proactor_events.py", line 727, in sock_connect
    return await self._proactor.connect(sock, address)
  File "C:\Program Files\Python312\Lib\asyncio\windows_events.py", line 798, in _poll
    value = callback(transferred, key, ov)
  File "C:\Program Files\Python312\Lib\asyncio\windows_events.py", line 594, in finish_connect
    ov.getresult()
ConnectionRefusedError: [WinError 1225] 远程计算机拒绝网络连接

@CMHopeSunshine
Copy link
Member

CMHopeSunshine commented Mar 11, 2024

TypeError: Payload.model_dump() got an unexpected keyword argument 'by_alias'

这个是nonebot2版本问题,升到最新2.2.1版才有这个参数

@Autuamn
Copy link
Contributor Author

Autuamn commented Mar 11, 2024

nonebot2用的就是2.2.1

@Autuamn
Copy link
Contributor Author

Autuamn commented Mar 11, 2024

class Payload(BaseModel):
if PYDANTIC_V2:
model_config = ConfigDict(extra="allow", populate_by_name=True)
def model_dump(
self,
*,
include: "IncEx" = None,
exclude: "IncEx" = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
) -> Dict[str, Any]:
return super().model_dump(
include=include,
exclude=exclude,
by_alias=True,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
)

是不是这里的问题

看日志是 Payload 类的 model_dump() 函数没有 by_alias 参数

@Autuamn
Copy link
Contributor Author

Autuamn commented Mar 24, 2024

一个新问题:
model_dump()没加 by_alias=True,导出的 payload 会是 {"opcode": 1, "data": null} 然后就

nonebot.exception.WebSocketClosed: WebSocketClosed(code=1006)

Log
(test) PS C:\Users\autua\Desktop\NoneBot\test> nb run
使用 Python: C:\Users\autua\Desktop\NoneBot\test\.venv\Scripts\python.exe
C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\pydantic\_migration.py:283: UserWarning: `pydantic.generics:GenericModel` has been moved to `pydantic.BaseModel`.
  warnings.warn(f'`{import_path}` has been moved to `{new_location}`.')
03-24 12:45:52 [SUCCESS] nonebot | NoneBot is initializing...
03-24 12:45:52 [INFO] nonebot | Current Env: prod
03-24 12:45:52 [DEBUG] nonebot | Loaded Config: {'driver': '~httpx+~aiohttp', 'host': IPv4Address('127.0.0.1'), 'port': 8080, 'log_level': 'TRACE', 'api_timeout': 30.0, 'superusers': set(), 'nickname': set(), 'command_start': {'/'}, 'command_sep': {'.'}, 'session_expire_timeout': datetime.timedelta(seconds=120), 'discord_bots': [{'token': 'xxx', 'intent': {'guild_messages': True, 'direct_messages': True}, 'application_commands': {'*': ['*']}}], 'discord_proxy': 'http://127.0.0.1:7890'}
03-24 12:45:52 [TRACE] nonebot | Detected driver <class 'abc.CombinedDriver'> with mixins [<class 'nonebot.drivers.aiohttp.Mixin'>].
03-24 12:45:52 [DEBUG] nonebot | Succeeded to load adapter "Discord"
03-24 12:45:52 [SUCCESS] nonebot | Running NoneBot...
03-24 12:45:52 [DEBUG] nonebot | Loaded adapters: Discord
03-24 12:45:52 [INFO] nonebot | Discord | Discord Adapter is starting up...
03-24 12:45:52 [DEBUG] nonebot | Discord | Discord api base url: https://discord.com/api/v10
03-24 12:45:52 [INFO] nonebot | Application startup completed.
03-24 12:45:53 [DEBUG] nonebot | Discord | Forwarding WebSocket Connection to wss://gateway.discord.gg...
03-24 12:45:54 [DEBUG] nonebot | Discord | WebSocket Connection to wss://gateway.discord.gg established
03-24 12:45:54 [DEBUG] nonebot | Discord | Received hello: opcode=<Opcode.HELLO: 10> data=Hello(heartbeat_interval=41250) t=None s=None
03-24 12:45:54 [DEBUG] nonebot | Discord | Waiting for first heartbeat to be send...
03-24 12:45:59 [TRACE] nonebot | Discord | Heartbeat
03-24 12:45:59 [TRACE] nonebot | Discord | Heartbeat Send: {"opcode": 1, "data": null}
03-24 12:45:59 [ERROR] nonebot | Discord | WebSocket Closed
Traceback (most recent call last):
  File "<string>", line 15, in <module>
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\__init__.py", line 334, in run
    get_driver().run(*args, **kwargs)
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\drivers\none.py", line 56, in run
    loop.run_until_complete(self._serve())
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 651, in run_until_complete
    self.run_forever()
  File "C:\Program Files\Python312\Lib\asyncio\windows_events.py", line 321, in run_forever
    super().run_forever()
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 618, in run_forever
    self._run_once()
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 1951, in _run_once
    handle._run()
  File "C:\Program Files\Python312\Lib\asyncio\events.py", line 84, in _run
    self._context.run(self._callback, *self._args)
> File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\adapters\discord\adapter.py", line 199, in _forward_ws
    await self._heartbeat_ack(ws)
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\adapters\discord\adapter.py", line 269, in _heartbeat_ack
    payload = await self.receive_payload(ws)
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\adapters\discord\adapter.py", line 431, in receive_payload
    data = await ws.receive()
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\drivers\aiohttp.py", line 146, in receive
    msg = await self._receive()
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\drivers\aiohttp.py", line 141, in _receive
    raise WebSocketClosed(self.websocket.close_code or 1006)
nonebot.exception.WebSocketClosed: WebSocketClosed(code=1006)

自行加上 by_alias=True 后,会在 sending Identify event 阶段报错

TypeError: Object of type Unset is not JSON serializable

log
03-24 12:46:34 [DEBUG] nonebot | Loaded adapters: Discord
03-24 12:46:34 [INFO] nonebot | Discord | Discord Adapter is starting up...
03-24 12:46:34 [DEBUG] nonebot | Discord | Discord api base url: https://discord.com/api/v10
03-24 12:46:34 [INFO] nonebot | Application startup completed.
03-24 12:46:35 [DEBUG] nonebot | Discord | Forwarding WebSocket Connection to wss://gateway.discord.gg...
03-24 12:46:36 [DEBUG] nonebot | Discord | WebSocket Connection to wss://gateway.discord.gg established
03-24 12:46:36 [DEBUG] nonebot | Discord | Received hello: opcode=<Opcode.HELLO: 10> data=Hello(heartbeat_interval=41250) t=None s=None
03-24 12:46:36 [DEBUG] nonebot | Discord | Waiting for first heartbeat to be send...
03-24 12:46:41 [TRACE] nonebot | Discord | Heartbeat
03-24 12:46:41 [TRACE] nonebot | Discord | Heartbeat Send: {"op": 1, "d": null}
03-24 12:46:41 [ERROR] nonebot | Discord | Error while sending Identify event
Traceback (most recent call last):
  File "<string>", line 15, in <module>
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\__init__.py", line 334, in run
    get_driver().run(*args, **kwargs)
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\drivers\none.py", line 56, in run
    loop.run_until_complete(self._serve())
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 651, in run_until_complete
    self.run_forever()
  File "C:\Program Files\Python312\Lib\asyncio\windows_events.py", line 321, in run_forever
    super().run_forever()
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 618, in run_forever
    self._run_once()
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 1951, in _run_once
    handle._run()
  File "C:\Program Files\Python312\Lib\asyncio\events.py", line 84, in _run
    self._context.run(self._callback, *self._args)
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\adapters\discord\adapter.py", line 207, in _forward_ws
    result = await self._authenticate(bot, ws, shard)
> File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\adapters\discord\adapter.py", line 323, in _authenticate
    await ws.send(json.dumps(model_dump(payload, exclude_none=True)))
  File "C:\Program Files\Python312\Lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Program Files\Python312\Lib\json\encoder.py", line 200, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Program Files\Python312\Lib\json\encoder.py", line 258, in iterencode
    return _iterencode(o, 0)
  File "C:\Program Files\Python312\Lib\json\encoder.py", line 180, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Unset is not JSON serializable

在鉴权连接阶段的 model_dump() 自行加上 by_alias=True, exclude_unset=True 后,发送的 payload 会是

{"d": {"token": "Bot xxx", "properties": {"os": "win32", "browser": "NoneBot2", "device": "NoneBot2"}, "compress": false, "shard": [0, 1], "intents": 3243773}}

缺少了 opcode

log
03-24 13:03:32 [DEBUG] nonebot | Loaded adapters: Discord
03-24 13:03:32 [INFO] nonebot | Discord | Discord Adapter is starting up...
03-24 13:03:32 [DEBUG] nonebot | Discord | Discord api base url: https://discord.com/api/v10
03-24 13:03:32 [INFO] nonebot | Application startup completed.
03-24 13:03:33 [DEBUG] nonebot | Discord | Forwarding WebSocket Connection to wss://gateway.discord.gg...
03-24 13:03:38 [DEBUG] nonebot | Discord | WebSocket Connection to wss://gateway.discord.gg established
03-24 13:03:38 [DEBUG] nonebot | Discord | Received hello: opcode=<Opcode.HELLO: 10> data=Hello(heartbeat_interval=41250) t=None s=None
03-24 13:03:38 [DEBUG] nonebot | Discord | Waiting for first heartbeat to be send...
03-24 13:03:43 [TRACE] nonebot | Discord | Heartbeat
03-24 13:03:43 [TRACE] nonebot | Discord | Heartbeat Send: {"op": 1, "d": null}
03-24 13:03:43 [TRACE] nonebot | Discord | Send Authenticate: {"d": {"token": "Bot xxx", "properties": {"os": "win32", "browser": "NoneBot2", "device": "NoneBot2"}, "compress": false, "shard": [0, 1], "intents": 3243773}}
03-24 13:03:43 [TRACE] nonebot | Discord | Heartbeat
03-24 13:03:43 [TRACE] nonebot | Discord | Heartbeat Send: {"op": 1, "d": null}
03-24 13:03:43 [ERROR] nonebot | Discord | WebSocket Closed
Traceback (most recent call last):
  File "<string>", line 15, in <module>
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\__init__.py", line 334, in run
    get_driver().run(*args, **kwargs)
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\drivers\none.py", line 56, in run
    loop.run_until_complete(self._serve())
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 651, in run_until_complete
    self.run_forever()
  File "C:\Program Files\Python312\Lib\asyncio\windows_events.py", line 321, in run_forever
    super().run_forever()
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 618, in run_forever
    self._run_once()
  File "C:\Program Files\Python312\Lib\asyncio\base_events.py", line 1951, in _run_once
    handle._run()
  File "C:\Program Files\Python312\Lib\asyncio\events.py", line 84, in _run
    self._context.run(self._callback, *self._args)
> File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\adapters\discord\adapter.py", line 207, in _forward_ws
    result = await self._authenticate(bot, ws, shard)
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\adapters\discord\adapter.py", line 341, in _authenticate
    payload = await self.receive_payload(ws)
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\adapters\discord\adapter.py", line 434, in receive_payload
    data = await ws.receive()
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\drivers\aiohttp.py", line 146, in receive
    msg = await self._receive()
  File "C:\Users\autua\Desktop\NoneBot\test\.venv\Lib\site-packages\nonebot\drivers\aiohttp.py", line 141, in _receive
    raise WebSocketClosed(self.websocket.close_code or 1006)
nonebot.exception.WebSocketClosed: WebSocketClosed(code=1006)

总结

不加 exclude_unset=True 会报

TypeError: Object of type Unset is not JSON serializable

加了就没 opcode

@CMHopeSunshine
Copy link
Member

麻烦帮忙试试最新 commit 版本
pydantic v1和v2的许多行为不一致可麻烦死了

@Autuamn
Copy link
Contributor Author

Autuamn commented Mar 25, 2024

已经可以连上了。
比我修得优雅多了

@Autuamn Autuamn closed this as completed Mar 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants