【发布时间】:2020-07-21 15:39:06
【问题描述】:
我正在努力在 TypeScript 中创建一个不和谐的机器人。我想创建一个通用的命令调度程序,这是我到目前为止的工作:
app.ts:
import * as Discord from 'discord.js';
import * as config from '../config'
import * as commands from './Commands/index'
const token : string = config.Token;
const _client = new Discord.Client();
_client.on('message', (msg) => {
let args : Array<string> = msg.content.split(' ')
let command : string = args.shift() || " ";
if(!command.startsWith("!")) return;
else{
commands[`${command.toLower().substring(1)}`]
}
})
命令/索引.ts
export {default as ping} from './ping';
export {default as prong} from './prong';
Ping.ts:所有命令的结构相同
import { Message } from "discord.js";
export default {
name : 'ping',
description: 'Ping!',
execute(message: Message, args: Array<string>){
message.channel.send('Pong.');
}
}
在索引命令导入时,我可以使用以下命令成功调用正确的执行函数:
commands['pong'].execute()
但是,当尝试像这样动态索引它时:
commands[command].execute()
我收到以下错误:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof import("c:/Users/alexs/Desktop/Discord Bot/src/Commands/index")'. No index signature with a parameter of type 'string' was found on type 'typeof import("c:/Users/alexs/Desktop/Discord Bot/src/Commands/index")'
无论如何我可以将命令导入类型转换为某种对象或集合吗?如果没有,有没有办法我可以创建某种访问器来完成这项工作?我是打字稿的新手,很好奇有什么可能。
【问题讨论】:
-
你怎么打电话给
commands[command].execute()?command变量从何而来?
标签: javascript node.js typescript discord.js