使Discord.js命令不区分大小写

时间:2020-07-28 12:48:52

标签: javascript node.js discord discord.js case-sensitive

所以我做了一个Discord机器人,而且我有很多命令。不断出现的问题是,对于具有自动大写字母的移动用户,该机器人无法识别该消息。我在这个主题上找到的所有教程都在Discord.js的另一个版本中。如何使用.toLowerCase()使所有命令不区分大小写?

2 个答案:

答案 0 :(得分:1)

您可以使用String.prototype.toLowerCase()来返回转换为小写字母的调用字符串值。

例如,如果在以下字符串上使用String.prototype.toLowerCase(),它将返回:

hello world-> hello world

hElLo WoRlD-> hello world

...-> ...

由于它是字符串,因此您可以在message.content上使用它,将其转换为小写,然后检查内容是否等于您的命令。

这是一个例子:

client.on("message", message => {
    /**
     * Any message like the following will pass the if statement:
     * -testcommand
     * -TeStCoMMaND
     * -TESTCOMMAND
     * etc...
     */
    if (message.content.toLowerCase() == "-testcommand") {
        message.reply(`This is a test command.`);
    }
});

答案 1 :(得分:0)

'use strict';

/**
 * A ping pong bot, whenever you send "ping", it replies "pong".
 */

// Import the discord.js module
const Discord = require('discord.js');

// Create an instance of a Discord client
const client = new Discord.Client();

/**
 * The ready event is vital, it means that only _after_ this will your bot start reacting to information
 * received from Discord
 */
client.on('ready', () => {
  console.log('I am ready!');
});

// Create an event listener for messages
client.on('message', message => {
  // If the message is "ping"
  if (message.content.toLowerCase().startsWith("ping")) {
    // Send "pong" to the same channel
    message.channel.send('pong');
  }
});

// Log our bot in using the token from https://discordapp.com/developers/applications/me
client.login('your token here');

相关行:

if (message.content.toLowerCase().startsWith("ping")) {