discord.js 如何 运行 函数然后打印答案

discord.js How to run a function then print the answer

我有一个情况,我正在编写一个不和谐的机器人,我正在尝试打印一个生成十六进制颜色代码的函数。

有什么办法可以解决吗?

在发送消息时,我尝试删除“”,它只发送代码。

请帮忙!

谢谢!

代码 :

const Discord = require("discord.js");

const TOKEN = "TOKEN";
const PREFIX = "~"

var bot = new Discord.Client();

var servers = {};

bot.on("ready", function() {
     console.log("Ready! ");
     bot.user.setActivity("Do ~help for help!");
});

function generateHex() {
    return "#" + Math.floor(Math.random() * 16777215).toString(16);
}

bot.on("message", function(message) {
     if (message.author.equals(bot.user)) return;

     if (!message.content.startsWith(PREFIX)) return;

     var args = message.content.substring(PREFIX.length).split(" ");

     switch (args[0].toLowerCase()) {
          case "genrandomhex":
              message.channel.send("generateHex")
     }
});

bot.login(TOKEN);

这不是调用函数的方式,您可以通过键入函数名称并为其提供参数(如果有)来调用函数。

message.channel.send(generateHex())

如果这是您第一次使用 javascript,请先查看一些基础 javascript 教程

我很清楚这个 post 的年龄,以及我对它的回应是徒劳的。我用它作为练习来提高我的技能。谁知道,也许它仍然会帮助某人。我也没有声称自己是某种专家;可能有更好的方法来完成这一切,甚至全部。

//START OF FILE: index.js
const Discord = require('discord.js');

/* Move these out of your main program file.
const TOKEN = "TOKEN";
const PREFIX = "~" */
const {TOKEN, PREFIX} = require('./config.json');
//See below for config.json file.

/* var , in this case should be*/ const bot = new Discord.Client();

var servers = {};
/* Note: Every time you launch this application it will set 'servers' to be empty. Also, you don't use this variable anywhere in this code. */

/* There are a few errors here...
bot.on("ready", function() { */
bot.once ('ready', () => {
     console.log('Ready! ');
     bot.user.setActivity('for you to do "~help", for help!', {type: 'Watching'}); //Made an artistic change xP
});

function generateHex() {
/* Break this up a bit...
    return "#" + Math.floor(Math.random() * 16777215).toString(16); */
    let hexMath = Math.floor(Math.random() * 16777215);
    let randHex = hexMath.toString (16);
    return(randHex);
} /* I have not checked your method here. If this doesn't return a valid HEX value, then check your math. */

// Several changes from here on...
bot.on('message', message => {
     if (message.author.id === bot.user.id) { return; }
     if (!message.content.startsWith(PREFIX)) { return; }

/* Your commands are worth hard-coding...
     var args = message.content.substring(PREFIX.length).split(" ");

     switch (args[0].toLowerCase()) {
          case "genrandomhex":
              message.channel.send("generateHex")
     } */

    let msg = message.content.toLowerCase();

    If  (msg === PREFIX + 'genrandomhex') {
        message.delete(1000);
        message.channel.send('#' + generateHex());
    }
})

bot.login(TOKEN);
//END OF FILE

//START OF FILE: config.json
//    Replace ### with your token.
{
    "TOKEN": "###",
    "PREFIX": "~"
}
//END OF FILE