Reputation: 11
I want to import joinVoiceChannel from discordjs/voice, but it says
SyntaxError: Cannot use import statement outside a module
That's because I'm using .cjs file, if I'm using .js file then nothing will work.
Can anybody help me how to connect DiscordBot to voice channel, I can ping him but can not connect him.
main.js
import DiscordJS, { Intents } from 'discord.js'
import dotenv from 'dotenv'
import { createRequire } from "module";
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
})
const prefix = '!';
const require = createRequire(import.meta.url);
const fs = require('fs');
client.commands = new DiscordJS.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.cjs'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('Mariachi is online!');
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
client.commands.get('ping').execute(message, args);
} else if (command === 'play') {
client.commands.get('play').execute(message, args);
} else if (command === 'leave') {
client.commands.get('leave').execute(message, args);
}
});
client.login(process.env.TOKEN);
play.cjs
import { joinVoiceChannel } from "@discordjs/voice";
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
module.exports = {
name: 'play',
description: 'Joins and plays a video from youtube',
async execute(message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissions');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissions');
if (!args.length) return message.channel.send('You need to send the second argument!');
const validURL = (str) =>{
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if(!regex.test(str)){
return false;
} else {
return true;
}
}
if(validURL(args[0])){
const connection = await joinVoiceChannel.join();
const stream = ytdl(args[0], {filter: 'audioonly'});
connection.play(stream, {seek: 0, volume: 1})
.on('finish', () =>{
voiceChannel.leave();
message.channel.send('leaving channel');
});
await message.reply(`:thumbsup: Now Playing ***Your Link!***`)
return
}
const connection = await joinVoiceChannel.join();
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
if(video){
const stream = ytdl(video.url, {filter: 'audioonly'});
connection.play(stream, {seek: 0, volume: 1})
.on('finish', () =>{
voiceChannel.leave();
});
await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
} else {
message.channel.send('No video results found');
}
}
}
package.json
{
"name": "discordbot",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@discordjs/opus": "^0.7.0",
"@discordjs/voice": "github:discordjs/voice",
"discord.js": "^13.3.1",
"dotenv": "^10.0.0",
"ffmpeg-static": "^4.4.0",
"yt-search": "^2.10.2",
"ytdl-core": "^4.9.1"
},
"type": "module"
}
These are the commands I've found on StackOverflow
import { joinVoiceChannel } from "@discordjs/voice";
const connection = joinVoiceChannel(
{
channelId: message.member.voice.channel,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
Upvotes: 1
Views: 422
Reputation: 1
const { joinVoiceChannel } = require('@discordjs/voice');
use this above your module.exports and it should start working, but i am having a problem with audio after that, it will join the call but not play any audio
my error code is connection.play(stream, {seek: 0, volume: 1, type: "opus"}) ReferenceError: connection is not defined
Upvotes: 0
Reputation: 9041
.cjs
files are CommonJS. These need require
rather than the import
keyword
const { joinVoiceChannel } = require("@discordjs/voice")
const ytdl = require('ytdl-core')
const ytSearch = require('yt-search')
And since you have "type": "module"
in package.json, the .js
files will need the import
keyword
Upvotes: 1