NodeJS 检查Discord.js DM是否通过

cidc1ykv  于 2023-06-22  发布在  Node.js
关注(0)|答案(3)|浏览(107)

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

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

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

我如何知道DM是否真的发送了?我知道这在Discord API中是可能的,因为其他机器人也这样做。

lymnna71

lymnna711#

如果用户有该选项,或者不能进行DM,则会抛出错误,即:

DiscordAPIError: Cannot send messages to this user

现在,我们可以捕获该错误并基于它运行一个命令,比如在通道中回复用户不能被DM。

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.

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

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

aurhwmvo2#

如果用户启用了该选项,则DMing他们将返回错误,因此您可以使用.catch()语句:

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

lvjbypge3#

您可以使用.catch()获取错误通知以及有关错误的信息
在本例中,我记录错误类型和描述

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

// async/await
try {
   await member.send(...);
} catch (err) {
   console.error(err);
   message.channel.send('There was an error when trying to DM this user');
}

相关问题