javascript - 你能在 Discord JS 中声明你自己的函数吗?
问题描述
通常我只是轻松地添加到命令文件或索引文件中,但它开始看起来很乱。最近我让这个调平系统工作了
if (!levels[message.author.id]) {
levels[message.author.id] = {
level: 1,
exp: 0
}
}
// Gives random EXP
let randomExp = Math.floor(Math.random() * 5 + 5);
// Adds the random EXP to their current EXP
levels[message.author.id].exp += randomExp;
// Checks their EXP and changes their level
for (x = 0; x < expLevels.length; x++) {
if (levels[message.author.id].exp > expLevels[x]) {
levels[message.author.id].level = x + 1;
message.channel.reply(`congratulations! You reached level ${levels[message.author.id].level + 1}!`);
}
}
fs.writeFile('./levels.json', JSON.stringify(levels), err => {
if (err) console.error(err);
});
if (levels[authorMessage.author.id].level >= 10) {
message.member.roles.remove('720109209479413761');
message.member.roles.add('719058151940292659');
}
我希望能够将其放入自己的函数中,然后在每次有人发送消息时在“消息”部分调用它。那有可能吗?或者没有,因为我需要访问“消息”变量?
我习惯了 C++ 的函数,它更容易处理。有谁知道是否可以用 C++ 编写机器人代码或者没有支持?如果有人可以指出我正确的开始方向,请告诉我。否则我可以很容易地和 JS 呆在一起。
解决方案
我不确定是否存在不和谐的 C++ 框架,但我不确定。
您当然可以在某处定义一个函数并在onMessage
事件中调用它。
有两种方法可以做到这一点。
- 在同一个文件中
- 在另一个文件中
同一个文件中的函数。
您可以声明一个函数,然后将参数传递给该函数。您无需声明此处传递的参数类型。来源
function leveling(message) { // here you can include all parameters that you might need
// the rest of your code
}
一旦你有了一个函数,你就可以像这样调用它。
leveling(message); // here we pass the values we need to the function
不同文件中的函数。
概念是相同的,但是我们需要导出函数以便在其他地方使用它。有两种方法可以做到这一点,要么只导出一个函数,要么导出所有函数,对于专用函数文件,这是更简单的选择。
注意:在此示例中,我命名文件functions.js
并将其放置在与我需要它的文件相同的目录中。
module.exports = {
// we need to declare the name first, then add the function
leveling: function (message) {
// the rest of your code
}
// here we can add more functions, divided by a comma
}
// if you want to export only one function
// declare it normally and then export it
module.exports = leveling;
调用函数。
要使用此功能,我们需要require
在要使用它的文件中使用它。这里我们还有两个选项。
要么需要整个文件并从那里获取函数
const myfunctions = require('./functions.js'); // this is the relative path to the file
// get the function via the new constant
myfunctions.leveling(message);
或者使用对象解构从导出的函数中仅获取您需要的内容。
const { leveling } = require('./functions.js');
leveling(message);
这两种选择都有优点和缺点,但最终它们都做同样的事情。
推荐阅读
- python - 模块 tesnorflow 没有属性 “UninitializedVariable” tensorflow hub 错误
- ios - 用于 3 窗格布局的单个 iOS 故事板与单独的 iPhone/iPad 故事板
- linux - 如何在未达到任何 while 语句时运行脚本
- java - SpringBoot:如何制作与框架不紧密耦合的泛型类?
- php - 将多维数组转换为一维时保留键
- node.js - 不需要的语法错误,说意外的令牌
- javascript - 动画滚动到溢出 div 中的元素顶部
- r - 从 R 中的网站抓取的段落文本创建数据框
- qt - 控制附加到 QToolButton 的弹出 QWidget
- java - 具有相同语句JAVA的多个条件