简体   繁体   中英

How to make a DM prompt in Discord.js?

I've just learned how to send a DM from a Discord.js bot, but how can I turn it into a prompt? My code looks like this at the moment:

client.on('message', message => {
  if (message.channel.type == "dm") {
    if (message.author.bot) return;
    if (message.content == "hello") {
      message.author.send("Hello!");
    }
  }
});

But how can I store data about what's happening in that dm? If I was making a bot like Application Bot, it would choose what to reply with based on previous dms, how can I make that work? Would I have to use a database? Thanks!

You can do this using a message collector, either with awaitMessages or createMessageCollector :

message.author.send("Hello!");

// With awaitMessages:
message.dmChannel.awaitMessages(
  // This is a filter function that allows you to only receive certain messages.
  // Return true to receive the message.
  // This filter will accept all messages.
  msg => true,
  // Options. This example makes the promise resolve after 1 message has been 
 collected.
  {max: 1}
).then(messages => {
  // messages is a Collection of messages
  const msg = messages.first();
  // do something...
});

// With createMessageCollector:
const collector = message.dmChannel.createMessageCollector(msg => true, {max: 1})
collector.on("collect", msg => {
  // do something...
});

You can also use ES2017's async / await syntax with awaitMessages :

// Note the async here
client.on('message', async message => {
  if (message.channel.type == "dm") {
    if (message.author.bot) return;
    if (message.content == "hello") {
      message.author.send("Hello!");

      const messages = await message.dmChannel.awaitMessages(msg => true, {max: 1});
      const msg = messages.first();
      // do something...
    }
  }
});

For more information see 'Collectors' on the discord.js guide .

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