【问题标题】:Check if a Discord.js DM went through检查 Discord.js DM 是否通过
【发布时间】:2020-12-25 09:32:05
【问题描述】:

我知道你可以这样发送 DM:

message.author.send("Go to example.com for help");

但有些人的设置允许其他服务器成员将他们 DM 关闭:

如何确定 DM 是否实际发送?我知道这在 Discord API 中是可能的,因为其他机器人会这样做。

【问题讨论】:

    标签: javascript node.js discord discord.js


    【解决方案1】:

    如果用户有该选项,或者不是 DMable,则会抛出错误,即:

    DiscordAPIError: Cannot send messages to this user   
    

    现在,我们可以捕获该错误并根据它运行命令,例如在频道中回复用户无法 DMed。

    user.send(...).catch(async err => message.reply("I can't DM this user"));
    // In the above, async is useless, but you can actually do what you want with it.
    

    要运行多行命令,请使用基于承诺的 catch。

    user.send(...).catch(async err => {
      console.log(err);
      message.reply("I can't DM this user");
    });
    

    【讨论】:

    • 是的,没关系。
    【解决方案2】:

    您可以使用.catch()获取错误通知以及有关错误的信息

    在这个例子中,我记录了错误类型和描述

    member.send(...).catch(error => {
       console.error(`${error.name} :\n${error}`)
       message.channel.send('There was an error when trying to DM this member')
    })
    

    【讨论】:

      【解决方案3】:

      如果用户启用了该选项,对他们发送消息将返回错误,因此您将能够使用 .catch() 语句:

      user.send().catch(() => console.log('Could not DM this user'));
      

      【讨论】:

        猜你喜欢
        • 2018-07-21
        • 2021-10-28
        • 2021-04-06
        • 2021-08-18
        • 1970-01-01
        • 2021-08-22
        • 2020-11-14
        • 1970-01-01
        • 2021-12-28
        相关资源
        最近更新 更多