join + leave command leave is not working? - javascript

Here i have a code to join and leave but leave does not work
(join is working, leave is working too but it does crash every time when he wanna leave)
> client.on('message', async message => {
if (!message.guild) return;
if (message.content === `${config.prefix}komm`) {
message.react('☘️');
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
} else {
message.reply('Du huens geh mal erst in nen channel');
}
}
});
client.on('message', async message => {
if (!message.guild) return;
if (message.content === `${config.prefix}geh`) {
message.react('☘️');
if (!message.guild.me.voice.channel.leave()) {
message.reply("bin ja schon weg ya salame!");
message.react('☘️');
} else {
!message.reply("warte, bin nirgendwo drin!");
message.channel.send()
}
}
});

Here is your Answer :)
Based on Discord.js Guide
// Discord.js v11.
// Inside of Message Event.
if (message.content === `${config.prefix}join`) {
if (!message.guild) return;
if (message.member.voiceChannel) {
message.member.voiceChannel.join()
.then(connection => { // Connection is an instance of VoiceConnection
message.reply('I am connected');
})
.catch(console.log);
} else {
message.reply('You need to join a voice channel first!');
}
}
if (message.content === `${config.prefix}leave`) {
if (!message.guild) return;
// check if the bot is connected to a voice channel
if (message.guild.me.voiceChannel !== undefined) {
message.guild.me.voiceChannel.leave();
message.reply("Left.");
} else {
message.reply("I'm not connected to a voice channel.");
}
}
// Discord.js v12
// Async message Event and await the command.
client.on('message', async message => {
if (!message.guild) return;
if (message.content === `${config.prefix}join`) {
// Join the same voice channel of the author of the message
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
await message.channel.send("Connected."); // await message.reply("Connected.");
// REST OF YOUR CODE
}
}
if (message.content === `${config.prefix}leave`) {
if(message.guild.me.voice.channel !== undefined) {
await message.guild.me.voice.channel.leave(); // disconnect();
await message.channel.send("Left");
}
}
});

Related

How do I fix my discord bot (in discord.js) not responding to my commands

I've been trying to get my discord bot to work, but it will only become online on discord and say that it's online in the console. What am I doing wrong
here's the code from my index.js
const Discord = require('discord.js')
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION" ], intents: ["GUILDS", /* Other intents... */]});
const token = '(token here)';
client.login(token);
client.on('ready', () => {
console.log('I ARRIVE FROM THE ASHES OF THE EARTH');
});
client.on('message', message => {
if (message.content === 'Hello') {
message.send('I HAVE A GUN');
}
});
client.on('disconnect', () => {
console.log('ZE POPCORN IS DEAD');
});
const prefix = '-';
client.on('message', message => {
if (message.content === prefix + 'ping') {
message.send('Gun').then(message => message.edit('Pong'));
}
});
client.on('message', message => {
if (message.content === prefix + 'shutdown') {
if (message.author.id === '262707958646901248') {
message.send('Shutting down...').then(message => client.destroy());
}
}
});
client.on('message', message => {
if (message.content.startsWith(prefix)) {
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
message.send('Gun');
}
}
});
client.on('message', message => {
if (message.content === prefix + 'help') {
message.send('figure it out I guess?');
}
});
client.on('message', message => {
if (message.content === prefix + 'info') {
message.send('I made this bot when popcorn "died". I hope you enjoy it.');
}
});
client.on('message', message => {
if (message.content === 'ping') {
message.send('https://tenor.com/view/heavy-tf2-the-rock-rock-the-rock-the-dwayne-johnson-gif-22149531');
}
});
I tried all the commands that I put in and such, but it didn't do anything.
Code needs a fair bit of work, primarily in organization. Also please take a minute to get familiar with this entire site as all the different elements of this are here and it is a tool you will use often.
discord v13
https://discord.js.org/#/docs/discord.js/v13/general/welcome
discord v12
https://discord.js.org/#/docs/discord.js/v12/general/welcome
const Discord = require('discord.js')
const client = new Discord.Client({
partials: ["MESSAGE", "CHANNEL", "REACTION"],
intents: ["GUILDS", "GUILD_MESSAGES" /* Other intents... */ ] // make sure GUILD_MESSAGES is in there
});
const prefix = '-';
const token = '(token here)';
client.login(token);
client.on('disconnect', () => {
console.log('ZE POPCORN IS DEAD');
});
client.on('ready', () => {
console.log('I ARRIVE FROM THE ASHES OF THE EARTH');
});
client.on('message', async message => { // add async
const content = message.content.toLowerCase() // For readability
// message.send will not work, it needs to be either message.channel.send() or message.reply()
// these will work without prefix
if (content === 'hello') {
message.reply('I HAVE A GUN');
} else if (content === 'ping') {
// Below will just send the link
message.reply('https://tenor.com/view/heavy-tf2-the-rock-rock-the-rock-the-dwayne-johnson-gif-22149531');
// Below will send the attachment
message.reply({
attachments: 'https://tenor.com/view/heavy-tf2-the-rock-rock-the-rock-the-dwayne-johnson-gif-22149531'
})
}
// these will require the prefix
if (content.startsWith(prefix)) {
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
message.reply('Gun');
} else if (command === 'shutdown') {
if (message.author.id === '262707958646901248') {
message.reply('Shutting down...').then(() => client.destroy()); // message not used, so not required
} else {
message.reply('Not allowed') // added else statement
}
} else if (command === 'help') {
message.reply('figure it out I guess?');
} else if (command === 'info') {
message.reply('I made this bot when popcorn "died". I hope you enjoy it.');
}
}
});

