简体   繁体   中英

How to make a discord bot repeat a certain part of a user's message

I am trying to make a discord bot that sends a message, then repeats a code the user gives. For example:

User: !play <code>

Bot: @everyone a new game has been started with the code <code>


I also want it to remember this variable until it's reset so that this could be possible:

User: !code

Bot: the current game code is <code>

Is it possible to do this, and if so, how? I cannot find anything showing what I'm looking for in a simple .js script

Here's what I have at the moment:

client.on('message', (msg) => {
 if (msg.content === '!play') {
  msg.reply('@everyone A new game has been started with the code');
 }
});

client.on('message', (msg) => {
 if (msg.content === '!code') {
  msg.reply('The current game code is');
 }
});

You could do it like this:

var code = '';

client.on('message', (msg) => {
 if (msg.content.startsWith('!play ')) {
  code = msg.content.substr(6); // Remove first 6 characters of message
  msg.reply(`@everyone A new game has been started with the code ${code}`);
 }
 if (msg.content.startsWith('!code ') && code.length > 0) {
  msg.reply(`The current game code is ${code}`);
 }
});

oh and also it gives me TypeError: msg.startsWith is not a function

Use message.content.startsWith()

That might work for !play, however I want !code to reply the code that was already defined in !play

True, to get the arguments of a message without a command it's

let args = message
.content // We need the content of the message
.split(' ') // Then we creates an array with the message separated with a space.
.slice(1) // We remove the command from the array

then you can use args as you want.

message.channel.send(args.join(' ')) // We join with a space to transform the array with a string

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