简体   繁体   English

为什么这个 if 语句会导致这个 JS 代码出现问题?

[英]Why is this if statement causing issues in this JS code?

I currently have a discord.js bot running on my server from this tutorial .我目前在本教程的服务器上运行了一个 discord.js 机器人。 However, when I put the if statement for listening for messages in, the node.js refuses to start it.但是,当我将用于侦听消息的 if 语句放入时,node.js 拒绝启动它。 Said if statement:说if语句:

if (message.content === '!ping') {
    message.channel.send('Pong.');
}

edit:编辑:

full code完整代码

const Discord = require('discord.js');
const client = new Discord.Client();

client.once('ready', () => {
    console.log('Ready!');
});

client.login('login token AAAAA');

client.on('message', message => {
    console.log(message.content);
});
if (message.content === '!ping') {
    message.channel.send('Pong.');
}

error thrown抛出错误

if (message.content === '!ping') {
^

ReferenceError: message is not defined
    at Object.<anonymous> (C:\Users\epopova1\Desktop\poserBot\index.js:13:1)
[90m    at Module._compile (internal/modules/cjs/loader.js:1133:30)[39m
[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)[39m
[90m    at Module.load (internal/modules/cjs/loader.js:977:32)[39m
[90m    at Function.Module._load (internal/modules/cjs/loader.js:877:14)[39m
[90m    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)[39m
[90m    at internal/main/run_main_module.js:18:47[39m

sorry for the bad question, I am completely new here抱歉这个不好的问题,我在这里是全新的

You need to put the if statement inside the message event handler, like this:您需要将if语句放在message事件处理程序中,如下所示:

const Discord = require('discord.js');
const client = new Discord.Client();

client.once('ready', () => {
    console.log('Ready!');
});

client.login('login token AAAAA');

client.on('message', message => {
    console.log(message.content);
    if (message.content === '!ping') {
        message.channel.send('Pong.');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM