discord.js 发送 DM 以响应用户的斜杠命令

Posted

技术标签:

【中文标题】discord.js 发送 DM 以响应用户的斜杠命令【英文标题】:discord.js sending DM in response to user's slash commands 【发布时间】:2021-04-04 03:08:31 【问题描述】:

当用户使用新的 Discord 斜杠命令之一时,我正尝试从我们的 Discord 机器人向用户发送 DM。

代码如下。 Discord 文档说 `interaction.member 应该是 Discord GuildMember,但是,下面的代码给了我以下错误:

类型错误:interaction.member.send 不是函数

我可以从数据字段调用其他本地函数,但无法弄清楚如何回复用户。我假设我做错了什么(根据错误),但我无法从斜杠命令回调中找出向用户发送消息的食谱。

client.ws.on("INTERACTION_CREATE", async (interaction) => 
    const command = interaction.data.name.toLowerCase();
    const args = interaction.data.options;

    if (command == "testing") 
        client.api.interactions(interaction.id, interaction.token).callback.post(
            data: 
                type: 2,
                data: interaction.member.send("hello").catch(console.error),
            ,
        );
    
);

编辑:在 Jakye 的帮助下的最终解决方案。注意,我必须使用“fetch”而不是“get”,因为 get 一直返回一个未定义的用户。

if (command == 'testing') 
  client.users.fetch(interaction.member.user.id)
    .then(user => user.send("hello").catch(console.error))
    .catch(console.error);

  client.api.interactions(interaction.id, interaction.token).callback.post(
    data: 
      type: 2,
    
  );


【问题讨论】:

【参考方案1】:

交互数据直接来自 Discord 的 API,因此interaction.member 将是一个对象。

member: 
    user: 
      username: 'Username',
      public_flags: 0,
      id: '0',
      discriminator: '0000',
      avatar: ''
    ,
    roles: [],
    premium_since: null,
    permissions: '0',
    pending: false,
    nick: null,
    mute: false,
    joined_at: '2020-12-26T19:10:54.943000+00:00',
    is_pending: false,
    deaf: false
  

您必须手动获取成员,方法是从缓存中获取或从 API 中获取。

const user = client.users.cache.get(interaction.member.user.id);
user.send("Hello").catch(console.error);

client.ws.on("INTERACTION_CREATE", async interaction => 
    const guild = client.guilds.cache.get(interaction.guild_id);
    const user = client.users.cache.get(interaction.member.user.id);

    user.send(`hello, you used the $interaction.data.name.toLowerCase() command in $guild.name`).catch(console.error);
);

【讨论】:

谢谢 Jakye。而且,对于愚蠢的后续行动感到抱歉,但我如何在 POST 回调中使用它?如果我将这两行放在内部 data: 字段中,我会在“const user =”中得到一个指向“user”的“Unexpected identifier”。 很遗憾,您无法使用斜杠命令在直接消息中发送响应。响应将在执行斜杠命令的同一通道中发送。您可以将响应作为普通消息发送。您只需像定义 commandargs 常量一样定义用户。我已经用一个例子更新了我的答案。 Jakye,非常感谢。我仍然对“get”有问题,但它适用于“fetch”。我更新了 OP 以包含解决方案。再次感谢您! 很高兴我能帮上忙。

以上是关于discord.js 发送 DM 以响应用户的斜杠命令的主要内容,如果未能解决你的问题,请参考以下文章