【问题标题】:Discord.js: Parameters with dynamic command handlingDiscord.js:具有动态命令处理的参数
【发布时间】:2020-12-08 20:06:57
【问题描述】:

我正在尝试使用discord.js 编写一个 Discord 机器人。我使用official guide 在我的 index.js 文件中设置动态命令处理。您可以在此处阅读命令处理程序:

const fs = require('fs');
const lobby = require('./scripts/lobby');
const context = require('./context');
const { token, prefix } = require('./context');

client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (!client.commands.has(command)) return;

    try {
        client.commands.get(command).execute(
            message, 
            args, 
            client,
            lobby,
            context
        );
    
    } catch (error) {
        console.error(error);
        message.reply('There was an error executing that command.');
    }
});

命令作为 JavaScript 模块存储在单独的文件中。一个简单的例子是 ping 命令:

module.exports = {
    name: 'ping',
    description: 'Ping!',
    execute(message, context) {
        console.log(context.activeLang.ping[0]);
    },
};

当我在我的 index.js 文件中将console.log(context.activeLang.ping[0]) 记录到控制台时,它会记录正确的值。当我在我的 ping 模块中这样做时,节点崩溃并出现以下类型错误:

TypeError: Cannot read property 'ping' of undefined

我不明白为什么我的命令脚本显然无法正确访问 context.js。如果有人对如何解决这个问题有建议,我将非常感激!

【问题讨论】:

    标签: javascript node.js discord discord.js


    【解决方案1】:

    现在context 实际上正在填充args 参数。参数名称,在这种情况下 messagecontext 只是相应参数的占位符。它们的值不是按名称计算的,而是按它们出现的顺序计算的。


    // example:
    
    // this function, command, will trigger the given 
    // function and pass the argument b (1)
    function command(func) {
      var b = 1
      func(b)
    };
    
    command((a, b, c) => {
    
      // even though the arguments name was b, it's value is still tied to a
      console.log(a)
    });

    即使您的参数命名context,它实际上是绑定到args

    用途:

    execute(message, args, client, lobby, context)
    

    相反,所有内容都将绑定到正确的参数。


    arguments info

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-21
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2021-01-12
      • 2020-10-02
      • 2021-08-01
      相关资源
      最近更新 更多