uptill now when i was in v11.x.x i was using
my dashboard.js looks like this
const perms = Discord.EvaluatedPermissions;
renderTemplate(res, req, "dashboard.ejs", {perms});
but now perms is undefined when i updated bot to discord.js v12 and they said evaluatedPermissions has been removed entirely, see the Permissions page
what can i do to replace Discord.EvaluatedPermissions to get perms
so i can use it in my dashboard.ejs file
user.guilds.forEach(guild => {
const permsOnGuild = new perms(guild.permissions);
if(!permsOnGuild.has("MANAGE_GUILD")) return;
Try using Discord.Permissions instead of EvaluatedPermissions
const perms = Discord.Permissions
renderTemplate(res, req, "dashboard.ejs", {perms});
Related
I've recently followed a slash command tutorial from discordjs guide. It all works, but the issue is that I am unable to have the slash commands in more than 1 server, as I have manually put the guild ID in, and cannot find a way to get the guild ID when the bot is ready. Here's the code:
const clientID = '942177936553959464';
const guildID = '936781831037157426';
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientID, guildID), // Error is at guildID, as it is not getting the actual guilds ID, just the one I set for testing.
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
The way you register is a guild-specific way of registering slash commands. There are 2 routes you can take.
First - Have an array of guild IDs and loop over them and register it per guild. Something like this would work fine
const clientID = "942177936553959464";
const guilds = ["id1", "id2", "id3"];
guilds.forEach((guildID) => {
// Register the slash commands here
});
Second - Register the slash commands globally(For all guilds). Do note global commands take some time to be cached and made available by the discord API.
https://discordjs.guide/interactions/registering-slash-commands.html#global-commands
Note - The First approach should be followed while the bot is in the development stage and not in production
I want to make my bot autorole if username of anyone member contains a specific tag and the code i made isn't working, bot starts fine but didn't assign role if user have tag in username than also so i thought to use stackoverflow to get some help
Here is the code:
client.on("userUpdate", async (oldUser, newUser) => {
if (oldUser.username !== newUser.username) {
let tag = "⚡";
let server_id = "793143091350470708";
let role = "888436049620119562";
if (newUser.username.includes(tag) && !client.guilds.get(server_id).members.get(newUser.id).roles.has(role)) {
client.guilds.get(server_id).members.get(newUser.id).addRole(role)
} if (!newUser.username.includes(tag) && client.guilds.get(server_id).members.get(newUser.id).roles.has(role)) {
client.guilds.get(server_id).members.get(newUser.id).removeRole(role)
}
}
})
You would require to define USER_UPDATE, GUILD_MEMBER_UPDATE, and
PRESENCE_UPDATE intents if you are on discord.js version 13 and further enable the members and presence intent too, they can be located in the Discord Developer Portal further I would like to suggest using the Client#guildMemberUpdate listener instead since your code has nothing to do with presence you would not need the "extra" intents.
Additional Information
Directed by this comment It has come to my notice that you are using version 12 of discord.js so you would want to make adequate changes to your code for that ( your code as it currently is, is clearly written for discord.js v11) the following changes would be made in your code:
client.on("guildMemberUpdate", async (oldUser, newUser) => {
if (oldUser.username !== newUser.username) {
let tag = "⚡";
let server_id = "793143091350470708";
let role = "888436049620119562";
if (newUser.username.includes(tag) && !client.guilds.cache.get(server_id).members.cache.get(newUser.id).roles.has(role)) {
client.guilds.cache.get(server_id).members.cache.get(newUser.id).roles.add(role)
} if (!newUser.username.includes(tag) && client.guilds.cache.get(server_id).members.cache.get(newUser.id).roles.has(role)) {
client.guilds.cache.get(server_id).members.cache.get(newUser.id).roles.remove(role)
}
}
})
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.
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).
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