python - discord.py 关于频道消息的问题
问题描述
我想知道我是否可以通过 id(一般、公告、赠品等)一次向更多频道发送消息。
这是我现在的错误,但我无法弄清楚为什么不起作用。
ERROR: Ignoring exception in on_ready
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 17, in on_ready
member = await bot.fetch_user(i)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 1384, in fetch_user
data = await self.http.get_user(user_id)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 250, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10013): Unknown User
并且代码在 pastebin 中:
解决方案
拿来
问题是您使用fetch_user()
而不是fetch_channel
在第 17 行。
您应该尝试使用以下代码:
channel = await bot.fetch_channel(i)
await channel.send("...")
您的错误是在您的.json
文件中有一些 ID,它们是频道的 ID。
使用成员 ID 等频道 ID 显然会引发错误。
在这种情况下,您的错误是说具有给定 ID 的成员fetch_user()
不存在。
建议
您应该使用异常处理从文件中删除尚不存在的通道。
例如:
with open(r"C:\\Your\Path\to\file.json", 'r+') as File:
data = json.load(File)
for ID in data:
try:
channel = bot.fetch_channel(ID)
except discord.errors.NotFound: # Raised if ID doesn't exist anymore
data.remove(ID)
os.remove(r"C:\\Your\Path\to\file.json")
with open(r"C:\\Your\Path\to\file.json", 'w') as File:
json.dump(data, File)
私信用户
如果你想从他们的 ID 中 DM 一些用户,你只需要这样做:
with open(r"C:\\IDs.json", 'r') as File:
data = json.load(File)
for ID in data:
user = await bot.fetch_user(ID)
await user.send("Your message")
请记住,这可能会引发异常,因为某些用户不允许机器人向他们发送消息。
推荐阅读
- python - Pandas 滚动总和,包括前几天和未来几天
- reactjs - 在 React 中使用一个或多个初始 useEffects?
- macos - 微星机械键盘在 MacBook Pro 上输入错误
- python - 使用python获取图像中的最高点(z)
- python-3.x - tf.reduce_mean 在 tf.function 中不起作用
- asp.net-mvc - 如何在多个网站 OpenIdConnect Azure AD B2C 中登录用户?
- flutter - 错误:在此小部件 Flutter [PropertiesGrid] 上方找不到正确的提供程序
- tcp - 当 RMI TCP 连接打开时,Jmeter 测试停止?
- python - 阅读卡片上的文字
- html - 边距底部自动取决于视图高度