Discord Bot js reactions - javascript

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.

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

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

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.

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

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