Discord.js on raw event breakage

Desired outcome: Assign role to a user who reacts to message in channel. On bot restart the message if not in cache, therefore user is not assigned role.
Issue: Code stops responding after guildID = client.guilds.get(packet.d.guild_id);
client has been defined at the start of the script.
Expected output: Returns guildID and adds the role to the user who reacted.
Followed this guide
client.on('raw', packet => {
if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
if (!(packet.d.channel_id === '<CHANNEL_ID>')) return;
//console.log(packet);
guildID = client.guilds.get(packet.d.guild_id);
if (packet.t === 'MESSAGE_REACTION_ADD') {
console.log("ADDED");
if (packet.d.emoji.name === '⭐') {
try {
guildID.members.cache.get(packet.d.user_id).roles.add('<ROLE_ID>').catch()
} catch (error) {
console.log(error);
}
}
}
if (packet.t === 'MESSAGE_REACTION_REMOVE') {
console.log("REMOVED");
}
});
Try to using these alternative way to use
And guildID = client.guilds.get(packet.d.guild_id); this wrong way to get guild since discord.js v12 updated it will be guildID = client.guilds.cache.get(packet.d.guild_id);
client.on('messageReactionAdd', (reaction, user) => {
console.log('a reaction has been added');
});
client.on('messageReactionRemove', (reaction, user) => {
console.log('a reaction has been removed');
});
Solved it with this
client.on('raw', async (packet) => {
if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
if (!(packet.d.channel_id === '800423226294796320')) return;
guild = client.guilds.cache.get(packet.d.guild_id);
if (packet.t === 'MESSAGE_REACTION_ADD') {
console.log("ADDED");
if (packet.d.emoji.name === '⭐') {
try {
member = await guild.members.fetch(packet.d.user_id);
role = await guild.roles.cache.find(role => role.name === 'star');
member.roles.add(role);
} catch (error) {
console.log(error);
}
}
}
if (packet.t === 'MESSAGE_REACTION_REMOVE') {
console.log("REMOVED");
if (packet.d.emoji.name === '⭐') {
try {
member = await guild.members.fetch(packet.d.user_id);
role = await guild.roles.cache.find(role => role.name === 'star');
member.roles.remove(role);
} catch (error) {
console.log(error);
}
}
}
});

discord.js error "channel is not defined"

