javascript - Discord js直接消息等待不起作用
问题描述
所以我的不和谐机器人向 DM 中的用户询问 API 机密。我想等待用户的响应,以便我可以用我的密钥做更多的事情。
从client.on('messageCreate')
用户请求添加密钥后,我调用此函数
async function takeApiSecret(msg) {
const botMsg = await msg.author.send("Please provide your api secret");
const filter = collected => collected.author.id === msg.author.id;
const collected = await botMsg.channel.awaitMessages(filter, {
max: 1,
time: 50000,
}).catch(() => {
msg.author.send('Timeout');
});
但是我无法等待用户的回复并收集它。相反,当我回复时,我的client.on('messageCreate')
. 任何线索我可能做错了什么?
解决方案
在 discord.js v13.x 中,参数awaitMessages()
略有变化。filter
和不再有单独的参数options
;filter
现在包含在选项中。这应该可以解决您的问题:
const filter = collected => collected.author.id === msg.author.id;
const collected = await botMsg.channel.awaitMessages({
filter,
max: 1,
time: 50000,
}).catch(() => {
msg.author.send('Timeout');
});
您可以在此处找到文档。出于某种原因,这些选项似乎没有完整记录,但您可以查看该页面上的示例以查看新格式。
此外,如果每当通过 DM 发送消息时调用此代码,您可能需要防止收集的消息触发其余的messageCreate
事件侦听器代码。这是您可以做到的一种方法:
外部messageCreate
处理程序:
const respondingUsers = new Set();
就在之前awaitMessages()
respondingUsers.add(msg.author.id);
在您的内部.then()
和.catch()
您的awaitMessages()
:
respondingUsers.delete(msg.author.id);
在您的处理程序顶部附近messageCreate
,在您进行其他检查之后(例如,检查消息是否为 DM):
if (respondingUsers.has(msg.author.id)) return;
如果我们将所有这些放在一起,它可能看起来像这样(显然,修改它以使用您的代码):
const respondingUsers = new Set();
client.on('messageCreate', msg => {
if (msg.channel.type != "DM") return;
if (respondingUsers.has(msg.author.id)) return;
respondingUsers.add(msg.author.id);
const filter = collected => collected.author.id === msg.author.id;
const collected = botMsg.channel.awaitMessages({
filter,
max: 1,
time: 50000,
})
.then(messages => {
msg.author.send("Received messages");
respondingUsers.delete(msg.author.id);
})
.catch(() => {
msg.author.send('Timeout');
respondingUsers.delete(msg.author.id);
});
})
推荐阅读
- pandas - 熊猫数据框从列表列 len >1 中获取元素并检查标志状态并更新同一行的组 ID
- apache-spark - 增加 Spark 工作者核心
- c++ - 将指针的值设置为类成员函数
- c++ - MariaDB 使用 C++ 连接链接器错误
- c - 更改编译语言中的函数以进行数值模拟
- c++ - 如何使用 CDatabase 通过 ODBC 连接到 SQL Server 数据库?
- c# - Serilog:如何记录,将具有不同“来源”的消息记录到不同的文件
- django - Django Rest Framework - 如何根据外键保存数据
- azure-active-directory - 邀请 API 没有用户组来添加受邀用户组
- git - 如何获取整个 git 历史的文件夹大小