Moderation Log Message Discord JS - node.js

Hello StackOverflow community, this is my first question in need help with for Discord, could someone please edit this code to made this command send a log to #logs channel with the following info
1) Title - Moderation Log
2) User the moderation action was performed on
3) What moderation action was performed (in this case ban)
4) Moderator
5) Footer - Proton Servers Bot©2020
const { client, config, functions } = require('../index.js');
module.exports.run = async (message, u) => {
if (!message.member.hasPermission('BAN_MEMBERS')) return message.channel.send(functions.errorEmbed('You are not permitted to do this.'));
if (!u) return message.channel.send(functions.usageEmbed(config.prefix + 'ban <user/id>'));
const userID = u.match(/[0-9]+/) ? u.match(/([0-9]+)/)[0] : undefined;
const user = message.guild.members.get(userID);
if (!user) return message.channel.send(functions.errorEmbed('**' + u + '** is not a valid user.'));
try {
await user.ban();
return message.channel.send(functions.successEmbed('Banned ' + user + ' successfully.'));
} catch {
return message.channel.send(functions.errorEmbed('Could not ban ' + user + '. Is their role higher than mine?'));
}
}
module.exports.description = 'Ban a user.';```

This answer is for discord.js v11. If you want to do this using discord.js v12 then use MessageEmbed instead of RichEmbed and use cache to get the channels collection message.guild.channels.cache
You could use a RichEmbed to create the embed you want and then send it to the log channel.
First, though, you have to get the log channel, there are 2 ways of doing this:
By name: const logChannel = message.guild.channels.find(channel => channel.name === 'log')
Or by ID: const logChannel = message.guild.channels.get(CHANNEL_ID)
Then you could use that to send the following embed
const embed = new Discord.RichEmbed() // Or new RichEmbed depending on how you're importing things
.setTitle('Moderation Log')
.addField('Banned', user)
.addField('Banned By', message.author)
.setFooter('Proton Servers Bot©2020')
logChannel.send(embed)

Related

Discord.js get user by nickname

I'm having a hard time figuring out
Is is possible to find a user by his or her nickname via the discord.js npm package.
How can I query a user by his or her nickname?
i've tried several things but nothing returns the nickname and I can't quite figure out how their documentation works.
So far I haven't been able to tell how to do it.
I've done as so in my code.
const { Client } = require('discord.js')
const discordClient = new Client()
discordClient.on('message', message => {
if (message.author.bot) return
if (message.content.startsWith('!gpwarn')) {
// The command is something like '!gpwarn thomas'.
// If his nick name is thomas but his username is john it doesn't work.
})
Yes, and it's pretty simple. Do this:
const user = client.users.cache.find(user => user.username == "The user's name");
Reference:
UserManager
To meet your exact requirements you would search the guild members cache for the provided nickname. However, I personally would suggest using either a direct tag or a UserID for this, as multiple people can have the same nickname in the server.
const U = message.guild.members.cache.find(E => E.nickname === 'NICKNAME')
Getting by Tag:
const U = message.mentions.members.first()
Getting by ID:
const U = message.guild.members.cache.find(U => U.id === 'IDHERE')
First you need to identify the nickname argument, you can do this by splitting, slicing, and joining message.content.
Next I recommend you fetch all of the GuildMembers from the guild using GuildMemberManager#fetch(), This way you don't run into the error of a member being uncached.
Handle the promise using async/await and use Collection#find() to return the member.
const { Client } = require('discord.js')
const discordClient = new Client()
discordClient.on('message', async message => {
if (message.author.bot) return
if (message.content.startsWith('!gpwarn')) {
// Returns all of the text after !gpwarn
const query = message.content.split(' ').slice(1).join(' ').toLowerCase()
const members = await message.guild.members.fetch()
const memberToWarn = members.find(m => m.nickname.toLowerCase() === query)
if (!memberToWarn) // No member found error
console.log(memberToWarn) // [GuildMember]
}
})

How to send a message if user has the permission

Okay so, im trying to make an announce command that makes the bot say what the user asks it to write,
the command is working fine but the main problem is that i dont want users that are not moderators/admins to use this command i tried to use if (user.hasPermission("KICK_MEMBERS") but i simply don't know how to implement this into my code, (here it is)
const Discord = require('discord.js');
module.exports = {
name: 'announce',
description: "announce",
execute(message, args){
const developerEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(`failed to send message`)
.setAuthor('♥Aiko♥', 'https://i.imgur.com/1q9zMpX.png')
.setDescription('please mention the channel first(if this promblem persists contact the developer)')
.setTimestamp()
.setFooter(`©Revenge#7005 | Requested by ${message.author.tag}.`);
if(message.mentions.channels.size === 0) {
message.channel.send(developerEmbed);
}
else {
let targetChannel = message.mentions.channels.first();
const args = message.content.split(" ").slice(2);
let userMessage = args.join(" ");
targetChannel.send(userMessage);
message.delete();
}
}
}
so yeah, any ideas how to make the bot check for the permission and then send the message if the user has it?
i'm pretty new to coding and this bot is my first bigger project so sorry if this question seems stupid
Make sure to use message.member in place of user, and you should implement it at the beginning of your code.
module.exports = {
name: 'announce',
description: "announce",
execute(message, args) {
if (!message.member.hasPermisson('KICK_MEMBERS')) // if member doesn't have permissions
return message.channel.send('Insufficient Permissions');
// rest of your code...

Discord.js: Verify channel

I'm trying to make my own bot for my server, for now i'm focusing on the verify. By acting to the check mark emoji it'll add the verified role, and then it should remove only the user reaction, but instead it'll remove every reaction right away
client.on('messageReactionAdd', async (reactionReaction, user) => {
const message = reactionReaction.message;
const verifyChannel = message.guild.channels.cache.find(c => c.name === 'approvazione');
const member = message.guild.members.cache.get(user.id);
if (member.user.bot) return;
const verify = message.guild.roles.cache.get('728000975046180988');
if (reactionReaction.emoji.name === '✅' && message.channel.id === verifyChannel.id) {
member.roles.add(verify).catch(console.error);
await reactionReaction.remove(member).catch(console.error);
}
here is the message sent by the bot with it's own reaction
and here is the same message after i reacted, and both mine and the bot reaction are removed, i just want my reaction to be removed
If you look at the docs it takes no parameter for the user:
https://discord.js.org/#/docs/main/stable/class/MessageReaction?scrollTo=remove
This was changed in v12, the method now is to use .users.remove:
reactionReaction.users.remove(member);

Issues with storing discord channel ID in sqlite DB

I have a sqlite DB with a table called "guildinfo".
This is used for storing the guild ID, bot prefix, welcome message, leave message, bot message, welcome channel ID, and the starboard ID.
I created a command - ?welcome - to change welcomeChannel to the ID of the channel the command was ran in.
However, when I try to use the data I have in my DB, I get two completely different IDs.
I wrote this to test -
const info = sql.prepare(`SELECT * FROM guildinfo WHERE guild = ${message.guild.id}`)
const info2 = info.get();
console.log(This looks like ${message.guild.name} with the ID: ${message.guild.id} in: channel ID ${message.channel.id}. In the DB, we have ${info2.welcomeChannel} for this guild.)
This returns - This looks like test2 with the ID: 516761210776059906 in: 517048171084382214. In the DB, we have 517048171084382200 for this guild.
When I check the DB manually, I have 517048171084382214
I should be getting 517048171084382214 from the DB, rather than 517048171084382200.
Any help would be appreciated.
EDIT: ?welcome command -
const Discord = require("discord.js");
const bot = new Discord.Client();
const path = require('path')
const SQLite = require("better-sqlite3");
const sql = new SQLite(path.join(__dirname, '../', 'db/db55.sqlite'))
const botConfig = require(path.join(__dirname, '../', "./botConfig.json"));
const prefix = botConfig.prefix;
exports.run = async (bot, message, args) => { // This function takes three arguments, the bot (client) message (full message with prefix etc.) and args (Arguments of command
if (message.author.id !== '264850435985113088') {
return message.channel.send("You shouldn't be using this command.")
}
// Get guild ID
bot.getDefaults = sql.prepare(`SELECT * FROM guildinfo WHERE guild = ${message.guild.id}`)
bot.setDefaults = sql.prepare('INSERT OR REPLACE INTO guildinfo (guild, prefix, welcomeMsg, leaveMsg, botMsg, welcomeChannel, starboard) VALUES (#guild, #prefix, #welcomeMsg, #leaveMsg, #botMsg, #welcomeChannel, #starboard);')
const info = sql.prepare(`SELECT * FROM guildinfo WHERE guild = ${message.guild.id}`)
const info2 = info.get();
let Defaults
Defaults = bot.getDefaults.get()
if (message.guild && !Defaults) {
Defaults = {
guild: `${message.guild.id}`,
prefix: prefix,
welcomeMsg: "`Welcome to ${guild.name}, ${bot.user.username}`.",
leaveMsg: "`Bye, `${bot.user.username}!`",
welcomeChannel: `${message.channel.id}`,
botMsg: null,
starboard: null
};
bot.setDefaults.run(Defaults);
message.channel.send(`Welcome messages will now be sent to ${message.channel.id} - First condition`)
} else if (sql.prepare(`SELECT * FROM guildinfo WHERE guild = ${message.guild.id}`)) {
sql.prepare(`UPDATE guildinfo SET welcomeChannel = ${message.channel.id};`).run()
message.channel.send(`Welcome messages will now be sent to ${message.channel.id} - Second condition`)
}
}
exports.help = {
name: 'welcome' // Insert your command's name here!
}
My database looks like this -
It seems like this is an issue with how node.js numbers work.
After 9,007,199,254,740,991 which is Number.MAX_SAFE_INTEGER ( see ) node will "round" the number.
If I use node.js eval and eval 517048171084382214
It returns 517048171084382200 Type: Number.
This means you should check that:
in your database that the channelId column is string and not a number
that your SQL query doesn't convert the string to a number.

Discord.js -- make presenceUpdate send a message

im trying to get my super simple bot to send a message stating the user status. as if someone is offline, online,..etc it automatically sends a message to the server saying that happened.
im just doing a work around so it can get updated (i know i need to !status everytime)
anyone has an idea to make it send the same message instantly after presenceUpdate fires?
let userStatus = [];
bot.on("presenceUpdate", (oldMember, newMember) => {
let username = newMember.user.username;
let status = newMember.user.presence.status;
userStatus.push(username, status);
console.log(`${newMember.user.username} is now ${newMember.user.presence.status}`);
})
bot.on('message', (message) => {
// if (!message.content.startsWith(prefix)) return;
if (console.log())
let [username, status] = userStatus;
if (message.content.startsWith(prefix + "status")) {
let botembed = new Discord.RichEmbed()
.setDescription("Status Update")
.setColor("#FFF")
.addField('.............................................', `${username} is now ${status}`);
message.channel.send(botembed);
userStatus = [];
}
});
The issue I think you're running into is that you don't have a direct reference to a channel anymore, which is why you can't "easily" call <TextChannel>.send(...). You'll have to decide which channel you want to send a message to, in your presenceUpdate event listener. Once you decide, you can use this code to get a reference to that channel using the channel's name:
client.on('presenceUpdate', (oldMember, newMember) => {
// get a reference to all channels in the user's guild
let guildChannels = newMember.guild.channels;
// find the channel you want, based off the channel name
// -> replace '<YOUR CHANNEL NAME>' with the name of your channel
guildChannels.find('name', '<YOUR CHANNEL NAME>')
.send('test message!')
.then(msg => {
// do something else if you want
})
.catch(console.error)
});
Note: you don't have to use the channel's name property to identify a unique channel, you can use the channel's id by doing
guildChannels.get('<YOUR CHANNEL ID')
.send('...
Hope this helps!

Resources