Why does my discord bot not add roles properly? - discord

I am trying to make a bot that would add a role that is in the server when a person types !join choiceOutOfVariousRoles. I am currently using discord version 12. My error message is:
fn = fn.bind(thisArg);
Although trying various techniques I could not get the code to work.
const Discord = require('discord.js');
const client= new Discord.Client();
const token = process.env.DISCORD_BOT_SECRET
client.on('ready', () => {
console.log("I'm in");
console.log(client.user.username);
});
client.on('message', msg => {
if (msg.content.toLowerCase().startsWith("!join"))
{
var args = msg.content.toLowerCase().split(" ")
console.log(args)
if (args[1] === 'sullen')
{
msg.channel.send('You have successfully joined Sullen!')
const sullenRole = msg.guild.roles.cache.find('name','Sullen')
msg.member.addRole(role.id)
}
}
});
client.login(token)
**EDIT: Fixed what everyone was saying and all I need to do now Is update the permissions, (my friend has to do that because its not my bot) and I should be all good. Thanks everyone! :D

discord.js introduces breaking changes very frequently, and v12 is no exception. You need to make sure you find up-to-date code otherwise it won't work. GuildMember#addRole was moved to GuildMemberRoleManager#add, which means you must use msg.member.roles.add(sullenRole).

Related

Trying to debug my bot but nothing shows up

Hi this is my code for my discord bot, I try to run it and it comes up without an error, even the "im alive" log comes up in console, but nothing else, thought it was my token but the bot logs in,
the only thing I can think of is the client.on but even in doc's I cant see the diffrence.
Im new to js so anybody's help is appreciated
const Discord = require("discord.js");
const client = new Discord.Client({intents: [Discord.Intents.FLAGS.GUILDS]});
const prefix = '!';
client.once('ready', () => {
console.log("I'm alive!");
});
client.on('message', message => {
console.log('asd');
if(message.content = '${prefix}hi'){
console.log('command detected');
message.channel.send('Hi ${message.author}');
}
});
client.login('my-token');
For getting the message data, you need to enable the GUILD_MESSAGES intent in your client as well as you need to go to your Discord Developer page and then in your application, go to the Bot option and the check the Message Content Intent

guildMemberAdd event not working even with intents enabled. (discord.js)

