首页 > 解决方案 > 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 中

标签: pythonpython-3.xdiscorddiscord.py

解决方案


拿来


问题是您使用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")

请记住,这可能会引发异常,因为某些用户不允许机器人向他们发送消息。


推荐阅读