简体   繁体   中英

Discord.js Get Number From Message Content

today i was trying to make a bot and i want to get a number from the user message. This was my attempt

Client.on ("message", (message) => {
    if (message.author.bot) return;

    if (message.content.startsWith (Config.prefix + 'resetHWID')){
        const Embed = new Discord.MessageEmbed()
            .setColor('#6f0bd4')
            .setTitle('Success!')
            .setDescription('Successfully reset HWID for user ' + (message.content - message.content.startsWith (Config.prefix + 'resetHWID')))
        message.channel.send(Embed);
    }
});

This was the message that i sent: flop.resetHWID 5

This is what the bot sent back: Image

The expected output is: 'Successfully reset HWID for user 5

Any ideas of how I can fix this?

While you could use regex, what I think you're looking for is substring. You want to find the message content after the command name

This should help you achieve that:

Client.on ("message", (message) => {
    if (message.author.bot) return;

    if (message.content.startsWith (Config.prefix + 'resetHWID ')){
        const Embed = new Discord.MessageEmbed()
            .setColor('#6f0bd4')
            .setTitle('Success!')
            .setDescription('Successfully reset HWID for user ' + message.content.substring((Config.prefix + 'resetHWID ').length));
        message.channel.send(Embed);
    }
});

I think the answer you are looking for is regex . You can match the message content and find the number.

let str = 'The time is 8 o clock';
let matched = str.match(/\d+/) // returns [8] (Array!)
let str2 = 'The answer is 42';
let newMatched = str2.match(/\d+/) //returns [42]

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