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

时间:2020-12-26 17:48:13

标签: javascript node.js discord http-post discord.js

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

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

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

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

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 个答案:

答案 0 :(得分:2)

交互数据直接来自 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);
});
相关问题