I want to change the name of a discord bot and I have read numerous tutorials and Stack Overflow posts and I still cannot get it. The code is primarily taken from open source bot code, so I know it works (something with my bot setup maybe?)
As I understand it, this code loops through each guild the bot is a member of and sets the nickname.
I found the botId by right clicking the bot in the channel and copying ID.
const { guildId } = require('../config');
module.exports = (client, botId, nickname) => {
client.guilds.cache.forEach((guild) => {
const { id } = guild;
client.guilds.cache
.get(id)
.members.cache.get(botId)
.setNickname(nickname);
});
};
The bot shows up in the channel (after using oauth2 url), so I'm assuming that means they are a member of the guild.
However, when running this code the bot is not found. I've tried several things from other posts like guild.array() to try and see a full list of the members in the guild, but nothing has worked.
const guild = client.guilds.cache.get('943284788004012072');
const bot = guild.members.cache.get('956373150864642159')
if (!bot) return console.log('bot not found');
Here is the full bot
require('dotenv').config();
const { Client, Intents } = require('discord.js');
const eventBus = require('../utils/events/eventBus');
const setNickname = require('../utils/setNickname');
const getPrice = require('../modules/statsGetters/getPriceDEX');
const { bots } = require('../config');
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
client.once('ready', async () => {
console.log('DEX Price Watch Bot Ready');
client.user.setPresence({
activities: [{ name: 'DEX Price', type: 'WATCHING' }],
status: 'online',
});
const price = await getPrice();
setNickname(client, bots.priceDEX, price);
eventBus.on(drip.update, async () => {
const price = await getPrice();
setNickname(client, bots.priceDEX, price); //update price in config file
});
});
client.login(process.env.DISCORD_PRICE_DEX);
This is the sample of changing bot's nickname for every guild that bot joined
client.guilds.cache.forEach((guild) => { //This is to get all guild that the bot joined
const nickname = args.slice(0).join(" ") //You wanted to change nickname
guild.me.setNickname(nickname); //setting the nickname of your bot
});
I believe you're doing it wrong.
Docs: https://discord.js.org/#/docs/discord.js/stable/class/GuildMember?scrollTo=setNickname
I would suggest using this module code:
const { guildId } = require('../config');
module.exports = (client, nickname) => {
client.guilds.cache
.get(guildId).me.setNickname(nickname);
};
And use it in this way in your main bot code: setNickname(client, price)
Edit:
Oh wait, I just realised you didn't use the correct intents (guild members), so you definitely need to use guild.me (as written above by me) or use guild.members.fetch() as it fetches members which aren't cached.
More info: https://discord.js.org/#/docs/discord.js/stable/class/GuildMemberManager?scrollTo=fetch
Related
I'm using the following code to create a quick database to store the ID of the user who called a bot via a slash command. I then want to compare this ID with the ID of the person interacting with the bot. My aim is to prevent anyone but the user that called the bot being able to interact with it.
The following code works but it's temperamental in that it fails without a clear reason on occasion (i.e. it returns the error which states that the person interacting isn't the person who sent the slash command even if they are).
I'm new to discord.js and quick.db tables so I'm hoping someone more competent than me has a better way of achieving this.
const { Client, Intents, MessageEmbed, MessageActionRow, MessageButton } = require('discord.js'),
client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES ] });
client.db = require("quick.db");
var quiz = require("./quiz.json");
client.login(config.token);
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
if ([null, undefined].includes(client.db.get(`quiz`))) client.db.set(`quiz`, {});
if ([null, undefined].includes(client.db.get(`quiz.spawns`))) client.db.set(`quiz.spawns`, {});
});
client.on('messageCreate', async (message) => {
if (!message.content.startsWith(config.prefix)) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift();
if (command == "unlock") {
message.delete();
const m = await message.channel.send(getMMenuPage());
client.db.set(`quiz.spawns.m${m.id}`, message.author.id);
}
});
client.on('interactionCreate', async (interaction) => {
if (interaction.isButton()) {
if (client.db.get(`quiz.spawns.m${interaction.message.id}`) != interaction.user.id) return interaction.reply(getMessagePermissionError(client.db.get(`quiz.spawns.m${interaction.message.id}`)));
const q = quiz;
Please let me know if you need more information.
Thanks.
Instead of using:
const db = require("quick.db");
You should be using:
const { QuickDB } = require("quick.db");
const db = new QuickDB();
Other than that I haven't see any problems.
I have been trying to fetch the list of all members in my guild using the syntax as mentioned in the docs here. But am not receiving any output. Below is the code that I am using.
const { Client, Intents, Guild } = require("discord.js");
require("dotenv").config();
const commandHandler = require("./commands");
const fetch = require("node-fetch");
const client = new Client({
intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_PRESENCES"],
});
client.once("ready", async (data) => {
console.log("Ready!");
console.log(`Logged in as ${client.user.tag}!`);
const Guilds = client.guilds.cache.map((guild) => guild);
console.log(Guilds[0]);
await Guilds[0].members.fetch().then(console.log).catch(console.error);
});
client.on("interactionCreate", async (interaction) => {
if (!interaction.isCommand()) return;
if (interaction.commandName === "ping") {
await interaction.reply(client.user + "💖");
}
});
client.on("messageCreate", commandHandler);
client.login(process.env.BOT_TOKEN); // Kushagra's bot
I am getting the information on Guild instance through the console.log on line 13. But do am not getting any output for line 15.
However, I noticed that I was getting some output if I add options to fetch() command on line 14. I received some output when I added {query: 'random text'}.
Just wanted to understand why I am unable to get a list of all members.
Thanks!🙂
I found that I had missed out on the Intent.
It seems that in order to fetch members you need to add an intent GUILD_MEMBERS while creating a client instance.
So replacing the client creation with the one below will work.
const client = new Client({
intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_PRESENCES", "GUILD_MEMBERS"]
});
I would like to know how to integrate reaction roles in my discord.js bot. I have tried the traditional methods of messageReactionAdd but it seem's very hard to make it extendable and editable, and it just became unusuable after having my bot in many guilds...
I have been trying to search for node modules that make this possible, but the only thing i found was this, and when trying to integrate it in my bot, it just made my commands and stuff no longer work, i have tried to read how to make reaction roles using that package, but at no avail, nothing worked...
I did try this:
const ReactionRole = require("reaction-role");
const system = new ReactionRole("my-token");
let option1 = system.createOption("x:697809640147105878", "697809380137107478");
let option2 = system.createOption("emoji-1:720843460158698152", "708355720436777033");
let option3 = system.createOption("pepe:720623437466435626", "703908514887761930");
system.createMessage("725572782157898450", "702115562158948432", 2, null, option1, option2, option3);
system.init();
But as i said, it made all my commands unusable...
Hope someone can help me!
You can easily implement this using the discord.js-collector package, it supports MongoDB, which is a database, so you'll no longer have to edit your bot manually!
Here's how to do it:
const { ReactionRoleManager } = require('discord.js-collector'); //We import the discord.js-collector package that'll make reaction roles possible
const { Client } = require('discord.js'); // We import the client constructor to initialize a new client
const client = new Client(); //We create a new client
const reactionRoleManager = new ReactionRoleManager(client, {
//We create a reaction role manager that'll handle everything related to reaction roles
storage: true, // Enable reaction role store in a Json file
path: __dirname + '/roles.json', // Where will save the roles if store is enabled
mongoDbLink: 'url mongoose link', // See here to see how setup mongoose: https://github.com/IDjinn/Discord.js-Collector/tree/dev/examples/reaction-role-manager/Note.md & https://medium.com/#LondonAppBrewery/how-to-download-install-mongodb-on-windows-4ee4b3493514
});
client.on('ready', () => {
console.log('ready');
});
client.on('message', async (message) => {
const client = message.client;
const args = message.content.split(' ').slice(1);
// Example
// >createReactionRole #role :emoji: MessageId
if (message.content.startsWith('>createReactionRole')) {
const role = message.mentions.roles.first();
if (!role)
return message
.reply('You need mention a role')
.then((m) => m.delete({ timeout: 1_000 }));
const emoji = args[1];
if (!emoji)
return message
.reply('You need use a valid emoji.')
.then((m) => m.delete({ timeout: 1_000 }));
const msg = await message.channel.messages.fetch(args[2] || message.id);
if (!role)
return message
.reply('Message not found!')
.then((m) => m.delete({ timeout: 1_000 }));
reactionRoleManager.addRole({
message: msg,
role,
emoji,
});
message.reply('Done').then((m) => m.delete({ timeout: 500 }));
}
});
client.login('Token');
And here's a live preview:
You can also use this package to do some other really cool stuff! Like embed paginator, questions, Yes/No Questions...
You can find them all here!
I'm making a warn command and I've run into a problem with the role giving. First, I have a command that sets the warned role for the guild. It reacts to &setwarnedrole {role ID}. It saves the role ID into a JSON file, next to the guild ID. Then, the warn command reads the file, and gets the role ID that was stored with the guild ID the command is executed in. You use &warn {user ping/user ID} to warn people. But when I do that, it gives me an error:
TypeError [INVALID_TYPE]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes.
My code for &setwarnedrole:
const { DiscordAPIError } = require("discord.js");
const Discord = require('discord.js');
const fs = require("fs");
let warnedRoleList = JSON.parse(fs.readFileSync("./roleIDs/warnedRole.json", "utf-8"));
module.exports = {
name: 'setwarnedrole',
description: "Set the warned role for your guild with this command",
execute(message, args){
const fs = require("fs");
let warnedRoleList = JSON.parse(fs.readFileSync("./roleIDs/warnedRole.json", "utf-8"));
if (!message.member.hasPermission("MANAGE_GUILD")) return message.reply("you are missing the manage server permissions")
let guildID = message.guild.id;
const warnedRole = message.guild.roles.cache.get(args[0]);
const warnedRoleID = warnedRole.id
if (!warnedRole) {
return message.reply('invalid role ID')
};
message.reply(`warned role succesfully set to ${warnedRole}`)
if(!warnedRoleList[guildID])warnedRoleList[guildID] = {
warnedRoleList: warnedRoleID
};
fs.writeFile("./roleIDs/warnedRole.json", JSON.stringify(warnedRoleList), err => {
if (err) console.log(err)
});
console.log(`Warned role ID = ${warnedRoleID}`)
console.log(`Guild ID = ${guildID}`)
}
}
My code for &warn:
const { DiscordAPIError } = require("discord.js");
const Discord = require('discord.js');
const fs = require("fs");
let warnedRoleList = JSON.parse(fs.readFileSync("./roleIDs/warnedRole.json", "utf-8"));
const commands = require("./commands");
module.exports = {
name: 'warn',
description: "The bot will warn the mentioned user",
execute(message, args){
let warnedRoleList = JSON.parse(fs.readFileSync("./roleIDs/warnedRole.json", "utf-8"));
let guildID = message.guild.id;
if(message.member.permissions.has('MANAGE_MESSAGES')){
var role = message.guild.roles.cache.get(`${warnedRoleList[guildID]}`);
var member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if(!member) {
message.reply('please specify the user that should be warned')
return
}
if(!role) {
message.reply('there is not a role set as the warned role, set it by doing &setwarnedrole (that requires manage server permissions)')
}
if (member.roles.cache.has(`${warnedRoleList[guildID]}`)) {
message.reply('this user is already warned!')
} else
member.roles.add(role)
.then(memberAdded => {
message.channel.send(`${member.displayName} was succesfully warned by ${message.author.tag}`);
})
.catch(error => {
console.log(error);
});
} else message.reply(`you don't have permissions to execute this command.`);
console.log(`${role}`)
console.log(`${warnedRoleList[guildID]}`)
}
}
and finally, this is how the role ID is saved with the guild ID in the JSON file:
{"745376827324760245":{"warnedRoleList":"751119465868951643"}}
with the first number being the guild ID and the second number being the warned role ID. But even if I remove the "" sign, making it:
{"745376827324760245":{"warnedRoleList":751119465868951643}}
it still doesn't work. The warn command works if I set role to a specific number. Also, logging role tells that role = undefined. Trying to log warnedRoleList[guildID] results into getting [objectObject]. What have I done wrong? Thanks :)
Ok, I found the mistake. I was setting the role in &warn to message.guild.roles.cache.get(`${warnedRoleList[guildID]}`);, but it is supposed to be message.guild.roles.cache.get(`${warnedRoleList[guildID].warnedRoleList}`);. Case closed.
So I am trying to make a raffle command for my discord bot. I kinda have two questions I am trying to make it have a winner based on who reacted to that message here is what I have so far
const discord = require("discord.js")
const bot = new discord.Client();
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission("MANAGE_CHANNELS")) return message.reply("sorry you dont have permission to use this command"); {
const embed = new discord.RichEmbed()
.setTitle('Raffle')
.addField('React to the message with a thumbs up to enter!', "Time for some fun!")
message.channel.send(embed).then(function (message) {
message.react('👍')
});
bot.on('messageReactionAdd', (reaction, user) => {
const user1 = reaction.random
const embed1 = new discord.RichEmbed()
.setTitle('Winner!!')
.addField(`${user1}`, "you are the winner!!")
message.channel.send(embed1);
});
}
}
module.exports.help = {
name: "Raffle",
name: "raffle"
}
So user1 keeps returning undefined thanks in advance and by the way I am semi new to JavaScript
In your code, you set user1 to reaction.random:
const user1 = reaction.random
reaction.random isn't a valid method of MessageReaction, and therefore, when you send the message, user1 is undefined.