简体   繁体   中英

discord.js sending DM in response to user's slash commands

I'm trying to send a DM from our Discord bot to the user when they use one of the new Discord slash commands.

The code is below. The Discord docs say that `interaction.member should be a Discord GuildMember, however, the code below gives me the following error:

TypeError: interaction.member.send is not a function

I can call other local functions from the data field but have been unable to figure out how to DM the user back. I assume I'm doing something wrong (per the error), but I can't figure out the cookbook to DM the user from the slash command callback.

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),
            },
        });
    }
});

EDIT: Final solution with help from Jakye. Note, I had to use "fetch" instead of "get", because get kept returning an undefined user.

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,
    }
  });
}

The interaction data is coming directly from Discord's API, as a consequence interaction.member will be an Object.

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
  }

You'll have to manually get the member, by either getting it from the cache or fetching it from the 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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM