Discord.js v12.5.3 Anyone know why this doesn't work? - javascript

EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
Code:
const discord = require('discord.js')
const newEmbed = require('embedcord')
const randomHex = require('random-hex')
module.exports = (client, message, options) => {
let links = require('./links.json')
let foundLink = false
let banReason = (options && options.banReason) || 'Sent a phishing link.'
let logs = (options && options.logs)
let member = message.mentions.members.first()
for(var i in links) {
if(message.content.toLowerCase().includes(links[i])) foundLink = true
}
if(foundLink) {
if(message.author.hasPermission('ADMINISTRATOR'))
return
message.delete()
member.ban({reason: banReason})
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
)
logs.send(embed)
}
}

Your return position might be preventing anything below if from running try changing this
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) return;
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
Or this if you want if/else
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) {
return;
} else {
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
}

EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
foundLink variable is unnecessary, you can move your code inside the loop.
Use message.member.hasPermission() instead of message.author.hasPermission().
Example code for v12.5.3(Message Event):
client.on('message', (message) => {
if (message.author.bot) return; // Ignore bot messages
const { member, channel, guild } = message; // Get the message author, channel, and guild
if (!member || !channel || !guild) return; // Ignore messages without a member, channel or guild
const { links } = require('./links.json'); // Get links from json file
for (let i = 0; i < links.length; i++) { // Check if the message contains a link in the links.json file
if (message.content.toLowerCase().includes(links[i])) { // If the message contains a link
if (member.hasPermission('ADMINISTRATOR')) return; // If the member has the administrator permission, don't ban them
const banReason = 'Sent a phishing link'; // Reason for the ban
message.delete(); // Delete the message
guild.member(member).ban({ reason: banReason }); // Ban the member
channel.send(`${member.displayName} has been banned for sending a phishing link.`) // Send a message to the channel
break;
}
}
})

Related

Discord.js bot was working, added one extra command and everything broke. Can anyone help me figure out why?

Tried to venture in to the realm of making discord bots. Followed along with a fairly simple tutorial, tweaking it along the way to fit what I was trying to make. The bot originally worked, but I went back in to add the "Mistake" command, and suddenly it's not working. I added in console.log pretty much everywhere, trying to figure out how far everything was getting.
When I start the bot, it will spit out the "Bot Online" log. When I input a command, it will spit out the "Commands" log, but it won't register the command at all. I've tried looking for any minor typos, missing brackets, etc... but I just can't seem to figure out what's gone wrong. I'm hoping that someone here can help! Thank you!
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
const SQLite = require('better-sqlite3');
const sql = new SQLite('./scores.sqlite');
client.on('ready', () => {
console.log('Bot Online');
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'goals';").get();
if (!table['count(*)']) {
sql.prepare('CREATE TABLE goals (id TEXT PRIMARY KEY, user TEXT, guild TEXT, goals INTEGER);').run();
sql.prepare('CREATE UNIQUE INDEX idx_goals_id ON goals (id);').run();
sql.pragma('synchronous = 1');
sql.pragma('journal_mode = wal');
}
//Statements to get and set the goal data
client.getGoals = sql.prepare('SELECT * FROM goals WHERE user = ? AND guild = ?');
client.setGoals = sql.prepare('INSERT OR REPLACE INTO goals (id, user, guild, goals) VALUES (#id, #user, #guild, #goals);');
});
client.on('message', (message) => {
if (message.author.bot) return;
let goalTotal;
if (message.guild) {
goalTotal = client.getGoals.get(message.author.id, message.guild.id);
if (!goalTotal) {
goalTotal = {
id: `${message.guild.id}-${message.author.id}`,
user: message.author.id,
guild: message.guild.id,
goals: 0,
};
}
}
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
console.log('Commands');
if (command === 'Goals') {
console.log('Goals');
return message.reply(`You Currently Have ${goalTotal.goals} Own Goals.`);
}
if (command === 'OwnGoal') {
console.log('Own Goal');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
userscore = {
id: `${message.guild.id}-${user.id}`,
user: user.id,
guild: message.guild.id,
goals: 0,
};
}
userscore.goals++;
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} has betrayed his team and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Mistake') {
console.log('Mistake');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
return message.reply('This person has no Rocket Bot activity.');
}
if (userscore === 0) {
return message.reply('This player currently has no goals.');
}
if (userscore > 0) {
userscore.goals--;
}
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} was falsely accused and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Leaderboard') {
console.log('Leaderboard');
const leaderboard = sql.prepare('SELECT * FROM goals WHERE guild = ? ORDER BY goals DESC;').all(message.guild.id);
const embed = new Discord.MessageEmbed()
.setTitle('Rocket Bot Leaderboard')
.setAuthor(client.user.username, client.user.avatarURL())
.setDescription('Total Goals Scored Against Own Team:')
.setFooter('Rocket Bot')
.setThumbnail('https://imgur.com/a/S9HN4bT')
.setColor('0099ff');
for (const data of leaderboard) {
embed.addFields({
name: client.users.cache.get(data.user).tag,
value: `${data.goals} goals`,
inline: true,
});
}
return message.channel.send({ embed });
}
if (command === 'RocketHelp') {
console.log('Help');
return message.reply(
'Rocket Bot Commands:' +
'\n' +
'!Goals - See How Many Goals You Have Scored Against Your Own Team' +
'\n' +
'!OwnGoal - Tag Another Player With # To Add One To Their Total' +
'\n' +
'!Mistake - Tag Another Player With # To Subtract One From Their Total' +
'\n' +
'!Leaderboard - Show The Current Leaderboard'
);
}
});
client.login(config.token);
You are improperly splitting the message content. You added g to the regex by accident.
Correct line:
const args = message.content.slice(config.prefix.length).trim().split(/ +/);
Because of improper args split, it could not find any command at all, hence no console log was invoked after Commands.

