'messageCreate' keeps firing when an image is attached to the message - javascript

client.on('messageCreate', message => {
if (message.author.id === client.user.id) return;
if (message.author.bot) return;
var findChannel = message.guild.channels.cache.find(ch => ch.name === "temp-channel");
if(message.channel === findChannel) {
if(message.attachments.size > 0) {
var playerPoints = db.get(`${message.author.id}_points`);
if (!playerPoints) {
db.set(`${message.author.id}_points`, 1);
} else {
db.add(`${message.author.id}_points`, 1);
}
message.reply(`**+1 Game Point**, you now have **${db.get(`${message.author.id}_points`)}** points`)
}
}
})
For the most part, it works. But the issue is when a message is sent with an image, it repeatedly replies to the message author non-stop. What have I done wrong here?
I've been on discord.js v12 for years, but v13 changed too much..
I have tried numerous ways to attempt to stop the bot from repeatedly replying to the author, but it doesn't work.

Related

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

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;
}
}
})

Discord Bot js reactions

Coding a discord bot trying to get it to react to a user adding a reaction and then remove that user's reaction, I managed to get that working but if there is more than one message with the reactions on it, it will run that reaction as well. For reference I'm trying to make a dice rolling bot that reacts to a users reaction and then re-rolls a previously entered roll. I do apologise if there is already a question like this but I could not find it when looking.
Here is an example:
example of bot in action
This is the code
Get command
Client.on('message', message=> {
if(!message.content.startsWith(PREFIX) || message.author.bot) return;
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0].toLowerCase())
{
case "roll": case "r":
if(!args[1] || args[1].indexOf("d") == -1) return message.channel.send('Invalid Roll');
Client.commands.get('torg').RollDice(message, args, Client);
break;
}});
This is then the code it gets.
Run command
module.exports = {
name: 'torg',
description: 'Die roller for Trog',
async RollDice(message, args, client)
{
const channel = 'XXXXXXXXXXXXXXXXXXXXX';
const reRoll = '🔄';
if(!args[2])//untrained
{
var roll = DieRoller(args[1]);
}
else if (args[2] == "t" || args[2] == "T")
{
var roll = DieRoller(args[1], true);
}
let rollEmbed = await message.channel.send(roll);
rollEmbed.react(reRoll);
client.on('messageReactionAdd', async (reaction, user) =>
{
if(reaction.message.partial) await reaction.message.fetch();
if(reaction.partial) await reaction.fetch();
if(user.bot) return;
if(!reaction.message.guild) return;
if(reaction.message.channel.id == channel)
{
if(reaction.emoji.name === reRoll)
{
var newRoll = DieRoller(args[1]);
await message.channel.send(newRoll);
await reaction.users.remove(user);
}
else
{
return;
}
}
});
}
What should I do to make sure that the bot doesn't react twice when it sees two messages with reactions?
Thanks in advance to anyone who reads this and can help, I've only recently tried my hand and coding discord bots.

Discord.js counting system

so I was trying to make my own version of a counting system for my server like how other bots such as countr do it, so I made the following:
if (message.channel.id === "794733520458612736") {
const numdb = db.get("numdb");
if (message.content === numdb) {
db.add("numdb", 1);
message.react("✅");
} else if (typeof message.content === "number") {
db.set("numdb", 1);
message.channel.send(`${message.author} ruined it at **${numdb}**! The next number is **1**.`);
message.react("❌");
};
};
Yet, when I try it, it doesn't seem to work. Does anyone know what I am doing wrong?
Alright, I solved it as shown below:
if (message.channel.id === "794733520458612736") {
const numdb = db.get("numdb");
if (message.content == `${numdb}`) {
db.add("numdb", 1);
message.react("✅");
} else if (!isNaN(message.content) && message.content != `${numdb}`) {
db.set("numdb", 1);
message.channel.send(`${message.author} ruined it at **${numdb-1}**! The next number is **1**.`);
message.react("❌");
};
};
I figured out that the reason was because === checks both value and type (credit to Zsolt) and the old method I used to check if it was a number didn't work, so I switched it to isNaN.

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.

Why doesn't kicking people work using discord.js

const Discord = require("discord.js"),
bot = new Discord.Client();
let pre = "?"
bot.on("message", async msg => {
var msgArray = msg.content.split(" ");
var args = msgArray.slice(1);
var prisonerRole = msg.guild.roles.find("name", "Prisoner");
let command = msgArray[0];
if (command == `${pre}roll`) {
if (!msg.member.roles.has(prisonerRole.id)) {
roll = Math.floor(Math.random()*6)+1;
msg.reply(`You rolled a ${roll}`)
} else {
msg.reply(`HaHa NOOB, you're in prison you don't get priveleges!`)
}
}
if (command == `${pre}kick`) {
var leaderRole = msg.guild.roles.find("name", "LEADER");
var co_leaderRole = msg.guild.roles.find("name", "CO-LEADER");
if (msg.member.roles.has(leaderRole.id) ||
msg.member.roles.has(co_leaderRole.id)) {
var kickUser = msg.guild.member(msg.mentions.users.first());
var kickReason = args.join(" ").slice(22);
msg.guild.member(kickUser).kick();
msg.channel.send(`${msg.author} has kicked ${kickUser}\nReason: ${kickReason}`);
} else {
return msg.reply("Ya pleb, you can't kick people!");
}
}
})
bot.login("token").then(function() {
console.log('Good!')
}, function(err) {
console.log('Still good, as long as the process now exits.')
bot.destroy()
})
Everything works except actually kicking the person. The message sends nut it doesn't kick people. For example, when I type in ?kick #BobNuggets#4576 inactive, it says
#rishabhase has kicked #BobNuggets
Reason: inactive
But it doesn't actually kick the user, which is weird, can you help me?
Change
msg.guild.member(kickUser).kick();
to
kickUser.kick();
also, make sure the bot is elevated in hierarchy
Use kickUser.kick();
I recommend using a command handler to neaten up your code. You don't want all your commands in one .js file.
Try something like this for the Ban command itself. I use this for my Bot:
client.on("message", (message) => {
if (message.content.startsWith("!ban")) {
if(!message.member.roles.find("name", "Role that can use this bot"))
return;
// Easy way to get member object though mentions.
var member= message.mentions.members.first();
// ban
member.ban().then((member) => {
// Successmessage
message.channel.send(":wave: " + member.displayName + " has been successfully banned :point_right: ");
}).catch(() => {
// Failmessage
message.channel.send("Access Denied");
});
}
});
That should work, set the role you want to use it (cAsE sEnSiTiVe) and change !ban to whatever you feel like using. If you change all "ban"s in this to kick, it will have the same effect. If this helped you, mark this as the answer so others can find it, if not, keep looking :)

Categories