I'm trying to set up a welcome message function on my discord bot, but no matter what I do, the bot doesn't seem to be able to use guildMemberAdd. I'm aware of the new update, and as suggested I've turned on both options under Private Giveaway Intents. But it still does not work. Here is my code:
client.on('guildMemberAdd', member => {
const emb = new MessageEmbed()
.setColor('#FFBCC9')
.setTitle("new member")
.setDescription("welcome to the server!")
member.guild.channels.get('780902470657376298').send(emb);
});
I have also found an answer online suggesting to use this:
const { Client, Intents } = require("discord.js");
const client = new Discord.Client({ ws: { intents: new Discord.Intents(Discord.Intents.ALL) }});
But no matter how I write that, my bot just won't even come online unless I use const client = new Discord.Client(); with nothing in the parentheses.
With v12 coming along, in order to get your full channels list you're only able to get the cached ones in your server. Hence why you should change this line:
member.guild.channels.get('780902470657376298').send(emb);
to:
member.guild.channels.cache.get('780902470657376298').send(emb);
You passed in the intents params wrong. Here is the correct way to do it.
const { Client, Intents } = require("discord.js");
const client = new Discord.Client({ ws: { intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_MEMBERS', 'GUILD_PRESENCES'] } });
If you use this the guildMemberAdd event will emit.
Make sure you have intents turned on in the developer portal. As Shown in this image https://i.imgur.com/WfBLtXY.png.

Guild Members TImeout: Members didn't arrive in time

So I have this command that shows the riches users in a server this command worked yesterday however recently it has stopped working.
const { MessageEmbed } = require("discord.js");
const { stripIndents } = require("common-tags");
const { prefix } = require("../../botconfig.json");
const db = require('quick.db')
let bal = require('../../database/balance');
let rep = require('../../database/rep');
let work = require('../../database/works');
module.exports = {
config:{
name: "rich",
aliases: ["r"],
category: "currency",
description: "Tells who is rich",
usage: ""
},
run: async (client, message, args) => {
// Get all members of the server before doing anything
message.guild.members.fetch().then(guildMembers => {
let board = [];
for (let key of Object.keys(bal)) {
// Checks if the collection of GuildMembers contains the key.
if (guildMembers.has(key)) {
let value = Object.assign({user: guildMembers.get(key).user}, bal[key]);
board.push(value);
}
}
const emojis = [':first_place:', ':second_place:', ':third_place:', ':small_blue_diamond:', ':small_blue_diamond:']
board = board.sort((a,b) => b.balance-a.balance).splice(0, 5);
let top = board.map((x, i) => `${emojis[i]} **${x.balance.toLocaleString()}** - ${x.user.tag}`).join('\n');
let embed = new MessageEmbed()
.setColor("RANDOM")
.addField(`Richest users in **${message.guild.name}**`, `${top}`)
.setFooter('Switch Version 1.1');
return message.channel.send(embed);
}).catch(console.error)
}
}
The error code when the !rich command is used is as follows:
Guild_Members_Timeout: Members didn't arrive in time
I don't know if this is an issue within the bot or if it is an issue with discord.
Okay I have found the answer to my own problem it seems I needed to add intents to my discord bot to fetch the members.
All I did was add this line of code and it worked.
const intents = new Intents([
Intents.NON_PRIVILEGED, // include all non-privileged intents, would be better to specify which ones you actually need
"GUILD_MEMBERS", // lets you request guild members (i.e. fixes the issue)
]);
const client = new Client({ ws: { intents } });
None of my discord.js guildmember events are emitting, my user caches are basically empty, and my functions are timing out? . In this post it is explained in great detail and that helped me out a lot.TLDR:go to discord developer portal on your particular application ,go to bot , on bot permissions tick whatever is needed and copy the number.Then use this number as a constructor parameter for new Discord.Intents('insert the number here').This worked for me.

Always getting back an, "Internal Server Error," when trying to run ban command on my Discord bot

I have tried many different ways of formatting the code, however, whenever I add code so that I must provide a reasoning to ban someone, I am always given an Internal Server Error. Here is my code.
module.exports.run = async (client, message, args) => {
const member = message.mentions.members.first();
const reason = args.slice(1).join(" ")
if (!message.member.hasPermission("BAN_MEMBERS")) {
return message.reply("you lack sufficiant permissions to execute this command.");
} else if (member.hasPermission("ADMINISTRATOR")) {
message.reply("you cannot ban this member.")
}
member.ban(reason).then((member) => {
message.channel.send(`${member} has been banned.`);
});
I use a command handler, and all my other commands work fine.
first step: Define the user
let user = message.mentions.members.first() || message.guild.members.cache.get(args.join(' '));
Second step: Create embed message or normal message
const userbanned = new Discord.MessageEmbed()
.setColor('#FF0000')
.setAuthor('User Banned')
.setDescription(`**${user.user.username}#${user.user.discriminator}** is now banned from this server`)
.setFooter(`bot_name`);
Third step: Send message
user.send(`You were banned from **${message.guild.name}** by ${message.author.username}#${message.author.discriminator}`)
return user
.ban()
.then(() => message.channel.send(userbanned))
.catch(error => message.reply("ERROR"));
Try changing
member.ban().then((member) =>//
to
member.ban({reason : args.slice(1).join(' ')}).then((member) =>//

SyntaxError: Unexpected Token ':'

So it's my first ever time coding and i'm creating a discord bot. It's all been going fine until I try to run the bot.js file on commmand line (using "node bot.js")
But It just comes up with a bunch of errors.
My Code:
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`)
});
client.login(auth.token);
client.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('pong');
}
});
Question: Will you re-post you error picture? When you click on it it says the page doesn't exist.
PLEASE READ ALL BEFORE MAKING CHANGES!
First (Bad) Guess: But without the picture, I would guess (and this is not a good guess) that it's because "client.login(auth.token)" isn't at the bottom. Another guess is that ".content ===" does nothing. You should try and remove ".content" to see if it then works.
Here is your code with just that change:
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}`)
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('pong')
}
});
client.login(auth.token);
Logging bot is ready: The is also some other things I think you should change, this changing "client.user.tag" to "client.user.username" to instead show the bot's username. Another thing is "msg.content" I'm pretty sure this does nothing, and should be changed to just "===", there are some other ones, but that's my favorite one because it's the least amount of characters and easiest to type.
Here is your code with all of these changes:
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}`)
});
client.on('message', msg => {
if (msg === "ping") {
msg.reply('pong')
}
});
client.login(auth.token);
Token (& patrik's answer): (No hate to patrik) What patrik says that putting your token in the actual script will help (It won't, and makes it easier to hack), now while I do this, I really don't care if my bot gets hacked, it's in one server. He/She also says that the token error means that discord.js can't get the token, this is a node.js error, not a discord.js error. You probably messed up on writing a piece of code, that is likely in "auth.json". You should probably re-run through your files before doing any of these changes.
A auth/config/token (token file) .json file should look like this:
{
"token":"TOKEN-HERE"
}
And then it should be used by doing
const auth|config|token = require(./auth|config|token.json);
client.login(auth.token);
I hope this helps with coding your bot!
It's because the node.js version is not updated to be compatible with the new discord.js version
First, install old version of discord.js in console type
npm i discord.js.old#11.6.4
In your script change
this:
const Discord = require('discord.js')
To:
const Discord = require('discord.js.old')
Glad to see you are into making bots too!
I would firstly suggest replacing all those "client" words with "bot"
The unexpected token might be because of that above mentioned thing or that your token is not just simply there.
Remove line:
client.login(auth.token);
and replace it with:
bot.login('YOUR-TOKEN-HERE');
You can check what if your token at the Discord Developer page

Resources