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');
Related
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.
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'
)
// ...
},
}
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)
})
I want to create an embedded welcome command and leave command. I would like an embedded DMS message for the person who joined the server.
This is the code I have so far:
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.on('guildMemberAdd', member => {
if (!member.guild) return;
let guild = member.guild
let channel = guild.channels.cache.find(c => c.name === "welcome");
let membercount = guild.members
if (!channel) return;
let embed = new Discord.MessageEmbed().setColor("GREEN").setTitle("New Server Member!").setDescription(`Welcome, ${member.user.tag} to **${guild.name}!**`).setThumbnail(member.user.displayAvatarURL()).setFooter(`You are the ${membercount}th member to join`);
message.guild.channels.cache.find(i => i.name === 'sp').send(embed)
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setPresence({
status: "idle", //You can show online, idle.... activity: {
name: "with lower lifeforms!", //The message shown type: "PLAYING", // url: "" //PLAYING: WATCHING: LISTENING: STREAMING:
}
});
});
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.Discord(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)) {
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(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.`);
}
}
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
Now on Discord, you will need to enable intents. To do this, go to the Discord Developer Portal, select your application, and go onto the Bot tab. If you scroll about half way down, you'll see a section called Privileged Gateway Intents. You need to tick Server Members Intent under that title. For what you're doing, Presence Intent shouldn't be required, but you can tick it in case you do ever need it.
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
...
}