Git Product home page Git Product logo

adapter-onebot's Issues

正向ws连接添加延迟时间参数

某些插件关联的时候,比如on_startup启动时初始化数据,on_bot_connect当bot连接时使用数据,一般是先启动完后连接,使用正向ws后,是先连接bot,后启动完毕,能否加一个延迟连接的参数?

同意加群邀请事件报错

addbot = on_request()

@addbot.handle()
async def _(bot: Bot, event: GroupRequestEvent):
    if event.sub_type == 'invite':
        await event.approve(bot)

功能就是这样的,会有一个报错

02-05 15:13:25 [INFO] nonebot | Matcher(type='request') running complete
02-05 15:13:25 [ERROR] nonebot | Running Matcher(type='request') failed.
Traceback (most recent call last):
  File "bot.py", line 37, in <module>
    nonebot.run(app="__mp_main__:app")
  File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/nonebot/__init__.py", line 273, in run
    get_driver().run(*args, **kwargs)
  File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/nonebot/drivers/fastapi.py", line 172, in run
    uvicorn.run(
  File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/uvicorn/main.py", line 569, in run
    server.run()
  File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/uvicorn/server.py", line 60, in run
    return asyncio.run(self.serve(sockets=sockets))
  File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/nonebot/message.py", line 142, in _check_matcher
    await _run_matcher(Matcher, bot, event, state, stack, dependency_cache)
> File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/nonebot/message.py", line 188, in _run_matcher
    await matcher.run(bot, event, state, stack, dependency_cache)
  File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/nonebot/internal/matcher/matcher.py", line 727, in run
    await self.simple_run(bot, event, state, stack, dependency_cache)
  File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/nonebot/internal/matcher/matcher.py", line 702, in simple_run
    await handler(
  File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/nonebot/dependencies/__init__.py", line 108, in __call__
    return await cast(Callable[..., Awaitable[R]], self.call)(**values)
  File "/home/ubuntu/QQbot/YomiNonebot/src/plugins/addbot/__init__.py", line 36, in _
    await event.approve(bot)
  File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/nonebot/adapters/onebot/v11/event.py", line 520, in approve
    return await bot.set_group_add_request(
  File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/nonebot/internal/adapter/bot.py", line 120, in call_api
    raise exception
  File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/nonebot/internal/adapter/bot.py", line 98, in call_api
    result = await self.adapter._call_api(self, api, **data)
  File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/nonebot/adapters/onebot/v11/adapter.py", line 132, in _call_api
    return handle_api_result(
  File "/home/ubuntu/.cache/pypoetry/virtualenvs/yomi-RV53Z6Ru-py3.8/lib/python3.8/site-packages/nonebot/adapters/onebot/v11/utils.py", line 58, in handle_api_result
    raise ActionFailed(**result)
nonebot.adapters.onebot.v11.exception.ActionFailed

可能是因为这个没有返回响应内容
image

真寻bot问答插件调用时报错

描述问题:

真寻机器人问答插件调用的时候报错,真寻那边看了日志说是NOnebot2的报错和他们没有关系,所以来这边询问一下。

如何复现?

期望的结果

寻求报错原因及解决方案
环境信息:

  • OS: [Windows]
  • Python Version: [e.g. 3.9]
  • Nonebot Version: [e.g. 2.0.0]

协议端信息:

  • 协议端: [e.g. go-cqhttp]
  • 协议端版本: [e.g. 1.0.0]

截图或日志

10-12 16:28:30 [INFO] plugins | (USER 1979318585, GROUP private) 添加词条 修改数据 成功!
10-12 16:28:30 [INFO] nonebot | Matcher <Matcher from plugins.word_bank.word_handle, type=message, priority=5, temp=False> running complete
10-12 16:28:30 [ERROR] nonebot | Error when running RunPostProcessors
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\pypoetry\Cache\virtualenvs\zhenxun-bot-Y33bbWyJ-py3.9\lib\site-packages\nonebot\message.py", line 146, in _check_matcher
    await _run_matcher(Matcher, bot, event, state, stack, dependency_cache)
> File "C:\Users\Administrator\AppData\Local\pypoetry\Cache\virtualenvs\zhenxun-bot-Y33bbWyJ-py3.9\lib\site-packages\nonebot\message.py", line 222, in _run_matcher
    await asyncio.gather(*coros)
  File "C:\Users\Administrator\AppData\Local\pypoetry\Cache\virtualenvs\zhenxun-bot-Y33bbWyJ-py3.9\lib\site-packages\nonebot\utils.py", line 138, in run_coro_with_catch
    return await coro
  File "C:\Users\Administrator\AppData\Local\pypoetry\Cache\virtualenvs\zhenxun-bot-Y33bbWyJ-py3.9\lib\site-packages\nonebot\dependencies\__init__.py", line 89, in __call__
    values = await self.solve(**kwargs)
  File "C:\Users\Administrator\AppData\Local\pypoetry\Cache\virtualenvs\zhenxun-bot-Y33bbWyJ-py3.9\lib\site-packages\nonebot\dependencies\__init__.py", line 188, in solve
    await checker._solve(**params)
  File "C:\Users\Administrator\AppData\Local\pypoetry\Cache\virtualenvs\zhenxun-bot-Y33bbWyJ-py3.9\lib\site-packages\nonebot\internal\params.py", line 210, in _solve
    return check_field_type(field, event)
  File "C:\Users\Administrator\AppData\Local\pypoetry\Cache\virtualenvs\zhenxun-bot-Y33bbWyJ-py3.9\lib\site-packages\nonebot\dependencies\utils.py", line 51, in check_field_type
    _, errs_ = field.validate(value, {}, loc=())
  File "pydantic\fields.py", line 857, in pydantic.fields.ModelField.validate
    v, errors = self._validate_singleton(v, values, loc, cls)
  File "pydantic\fields.py", line 1074, in pydantic.fields.ModelField._validate_singleton
    return self._apply_validators(v, values, loc, cls, self.validators)
  File "pydantic\fields.py", line 1121, in pydantic.fields.ModelField._apply_validators
    v = validator(cls, v, values, self, self.model_config)
  File "pydantic\class_validators.py", line 313, in pydantic.class_validators._generic_validator_basic.lambda12
    return lambda cls, v, values, field, config: validator(v)
  File "C:\Users\Administrator\AppData\Local\pypoetry\Cache\virtualenvs\zhenxun-bot-Y33bbWyJ-py3.9\lib\site-packages\nonebot\internal\adapter\event.py", line 23, in validate
    raise TypeError(f"{value} is incompatible with Event type {cls}")
  File "C:\Users\Administrator\AppData\Local\pypoetry\Cache\virtualenvs\zhenxun-bot-Y33bbWyJ-py3.9\lib\site-packages\nonebot\internal\adapter\event.py", line 42, in __str__
    return f"[{self.get_event_name()}]: {self.get_event_description()}"
  File "C:\Users\Administrator\AppData\Local\pypoetry\Cache\virtualenvs\zhenxun-bot-Y33bbWyJ-py3.9\lib\site-packages\nonebot\adapters\onebot\v11\event.py", line 185, in get_event_description
    + "".join(
  File "C:\Users\Administrator\AppData\Local\pypoetry\Cache\virtualenvs\zhenxun-bot-Y33bbWyJ-py3.9\lib\site-packages\nonebot\adapters\onebot\v11\event.py", line 188, in <lambda>
    if x.is_text()
AttributeError: 'str' object has no attribute 'is_text'

[QUESTION]file_id的获取

今天看v12的文档里一些如image, video之类的都需要填写一个类似UUID的file_id,请问其该如何获取?

Bug: 设为精华和取消精华时会报错

操作系统

Windows

Python 版本

3.8.16

NoneBot 版本

2.0.1

适配器

2.2.4

协议端

gocqhttp dev 5db037c

描述问题

在使用on_notice注册通知类消息响应后
当有人在群里设置精华和取消精华时
会出现报错

windows和linux均有这个问题

复现步骤

1.使用on_notice注册一个消息响应并写回调函数(我只在参数里指定了GroupIncreaseNoticeEvent)
@func.handle()
async def _(event: Union[GroupIncreaseNoticeEvent]):

2.登录并设置精华/取消精华

3.观察结果

期望的结果

期望可以不报错

截图或日志

报错内容如下:

Traceback (most recent call last):
  File "../mybot", line 8, in <module>
    sys.exit(main())
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/click/core.py", line 1157, in __call__
    return self.main(*args, **kwargs)
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/click/core.py", line 1078, in main
    rv = self.invoke(ctx)
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/click/core.py", line 1688, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/click/core.py", line 1434, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/click/core.py", line 783, in invoke
    return __callback(*args, **kwargs)
  File "/home/mybot/haruka_bot/cli/__init__.py", line 16, in run
    run()
  File "/home/mybot/haruka_bot/cli/bot.py", line 36, in run
    nonebot.run(app="haruka_bot.cli.bot:app")
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/nonebot/__init__.py", line 333, in run
    get_driver().run(*args, **kwargs)
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/nonebot/drivers/fastapi.py", line 199, in run
    uvicorn.run(
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/uvicorn/main.py", line 568, in run
    server.run()
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/uvicorn/server.py", line 59, in run
    return asyncio.run(self.serve(sockets=sockets))
  File "/usr/local/python3.8.16/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/local/python3.8.16/lib/python3.8/asyncio/base_events.py", line 603, in run_until_complete
    self.run_forever()
  File "/usr/local/python3.8.16/lib/python3.8/asyncio/base_events.py", line 570, in run_forever
    self._run_once()
  File "/usr/local/python3.8.16/lib/python3.8/asyncio/base_events.py", line 1859, in _run_once
    handle._run()
  File "/usr/local/python3.8.16/lib/python3.8/asyncio/events.py", line 81, in _run
    self._context.run(self._callback, *self._args)
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/nonebot/message.py", line 467, in check_and_run_matcher
    await _run_matcher(

> File "/usr/local/python3.8.16/lib/python3.8/site-packages/nonebot/message.py", line 419, in _run_matcher
    await matcher.run(bot, event, state, stack, dependency_cache)
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/nonebot/internal/matcher/matcher.py", line 759, in run
    await self.simple_run(bot, event, state, stack, dependency_cache)
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/nonebot/internal/matcher/matcher.py", line 734, in simple_run
    await handler(
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/nonebot/dependencies/__init__.py", line 108, in __call__
    return await cast(Callable[..., Awaitable[R]], self.call)(**values)
  File "/home/mybot/plugins/__init__.py", line 60, in handle
    user_id = int(event.get_user_id())
  File "/usr/local/python3.8.16/lib/python3.8/site-packages/nonebot/adapters/onebot/v11/event.py", line 53, in get_user_id
    raise ValueError("Event has no context!")
ValueError: Event has no context!

自定义音乐分享出问题啦

这是我使用自定义音乐分享写的消息, 但是只显示一个url, 是我的问题 还是cq那边的问题

链接是我个人网站上的图片和音频, 还是说不能这样分享

    share_music = MS.music_custom(
        url="https://xxx.com/",
        title="测试",
        content="测试",
        img_url="http://xxx/111.jpg",
        audio="https://xxx/1.wav"
    )

MessageSegment.node_custom 的 user_id 的类型注释应该同时支持 int 与 str

最后都会类型转换

目前:

    @staticmethod
    def node_custom(
        user_id: int, nickname: str, content: Union[str, "Message"]
    ) -> "MessageSegment":
        return MessageSegment(
            "node", {"user_id": str(user_id), "nickname": nickname, "content": content}
        )

期待:

    @staticmethod
    def node_custom(
        user_id: Union[str, int], nickname: str, content: Union[str, "Message"]
    ) -> "MessageSegment":
        return MessageSegment(
            "node", {"user_id": str(user_id), "nickname": nickname, "content": content}
        )

关于v12 `MessageEvent` 的 `message`

nb 去掉了 昵称 和 首尾的 @机器人,而 v12 的 MessageEvent 又没有 raw_message 字段,
是否应该添加 raw_message 字段,内容为原始的 message

Bug: go-cqhttp与nonebot2时不时出现ws连接错误:unexpected disconnect: EOF

描述问题:
go-cqhttp在与nonebot2通信的时候时不时会出现[2022-08-13 12:57:31] [ERROR]: Protocol -> unexpected disconnect: EOF,并且无法接受消息,但是时隔一会重连又好了
并且该错误偶尔会伴随着:

[2022-08-13 00:24:26] [WARNING]: 监听反向WS Universal时出现错误: websocket: close 1006 (abnormal closure): unexpected EOF 
[2022-08-13 00:24:33] [WARNING]: 向反向WS Universal服务器推送 Event 时出现错误: write tcp 127.0.0.1:43570->127.0.0.1:8080: use of closed network connection 
[2022-08-13 00:24:36] [WARNING]: 连接到反向WebSocket Universal服务器 ws://127.0.0.1:8080/cqhttp/ws 时出现错误: dial tcp 127.0.0.1:8080: connect: connection refused

有时候错误会变成:[2022-08-12 00:45:05] [WARNING]: 连接到反向WebSocket Universal服务器 ws://127.0.0.1:8080/cqhttp/ws 时出现错误: dial tcp 127.0.0.1:8080: connect: connection refused

如何复现?

  1. nb run 或者 python bot.py

期望的结果

至少ws能保证不断开,或者能自行将ws连接换成其它方式。比如说反向post之类的。

环境信息:

  • OS: Ubuntu 20.04 LTS x86_64(Py3.7.9)
  • Python Version: 3.9.7
  • Nonebot Version: 2.0.0a16

协议端信息:

  • 协议端: go-cqhttp
  • 协议端版本: v1.0.0-rc3

截图或日志

[2022-08-12 15:29:55] [WARNING]: 连接到反向WebSocket Universal服务器 ws://127.0.0.1:8080/cqhttp/ws 时出现错误: dial tcp 127.0.0.1:8080: connect: connection refused 
[2022-08-12 15:29:58] [WARNING]: 连接到反向WebSocket Universal服务器 ws://127.0.0.1:8080/cqhttp/ws 时出现错误: dial tcp 127.0.0.1:8080: connect: connection refused 
[2022-08-12 15:30:01] [WARNING]: 连接到反向WebSocket Universal服务器 ws://127.0.0.1:8080/cqhttp/ws 时出现错误: dial tcp 127.0.0.1:8080: connect: connection refused 
[2022-08-12 15:48:56] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 16:14:45] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 16:34:48] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 16:54:51] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 17:02:51] [WARNING]: 获取消息时出现错误: get value error: leveldb: not found 
[2022-08-12 17:14:55] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 17:34:58] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 18:04:13] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 18:04:52] [WARNING]: 获取消息时出现错误: get value error: leveldb: not found 
[2022-08-12 18:37:23] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 18:57:26] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 19:33:11] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 19:59:44] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 20:19:48] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 20:26:51] [WARNING]: 获取消息时出现错误: get value error: leveldb: not found 
[2022-08-12 20:48:54] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 21:08:57] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 21:28:53] [FATAL]: open image cache failed: 文件被其他进程占用 
[2022-08-12 21:29:00] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 21:50:12] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 22:10:15] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 22:30:18] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 22:50:22] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 23:10:07] [FATAL]: open image cache failed: 文件被其他进程占用 
[2022-08-12 23:25:05] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-12 23:45:08] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-13 00:20:20] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-13 00:24:26] [WARNING]: 监听反向WS Universal时出现错误: websocket: close 1006 (abnormal closure): unexpected EOF 
[2022-08-13 00:24:33] [WARNING]: 向反向WS Universal服务器推送 Event 时出现错误: write tcp 127.0.0.1:43570->127.0.0.1:8080: use of closed network connection 
[2022-08-13 00:24:36] [WARNING]: 连接到反向WebSocket Universal服务器 ws://127.0.0.1:8080/cqhttp/ws 时出现错误: dial tcp 127.0.0.1:8080: connect: connection refused 
[2022-08-13 00:52:04] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-13 01:12:08] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-13 01:32:11] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-13 02:04:52] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-13 02:24:55] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-13 02:44:58] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-13 03:05:01] [ERROR]: Protocol -> unexpected disconnect: EOF 
[2022-08-13 03:25:04] [ERROR]: Protocol -> unexpected disconnect: EOF