So im making a mute command which creates a mute role and gives it to the mentioned user, and currently i am getting an error: channel is not defined,
I do not know how to fix this error and i need help with this
module.exports = class MuteCommand extends BaseCommand {
constructor() {
super('mute', 'moderation', []);
}
async run(client, message, args) {
if (!message.member.hasPermission("MUTE_MEMBERS")) return message.channel.send("You do not have Permission to use this command.");
if (!message.guild.me.hasPermission('MANAGE_ROLES')) return message.channel.send("I do not have Permission to mute members.");
let reason = args.slice(1).join(' ');
let roleName = 'Muted';
let muteRole = message.guild.roles.cache.find(x => x.name === roleName);
if (typeof muteRole === undefined) {
guild.roles.create({ data: { name: 'Muted', permissions: ['SEND_MESSAGES', 'ADD_REACTIONS'] } });
} else {
}
muteRole = message.guild.roles.cache.find(x => x.name === roleName);
channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });
const mentionedMember = message.mentions.member.first() || message.guild.members.cache.get(args[0]);
const muteEmbed = new Discord.MessageEmbed()
.setTitle('You have been Muted in '+message.guild.name)
.setDescription('Reason for Mute: '+reason)
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL())
.setImage(message.mentionedMember.displayAvatarURL());
if (!args[0]) return message.channel.send('You must mention a user to mute.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
if (mentionedMember.user.id == message.author.id) return message.channel.send('You cannot mute yourself.');
if (mentionedMember.user.id == client.user.id) return message.channel.send('You cannot mute me smh.');
if (!reason) reason = 'No reason given.';
if (mentionedMember.roles.cache.has(muteRole.id)) return message.channel.send('This user has already been muted.');
if (message.member.roles.highest.position <= mentionedMember.roles.highest.position) return message.chanel.send('You cannot mute someone whos role is higher and/or the same as yours');
await mentionedMember.send(muteEmbed).catch(err => console.log(err));
await mentionedMember.roles.add(muteRole.id).catch(err => console.log(err).then(message.channel.send('There was an issue while muting the mentioned Member')));
}
}
I beileive that there could be even more errors than i think in this code as I am fairly new to coding.
You have used "channel" without declaring it. Hence, it is undefined.
check your line "channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });"
const { Client, Intents } = require('discord.js')
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.channel.send('pong');
});
});
Please refer the below links
Discord.JS documentation: https://github.com/discordjs/discord.js
Stack-overflow answer: Discord.js sending a message to a specific channel

How do I make a ban, kick and clear command for my bot?

