使用配置文件时的前缀问题

Prefix issue when using config file

我试图从 (https://discordjs.guide) 中学习 discord.js,但我对这个问题感到震惊。

Index.js

const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.on('ready', () => {
    console.log('Ready!');
});

client.on('message', message => {
    if (message.content === '${prefix}ping') {
        // send back "Pong." to the channel the message was sent in
        message.channel.send('Pong.');
    }  
    if (message.content === '!test') {
        // send back "Pong." to the channel the message was sent in
        message.channel.send('Test not found');
    }     
});
client.login(token);

Config.json

{
    "prefix": "!",
    "token": "Token"
}

问题是它根本无法识别前缀

如果我输入 !ping,没有回复,如果我输入 !test

,我会收到回复

您使用的是单引号而不是 template literals 所需的反引号。所以你要检查的是: ${prefix}ping 而不是 !ping

应该是:

if (message.content === `${prefix}ping`) {
    // send back "Pong." to the channel the message was sent in
    message.channel.send('Pong.');
}  

const prefix = '!';

console.log('${prefix}ping'); // What you have
console.log(`${prefix}ping`);

您需要使用 backtick 而不是单引号。可以在 esc 键下和 1

的左侧找到反引号
if (message.content === `${prefix}ping`) {
  // send back "Pong." to the channel the message was sent in
  message.channel.send('Pong.');
}