Discord JS self nickname command

hello guys iam trying to make self role and nickname change command but its not working i dont know where is the problem i earn the role but name not changing can someone tell me what is wrong on my code
client.on('message', (message,member )=> {
if (message.content.toLowerCase() === '*Test') {
if(!message.channel.guild) return;
message.member.addRole(message.guild.roles.find(role => role.name === "Test"));
let member = message.member; //message.guild.members.cache.get(user.id);
let nick = "[PRO] "
// message.guild.member(r=>r.setNickname(nick + r.user.username));
member.setNickname(nick + member.user.username);
}
});
To set Discord nickname. You can use message.member.setNickname("new member") .
as example :
if you want to create #setnick [nickname] and [nickname] is your args.
and you can use this example with role for member
client.on('message', async message => {
let messageArray = message.content.split(" ");
let args = messageArray.slice(1);
var argresult = message.content.split(` `).slice(1).join(' ');
if(message.channel.type === "dm" || message.author.bot) return;
if(message.content.toLowerCase().startsWith('#setnick')) {
if(!message.guild.me.hasPermission('MANAGE_NICKNAMES')) return message.reply('I dont have Permission to do this action.!');
try {
if(!args[0]) {
message.member.setNickname(message.author.username)
} else {
message.member.setNickname(argresult, "Member wants to change nickname")
}
} catch(error) {
return console.error('[ SET_NICKNAME ] Error')
}
}
})

roles are not being changed for the mentioned user

When a staff does !mute #user time , it should give the role Muted and take away the role Speaker, this does not happen though, instead everything else happens and the roles are not given or taken away.
const Discord = require('discord.js');
const bot = new Discord.Client();
const ms = require('ms');
const token = '';
const PREFIX = '!';
bot.on('ready', () => {
console.log('This bot is active!');
})
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'mute':
if(!message.member.hasPermission("MUTE_MEMBERS")) return message.reply("You cannot run this command");
let mperson = message.guild.member(message.mentions.users.first() || message.guild.members.cache.get(args[1]));
if(!mperson) return message.reply("I cannot find the user " + mperson)
var mainrole = message.guild.roles.cache.get("718166462862196777");
var muterole = message.guild.roles.cache.get("717606607910993930");
if(!muterole) return message.reply("Couldn't find the mute role.")
let time = args[2];
if(!time){
return message.reply("You didnt specify a time!");
}
mperson.roles.add(mainrole).catch(console.error)
mperson.roles.remove(muterole).catch(console.error);
message.channel.send(`${mperson.user} has now been muted for ${ms(ms(time))}`)
setTimeout(function(){
mperson.roles.add(mainrole)
mperson.roles.remove(muterole);
console.log(muterole)
message.channel.send(`${mperson.user} has been unmuted.`)
}, ms(time));
break;
}
});
bot.login(token);
The roles that I want to add and remove from the mentioned player do not change, any way that I can fix this?
I changed mperson.roles.add(mainrole).catch(console.error) to mperson.roles.add("717631710761844757").catch(console.error) and now everything works. This is discord.js v12.