I would like to know how to make a ban, kick and clear commands for my bot. I will show you the code but before that I have been doing reasearch and nothing been working. I use node.js and i am a beginner so here's what i need you to tell me.
-The code for the command (No external links)
-How to to get the code to work.
-Where to put the code.
Okay, heres the code.
const Discord = require('discord.js');
const bot = new Discord.Client();
const { MessageEmbed } = require("discord.js");
bot.once('ready', () => {
console.log('Ready!');
});
bot.on('message', message => {
if(message.content === '!help') {
let embed = new MessageEmbed()
.setTitle("Ratchet Commands")
.setDescription("!getpizza, !shutup, !playdead, !server-info, !myname, !banhammer, !yourcreator, !annoy, !youare")
.setColor("RANDOM")
message.channel.send(embed)
}
});
bot.on('message', message => {
if (message.content === '!getpizza') {
message.channel.send('Welcome to Ratchets Pizza!!! Heres your pizza and have a nice day!!! :pizza:');
}
});
bot.on('message', message => {
if (message.content === '!shutup') {
message.channel.send('Okay, I am sorry.');
}
});
bot.on('message', message => {
if (message.content === '!server-info') {
message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
}
});
bot.on('message', message => {
if (message.content === '!myname') {
message.channel.send(`Your username: ${message.author.username}`);
}
});
bot.on('message', message => {
if (message.content === '!rocket') {
message.channel.send('3..2..1..Blast Off!!! :rocket:');
}
});
bot.on('message', message => {
if (message.content === '!youare') {
message.channel.send(`I am <#!808773656700256318>`);
}
});
bot.on('message', message => {
if(message.content === '!yourcreator') {
let embed = new MessageEmbed()
.setTitle("Ratchets Creator")
.setDescription("My creator is <#!765607070539579402>")
.setColor("RANDOM")
message.channel.send(embed)
}
});
bot.on('message', message => {
if(message.content.startsWith(`!annoy`)) {
const mentionedUser = message.mentions.users.first();
if(!mentionedUser) return message.channel.send("You have to mention someone to continue annoying someone :rofl:");
mentionedUser.send('You have a problem with me?');
message.channel.send("Annoyed " + mentionedUser + "! (Oh wait, I annoyed them 2 times!)");
}
});
module.exports = {
name: '!kick',
description: "this command kicks people",
execute(message, args){
const member = message.mentions.users.first();
if(member){
const memberTarget = message.guild.member(member);
memberTarget.kick();
message.channel.send("bing bong he is gone!");
}else{
message.channel.send('you couldnt kick that person');
}
}
}
bot.login('TOKEN');
I know I need a command handler but I don't know how to do that neither.
Thank you!!!
So first you did a very big error, you always recall the message event, optimize your code like this:
const Discord = require('discord.js');
const bot = new Discord.Client();
const { MessageEmbed } = require("discord.js");
bot.once('ready', () => {
console.log('Ready!');
});
bot.on('message', message => {
if(message.content === '!help') {
let embed = new MessageEmbed()
.setTitle("Ratchet Commands")
.setDescription("!getpizza, !shutup, !playdead, !server-info, !myname, !banhammer, !yourcreator, !annoy, !youare")
.setColor("RANDOM")
message.channel.send(embed)
if (message.content === '!getpizza') {
message.channel.send('Welcome to Ratchets Pizza!!! Heres your pizza and have a nice day!!! :pizza:');
}
if (message.content === '!server-info') {
message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
}
if (message.content === '!myname') {
message.channel.send(`Your username: ${message.author.username}`);
}
if (message.content === '!rocket') {
message.channel.send('3..2..1..Blast Off!!! :rocket:');
}
if (message.content === '!youare') {
message.channel.send(`I am <#!808773656700256318>`);
}
if(message.content === '!yourcreator') {
let embed = new MessageEmbed()
.setTitle("Ratchets Creator")
.setDescription("My creator is <#!765607070539579402>")
.setColor("RANDOM")
message.channel.send(embed)
}
if(message.content.startsWith(`!annoy`)) {
const mentionedUser = message.mentions.users.first();
if(!mentionedUser) return message.channel.send("You have to mention someone to continue annoying someone :rofl:");
mentionedUser.send('You have a problem with me?');
message.channel.send("Annoyed " + mentionedUser + "! (Oh wait, I annoyed them 2 times!)");
}
});
module.exports = {
name: '!kick',
description: "this command kicks people",
execute(message, args){
const member = message.mentions.users.first();
if(member){
const memberTarget = message.guild.member(member);
memberTarget.kick();
message.channel.send("bing bong he is gone!");
}else{
message.channel.send('you couldnt kick that person');
}
}
}
bot.login('TOKEN');
then to do a !ban #mention you can do:
if (message.content.startsWith('!ban ')) {
if (message.mentions.members.first()) {
if (!message.mentions.members.first().bannable) {
message.channel.send('I can\'t ban the specified user')
return
}
try {
message.mentions.members.first().ban()
}finally {
message.channel.send('The member was correctly banned')
}
}
}
and for a !kick
if (message.content.startsWith('!kick ')) {
if (message.mentions.members.first()) {
if (!message.mentions.members.first().kickable) {
message.channel.send('I can\'t kick the specified user')
return
}
try {
message.mentions.members.first().kick
}finally {
message.channel.send('The member was correctly kicked')
}
}
}
and finally for the clear command
if (message.content.startsWith('!clear ')) {
let toClear = args[1]
for (let i = 0; i < toClear; i++) {
m.channel.lastMessage.delete()
}
}
Hope i helped you ^^

Discord Bot selection role won't give the role to the user

This is my discord bot im working on recently, after i moved all the code to my VPS the reactionroles don't work anymore.
So for some reason every time you click the emoij it doesn't add the role to the user, i've tried a lot but nothing worked. It seems like it should work, am i missing something? When i start the bot everything seems alright, even the command works. I havn't made any mistakes in the role.id because i tried role.name aswell and entered the name in there. This didn't work either, i hope you have enough info.
The first part is the index.js and the second part is the module i used.
//This is the index.js
const Discord = require('discord.js');
const bot = new Discord.Client({partials: ["MESSAGE", "CHANNEL", "REACTION"]});
const fs = require('fs');
const prefix = '!';
bot.once('ready', () => {
console.log('Commandor is online!')
});
bot.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./Commands/').filter(file => file.endsWith('.js'))
for(const file of commandFiles){
const command = require (`./Commands/${file}`);
bot.commands.set(command.name, command)
}
bot.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 === 'reactionrole') {
bot.commands.get('reactionrole').execute(message, args, Discord, bot);
} else if (command === 'twitchandyoutube') {
bot.commands.get('twitchandyoutube').execute(message, args, Discord, bot);
} else if (command === 'games') {
bot.commands.get('games').execute(message, args, Discord, bot);
} else if (command === 'clear') {
bot.commands.get('clear').execute(message, args);
}
});
bot.login(This is my very secret token :) );
//this is the module i made.
module.exports = {
name: 'games',
description: "Select the games",
async execute(message, args, Discord, bot) {
if(message.member.roles.cache.has('794900472632836116')) {
const channel = '795030215361429565';
const rlRole = message.guild.roles.cache.find(role => role.name === "Rocket League");
const csgoRole = message.guild.roles.cache.find(role => role.name === "Counter-Strike Global Offensive");
const rl = ('<:RocketLeague:796401366804856842>');
const csgo = ('<:CSGO:796402447739912202>');
const rlEmoij = ('796401366804856842');
const csgoEmoij = ('796402447739912202');
let embed = new Discord.MessageEmbed()
.setColor('#e42643')
.setTitle('Game selection')
.setDescription(`What games do you play?
Select here which games you like to play and see the text/voice channels from.\n\n`
+ `${rl} **(** Rocket League **)**\n`
+ `${csgo} **(** Counter-Strike Global Offensive **)**`);
let messageEmbed = await message.channel.send(embed);
messageEmbed.react(rlEmoij);
messageEmbed.react(csgoEmoij);
bot.on('messageReactionAdd', async (reaction, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id == channel) {
if (reaction.emoji.name === rlEmoij) {
await reaction.message.guild.members.cache.get(user.id).roles.add(rlRole);
}
if (reaction.emoji.name === csgoEmoij) {
await reaction.message.guild.members.cache.get(user.id).roles.add(csgoRole);
}
} else {
return;
}
});
bot.on('messageReactionRemove', async (reaction, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id == channel) {
if (reaction.emoji.name === rlRole) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(rlRole);
}
if (reaction.emoji.name === csgoEmoij) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(csgoRole);
}
} else {
return;
}
});
} else {
message.channel.send("You don't have the right permissions to do this.");
}
}
}
In both events (messageReactionAdd, messageReactionRemove) you're checking if the reaction.emoji.name is rlEmoij / csgoEmoij.
But the property reaction.emoji.name is only the name of the emoji. So in your case it would be RocketLeague or CSGO. You need to get the ID: reaction.emoji.id.
Do something like this:
if (reaction.emoji.id === rlEmoij) {
await reaction.message.guild.members.cache.get(user.id).roles.add(rlRole);
}
if (reaction.emoji.id === csgoEmoij) {
await reaction.message.guild.members.cache.get(user.id).roles.add(csgoRole);
}

Categories