SyntaxError: Cannot use import statement outside a module discord.js - javascript

I'm new to coding in general so expect nooby behaviour.
i try to make discord music bot and it cant join voice chat and when i type node .an error pops up
i dont know where put import, i tried everywhere but i doesnt work, ping and youtube command work only play doesnt
This is the main code:
const { Client, Intents, DiscordAPIError } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const prefix = '!';
const fs = require('fs');
const Discord = require('discord.js');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('Musicbot 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 == 'youtube'){
client.commands.get('youtube').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('token');
https://stackoverflow.com/questions/ask#
This is the play command code:
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
module.exports = {
name: 'play',
async execute(message, args){
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('Musisz być na kanale głosowym by użyć tej komendy!');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('Nie masz odpowiednich uprawnień');
if (!permissions.has('SPEAK')) return message.channel.send('Nie masz odpowiednich uprawnień');
if (!args.length) return message.channel.send('You need to send the second argument!');
import { joinVoiceChannel } from "#discordjs/voice";
const connection = joinVoiceChannel(
{
channelId: message.member.voice.channel,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
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('Nie znaleziono wideo');
}
}
}
Pls help

Try replacing import { joinVoiceChannel } from "#discordjs/voice"; with const { joinVoiceChannel } = require("#discordjs/voice");.
This error occurred because you tried using es modules import inside commonjs. You can however use dynamic imports on commonjs if needed.

Related

TypeError: command.execute is not a function. (After typing !rps on discord channel)

When I try to use !rps, discord shows me that there is no command and I get somethink like that in the console
I don`t know do I need to change something in my index.js code or in my rps.js code
https://imgur.com/sGjGR4t
const Discord = require('discord.js');
const fs = require('fs');
const client = new Discord.Client({ intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES] });
client.command = new Discord.Collection();
const commandFolders = fs.readdirSync('./commands');
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./commands/${folder}/`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`);
client.command.set(command.name, command);
}
}
const prefix = '!';
client.once('ready', () => {
console.log('Bot jest online');
client.user.setActivity('Minecraft')
});
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
if (!client.command.has(commandName)) return;
const command = client.command.get(commandName);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('Nie ma takiej komendy!')
}
});
client.login("TOKEN");
And the rps.js code, I tried to move rps.js to other folder but it does not solve the problem
const Discord = require('discord.js')
module.exports = {
name: "rps",
description: "rock paper scissors command",
usage: "!rps",
async run(bot, message, args) {
let embed = new Discord.MessageEmbed()
.setTitle("RPS")
.setDescription("React to play!")
.setTimestamp()
let msg = await message.channel.send(embed)
await msg.react("🗻")
await msg.react("✂")
await msg.react("📝")
const filter = (reaction, user) => {
return ['🗻', '✂', '📝'].includes(reaction.emoji.name) && user.id === message.author.id;
}
const chices = ['🗻', '✂', '📝']
const me = choices[Math.floor(Math.random() * choices.lenght)]
msg.awaitReactions(filter, { max: 1, time: 60000, error: ["time"] }).then(async (collected) => {
const reaction = collected.first()
let result = new Discord.MessageEmbed()
.setTitle("Result")
.addFields("Your Choice", `${reaction.emoji.name}`)
.addField("Bots choice", `${me}`)
await msg.edit(result)
if ((me === "🗻" && reaction.emoji.name === "✂") ||
(me === "✂" && reaction.emoji.name === "📝") ||
(me === "📝" && reaction.emoji.name === "🗻")) {
message.reply('You lost!');
} else if (me === react.emoji.name) {
return message.reply(`It's a tie!`);
} else {
return message.reply('You won!');
}
})
.catch(collected => {
message.reply('Process has been canceled, you failed to respond in time!');
})
}
}
In your rps.js file, you are defining the function to be run as run but in your index.js file, you are using the execute function so you can either change how you run the command in your main file or you can change the function name in your command file. Another place where you could get an error is the arguments you pass. In your main file, you are passing two arguments to your command file, message and args while in your command file, you are expecting three, bot, message and args. So you can either change the order of the arguments you pass or you can just remove the bot parameter in the command file:

Discord.js bot can't send message to specific channel

I'm trying to make my bot send a message to a specific channel on Discord. However, when I use the command it results in an error: TypeError: Cannot read property 'cache' of undefined .
Here's my code:
module.exports = {
name: 'send',
description: 'sends a message testing',
execute(client) {
const channel01 = client.channels.cache.find(channel => channel.id === "768667222527705148");
channel01.send('Hi');
},
};
In my index.js file, I have the following in the beginning, so I don't think the client usage in front of .channels is the problem.
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();
Here's my Index.js file.
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
const cooldowns = new Discord.Collection();
client.once('ready', () => {
console.log('Ready!');
client.user.setActivity("KevinYT", {
type: "WATCHING",
url: "https://www.youtube.com/channel/UCUr50quaTjBKWL1fLuWRvCg?view_as=subscriber"
});
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName)
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 3) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
What am I missing? Thanks!
command.execute(message, args)
You're passing the execute function message (a Message object) as the first argument but you're trying to use it as a Client object. The code fails since message.channels is undefined (the confusion arises from the argument name used in the execute function).
You can use message.client to get access to the Client object.
module.exports = {
// ...
execute (message) {
const channel01 = message.client.channels.cache.find(
(channel) => channel.id === '768667222527705148'
)
// ...
},
}