Discord js check reaction user role

I am trying to close a ticket by reacting to a button. But reaction must be given by "support" role. I couldnt do it. reaction.message.member.roles.has is not helping me at this point. Here is my code ;
client.on("messageReactionAdd", (reaction, user) => {
if(reaction.message.member.roles.has('ROLE')) {
let id = user.id.toString().substr(0, 4) + user.discriminator;
let chan = `ticket-${id}`;
const supchan = reaction.message.guild.channels.find(
(channel) => channel.name === chan
);
const chan_id = supchan ? supchan.id : null;
if (
reaction.emoji.name === "🔒" &&
!user.bot &&
user.id != "ID"
) {
reaction.removeAll();
const channel = client.channels.find("name", chan);
const delMsg = new Discord.RichEmbed()
.setColor("#E74C3C")
.setDescription(`:boom: Ticket will be deleted in 5 seconds.`);
channel.send(delMsg).then(() => {
var counter = 0;
const intervalObj = setInterval(() => {
counter++;
if (counter == 5) {
const message = reaction.message;
message.delete();
Thanks for helps !
All of this wrapped inside the messageReactionAdd event
// Replace "message_id" with the proper message id
// Checks if it's the correct message
if (reaction.message.id == "message_id") {
// Check if author of ticket message is from the same user who reacted
if (reaction.message.author == user) {
// Check correct emoji
if (reaction.emoji.name == "🔒") {
// Code to close ticket
}
}
}
EDIT:
Again, this would be wrapped inside the messageReactionAdd event:
// Try to get the ticket message
// If there's none then the user was never opened a ticket so we simply return the code
const ticketMessage = client.tickets.get(user);
if (!ticketMessage) return;
// Checks if it's the correct message
if (reaction.message.id == ticketMessage.id) {
// Check correct emoji
if (reaction.emoji.name == "🔒") {
// Code to close ticket
}
}
I removed the code that check for the reaction message author because getting ticketMessage already handles that. Do note that this means you can make sure a user can only open one ticket.

Return message after mention

I want to code a game for a Discord bot and I have a little problem with this code:
(async function() {
if (command == "rps") {
message.channel.send("**Please mention a user you want to play with.**");
var member = message.mentions.members.first()
if (!member) return; {
const embed = new Discord.RichEmbed()
.setColor(0xffffff)
.setFooter('Please look in DMs')
.setDescription(args.join(' '))
.setTitle(`<#> **Do you accept** <#>**'s game?**`);
let msg = await message.channel.send(embed);
await msg.react('✅');
await msg.react('❎');
}
}
})();
I want to EmbedMessage return after mention member. Like this:
User: rps
Bot: Please mention a user
User: mention user
Bot: embed
You can use TextChannel.awaitMessages():
(async function() {
if (command == "rps") {
message.channel.send("**Please mention a user you want to play with.**");
let filter = msg => {
if (msg.author.id != message.author.id) return false; // the message has to be from the original author
if (msg.mentions.members.size == 0) { // it needs at least a mention
msg.reply("Your message has no mentions.");
return false;
}
return msg.mentions.members.first().id != msg.author.id; // the mention should not be the author itself
};
let collected = await message.channel.awaitMessages(filter, {
maxMatches: 1,
time: 60000
});
// if there are no matches (aka they didn't reply)
if (collected.size == 0) return message.edit("Command canceled.");
// otherwise get the member
let member = collected.first().mentions.members.first();
const embed = new Discord.RichEmbed()
.setColor(0xffffff)
.setFooter('Please look in DMs')
.setDescription(args.join(' '))
.setTitle(`<#> **Do you accept** <#>**'s game?**`);
let msg = await message.channel.send({
embed
});
await msg.react('✅');
await msg.react('❎');
}
})();

Categories