获得"#ReferenceError: connection is not defined"



我一直在使用discord.js指南中的代码,当我尝试使其加入时,不断出现这个错误这是我的代码:

const Discord = require('discord.js');
const client = new Discord.Client();
const PREFIX = '%';
const request = require('request');
const cheerio = require('cheerio');
var servers = {};
client.on('ready', () => {
console.log('This client is online!');
})
client.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'image':
var imreq = (args[1])
image(message, imreq);
break;
case 'bruh':
client.on('message', async message => {
// Join the same voice channel of the author of the message
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
}
});
const dispatcher = connection.play('C:UsersjayjaDownloadsBruh Sound Effect 2.mp3 ');
dispatcher.on('start', () => {
console.log('audio.mp3 is now playing!');
});
dispatcher.on('finish', () => {
console.log('audio.mp3 has finished playing!');
});
// Always remember to handle errors appropriately!
dispatcher.on('error', console.error);
break;
}
});
function image(message, imreq) {
var options = {
url: "http://results.dogpile.com/serp?qc=images&q=" + imreq,
method: "GET",
headers: {
"Accept": "text/html",
"User-Agent": "Chrome"
}
};
request(options, function(error, response, responseBody) {
if (error) {
return;
}
$ = cheerio.load(responseBody);
var links = $(".image a.link");
var urls = new Array(links.length).fill(0).map((v, i) => 
links.eq(i).attr("href"));
console.log(urls);
if (!urls.length) {
return;
}
// Send result
message.channel.send(urls[Math.floor(Math.random() * urls.length)]);
});
}
client.login(token)

以下是终端的屏幕截图:屏幕截图

所以,正如我所猜测的,您不需要监听客户端的消息事件。您已经通过初始命令触发器获得了消息对象。

if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play('C:UsersjayjaDownloadsBruh Sound Effect 2.mp3 ');
dispatcher.on('start', () => {
console.log('audio.mp3 is now playing!');
});
dispatcher.on('finish', () => {
console.log('audio.mp3 has finished playing!');
});
// Always remember to handle errors appropriately!
dispatcher.on('error', console.error);
}

这应该是你所需要的。你可能也会觉得这本指南读起来很有趣。

最新更新