Cannot read property 'run' of undefined discord js

There was a post for this but it didn't seem to fix my problem. I'm writing a simple discord.js program and when I created a new command called forceverify, it gave the error "Cannot read property 'run' of undefined"
main.js:
const Discord = require('discord.js');
const client = new Discord.Client();
let fetch = require('node-fetch');
const prefix = '!'
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('Loaded');
})
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 === 'help') {
client.commands.get('help').execute(message, args, Discord);
} else if (command === 'verify') {
client.commands.get('verify').execute(message, args, Discord);
} else if (command === 'forceverify') {
client.commands.get('forceverify').run(message, args, Discord);
}
})
client.on('guildMemberAdd', member => {
const welcomeChannel = client.channels.cache.find(ch => ch.name === 'member-log');
if (!welcomeChannel) {
console.log('No channel was found');
}
welcomeChannel.send(`Welcome!`);
client.login('The token is there');
forceverify.js
const { DiscordAPIError } = require("discord.js");
const fetch = require("node-fetch");
const packageData = require("../package.json");
module.exports = {
name: 'verify',
description: "Verify yourself to get access to the server",
execute(message, args, Discord) {
if (message.member.roles.cache.has('805210755800367104')) {
const clientUser = client.users.fetch(args[1]);
let myRole = message.guild.roles.cache.get("805531649131151390");
fetch(`https://api.sk1er.club/player/${args[0]}`)
.then(res => res.json())
.then(({ player }) => {
clientUser.member.setNickname(player.displayname).catch(console.error);
})
.catch(err => console.log(err));
} else {
message.channel.reply("You don't have sufficient permissions.");
}
}
}
Every other command works properly but for some reason, this one simply doesn't work. I tried what the other question said to do (which is add .execute to module.exports or change .execute to .run) neither worked probably because it simply can't find the file (everything was spelled correctly)
The export from forceverify.js has the name verify but it should be forceverify. So, the forceverify command isn't registered and client.commands.get('forceverify') returns undefined.
// commands/forceverify.js
module.exports = {
name: 'forceverify',
description: 'Force verify yourself to get access to the server',
execute(message, args, Discord) {
// do stuff
}
}
And you should call the execute function when invoking the command.
client.commands.get('forceverify').execute(message, args, Discord)
You can refactor your code to simplify the command invocation code.
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 (!client.commands.has(command)) {
return
}
client.commands.get(command).execute(message, args, Discord)
})

making an invite manager with discord.js

I am making a discord bot that has a command where it will tell you every bodies invites from greatest to least in the discord server. This is the code I have but I don't know why it isn't working.
module.exports = {
name: 'invites',
description: 'invite command',
callback: (message) => {
const { guild } = message;
guild.fetchInvites().then((invites) => {
const inviteCounter = {};
invites.forEach((Invite) => {
const { uses, inviter } = Invite;
const { username, discriminator } = inviter;
const name = `${username}#${discriminator}`;
inviteCounter[name] = (inviteCounter[name] || 0) + uses;
});
let replyText = 'invites:';
for (const invite in inviteCounter) {
const count = inviteCounter[invite];
replyText += `\n${invite} has invited ${count} member(s)!`;
}
message.reply(replyText);
});
},
};
This is my command handler, i have 2 other commands that i know work and I've been changing the invite command some cause I cant get it to work.
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '+';
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () =>{
console.log('Baysides-utilities 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 === 'ticket'){
client.commands.get('ticket').execute(message, args, client, fs);
}
if(command === 'invites'){
client.commands.get('invites');
}
if(command === 'grow'){
client.commands.get('grow').execute(message, args, client, fs);
}
});
client.login('I have it in the code just not showing it here');

How to add timed mute to discord.js

I'm making a discord bot and i want to add a timed mute function like in other moderation bots where you can say who you want to mute and for how long. I have done muting in general but now need the timed mute stuff so please help me. I am also not very good with Javascript so please tell me where i implement the code if you give me some. The mute file:
module.exports = {
name: "mute",
description: "mutes the mentioned user",
execute(message, args) {
const mutedRole = message.guild.roles.cache.find(
(role) => role.name === "muted"
);
const target = message.mentions.members.first();
if (!mutedRole) {
message.channel.send("Cannot find mute role.");
} else {
target.roles.add(mutedRole);
message.channel.send("Muted " + target + " ✅");
}
},
};
i want it that its -mute {user} {time}
an example is: -mute #ani 10s
if you want the main file here you go:
const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = "!";
const fs = require("fs");
client.commands = new Discord.Collection();
const commandFiles = fs
.readdirSync("./commands/")
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once("ready", () => {
console.log("Ani Bot is online!");
client.user.setActivity("with depression");
});
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 === "test") {
client.commands.get("test").execute(message, args);
} else if (command === "mute") {
client.commands.get("mute").execute(message, args);
} else if (command === "unmute") {
client.commands.get("unmute").execute(message, args);
} else if (command === "join") {
client.commands.get("join").execute(message, args);
} else if (command === "leave") {
client.commands.get("leave").execute(message, args);
}
});
You can use the function setTimeout() right after you mute a user.
//you call the function unmuteUser after 10000 milliseconds
setTimeout(unmuteUser(user), 10000);
function unmuteUser(user){
//code that unmute
...
}

Categories

Resources