Bot.send在某些情况下出了问题

机器人私聊的情况下触发自身指令,然后发送消息

这时候user_id是机器人的id,target_id才是对话的用户

导致消息会发给机器人自己,而不是对话的用户

不确定是不是bug

BUG:取消禁言时,实际参数的类型为NoticeEvent而非GroupBanNoticeEvent

操作系统

Windows

Python 版本

3.11.16

NoneBot 版本

2.1.2

协议端

openShamrock

描述问题

image
这里执行了取消禁言的操作,此时调用进来发现event的类型是NoticeEvent
期望是其为GroupBanNoticeEvent

复现步骤

1.使用on_notice监视事件,并打印event类型
2.解除禁言

期望的结果

期望可以识别event为GroupBanNoticeEvent类型

截图或日志

见上图

添加 Access Token 验证钩子

在一些需要中心化部署Bot端,但分布式部署OneBot实现端的情况,有可能需要为不同的Bot账号制定不同的access token验证策略以最大程度确保Bot端的安全,我们应当可以通过添加一个验证钩子来实现这一点。

Bug: 出现异常 http连接无法使用

操作系统

Windows

Python 版本

3.9.0

NoneBot 版本

2.1.3

适配器

onebot v11 2.3.1

协议端

llonebot 2.3.0

描述问题

