如何将EventEmitter与discord.js一起使用

问题描述 投票:0回答:1

我有一个正在编写的打字稿应用程序,想添加不和谐的嵌入。但是,我在向其中添加

discord.js
模块时遇到问题,因为它不允许我调用
this.emit
或使用从
myClass.on
扩展的类调用
EventEmitter

这是我的

Listeners
课程扩展
EventEmitter

import { EventEmitter } from 'events';

export class Listeners extends EventEmitter {
    private subscriptions: number[] = [];

    constructor() {
        super(); // Call the parent class constructor
    }

    public async start() {
        const mySub = await this.subscribe('test');
        this.subscriptions.push(mySub);
    }

    private async subscribe(msg: string): Promise<number> {
        this.emit('market', msg);
        return Promise.resolve(1);
    }
}

这是我的

index.ts

import { Listeners } from './listeners';

const runListener = async () => {
    const listeners = new Listeners(connection);
    await listeners.start();

    listeners.on('message', (msg: string) => {
        // do something here...
    });
}

runListener();

一旦我

npm install discord.js
我就收到以下错误:

Property 'on' does not exist on type 'Listeners'. Did you mean to access the static member 'Listeners.on' instead?

Property 'emit' does not exist on type 'Listeners'.ts(2339)

我尝试环顾四周,但没有找到任何原因。我认为它与也使用

discord.js
EventEmitters
模块有关?有谁知道我该如何解决这个问题?

typescript events discord.js eventemitter
1个回答
0
投票

首先,请注意,您没有听到发出的“市场”事件。试试这个:

listeners.on('market', (msg: string) => {
        // do something here...
    });

其次,您在实例化中通过了

connection
-
const listeners = new Listeners(connection);
。如果需要,请确保正确通过:

    constructor(private connection: any) {
        super();
    }

关于错误,请尝试将 tsconfig.json 更改为如下所示:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true // ignore type checking, may resolve conflict
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.