【问题标题】:Discord-Bot fails to message UsersDiscord-Bot 无法向用户发送消息
【发布时间】:2021-10-23 04:43:38
【问题描述】:

我目前正在开发一个机器人,它会在特定时间间隔内向给定 json 文件中的用户发送消息。我试过这段代码,但它没有做它应该做的事情,也没有给我一个我可以处理的错误。

@tasks.loop(seconds=10)
async def dm_loop():
    with open("users.json" "r") as file:
        users = json.load(file)
    for stgru in users:
        for i in users[stgru]:
            user = await client.fetch_user(i)
            await user.send("hello")

以防万一您想知道:短时间间隔和不必要的消息:“你好”,仅用于测试目的。代码中提到的“users.json”文件格式如下:

{
"724": ["name1#2819", "name2#2781", "name3#2891"],
"727": [],
"986": ["name4#0192"],
"840": ["name5#1221", "name6#6652"],
"798": ["name7#3312", "name8#8242", "name9#1153", "name10#3318"]
}

我已经在我的“on_ready()”中添加了“dm_loop.start()”方法,但它根本不起作用。

如果有人可以在这里帮助我,我会很高兴。谢谢

【问题讨论】:

    标签: python json discord.py


    【解决方案1】:

    根据文档,fetch_user 通过 ID 查找用户,因此您需要存储用户 ID 而不是用户名。

    https://discordpy.readthedocs.io/en/master/ext/commands/api.html?highlight=fetch_user#discord.ext.commands.Bot.fetch_user

    否则,您可以创建自己的UserConverter。这是一个关于如何做到这一点的示例。

    from discord.ext import commands
    
    [...]
    
    user_name = "some_tag#1234"
    user = await commands.converter.UserConverter().convert(ctx, argument=user_name)
    await user.send("Hello")
    

    我确实推荐第一个选项,它更简单。因为如果您不在命令中使用它,我相信您将不得不创建一个自定义上下文。

    【讨论】:

      猜你喜欢
      • 2021-03-02
      • 2021-07-06
      • 2021-01-10
      • 2021-05-29
      • 2021-06-17
      • 2020-12-01
      • 2021-01-12
      • 2021-06-05
      • 1970-01-01
      相关资源
      最近更新 更多