可以收到消息不能发送,
经测试是site-packages\nonebot\adapters\onebot\v11\adapter.py中148行elif isinstance(self.driver, HTTPClientMixin):鉴定为假导致的
如果.env.pordDRIVER=~fastapi换为DRIVER=~httpx则根本没有02-04 02:56:34 [INFO] uvicorn | Uvicorn running on http://127.0.0.1:11451 (Press CTRL+C to quit)这一行

复现步骤

启动ntqq,前端上报地址为http://127.0.0.1:11451/onebot/v11/,监听端口为5141
.env.pordONEBOT_API_ROOTS={"3556822808": "http://127.0.0.1:5141/"}
浏览器中访问http://127.0.0.1:5141/看到llonebot已启动
向bot发送echo 1

期望的结果

回复1

截图或日志

(nb) PS E:\nb\plugin_test> nb run
02-04 02:56:33 [SUCCESS] nonebot | NoneBot is initializing...
02-04 02:56:33 [INFO] nonebot | Current Env: prod
02-04 02:56:33 [DEBUG] nonebot | Loaded Config: {'driver': '~fastapi', 'host': IPv4Address('127.0.0.1'), 'port': 11451, 'log_level': 'DEBUG', 'api_timeout': 30.0, 'superusers': {'3596094466'}, 'nickname': {'池烟 
然', '天真有邪'}, 'command_start': {'', '/'}, 'command_sep': {'.', ' '}, 'session_expire_timeout': datetime.timedelta(seconds=120), 'jinyan_group': ['563484241'], 'jinyan_max_count': 3, 'jinyan_max_time': 20, 'onebot_api_roots': {'3556822808': 'http://127.0.0.1:5141/'}}
02-04 02:56:33 [DEBUG] nonebot | Succeeded to load adapter "OneBot V11"
02-04 02:56:33 [SUCCESS] nonebot | Succeeded to load plugin "echo" from "nonebot.plugins.echo"
02-04 02:56:34 [SUCCESS] nonebot | Succeeded to load plugin "nonebot-plugin-jinyan" from "plugins.nonebot-plugin-jinyan"
02-04 02:56:34 [SUCCESS] nonebot | Running NoneBot...
02-04 02:56:34 [DEBUG] nonebot | Loaded adapters: OneBot V11
02-04 02:56:34 [INFO] uvicorn | Started server process [14576]
02-04 02:56:34 [INFO] uvicorn | Waiting for application startup.
02-04 02:56:34 [INFO] uvicorn | Application startup complete.
02-04 02:56:34 [INFO] uvicorn | Uvicorn running on http://127.0.0.1:11451 (Press CTRL+C to quit)
02-04 02:56:44 [INFO] nonebot | OneBot V11 | Bot 3556822808 connected
02-04 02:56:44 [INFO] uvicorn | 127.0.0.1:9971 - "POST /onebot/v11/ HTTP/1.1" 204
02-04 02:56:44 [SUCCESS] nonebot | OneBot V11 3556822808 | [message.private.friend]: Message 7331451640639909361 from 3596094466 'echo 1'
02-04 02:56:44 [DEBUG] nonebot | Checking for matchers in priority 1...
02-04 02:56:44 [INFO] nonebot | Event will be handled by Matcher(type='message', module=nonebot.plugins.echo, lineno=17)
02-04 02:56:44 [DEBUG] nonebot | Running Matcher(type='message', module=nonebot.plugins.echo, lineno=17)
02-04 02:56:44 [DEBUG] nonebot | Running handler Dependent(call=handle_echo)
02-04 02:56:44 [DEBUG] nonebot | OneBot V11 | Calling API send_msg
02-04 02:56:44 [INFO] nonebot | Matcher(type='message', module=nonebot.plugins.echo, lineno=17) running complete
02-04 02:56:44 [ERROR] nonebot | Running Matcher(type='message', module=nonebot.plugins.echo, lineno=17) failed.
Traceback (most recent call last):
  File "E:\nb\plugin_test\bot.py", line 17, in <module>
    nonebot.run()
  File "E:\anaconda\envs\nb\lib\site-packages\nonebot\__init__.py", line 331, in run
    get_driver().run(*args, **kwargs)
  File "E:\anaconda\envs\nb\lib\site-packages\nonebot\drivers\fastapi.py", line 189, in run
    uvicorn.run(
  File "E:\anaconda\envs\nb\lib\site-packages\uvicorn\main.py", line 587, in run
    server.run()
  File "E:\anaconda\envs\nb\lib\site-packages\uvicorn\server.py", line 61, in run
    return asyncio.run(self.serve(sockets=sockets))
  File "E:\anaconda\envs\nb\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "E:\anaconda\envs\nb\lib\asyncio\base_events.py", line 629, in run_until_complete
    self.run_forever()
  File "E:\anaconda\envs\nb\lib\asyncio\windows_events.py", line 316, in run_forever
    super().run_forever()
  File "E:\anaconda\envs\nb\lib\asyncio\base_events.py", line 596, in run_forever
    self._run_once()
  File "E:\anaconda\envs\nb\lib\asyncio\base_events.py", line 1890, in _run_once
    handle._run()
  File "E:\anaconda\envs\nb\lib\asyncio\events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "E:\anaconda\envs\nb\lib\site-packages\nonebot\message.py", line 476, in check_and_run_matcher
    await _run_matcher(
> File "E:\anaconda\envs\nb\lib\site-packages\nonebot\message.py", line 428, in _run_matcher
    await matcher.run(bot, event, state, stack, dependency_cache)
  File "E:\anaconda\envs\nb\lib\site-packages\nonebot\internal\matcher\matcher.py", line 846, in run
    await self.simple_run(bot, event, state, stack, dependency_cache)
  File "E:\anaconda\envs\nb\lib\site-packages\nonebot\internal\matcher\matcher.py", line 821, in simple_run
    await handler(
  File "E:\anaconda\envs\nb\lib\site-packages\nonebot\dependencies\__init__.py", line 113, in __call__
    return await cast(Callable[..., Awaitable[R]], self.call)(**values)
  File "E:\anaconda\envs\nb\lib\site-packages\nonebot\plugins\echo.py", line 22, in handle_echo
    await echo.send(message=message)
  File "E:\anaconda\envs\nb\lib\site-packages\nonebot\internal\matcher\matcher.py", line 554, in send
    return await bot.send(event=event, message=_message, **kwargs)
    return await self.__class__.send_handler(self, event, message, **kwargs)
  File "E:\anaconda\envs\nb\lib\site-packages\nonebot\adapters\onebot\v11\bot.py", line 178, in send
    return await bot.send_msg(**params)
  File "E:\anaconda\envs\nb\lib\site-packages\nonebot\internal\adapter\bot.py", line 123, in call_api
    raise exception
  File "E:\anaconda\envs\nb\lib\site-packages\nonebot\internal\adapter\bot.py", line 98, in call_api
    result = await self.adapter._call_api(self, api, **data)
  File "E:\anaconda\envs\nb\lib\site-packages\nonebot\adapters\onebot\v11\adapter.py", line 186, in _call_api
    raise ApiNotAvailable
nonebot.adapters.onebot.v11.exception.ApiNotAvailable: ApiNotAvailable()

Feature: 发起连接后不等待 heartbeat

mirai端使用https://github.com/cnlimiter/onebot-mirai插件,nonebot中使用onebot11适配器连接,发现mirai端有日志显示连接成功,但nonebot无日志输出,也无法收发消息,通过查阅代码发现onebot11适配器建立连接时会等待收到heartbeat才会创建bot对象。
尝试删除nonebot/adapters/onebot/v11/adapter.py中的部分代码(如下图所示)
image
之后可以连接并收到消息且可触发插件事件,但插件尝试发送消息会报错

03-08 21:29:46 [INFO] nonebot | Matcher(type='message', module=nonebot_plugin_bilicover, lineno=8) running complete
03-08 21:29:46 [ERROR] nonebot | Running Matcher(type='message', module=nonebot_plugin_bilicover, lineno=8) failed.
Traceback (most recent call last):
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\httpx\_transports\default.py", line 67, in map_httpcore_exceptions
    yield
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\httpx\_transports\default.py", line 371, in handle_async_request
    resp = await self._pool.handle_async_request(req)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\httpcore\_async\connection_pool.py", line 167, in handle_async_request
    raise UnsupportedProtocol(
httpcore.UnsupportedProtocol: Request URL is missing an 'http://' or 'https://' protocol.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\adapters\onebot\v11\adapter.py", line 173, in _call_api
    response = await self.driver.request(request)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\drivers\httpx.py", line 55, in request
    response = await client.request(
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\httpx\_client.py", line 1559, in request
    return await self.send(request, auth=auth, follow_redirects=follow_redirects)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\httpx\_client.py", line 1646, in send
    response = await self._send_handling_auth(
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\httpx\_client.py", line 1674, in _send_handling_auth
    response = await self._send_handling_redirects(
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\httpx\_client.py", line 1711, in _send_handling_redirects
    response = await self._send_single_request(request)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\httpx\_client.py", line 1748, in _send_single_request
    response = await transport.handle_async_request(request)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\httpx\_transports\default.py", line 370, in handle_async_request
    with map_httpcore_exceptions():
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\contextlib.py", line 158, in __exit__
    self.gen.throw(typ, value, traceback)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\httpx\_transports\default.py", line 84, in map_httpcore_exceptions
    raise mapped_exc(message) from exc
httpx.UnsupportedProtocol: Request URL is missing an 'http://' or 'https://' protocol.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<string>", line 19, in <module>
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\__init__.py", line 333, in run
    get_driver().run(*args, **kwargs)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\drivers\fastapi.py", line 185, in run
    uvicorn.run(
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\uvicorn\main.py", line 587, in run
    server.run()
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\uvicorn\server.py", line 62, in run
    return asyncio.run(self.serve(sockets=sockets))
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 641, in run_until_complete
    self.run_forever()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\asyncio\windows_events.py", line 321, in run_forever
    super().run_forever()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 608, in run_forever
    self._run_once()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 1936, in _run_once
    handle._run()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\asyncio\events.py", line 84, in _run
    self._context.run(self._callback, *self._args)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\message.py", line 476, in check_and_run_matcher
    await _run_matcher(
> File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\message.py", line 428, in _run_matcher
    await matcher.run(bot, event, state, stack, dependency_cache)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\internal\matcher\matcher.py", line 842, in run
    await self.simple_run(bot, event, state, stack, dependency_cache)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\internal\matcher\matcher.py", line 817, in simple_run
    await handler(
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\dependencies\__init__.py", line 106, in __call__
    return await cast(Callable[..., Awaitable[R]], self.call)(**values)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot_plugin_bilicover\__init__.py", line 28, in bilibili_cover
    await matcher.finish("请输入BV号或AV号或视频地址")
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\internal\matcher\matcher.py", line 574, in finish
    await cls.send(message, **kwargs)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\internal\matcher\matcher.py", line 558, in send
    return await bot.send(event=event, message=_message, **kwargs)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\adapters\onebot\v11\bot.py", line 229, in send
    return await self.__class__.send_handler(self, event, message, **kwargs)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\adapters\onebot\v11\bot.py", line 181, in send
    return await bot.send_msg(**params)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\internal\adapter\bot.py", line 122, in call_api
    raise exception
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\internal\adapter\bot.py", line 97, in call_api
    result = await self.adapter._call_api(self, api, **data)
  File "D:\Portable-Program-Files\nonebot\onebot-mirai\.venv\Lib\site-packages\nonebot\adapters\onebot\v11\adapter.py", line 187, in _call_api
    raise NetworkError("HTTP request failed") from e
nonebot.adapters.onebot.v11.exception.NetworkError: NetWorkError(message='HTTP request failed')
03-08 21:29:46 [INFO] nonebot | Event will be handled by Matcher(type='message', module=nonebot_plugin_bilicover, lineno=8)
03-08 21:29:46 [INFO] nonebot | Matcher(type='message', module=nonebot_plugin_bilicover, lineno=8) running complete

因此请求添加“发起连接后是否等待heartbeat“的开关以适配onebot-mirai

Defect: send 函数未转义传入的 message, 使得 cq 码会直接被 Message 构造, 可能导致注入风险

环境信息

  • nonebot v2.0.0-beta.3
  • nonebot-adapter-onebot 2.1.0 (v11)
  • python 3.10.4
  • go-cqhttp v1.0.0-rc2

问题描述

bot.send 将直接构造并发送字符串形式的cq码

如何复现

简单编写一个插件即可复现:

from nonebot import on_command
from nonebot.matcher import Matcher


test = on_command('test')


@test.handle()
async def handle_arg(matcher: Matcher):
    cq = r'[CQ:image,file=https://gchat.qpic.cn/gchatpic_new/0/0-0-EF1AEEDD07F623934B59A0DF85FD8E7C/0?term=2]'
    await matcher.finish(cq)

这个问题仅在 adapter-onebot 2.1.0 版本中存在, 使用上面的测试插件分别在 2.0.0b1 和 2.1.0 两个版本的 adapter 中测试, 结果区别如下:

2.0.0b1

06-15 20:39:40 [SUCCESS] nonebot | ONEBOT V11 0000 | [message.group.normal]: Message -0000 from 0000@[:0000] "/test"
06-15 20:39:40 [INFO] nonebot | Event will be handled by <Matcher from test.message_test, type=message, priority=1, temp=False>
06-15 20:39:41 [INFO] nonebot | Matcher <Matcher from test.message_test, type=message, priority=1, temp=False> running complete
06-15 20:39:41 [SUCCESS] nonebot | ONEBOT V11 0000  | [message_sent]: {'time': 1655296771, 'self_id': 0000, 'post_type': 'message_sent', 'group_id': 0000, 'sender': {'age': 0, 'area': '', 'card': '', 'level': '', 'nickname': 'xxxx', 'role': 'admin', 'sex': 'unknown', 'title': '', 'user_id': 0000}, 'anonymous': None, 'raw_message': '&#91;CQ:image,file=https://gchat.qpic.cn/gchatpic_new/0/0-0-EF1AEEDD07F623934B59A0DF85FD8E7C/0?term=2&#93;', 'sub_type': 'normal', 'message_type': 'group', 'font': 0, 'message_seq': 52033, 'message_id': -1283735336, 'message': [{'type': 'text', 'data': {'text': '[CQ:image,file=https://gchat.qp'}}, {'type': 'text', 'data': {'text': 'ic.cn/gchatpic_new/0/0-0-EF1AEEDD07F623934B59A0DF85FD8E7C/0?term=2]'}}], 'user_id': 0000}

2.1.0

06-15 21:02:24 [SUCCESS] nonebot | ONEBOT V11 0000 | [message.group.normal]: Message -0000 from 0000@[:0000] "/test"
06-15 21:02:24 [INFO] nonebot | Event will be handled by <Matcher from test.message_test, type=message, priority=1, temp=False>
06-15 21:02:26 [INFO] nonebot | Matcher <Matcher from test.message_test, type=message, priority=1, temp=False> running complete
06-15 21:02:26 [SUCCESS] nonebot | ONEBOT V11 0000 | [message_sent]: {'time': 1655298136, 'self_id': 0000, 'post_type': 'message_sent', 'font': 0, 'group_id': 0000, 'sender': {'age': 0, 'area': '', 'card': '', 'level': '', 'nickname': 'xxxx', 'role': 'admin', 'sex': 'unknown', 'title': '', 'user_id': 0000}, 'anonymous': None, 'sub_type': 'normal', 'message': [{'type': 'image', 'data': {'file': 'ef1aeedd07f623934b59a0df85fd8e7c.image', 'subType': '0', 'url': 'https://gchat.qpic.cn/gchatpic_new/0/0-0-EF1AEEDD07F623934B59A0DF85FD8E7C/0?term=2'}}], 'user_id': 0000, 'message_id': -0000, 'message_seq': 52037, 'message_type': 'group', 'raw_message': '[CQ:image,file=ef1aeedd07f623934b59a0df85fd8e7c.image,subType=0,url=https://gchat.qpic.cn/gchatpic_new/0/0-0-EF1AEEDD07F623934B59A0DF85FD8E7C/0?term=2]'}

注意到, 在 2.0.0b1 版本中 cq 码被原样发送, 在 2.1.0 版本中 cq 码是在被构造后发送的

其他信息

在 2.0.0b1 版本的 adapter 中, send 函数对于传入的 str 类型 message 会首先被转义后再进行接下来的处理:

message = (
escape(message, escape_comma=False) if isinstance(message, str) else message
)

而在 2.1.0 版本的 adapter 中, send 函数对于传入任意类型的 message 都会直接与 Message 拼接, 使得其中的 cq 码被被构造:

full_message = Message() # create a new message with at sender segment
if reply_message:
full_message += MessageSegment.reply(event_dict["message_id"])
if at_sender and params["message_type"] != "private":
full_message += MessageSegment.at(params["user_id"]) + " "
full_message += message

这部分的变化是在 b93dd11 中被引入的

Question:在私聊中回复机器人消息会过滤图片

相关代码:

    try:
        event.reply = Reply.parse_obj(await bot.get_msg(message_id=msg_seg.data["id"]))
        logger.info(f"获取到的回复消息: {event.reply}")
    except Exception as e:
        log("WARNING", f"Error when getting message reply info: {repr(e)}", e)
        return

没有任何报错,但是会使私聊中回复机器人消息时event.reply中的图片消息为空,群聊正常
私聊测试:

image
image

群聊测试:
image

Bug: 无法正确响应私聊时的poke事件

描述问题:

在响应私聊戳一戳事件时会把它误当成群聊事件

如何复现?

from nonebot.adapters.onebot.v11 import PokeNotifyEvent
from nonebot import on_notice


poke = on_notice()


@poke.handle()
async def _(event: PokeNotifyEvent):
    await poke.send('111')

私聊戳bot后 报错如下

> File "F:\env\miyuki\lib\site-packages\nonebot\message.py", line 196, in _run_matcher
    await matcher.run(bot, event, state, stack, dependency_cache)
  File "F:\env\miyuki\lib\site-packages\nonebot\internal\matcher.py", line 668, in run
    await self.simple_run(bot, event, state, stack, dependency_cache)
  File "F:\env\miyuki\lib\site-packages\nonebot\internal\matcher.py", line 635, in simple_run
    await handler(
  File "F:\env\miyuki\lib\site-packages\nonebot\dependencies\__init__.py", line 92, in __call__
    return await self.call(**values)
  File "E:\bot\bot\bot\miyuki\.\miyuki\plugins\poke\__init__.py", line 10, in _
    await poke.send('111')
  File "F:\env\miyuki\lib\site-packages\nonebot\internal\matcher.py", line 449, in send
    return await bot.send(event=event, message=_message, **kwargs)
  File "F:\env\miyuki\lib\site-packages\nonebot\adapters\onebot\v11\bot.py", line 220, in send
    return await self.__class__.send_handler(self, event, message, **kwargs)
  File "F:\env\miyuki\lib\site-packages\nonebot\adapters\onebot\v11\bot.py", line 175, in send
    return await bot.send_msg(**params)
  File "F:\env\miyuki\lib\site-packages\nonebot\internal\adapter\bot.py", line 117, in call_api
    raise exception
  File "F:\env\miyuki\lib\site-packages\nonebot\internal\adapter\bot.py", line 94, in call_api
    result = await self.adapter._call_api(self, api, **data)
  File "F:\env\miyuki\lib\site-packages\nonebot\adapters\onebot\v11\adapter.py", line 131, in _call_api
    return handle_api_result(
  File "F:\env\miyuki\lib\site-packages\nonebot\adapters\onebot\utils.py", line 45, in handle_api_result
    raise ActionFailed(**result)
nonebot.adapters.onebot.exception.ActionFailed: <ActionFailed data=None, echo=1, msg=GROUP_NOT_FOUND, retcode=100, status=failed, wording=群聊不存在>

环境信息:

  • OS: Windows
  • Python : 3.9
  • Nonebot : v2.0.0-beta.4
  • nonebot-adapter-onebot: 2.1.1 (v11)

协议端信息:

  • 协议端: go-cqhttp
  • 协议端版本: 1.0.0-rc3

可能下面这行出了问题,发送消息时event_dict有“group_id”的键但他的值为None,误把这个事件当群聊事件处理了

if "group_id" in event_dict: # copy the group_id to the API params if exists

Bug: 回复视频消息时,event.dict()['reply']['message'] 字符串转码错误

描述问题:

如题,回复视频消息时,event.dict()['reply']['message'] 中,[CQ:video,xxxx] 变成了 &#91;CQ:video,xxxx&#93;

image

目前只发现视频有这个问题,图片等其他的 CQ 码,就是正常的(当然不排除还有些特殊的 CQ 码也有转义错误我没发现的)

image

如何复现?

  1. 发送一段视频
  2. 回复这条视频
  3. nonebot 收到 2 中的回复,event.dict()['reply']['message'] 出现该转码错误

image

  1. 同样的情况如果是一张图片,则没有该问题:

image

期望的结果

能正确给出 [CQ:video,xxxx] , 而不是 &#91;CQ:video,xxxx&#93;

环境信息:

  • OS: Ubuntu 20.04
  • Python Version: Python 3.8.10
  • Nonebot Version: 2.0.0-beta.1

协议端信息:

  • 协议端: go-cqhttp
  • 协议端版本: v1.0.0-rc1

截图或日志

如上

OnebotV11使用call_api时抛出异常

版本:
nonebot-adapter-onebot 2.1.1
异常日志:

await bot.call_api("send_group_forward_msg",group_id=event.group_id,message=msg2)
  File "D:\ProgramData\Anaconda3\envs\Nonebot_Env\lib\site-packages\nonebot\internal\adapter\bot.py", line 117, in call_api
    raise exception
  File "D:\ProgramData\Anaconda3\envs\Nonebot_Env\lib\site-packages\nonebot\internal\adapter\bot.py", line 94, in call_api
    result = await self.adapter._call_api(self, api, **data)
  File "D:\ProgramData\Anaconda3\envs\Nonebot_Env\lib\site-packages\nonebot\adapters\onebot\v11\adapter.py", line 131, in _call_api      
    return handle_api_result(
  File "D:\ProgramData\Anaconda3\envs\Nonebot_Env\lib\site-packages\nonebot\adapters\onebot\utils.py", line 47, in handle_api_result     
    raise ActionFailed(**result)
nonebot.adapters.onebot.exception.ActionFailed: <ActionFailed data=None, echo=5, msg=, retcode=100, status=failed, wording=>
08-03 22:32:39 [DEBUG] nonebot | Stop event propagation

GoCQHttp端没有错误输出(日志等级是Trace)。
请问一下,这个异常要如何解决?
感谢!

请问如何在定时任务函数中获得onebot的bot对象?

我在文档中发现了send_private_msg这个函数,我想要在定时任务中使用,因此我使用了nonebot_plugin_apscheduler插件,并且定义了async def notify_weather_warn()函数,使用scheduler.add_job添加了一个任务。

由于定时任务无法使用依赖注入,所以如果要发送消息,只能拿到Bot对象,然后使用bot对象的API。如果使用nonebot.get_bot()方法,得到的是一个nonebot.bot,而不是onebot的bot对象。我尝试了下直接强行使用nonebot.get_bot()得到的bot对象调用只有onebot才有的方法,相关代码为: print(await bot.get_login_info()),但是报错RuntimeError: Not within a websocket context

这个报错看起来像是一个网络报错,但是我可以确认其他的插件是能正常收发消息的,所以应该不是网络问题,是我的使用方法有问题,请问一下正确的使用方法是什么呢?

相关完整代码如下:

from nonebot import get_driver,require,get_bot

from nonebot.adapters.onebot.v11 import Message,MessageSegment
from nonebot.adapters.onebot.v11 import Bot as OneBot

require("nonebot_plugin_apscheduler")
require("weather")
from ..weather.weather import get_warn_from_api
from ..weather import get_default_city
from nonebot_plugin_apscheduler import scheduler

from .config import Config

global_config = get_driver().config
config = Config.parse_obj(global_config)

notify_user = config.shedular_notify_user

async def notify_weather_warn():
    bot = get_bot()
    private_users = notify_user['weather_warn_private']
    for user in private_users:
        city = await get_default_city(user_id=user)
        if city is None:
            return
        warn = get_warn_from_api(city)
        if warn is None:
            return
        msg = Message(MessageSegment.text(warn))    
        print(await bot.get_login_info())
        # await bot.send_private_msg(user_id=int(user),message=msg)

scheduler.add_job(notify_weather_warn,"interval",seconds=10)

onebot v11 API: set_group_anonymous 无法使用

我按着文档写的api,但无法使用。两种调用方法都试过。不知道出了什么问题,请各位大佬指教。
撤回信息和禁言匿名者都可以调用,就是设置匿名开关无法使用。

版本:

nb: nonebot cli version 1.0.3
onebot v11
go-cqhttp_windows_amd64,协议ipad:
20230201220420

原文档:

20230201215722

报错:

20230201215742

代码:

20230201215813

Bug: `\`参数输出转义

操作系统

Windows/Linux/MacOS均出现

Python 版本

3.10.12

NoneBot 版本

2.1.0

适配器

Onebot v11

协议端

go-cqhttp

描述问题

日志输出错误:

09-18 22:28:54 [INFO] nonebot | Event will be handled by Matcher(type='message', module=dicergirl, lineno=80)
09-18 22:28:54 [INFO] nonebot | Matcher(type='message', module=dicergirl, lineno=80) running complete
Task exception was never retrieved
future: <Task finished name='Task-8213' coro=<Bot.handle_event() done, defined at /root/oracle-dicer/.venv/lib/python3.10/site-packages/nonebot/adapters/onebot/v11/bot.py:186> exception=ValueError('Closing tag "</le>" has no corresponding opening tag')>
Traceback (most recent call last):
  File "/root/oracle-dicer/.venv/lib/python3.10/site-packages/nonebot/adapters/onebot/v11/bot.py", line 194, in handle_event
    await handle_event(self, event)
  File "/root/oracle-dicer/.venv/lib/python3.10/site-packages/nonebot/message.py", line 497, in handle_event
    logger.opt(colors=True).success(log_msg)
  File "/root/oracle-dicer/.venv/lib/python3.10/site-packages/loguru/_logger.py", line 2018, in success
    __self._log("SUCCESS", False, __self._options, __message, args, kwargs)
  File "/root/oracle-dicer/.venv/lib/python3.10/site-packages/loguru/_logger.py", line 1987, in _log
    colored_message = Colorizer.prepare_simple_message(str(message))
  File "/root/oracle-dicer/.venv/lib/python3.10/site-packages/loguru/_colorizer.py", line 368, in prepare_simple_message
    parser.feed(string)
  File "/root/oracle-dicer/.venv/lib/python3.10/site-packages/loguru/_colorizer.py", line 244, in feed
    raise ValueError('Closing tag "%s" has no corresponding opening tag' % markup)
ValueError: Closing tag "</le>" has no corresponding opening tag

复现步骤

监听一个消息事件,例如on_startswith("xxx"),然后发送消息:\+图片(一个反斜杠+图片)

怀疑是\转义了CQ码的[而导致输出错误。

期望的结果

No response

截图或日志

No response

Bug: `loguru` tag 转义问题

描述问题:

escape tag转义不正确

如何复现?

有一个on_command("sgpt")
运行时输入以下内容:

/sgpt 请给我检查一下我的检查图中是否有回路的C++代码是否有问题
/**/
#include <bits/stdc++.h>
#define maxn 1001
using namespace std;
vector<int> edge[maxn];
int temp[maxn];
bool dfs(int u){
	int v;
	
	if (temp[u]==1) return false;
	temp[u] = 1;
	
	for(int i=0;i<edge[u].size();i++){
		v = edge[u][i];
		
		if (not dfs(v)){
			return false;
		} 
		
	}
	return true;
}
int main(){
	int n,m;
	cin>>n>>m;
	int u,v;
	
	for(int i=1;i<=m;i++){
		cin>>u>>v;
		edge[u].push_back(v);
	}
	
	for(int i=1;i<=n;i++){
		
		if (temp[i]==1) continue;
		
		if (not dfs(i)){
			cout<<"circle"<<endl;
			return 0;
		}
		
	}
	cout<<"not circle"<<endl;
	return 0;
}

期望的结果

这个响应器能正常运行

环境信息:

  • OS: [e.g. Linux]
  • Python Version: [e.g. 3.11]
  • Nonebot Version: [e.g. 2.0.0rc4]

协议端信息:

  • 协议端: [e.g. go-cqhttp]
  • 协议端版本: [e.g. 1.0.0-rc5]

截图或日志

HQQC3KKULO_9J{C)9YH{J(J

`MessageSegment.node_custom`不支持`asdict`导致json序列化的过程中会报错

复现代码:

In [1]: from nonebot.utils import DataclassEncoder

In [2]: from nonebot.adapters.onebot.v11.message import Message, MessageSegment

In [3]: to_node = Message("test message")

In [4]: node = MessageSegment.node_custom(123, "test", to_node)

In [5]: import json

In [6]: json.dumps(node, cls=DataclassEncoder)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [6], in <module>
----> 1 json.dumps(node, cls=DataclassEncoder)

File /usr/lib/python3.9/json/__init__.py:234, in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
    232 if cls is None:
    233     cls = JSONEncoder
--> 234 return cls(
    235     skipkeys=skipkeys, ensure_ascii=ensure_ascii,
    236     check_circular=check_circular, allow_nan=allow_nan, indent=indent,
    237     separators=separators, default=default, sort_keys=sort_keys,
    238     **kw).encode(obj)

File /usr/lib/python3.9/json/encoder.py:199, in JSONEncoder.encode(self, o)
    195         return encode_basestring(o)
    196 # This doesn't pass the iterator directly to ''.join() because the
    197 # exceptions aren't as detailed.  The list call should be roughly
    198 # equivalent to the PySequence_Fast that ''.join() would do.
--> 199 chunks = self.iterencode(o, _one_shot=True)
    200 if not isinstance(chunks, (list, tuple)):
    201     chunks = list(chunks)

File /usr/lib/python3.9/json/encoder.py:257, in JSONEncoder.iterencode(self, o, _one_shot)
    252 else:
    253     _iterencode = _make_iterencode(
    254         markers, self.default, _encoder, self.indent, floatstr,
    255         self.key_separator, self.item_separator, self.sort_keys,
    256         self.skipkeys, _one_shot)
--> 257 return _iterencode(o, 0)

File ~/.cache/pypoetry/virtualenvs/nonebot-bison-kzZsl6Yw-py3.9/lib/python3.9/site-packages/nonebot/utils.py:148, in DataclassEncoder.default(self, o)
    145 @overrides(json.JSONEncoder)
    146 def default(self, o):
    147     if dataclasses.is_dataclass(o):
--> 148         return dataclasses.asdict(o)
    149     return super().default(o)

File /usr/lib/python3.9/dataclasses.py:1075, in asdict(obj, dict_factory)
   1073 if not _is_dataclass_instance(obj):
   1074     raise TypeError("asdict() should be called on dataclass instances")
-> 1075 return _asdict_inner(obj, dict_factory)

File /usr/lib/python3.9/dataclasses.py:1082, in _asdict_inner(obj, dict_factory)
   1080 result = []
   1081 for f in fields(obj):
-> 1082     value = _asdict_inner(getattr(obj, f.name), dict_factory)
   1083     result.append((f.name, value))
   1084 return dict_factory(result)

File /usr/lib/python3.9/dataclasses.py:1112, in _asdict_inner(obj, dict_factory)
   1110     return type(obj)(_asdict_inner(v, dict_factory) for v in obj)
   1111 elif isinstance(obj, dict):
-> 1112     return type(obj)((_asdict_inner(k, dict_factory),
   1113                       _asdict_inner(v, dict_factory))
   1114                      for k, v in obj.items())
   1115 else:
   1116     return copy.deepcopy(obj)

File /usr/lib/python3.9/dataclasses.py:1113, in <genexpr>(.0)
   1110     return type(obj)(_asdict_inner(v, dict_factory) for v in obj)
   1111 elif isinstance(obj, dict):
   1112     return type(obj)((_asdict_inner(k, dict_factory),
-> 1113                       _asdict_inner(v, dict_factory))
   1114                      for k, v in obj.items())
   1115 else:
   1116     return copy.deepcopy(obj)

File /usr/lib/python3.9/dataclasses.py:1110, in _asdict_inner(obj, dict_factory)
   1105     return type(obj)(*[_asdict_inner(v, dict_factory) for v in obj])
   1106 elif isinstance(obj, (list, tuple)):
   1107     # Assume we can create an object of this type by passing in a
   1108     # generator (which is not true for namedtuples, handled
   1109     # above).
-> 1110     return type(obj)(_asdict_inner(v, dict_factory) for v in obj)
   1111 elif isinstance(obj, dict):
   1112     return type(obj)((_asdict_inner(k, dict_factory),
   1113                       _asdict_inner(v, dict_factory))
   1114                      for k, v in obj.items())

File ~/.cache/pypoetry/virtualenvs/nonebot-bison-kzZsl6Yw-py3.9/lib/python3.9/site-packages/nonebot/internal/adapter/message.py:111, in Message.__init__(self, message)
    109     self.append(message)
    110 elif isinstance(message, Iterable):
--> 111     self.extend(message)
    112 else:
    113     self.extend(self._construct(message))

File ~/.cache/pypoetry/virtualenvs/nonebot-bison-kzZsl6Yw-py3.9/lib/python3.9/site-packages/nonebot/internal/adapter/message.py:308, in Message.extend(self, obj)
    302 """拼接一个消息数组或多个消息段到消息数组末尾。
    303 
    304 参数:
    305     obj: 要添加的消息数组
    306 """
    307 for segment in obj:
--> 308     self.append(segment)
    309 return self

File ~/.cache/pypoetry/virtualenvs/nonebot-bison-kzZsl6Yw-py3.9/lib/python3.9/site-packages/nonebot/internal/adapter/message.py:298, in Message.append(self, obj)
    296     self.extend(self._construct(obj))
    297 else:
--> 298     raise ValueError(f"Unexpected type: {type(obj)} {obj}")  # pragma: no cover
    299 return self

ValueError: Unexpected type: <class 'dict'> {'type': 'text', 'data': {'text': 'test message'}}

Bug: 当被回复消息不存在时,`event.message` 无法正确解析

描述问题:

RT, 在刚启动 nb 及后端时,经常会出现前面的被回复消息不存在的情况。这时候会报错 ActionFailed 消息不存在,但是 message 本身也出现了不解析的问题(还是 CQ 文本)

如何复现?

  1. 在群里发一些消息
  2. 启动 nb 及后端(我用的是 go-cqhttp)
  3. 回复启动前的一条消息
  4. See error

期望的结果

异常情况,这里给的还是 CQ 的文本,没有被解析成 dict (或者说是 Message 类型)

image

正常情况(一条能正常被回复的消息),成功被解析成了 Message

20230220232939

期望即使获取不到 reply 的其他信息,也保证 Message 类型能正常解析出来

环境信息:

  • OS: Ubuntu 22.04
  • Python Version: 3.8
  • Nonebot Version:
$ nb --version
nb: nonebot cli version 1.0.3

协议端信息:

  • 协议端: go-cqhttp
  • 协议端版本: 1.0.0-rc.4

截图或日志

部分复现代码

image

No more.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.