tencent-connect / botpy Goto Github PK
View Code? Open in Web Editor NEWQQ频道机器人PythonSDK
License: MIT License
QQ频道机器人PythonSDK
License: MIT License
await message.reply(
content=f"机器人{self.robot.name}收到你的@消息了: {message.content}",
file_image="test.png",
)
当使用以上代码时会正常使用图片发送被动消息,但是当使用以下代码时会报错
await message.reply(
content=f"机器人{self.robot.name}收到你的@消息了: {message.content}",
file_image="test.png",
+ message_reference=message_reference,
)
file_image
和message_reference
同时存在时,使用logging
警告,并按优先级发送,而不是报未知错误?我比较菜,只能用现成的SDK,不会自己调整
目前日志保存是在同一个log文件中,很不方便,数据多了使得整个日志文件很大。
能不能修改成按日期保存呢?
如题, API 接口文档中存在字段 application_id
https://bot.q.qq.com/wiki/develop/api/openapi/channel/post_channels.html
但是 SDK 中对应方法无法传入这个字段。
Line 354 in 636f98a
这会导致该方法创建应用子频道时出现 application_id error
异常。
官方发布的 新的api 支持了对qq群的相关api。请问接下来会支持v2 api吗?
简易复现代码:
async def on_message_create(self, message: Message):
_log.info(message.author.avatar)
_log.info(message.content)
if hasattr(message, "attachments"):
_log.info("Files attached")
_log.info(message.attachments)
运行后频道内发送文件后日志显示为:
[INFO] (bot.py:100)on_message_create https://qqchannel-profile-<hidden>.file.myqcloud.com/<hidden>?t=1662768954
[INFO] (bot.py:101)on_message_create 当前版本不支持查看,请升级QQ版本
[INFO] (bot.py:103)on_message_create Files attached
[INFO] (bot.py:104)on_message_create []
所用版本为
qq-botpy==1.1.2
在文档里翻遍了找不到申请的地方
示例调用:
async def on_message_create(self, message: Message):
await self.api.post_message(channel_id=message.channel_id, file_image="resource/test.png")
错误信息
[ERROR] (http.py:35)_handle_response [botpy] 接口请求异常,, 错误代码: 500, 返回内容: {'code': 40011, 'message': 'dns resolve'}, trace_id:e127e4746b17b578e9f1a9d8cf0fc79b
Traceback (most recent call last):
File "D:\software\Anaconda3\lib\site-packages\botpy\client.py", line 277, in _run_event
await coro(*args, **kwargs)
File "at_reply.py", line 33, in on_message_create
await self.api.post_message(channel_id=message.channel_id, file_image="resource/test.png")
File "D:\software\Anaconda3\lib\site-packages\botpy\api.py", line 508, in post_message
return await self._http.request(route, json=payload)
File "D:\software\Anaconda3\lib\site-packages\botpy\http.py", line 135, in request
return await _handle_response(response)
File "D:\software\Anaconda3\lib\site-packages\botpy\http.py", line 45, in _handle_response
raise error_dict_get(msg=message)
botpy.errors.ServerError: dns resolve
假如我模仿message.reply
的实现在self.api.post_message
的调用参数里加上msg_id=message.id
,此时就正常发送了。请问发送本地图片必须加上msg_id是必要的吗0 0?
在widows上日志模块会出现编码问题。
widows终端默认gbk编码,在用户名是特殊字符时日志模块会抛出编码错误。
就你的example中公告的例子。
我这里贴出修改的地方:
# 输入/xxx后的处理
# 修改了这里、修改了这里、修改了这里
message_id = message.id
# 08a0e699f5d3ebc1a47e10bae790a401386248c0aabfa106
print(message_id)
if "/建公告" in message.content:
await self.api.create_announce(message.guild_id, message.channel_id, message_id)
elif "/删公告" in message.content:
await self.api.delete_announce(message.guild_id, message_id)
报错:
[ERROR] (http.py:73)_handle_response [botpy] 接口请求异常,请求连接: https://api.sgroup.qq.com/guilds/9099812619143246624/announces/08a0e699f5d3ebc1a47e10bae790a40138664884b4bfa106, 错误代码: 500, 返回内容: {'code': 501008, 'message': 'message id invalid'}, trace_id:a410df568d94e7569c3f9d2098cd0d8c
Traceback (most recent call last):
File "/usr/local/lib/python3.11/site-packages/botpy/client.py", line 279, in _run_event
await coro(*args, **kwargs)
File "/Users/yutao/vscodeproject/qqbotpy/announce.py", line 31, in on_at_message_create
await self.api.delete_announce(message.guild_id, message_id)
File "/usr/local/lib/python3.11/site-packages/botpy/api.py", line 888, in delete_announce
return await self._http.request(route)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/botpy/http.py", line 186, in request
return await _handle_response(response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/botpy/http.py", line 83, in _handle_response
raise error_dict_get(msg=message) from None
botpy.errors.ServerError: message id invalid
官网的居然都错了,我不李姐,请求支援~~~
看了半天没弄明白,主动发消息或者帖子,用Botpy怎么实现的?
我希望机器人在接收到频道成员的at命令时创建日程,并将日程的创建者设置为发送命令的频道成员。看文档应该在创建 ScheduleToCreate 对象时指定 creator 参数。我在 message.author 中获取到发送命令的成员 id,再利用 get_guild_member 获得了对应成员的 Member 对象。利用这个对象创建 ScheduleToCreate 对象之后检查发现 creator 这部分符合预期,但是调用 create_schedule 之后生成的日程里创建者永远是机器人。这种情况应该如何解决?
运行环境: win10, py3.8.6
问题描述: 在使用该api发送包含图片的信息时, 有概率出现"upload image error", 错误号: 500; 我不确定是哪里出了问题, 因为重新发送命令@机器人又可以收到图片信息, 但这个错误会不时地出现
调用方式:
filename = "xxx.jpg"
with open(filename, "rb") as img:
img_bytes = img.read()
await message.reply(content=f"xxxxxx", file_image=img_bytes)
错误信息:
[ERROR] (http.py:73)_handle_response [botpy] 接口请求异常,请求连接: https://api.sgroup.qq.com/channels/1xxxxxxxx/messages, 错误代码: 500,
返回内容: {'code': 304017, 'message': 'upload image error'}, trace_id:0f08db94515b223207dd481c18b58f6b
Traceback (most recent call last):
File "D:\Python\Python-3.8.6\lib\site-packages\botpy\client.py", line 279, in _run_event
await coro(*args, **kwargs)
File "d:\qqbot\sample1.py", line 36, in on_at_message_create
await message.reply(content=f"{parseResult[2]}", file_image=img_bytes)
File "D:\Python\Python-3.8.6\lib\site-packages\botpy\message.py", line 84, in reply
return await self._api.post_message(channel_id=self.channel_id, msg_id=self.id, **kwargs)
File "D:\Python\Python-3.8.6\lib\site-packages\botpy\api.py", line 508, in post_message
return await self._http.request(route, json=payload)
File "D:\Python\Python-3.8.6\lib\site-packages\botpy\http.py", line 186, in request
return await _handle_response(response)
File "D:\Python\Python-3.8.6\lib\site-packages\botpy\http.py", line 83, in _handle_response
raise error_dict_get(msg=message) from None
botpy.errors.ServerError: upload image error
Python异步具有传染性,使用异步的botpy框架构建具有一定规模的同步程序非常麻烦,已有的同步程序适配异步的botpy框架同样难以完成。同时,新生入门学习和编写的多为同步风格的代码,强行要求使用异步,不便于推广。故请求发行同步版本SDK。
你好,我在使用python版sdk开发的时候遇到了一个错误无法解决
async def sendDms(self, message, **data): """发送私信""" await self.api.create_dms(guild_id=message.guild_id, user_id=message.author.id) # await self.api.post_dms(guild_id=message.guild_id, **data) await self.api.post_dms(guild_id=message.guild_id, content="123123",msg_id=message.id)
写了一个方法专门用于来发送私聊信息,不知道哪儿出现了问题,返回报错为
File "C:/Users/16917/Desktop/qq/qqbot_django/QQ_bot/bot_main2.py", line 126, in sendDms await self.api.post_dms(guild_id=message.guild_id, content="123123",msg_id=message.id) File "C:\Users\16917\AppData\Local\Programs\Python\Python38\lib\site-packages\botpy\api.py", line 628, in post_dms return await self._http.request(route, json=payload) File "C:\Users\16917\AppData\Local\Programs\Python\Python38\lib\site-packages\botpy\http.py", line 121, in request return await _handle_response(route.url, response) File "C:\Users\16917\AppData\Local\Programs\Python\Python38\lib\site-packages\botpy\http.py", line 44, in _handle_response raise error_dict_get(msg=message) botpy.errors.ServerError: internal error: direct message error
请问帖子频道事件如何监听?我尝试了订阅forums,然后重载了async def on_forum_post_create函数,但似乎没有任何反应?请问我是哪里有错误吗?请指教。
class MyClient(botpy.Client):
async def on_ready(self):
_log.info(f"robot 「{self.robot.name}」 on_ready!")
async def on_forum_post_create(self, post: Post):
print("create")
print(post.values)
print(post.items)
print(post.keys)
intents = botpy.Intents(public_guild_messages=True, forums=True)
client = MyClient(intents=intents)
client.run(appid=test_config["appid"], token=test_config["token"])
开发者社区引用的二维码失效了,无法显示二维码
直接访问链接提示Not Found
运行环境:Win10,py3.8
问题描述:在使用self.api.post_message发送本地图片时,出现 TypeError: Can not serialize value type: <class 'dict'>
日志:
Traceback (most recent call last):
File "C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\formdata.py", line 143, in _gen_form_data
part = payload.get_payload(
File "C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\payload.py", line 73, in get_payload
return PAYLOAD_REGISTRY.get(data, *args, **kwargs)
File "C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\payload.py", line 112, in get
raise LookupError()
aiohttp.payload.LookupError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\site-packages\botpy\client.py", line 275, in _run_event
await coro(*args, **kwargs)
File "C:\Users\xx\Desktop\qq-guildbook\bot.py", line 39, in on_at_message_create
await self.api.post_message(
File "C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\site-packages\botpy\api.py", line 518, in post_message
return await self._http.request(route, json=payload)
File "C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\site-packages\botpy\http.py", line 118, in request
async with self._session.request(method=route.method, url=route.url, **kwargs) as response:
File "C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 1117, in __aenter__
self._resp = await self._coro
File "C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 492, in _request
req = self._request_class(
File "C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client_reqrep.py", line 313, in __init__
self.update_body_from_data(data)
File "C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client_reqrep.py", line 507, in update_body_from_data
body = body()
File "C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\formdata.py", line 168, in __call__
return self._gen_form_data()
File "C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\formdata.py", line 147, in _gen_form_data
raise TypeError(
TypeError: Can not serialize value type: <class 'dict'>
headers: {}
value: {'message_id': '0884e6d78bb9e2aaf1990110ecf79a01384048b3c5bd9806'}
代码复现:
...
def download_img(img_url,path):
r = requests.get(img_url, stream=True)
if r.status_code == 200:
open(os.getcwd()+path, 'wb').write(r.content)
return os.getcwd()+path
del r
...
class MyClient(botpy.Client):
async def on_guild_member_add(self, member: Member):
pass
async def on_at_message_create(self, message: Message):
message_reference = Reference(message_id=message.id)
a=await self.api.get_message(channel_id=message.channel_id, message_id=message.id)
if str(a['message']['content'][23:len(a['message']['content'])]).startswith("xxx"):
api=transfurutil.Tailapi("./config/bot.conf")
context=api.getFursuitRand()
await self.api.post_message(
channel_id=message.channel_id,
content="xx{} {}".format(context['data']['id'],context['data']['name']),
file_image=download_img(context['data']['url'],'\cache\{}.jpg'.format(context['data']['id'])),#在尝试上传图片的这一步报错
msg_id=message.id,
message_reference=message_reference,
)
...
这看起来像是aiohttp的序列化问题,
我在 https://bleepcoder.com/cn/aiohttp/421745175/typeerror-can-not-serialize-value-type-class-int 找到了相关问题,但是并没有找到合适的解决方案
我该如何解决这个问题?
长期使用中可能会遇到WebSocket关闭后重连失败的问题,导致程序无法继续提供服务。
log和报错结果如下:
[INFO] on_closed (gateway.py:54):[botpy] 关闭, 返回码: 4009, 返回信息: Session timed out
[INFO] multi_run (connection.py:59):[botpy] 最大并发连接数: 1, 启动会话数: 1
[INFO] bot_connect (client.py:234):[botpy] 会话启动中...
[INFO] ws_connect (gateway.py:110):[botpy] 启动中...
[ERROR] on_error (gateway.py:50):[botpy] websocket连接: None, 异常信息 : Cannot connect to host api.sgroup.qq.com:443 ssl:default [nodename nor servname provided, or not known]
Traceback (most recent call last):
File "/Users/hakubill/PycharmProjects/qqpixivbot/venv/lib/python3.9/site-packages/aiohttp/connector.py", line 999, in _create_direct_connection
hosts = await asyncio.shield(host_resolved)
File "/Users/hakubill/PycharmProjects/qqpixivbot/venv/lib/python3.9/site-packages/aiohttp/connector.py", line 865, in _resolve_host
addrs = await self._resolver.resolve(host, port, family=self._family)
File "/Users/hakubill/PycharmProjects/qqpixivbot/venv/lib/python3.9/site-packages/aiohttp/resolver.py", line 31, in resolve
infos = await self._loop.getaddrinfo(
File "/usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 856, in getaddrinfo
return await self.run_in_executor(
File "/usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/concurrent/futures/thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "/usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socket.py", line 954, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/hakubill/PycharmProjects/qqpixivbot/venv/lib/python3.9/site-packages/botpy/client.py", line 238, in bot_connect
await client.ws_connect()
File "/Users/hakubill/PycharmProjects/qqpixivbot/venv/lib/python3.9/site-packages/botpy/gateway.py", line 117, in ws_connect
async with session.ws_connect(self._session["url"]) as ws_conn:
File "/Users/hakubill/PycharmProjects/qqpixivbot/venv/lib/python3.9/site-packages/aiohttp/client.py", line 1117, in __aenter__
self._resp = await self._coro
File "/Users/hakubill/PycharmProjects/qqpixivbot/venv/lib/python3.9/site-packages/aiohttp/client.py", line 754, in _ws_connect
resp = await self.request(
File "/Users/hakubill/PycharmProjects/qqpixivbot/venv/lib/python3.9/site-packages/aiohttp/client.py", line 520, in _request
conn = await self._connector.connect(
File "/Users/hakubill/PycharmProjects/qqpixivbot/venv/lib/python3.9/site-packages/aiohttp/connector.py", line 535, in connect
proto = await self._create_connection(req, traces, timeout)
File "/Users/hakubill/PycharmProjects/qqpixivbot/venv/lib/python3.9/site-packages/aiohttp/connector.py", line 892, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
File "/Users/hakubill/PycharmProjects/qqpixivbot/venv/lib/python3.9/site-packages/aiohttp/connector.py", line 1011, in _create_direct_connection
raise ClientConnectorError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api.sgroup.qq.com:443 ssl:default [nodename nor servname provided, or not known]
Python版本:3.8.10
qq-botpy版本:1.1.4
我在监听机器人被@的事件on_group_at_message_create
时试图输出message
对象(该对象为GroupMessage
类)的信息,结果没有输出group_openid
和author
的信息。我的代码如下:
import os.path
import botpy
from botpy import BotAPI
from botpy.message import Message, GroupMessage
from botpy.types import gateway
from botpy.types.message import Reference
import yaml
def read_yaml(path=os.path.join(os.path.dirname(__file__), "config.yaml"), encoding="utf-8"):
with open(path, encoding=encoding) as config_file:
config = yaml.load(config_file, Loader=yaml.FullLoader)
return config
__config = read_yaml(os.path.join(os.path.dirname(__file__), "config.yaml"))
class MyClient(botpy.Client):
async def on_group_at_message_create(self, message: GroupMessage):
print(f"邦邦卡邦,爱丽丝收到了你的消息!")
await message._api.post_group_message(
group_openid=message.group_openid,
content=f"邦邦卡邦,爱丽丝收到了你的消息!",
msg_type=0, msg_id=message.id,
message_reference=Reference(message_id=message.id)
)
print(message)
if __name__ == "__main__":
intents = botpy.Intents(public_guild_messages=True, guild_messages=True, public_messages=True)
client = MyClient(intents=intents)
client.run(appid=__config["appid"], secret=__config["secret"])
在QQ群中直接@机器人
得到的输出如下:
{'content': ' ', 'id': 'ROBOT1.0_zhoSHCJTvhP2CO01nKCpFJXrhTD3hPmLOOAriJxDbBu.p-PhcIIIVm8t.7Nz-G82R5ZAa0RsxaDexZgPXfcnqA!!', 'message_reference': "{'message_id': None}", 'mentions': '[]', 'attachments': '[]', 'msg_seq': 'None', 'timestamp': '2023-12-10T03:00:14+08:00', 'event_id': 'GROUP_AT_MESSAGE_CREATE:zhoshcjtvhp2co01nkcpfplws1y1ffkp1cbxzdebtxqkgxwpynhysl6q6ws849'}
以上输出中缺少group_openid
和author
的信息,我阅读源代码以后发现,根据GroupMessage
类的__repr__()
方法,输出应当包含self.__slots__ + super().__slots__
(二者结尾都是两个下划线),我发现GroupMessage
类第一行是__slots___
(结尾三个下划线),我删除了最后一个下划线,,将_User
类__repr__()
方法的返回值修改为str(self.__dict__)
(如果不修改返回值会报错,提示没有__dict__
属性),保持源代码不变,重启机器人,在QQ群中@机器人,得到输出:
{'author': "{'user_openid': ''}", 'group_openid': '398E8306A4FE17687DB13989605994D0', 'content': ' ', 'id': 'ROBOT1.0_zhoSHCJTvhP2CO01nKCpFNzob4xv-Rv1LwX6MZMwiNnJwru0lZdYaGsTQmOat-NmR5ZAa0RsxaDexZgPXfcnqA!!', 'message_reference': "{'message_id': None}", 'mentions': '[]', 'attachments': '[]', 'msg_seq': 'None', 'timestamp': '2023-12-10T03:31:14+08:00', 'event_id': 'GROUP_AT_MESSAGE_CREATE:zhoshcjtvhp2co01nkcpfc9uhvbwgys9qzgbtr1z5xqkgxwpynhysl6q6ws849'}
虽然我注意到在 #24 里已经提出了关于timeout的问题,也看到了修改方案,但是添加的with_timeout
方法的运行顺序应当在类的初始化之后,而关键的应该是初始化中创建的Http类的实例中的timeout属性的值。经过测试和实际上线运行我确信添加的with_timeout
方法未能修改到其值,仍然是3。因此实际运行时还是会时常报错HTTPSConnectionPool: Read timed out(read timeout = 3)。
通过以下代码测试可证明以上结论。
class test_http:
def __init__(self, timeout):
self.timeout = timeout
class test_api:
timeout = 3
def __init__(self, tebool: bool):
self.tebool = tebool
self.http = test_http(timeout=self.timeout)
def with_timeout(self, timeout):
self.timeout = timeout
return self
if __name__ == '__main__':
teapi = test_api(False).with_timeout(10)
print(teapi.http.timeout) # 输出3
print(teapi.timeout) # 输出10
在调用机器人发送在线图片时报错:
接口请求异常,请求连接: https://api.sgroup.qq.com/dms/0507158902224518833/messages, 错误代码: 500, 返回内容: {'code': 40002, 'message': 'download file err'},
version: 1.1.2
以下是报错信息:
[ERROR] on_error (ws_async_client.py:32):on_error: websocket connection: <aiohttp.client_ws.ClientWebSocketResponse object at 0x7f7c83bbc3a0>, exception : An asyncio.Future, a coroutine or an awaitable is required
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/qqbot/core/network/ws_async/ws_async_manager.py", line 114, in new_connect
await client.connect()
File "/usr/local/lib/python3.8/dist-packages/qqbot/core/network/ws_async/ws_async_client.py", line 89, in connect
await self.dispatch(msg, ws_conn)
File "/usr/local/lib/python3.8/dist-packages/qqbot/core/network/ws_async/ws_async_client.py", line 99, in dispatch
await self.on_message(ws_conn, msg.data)
File "/usr/local/lib/python3.8/dist-packages/qqbot/core/network/ws_async/ws_async_client.py", line 66, in on_message
await parse_and_handle(message_event, message)
File "/usr/local/lib/python3.8/dist-packages/qqbot/core/network/ws_async/ws_async_handler.py", line 35, in parse_and_handle
asyncio.ensure_future(callback(context, resolved))
File "/usr/lib/python3.8/asyncio/tasks.py", line 684, in ensure_future
raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
TypeError: An asyncio.Future, a coroutine or an awaitable is required
3秒实在是太短了。
await self.api.delete_channel(channel_id='xxx')
返回
[botpy] 接口请求异常,请求连接: https://api.sgroup.qq.com/channels/307936565, 错误代码: 401, 返回内容: {'message': 'get guild id failed', 'code': 11263}, trace_id:231f87dfca8648b3caef5c49838b406f
token应该是那个页面端三串数据中间的那个吧,我启动一直报错:
[botpy] 接口请求异常,请求连接: https://api.sgroup.qq.com/users/@me, 错误代码: 401, 返回内容: {'message': 'wrong bot token', 'code': 11242}, trace_id:f0b5d91f48b742eb9190f6981dfcc798 Traceback (most recent call last): File "e:\SystemApp\Desktop\Channel_Zero\run.py", line 18, in <module> client.run(appid={appid}, token={token}) File "E:\SystemApp\Desktop\Channel_Zero\botEnv\Lib\site-packages\botpy\client.py", line 132, in run self.loop.run_until_complete(runner()) File "E:\python\Lib\asyncio\base_events.py", line 653, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "E:\SystemApp\Desktop\Channel_Zero\botEnv\Lib\site-packages\botpy\client.py", line 129, in runner await self.start(*args, **kwargs) File "E:\SystemApp\Desktop\Channel_Zero\botEnv\Lib\site-packages\botpy\client.py", line 155, in start await self._bot_login(token) File "E:\SystemApp\Desktop\Channel_Zero\botEnv\Lib\site-packages\botpy\client.py", line 161, in _bot_login user = await self.http.login(token) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\SystemApp\Desktop\Channel_Zero\botEnv\Lib\site-packages\botpy\http.py", line 201, in login data = await self.request(Route("GET", "/users/@me")) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\SystemApp\Desktop\Channel_Zero\botEnv\Lib\site-packages\botpy\http.py", line 186, in request return await _handle_response(response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\SystemApp\Desktop\Channel_Zero\botEnv\Lib\site-packages\botpy\http.py", line 83, in _handle_response raise error_dict_get(msg=message) from None botpy.errors.AuthenticationFailedError: wrong bot token
用的官方例子:demo_at_reply_keyboard.py
没有任何改动,执行就报如下错误:(频道非私域频道):
[ERROR] (http.py:73)_handle_response [botpy] 接口请求异常,请求连接: https://api.sgroup.qq.com/channels/344208314/messages, 错误代码: 500, 返回内容: {'code': 304037, 'message': 'no permission to use this keyboard template'}, trace_id:a5aec73999d90b58394b84185600b842
Traceback (most recent call last):
File "/usr/local/lib/python3.11/site-packages/botpy/client.py", line 279, in _run_event
await coro(*args, **kwargs)
File "/Users/yutao/vscodeproject/qqbotpy/demo_at_reply_keyboard.py", line 17, in on_at_message_create
await send_template_keyboard(self.api, message)
File "/Users/yutao/vscodeproject/qqbotpy/demo_at_reply_keyboard.py", line 24, in send_template_keyboard
await api.post_keyboard_message(message.channel_id, markdown=markdown, keyboard=keyboard)
File "/usr/local/lib/python3.11/site-packages/botpy/api.py", line 559, in post_keyboard_message
return await self._http.request(route, json=payload)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/botpy/http.py", line 186, in request
return await _handle_response(response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/botpy/http.py", line 83, in _handle_response
raise error_dict_get(msg=message) from None
botpy.errors.ServerError: no permission to use this keyboard template
我的机器人有管理员权限的。所以不是很明白,为啥会报这种错误!!!
[ERROR] (http.py:73)_handle_response [botpy] 接口请求异常,请求连接: https://api.sgroup.qq.com/channels/371818661/messages, 错误代码: 500, 返回内容: {'code': 304046, 'message': 'push channel message not allow'}, trace_id:54f641d210b7e954703564e7530be5d7
Traceback (most recent call last):
File "/usr/local/lib/python3.11/site-packages/botpy/client.py", line 279, in _run_event
await coro(*args, **kwargs)
File "/Users/yutao/vscodeproject/qqbotpy/announce.py", line 21, in on_at_message_create
await self.api.post_message(message.channel_id, content="command received: %s" % message.content)
File "/usr/local/lib/python3.11/site-packages/botpy/api.py", line 508, in post_message
return await self._http.request(route, json=payload)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/botpy/http.py", line 186, in request
return await _handle_response(response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/botpy/http.py", line 83, in _handle_response
raise error_dict_get(msg=message) from None
botpy.errors.ServerError: push channel message not allow
之前都可以创建公告,多测试几次后,居然直接报错了~,公告创建然后删除,重复这种操作不可以吗?难道还有次数限制?开发代码肯定要来来回回测试的呀!
正常使用中出现,但不清楚具体复现条件
[ERROR] (gateway.py:50)on_error [botpy] websocket连接: <aiohttp.client_ws.ClientWebSocketResponse object at 0x00000177BA2EA4A0>, 异常信息 : 'NoneType' object has no attribute 'get'
Traceback (most recent call last):
File "C:\Users\Administrator\miniconda3\envs\nonebot2\lib\site-packages\botpy\client.py", line 237, in bot_connect
await client.ws_connect()
File "C:\Users\Administrator\miniconda3\envs\nonebot2\lib\site-packages\botpy\gateway.py", line 123, in ws_connect
await self.on_message(ws_conn, msg.data)
File "C:\Users\Administrator\miniconda3\envs\nonebot2\lib\site-packages\botpy\gateway.py", line 95, in on_message
func(ctx, msg.get("d"))
File "C:\Users\Administrator\miniconda3\envs\nonebot2\lib\site-packages\botpy\connection.py", line 136, in parse_message_delete
_message = Message(self.api, ctx, data)
File "C:\Users\Administrator\miniconda3\envs\nonebot2\lib\site-packages\botpy\message.py", line 26, in init
self.author = self._User(data.get("author"))
File "C:\Users\Administrator\miniconda3\envs\nonebot2\lib\site-packages\botpy\message.py", line 41, in init
self.id = data.get("id")
AttributeError: 'NoneType' object has no attribute 'get'
就企业微信, 钉钉之类的那种.
可以用于比如 github actions 完成后发通知之类的.
代码如下:
await self.api.post_message(channel_id=message.channel_id, content="1.sh")
错误信息:
错误代码: 403, 返回内容: {'code': 304003, 'message': 'url not allowed'}
应该是为了防止命令注入 被拦截了
有什么办法将消息中的.
转义吗
环境:Ubuntu20.04 LTS
前台启动命令:python3 route_bot.py
后台启动命令:nohup python3 route_bot.py &
我在使用前台启动命令时,频道机器人是能够正常访问并输出结果的,证明我的代码并没有问题。
但在使用nohup命令将该程序启动时,频道机器人无法正常输出结果,且查看nohup命令结果如下:
'''
[INFO] (client.py:159)_bot_login [botpy] 登录机器人账号中...
[INFO] (client.py:178)_bot_init [botpy] 程序启动...
[INFO] (connection.py:59)multi_run [botpy] 最大并发连接数: 1, 启动会话数: 1
[INFO] (client.py:236)bot_connect [botpy] 会话启动中...
[INFO] (gateway.py:110)ws_connect [botpy] 启动中...
[INFO] (gateway.py:136)ws_identify [botpy] 鉴权中...
[INFO] (gateway.py:80)on_message [botpy] 机器人「路线bot」启动成功!
[INFO] (gateway.py:217)_send_heart [botpy] 心跳维持启动...
[ERROR] (http.py:73)_handle_response [botpy] 接口请求异常,请求连接: https://api.sgroup.qq.com/channels/633600421/messages, 错误代码: 500, 返回内容: {'message': 'internal error', 'code': 102}, trace_id:b2f1b2bee7870754fa7a3edab3e1e150
'''
如该日志所示,报了500错误并且102的code,我尝试了不下10次都是同样的结果,请问这个问题该怎么解决?
错误提示:
TypeError: Client.start() got an unexpected keyword argument 'token'
开发环境:python3
尝试将主要的Client类放到子线程中运行时,程序报错:
File "/Users/hakubill/PycharmProjects/qqpixivbot/main.py", line 200, in start_general_event_handler
client = AyakiClient(intents=intents)
File "/Users/hakubill/PycharmProjects/qqpixivbot/venv/lib/python3.9/site-packages/botpy/client.py", line 56, in __init__
self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()
File "/usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/events.py", line 642, in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'general_thread'.
(不知道这个StackOverflow上的讨论是否有用)
[INFO] (client.py:159)_bot_login [botpy] 登录机器人账号中...
[WARNING] (http.py:188)request 请求超时,请求连接: https://api.sgroup.qq.com/gateway/bot
Traceback (most recent call last):
File "/home/keyblue/PythonProject/qqbot-demo/bot2.py", line 331, in <module>
client.run(appid=config['qqbot']['appid'], token=config['qqbot']['token'])
File "/home/keyblue/.conda/envs/qqbot/lib/python3.10/site-packages/botpy/client.py", line 132, in run
self.loop.run_until_complete(runner())
File "/home/keyblue/.conda/envs/qqbot/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "/home/keyblue/.conda/envs/qqbot/lib/python3.10/site-packages/botpy/client.py", line 129, in runner
await self.start(*args, **kwargs)
File "/home/keyblue/.conda/envs/qqbot/lib/python3.10/site-packages/botpy/client.py", line 155, in start
await self._bot_login(token)
File "/home/keyblue/.conda/envs/qqbot/lib/python3.10/site-packages/botpy/client.py", line 168, in _bot_login
max_async=self._ws_ap["session_start_limit"]["max_concurrency"],
TypeError: 'NoneType' object is not subscriptable
windows下没有这个问题
’os.system(command)
的作用是在操作系统下运行一个命令。\n\n例如,以下代码可以打开系统自带的计算器:\n\npython\nimport os\n\nos.system("calc")\n
\n\n在命令行中输入 calc
也可以打开计算器,os.system("calc")
的效果等同于在命令行中输入 calc
。\n\n需要注意的是,os.system
执行命令后返回的是操作系统的返回码。如果命令执行成功,返回码为 0,否则返回其他值,可以根据返回码判断命令是否执行成功。\n\n值得注意的是,在使用 os.system
的时候,要谨慎使用涉及敏感文件或系统权限的命令,以免造成不必要的影响。'
[ERROR] (http.py:73)_handle_response [botpy] 接口请求异常,请求连接: https://api.sgroup.qq.com/channels/530103214/messages, 错误代码: 501, 返回内容: None, trace_id:None
Traceback (most recent call last):
File "/home/workspace/gptbot/env/lib/python3.9/site-packages/botpy/client.py", line 279, in _run_event
await coro(*args, **kwargs)
File "/home/workspace/gptbot/qqbot.py", line 148, in on_at_message_create
await message.reply(content= content,message_reference=message_reference)
File "/home/workspace/gptbot/env/lib/python3.9/site-packages/botpy/message.py", line 84, in reply
return await self._api.post_message(channel_id=self.channel_id, msg_id=self.id, **kwargs)
File "/home/workspace/gptbot/env/lib/python3.9/site-packages/botpy/api.py", line 508, in post_message
return await self._http.request(route, json=payload)
File "/home/workspace/gptbot/env/lib/python3.9/site-packages/botpy/http.py", line 186, in request
return await _handle_response(response)
File "/home/workspace/gptbot/env/lib/python3.9/site-packages/botpy/http.py", line 82, in _handle_response
raise ServerError(message) from None # adding from None to prevent chain exception being raised
botpy.errors.ServerError: None
目前 qqbot.Reaction 类
class Reaction:
def __init__(self, data=None):
self.user_id: str = ""
self.guild_id: str = ""
self.channel_id: str = ""
self.target: ReactionTarget = ReactionTarget()
self.emoji: Emoji = Emoji()
if data:
self.__dict__ = data
class ReactionTarget:
def __init__(self, data=None):
self.id: str = ""
self.type: int = 0
if data:
self.__dict__ = data
下只有 user_id,也就是表情发送者的id
Reaction.target: ReactioinTarget 只有id和type两个键名,也就是表情所回复的消息id和消息类型
如果我需要知道该消息id 是谁发的就必须调用 qqbot.MessageAPI.get_message(channel_id, message_id) 方法
class MessageAPI(APIBase):
def get_messages(self, channel_id: str, pager: MessagesPager) -> List[Message]:
"""
获取指定消息列表
:param channel_id: 频道ID
:param pager: MessagesPager对象
:return: Message 对象
"""
url = get_url(APIConstant.messagesURI, self.is_sandbox).format(
channel_id=channel_id
)
query = {}
if pager.limit != "":
query["limit"] = pager.limit
if pager.type != "" and pager.id != "":
query[pager.type] = pager.id
response = self.http.get(url, params=query)
return json.loads(response.content, object_hook=Message)
才能从返回值中(qqbot.Message)获取消息创建者 id,很不方便。
请问能否在qqbot.ReactionTarget类中添加 self.author 这样一个键名?
另外,使用上述 qqbot.MessageAPI.get_message(channel_id, message_id) 方法获取到的 message,
其 message.author.id 跟 监听 WsEvent.EventMessageCreate 事件收到的 payload 的 message.author.id 并不相同。
但是用f"<@!{message.author.id}>"返回出来的都是正确的用户,请问这两种id有何不同?能够互相查询吗?
错误提示:
TypeError: Client.start() got an unexpected keyword argument 'token'
开发环境:python3
当我尝试监听私信消息并获取用户私信发送的图片时,我无法通过attachments获取图片的地址
错误提示:
TypeError: Client.start() got an unexpected keyword argument 'token'
开发环境:python3
期待出java版的
长时间运行后报错
on_error [botpy] websocket连接: None, 异常信息 : 200, message='Invalid response status', url=URL('http://192.168.3.1/html/redirect.html?origin=xxx'
之后再对机器人发送任何消息都无响应,只能重启
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.