javascript - 无法读取未定义的属性 'on' (TypeError)

标签 javascript discord discord.js

我正在使用 discord.js 编写音乐不和谐机器人,但我不断收到此错误:

client.on('warn', console.warn);
       ^

TypeError: Cannot read property 'on' of undefined

So I wonder what it is. I have the bot code down below. Take a look through if you want and if you know how to fix it I would be happy.

The bot code:

const { client } = require('discord.js');
const { TOKEN, PREFIX } = require('./config');
const ytdl = require('ytdl-core');


client.on('warn', console.warn);

client.on('error', console.error);

client.on('ready', console.log('Primary systems online'));

client.on('disconnect', console.log('So you know i disconnected, i will reconnect soon...'));

client.on('reconnecting', console.log('I am reconnecting'));

client.on('message', async msg => {
    if (msg.author.bot) return undefined;
    if (msg.content.startswith(PREFIX)) return undefined;
    const args = msg.content.split(' ');

    if (msg.content.startswith('${PREFIX}play')) {
       const voiceChannel = msg.member.voiceChannel;
       if (!voiceChannel) return msg.channel.send('you need to be in a voice channel to use this function.')
       const permissions = voiceChannel.premissionsfor(msg.client.user)
       if (!permissions.has('CONNECT')) {
            return msg.channel.send('i cant go there give me the permission to go there')
       }
       if (!permissions.has('SPEAK')){
           return msg.channel.send('i cannot speak here! I dont have the rights too')
       }

       try {
            var connection = await voiceChannel.join();
       } catch (error) {

            console.error('i could not join the voice channel: ${error}');
            return msg.channel.send('i could not join the voice channel');
       }

       const dispatcher = connection.playstream(ytdl(args[1]))
            .on('end', () => {
                console.log('song ended!')
                voiceChannel.leave();
            })
            .on('error', error => {
                console.error(error)
            });
        dispatcher.setVolumeLogarithmic(5 / 5);
    }
});

client.login(TOKEN);

最佳答案

问题是您通过要求 Dicord.js 来设置客户端,但您应该通过将其设置为 Discord.Client 的新实例来创建客户端。 .
尝试这样做:

const Discord = require("discord.js");
const client = new Discord.Client();

然后您可以保留其余代码。

关于javascript - 无法读取未定义的属性 'on' (TypeError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51251243/

相关文章:

javascript - 如何添加按下时切换视频声音的按钮?

javascript - 无法同时运行 2 个 nodemon 检查程序

javascript - Discord bot TypeError : client. guilds.forEach 不是函数

node.js - 尝试从 channel ID 获取公会

javascript - 如何以数字和字母组合的形式显示javascript对象的值?

javascript - 如何使用javascript获取已删除项目的值

javascript - 具有相同功能的多个事件监听器存储单独的局部变量?

node.js - 我在 ytdl-core 包上收到 404 错误

javascript - Discord.js 按 ID 删除消息

javascript - 无法正确读取 .txt 文件中的值