Mute Role Saves To The Muted User When They Leave - javascript

Hi, I've been working on "Saving / giving the mute role to the muted user who left the server" for quite awhile now. I even tried using quick.db, but it didnt worked
Is there anything I can do to make this? I would appriciate your help!

I suggest you store your users in a JSON database with lowdb.
Example of your bot code:
const Discord = require('discord.js');
const client = new Discord.Client();
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('db.json')
const db = low(adapter)
client.once('ready', () => {
db.defaults({users: [] })
.write()
console.log('Ready!');
});
client.on('message', message => {
//when you mute a user add you multiple actions and:
db.get('users')
.push({ user: userID, muted: 'yes'})
.write()
});
You will have to create a db.json file beforehand of course.

Related

Discord bot not giving reply [duplicate]

This question already has an answer here:
message.content doesn't have any value in Discord.js
(1 answer)
Closed last month.
Can someone help me out? I'm actually stuck. This the the source code for a bot I made to send GIFs when requesed by a user in a server. The bot is online and connecting to the Discord API.
Discord bot getting online image
The bot should be activated when typed !gif , in keyword the user can type any categorie or emotion they want and the bot would get the gif.
There are no errors shown yet but the bot is still not replying.
No reply image
Bot online image
I am also getting valid reply when used the giphy api url.
const Discord = require('discord.js');
require('dotenv').config();
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("messageCreate", async (message) => {
const tokens = message.content.split(" ");
if (tokens[0] == "!gif") {
const keywords = tokens.slice(1, tokens.length).join(" ");
const url = `http://api.giphy.com/v1/gifs/search?q=tag&api_key=token&limit=5`;
const response = await fetch(url);
const result = await response.json();
const index = Math.floor(Math.random() * result.results.length);
message.channel.send(result.results[index].url);
}
});
client.login(process.env.DISCORD_BOT_TOKEN);
I tried many online fixes none worked I also tried changing version of Discord.js, node-fetch as well as dotenv but none worked.
Discord.js v14
const { Client, GatewayIntentBits, Events } = require('discord.js')
require('dotenv').config()
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
],
})
client.on(Events.MessageCreate, async (message) => {
if (message.author.id === client.user.id) return
const token = message.content.split(' ')
if (token[0] === '!gif')
message.channel.send({
content: `<#${message.author.id}>`,
files: ['https://media.tenor.com/fTTVgygGDh8AAAAM/kitty-cat-sandwich.gif'],
})
})
client.on(Events.ShardReady, () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.login(process.env.TOKEN)

How to store the ID of the user who sent a slash command and compare with user who interacted with a button in Discord.js

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 want to change nickname of discord bot

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

Is there a way to get user from mention discordjs v12?

Sorry if there are any typos, but english is not my first language.
Hi, I have a problem when I am trying to get userinfo from a mention. It works perfectly fine when I am doing the command on a non nicknamed user, but when I try on a nicknamed user, it only returns undefined.
Keep in mind that I am using WOKCommands to handle my slash commands, and the error is happening on a slash command.
Here is the code for the command:
const { MessageEmbed } = require('discord.js');
const moment = require('moment');
module.exports = {
slash: true,
testOnly: true,
description: 'En spioneringskommando.',
minArgs: 1,
expectedArgs: '<Mention>',
callback: ({ args, client, interaction }) => {
const userId = args[0].toString().replace(/[\\<>##&!]/g, "");
const guild = client.guilds.cache.get(interaction.guild_id);
const member = guild.members.cache.get(userId);
const embed = new MessageEmbed()
.setTitle("Spioneringsprogram v1.0")
.setDescription(`Bruker: ${member.user.username}`)
.setColor("RANDOM")
.addField("Kallenavn:", `${member.nickname ? `${member.nickname}` : 'Ingen'}`, false)
.addField("Ble medlem av discord:", `${moment.utc(member.user.createdAt).format('DD/MM/YY')}`, false)
.addField("Ble medlem av discord serveren:", `${moment.utc(member.joinedAt).format('DD/MM/YY')}`, false)
.setFooter(`ID: ${member.user.id}`)
.setTimestamp();
return embed;
}
}
And here is my index.js file:
require('dotenv').config();
const Discord = require("discord.js");
const WOKCommands = require('wokcommands');
const client = new Discord.Client();
const guildId = 'censored'
client.on('ready', () => {
console.log("Bot is ready!");
new WOKCommands(client, {
commandsDir: 'commands',
testServers: [guildId],
showWarns: false
});
});
Thanks for any help I can get.
since you got the command as a slash command ("slashCommand:true")
You should be using "interaction."
examples:
(interaction.user.username) // The username of the interaction's user
(interaction.user.id) // The id of the interaction's user
(interaction.user.avatarURL)// The avatar's url of the interaction's user
But you seem to be new to wokcommands, and slash commands at general, so contact me at: Glowy#8213
And i'll help you out

How to make reaction roles in discord.js?

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!

Categories