Discord.js on raw event breakage - javascript

Desired outcome: Assign role to a user who reacts to message in channel. On bot restart the message if not in cache, therefore user is not assigned role.
Issue: Code stops responding after guildID = client.guilds.get(packet.d.guild_id);
client has been defined at the start of the script.
Expected output: Returns guildID and adds the role to the user who reacted.
Followed this guide
client.on('raw', packet => {
if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
if (!(packet.d.channel_id === '<CHANNEL_ID>')) return;
//console.log(packet);
guildID = client.guilds.get(packet.d.guild_id);
if (packet.t === 'MESSAGE_REACTION_ADD') {
console.log("ADDED");
if (packet.d.emoji.name === '⭐') {
try {
guildID.members.cache.get(packet.d.user_id).roles.add('<ROLE_ID>').catch()
} catch (error) {
console.log(error);
}
}
}
if (packet.t === 'MESSAGE_REACTION_REMOVE') {
console.log("REMOVED");
}
});

Try to using these alternative way to use
And guildID = client.guilds.get(packet.d.guild_id); this wrong way to get guild since discord.js v12 updated it will be guildID = client.guilds.cache.get(packet.d.guild_id);
client.on('messageReactionAdd', (reaction, user) => {
console.log('a reaction has been added');
});
client.on('messageReactionRemove', (reaction, user) => {
console.log('a reaction has been removed');
});

Solved it with this
client.on('raw', async (packet) => {
if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
if (!(packet.d.channel_id === '800423226294796320')) return;
guild = client.guilds.cache.get(packet.d.guild_id);
if (packet.t === 'MESSAGE_REACTION_ADD') {
console.log("ADDED");
if (packet.d.emoji.name === '⭐') {
try {
member = await guild.members.fetch(packet.d.user_id);
role = await guild.roles.cache.find(role => role.name === 'star');
member.roles.add(role);
} catch (error) {
console.log(error);
}
}
}
if (packet.t === 'MESSAGE_REACTION_REMOVE') {
console.log("REMOVED");
if (packet.d.emoji.name === '⭐') {
try {
member = await guild.members.fetch(packet.d.user_id);
role = await guild.roles.cache.find(role => role.name === 'star');
member.roles.remove(role);
} catch (error) {
console.log(error);
}
}
}
});

Related

Discord.js: Embed not sending

I'm trying to make a help embed command with reactions, but I keep getting this error
I'm trying to make a help embed with reactions, but when I do !help, it doesnt send the embed???
I'm trying to make a help embed command with reactions, but I keep getting this error I'm trying to make a help embed with reactions, but when I do !help, it doesnt send the embed???
This is my code:
const Discord = require('discord.js')
module.exports = {
name: 'help',
description: "Help command",
execute(message, args){
async function helpEmbed(message, args) {
const helpEmbed = new Discord.MessageEmbed()
.setTitle('Help!')
.setDescription(`**React with one of the circles to get help with a category!**`)
.addFields(
{ name: 'Moderation', value: ':blue_circle:'},
{ name: 'Fun', value: ':green_circle:'},
{ name: 'Misc', value: ':purple_circle:'},
)
.setColor(4627199)
message.channel.send({embed: helpEmbed}).then(embedMessage => {
embedMessage.react('🔵')
embedMessage.react('🟢')
embedMessage.react('🟣')
})
const msg = await sendReact()
const userReactions = message.reactions.cache.filter(reaction => reaction.users.cache.has(userId));
const filter = (reaction, user) =>{
return ['🔵', '🟢', '🟣'].includes(reaction.emoji.name) && user.id === message.author.id;
}
msg.awaitReactions(filter, { max: 1, time: 10000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '🔵') {
try {
for (const reaction of userReactions.values()) {
reaction.users.remove(userId)
}
} catch (error) {
console.error('Failed to remove reactions.')
}
message.channel.send('Moderation');
} else if (reaction.emoji.name === '🟢') {
try {
for (const reaction of userReactions.values()) {
reaction.users.remove(userId)
}
} catch (error) {
console.error('Failed to remove reactions.')
}
message.channel.send('Fun');
} else if (reaction.emoji.name === '🟣') {
try {
for (const reaction of userReactions.values()) {
reaction.users.remove(userId)
}
} catch (error) {
console.error('Failed to remove reactions.')
}
message.channel.send('Misc')
}
})
.catch(collected => {
message.reply('you reacted with neither a thumbs up, nor a thumbs down.');
});
}
}
}
You defined helpEmbed funcion but not called it.
try writing "helpEmbed()" after "execute(message, args){"
if still doesn't work:
Check bot's permission
Bot needs SEND_EMBED_LINKS Permission in that channel.

join + leave command leave is not working?

Here i have a code to join and leave but leave does not work
(join is working, leave is working too but it does crash every time when he wanna leave)
> client.on('message', async message => {
if (!message.guild) return;
if (message.content === `${config.prefix}komm`) {
message.react('☘️');
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
} else {
message.reply('Du huens geh mal erst in nen channel');
}
}
});
client.on('message', async message => {
if (!message.guild) return;
if (message.content === `${config.prefix}geh`) {
message.react('☘️');
if (!message.guild.me.voice.channel.leave()) {
message.reply("bin ja schon weg ya salame!");
message.react('☘️');
} else {
!message.reply("warte, bin nirgendwo drin!");
message.channel.send()
}
}
});
Here is your Answer :)
Based on Discord.js Guide
// Discord.js v11.
// Inside of Message Event.
if (message.content === `${config.prefix}join`) {
if (!message.guild) return;
if (message.member.voiceChannel) {
message.member.voiceChannel.join()
.then(connection => { // Connection is an instance of VoiceConnection
message.reply('I am connected');
})
.catch(console.log);
} else {
message.reply('You need to join a voice channel first!');
}
}
if (message.content === `${config.prefix}leave`) {
if (!message.guild) return;
// check if the bot is connected to a voice channel
if (message.guild.me.voiceChannel !== undefined) {
message.guild.me.voiceChannel.leave();
message.reply("Left.");
} else {
message.reply("I'm not connected to a voice channel.");
}
}
// Discord.js v12
// Async message Event and await the command.
client.on('message', async message => {
if (!message.guild) return;
if (message.content === `${config.prefix}join`) {
// Join the same voice channel of the author of the message
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
await message.channel.send("Connected."); // await message.reply("Connected.");
// REST OF YOUR CODE
}
}
if (message.content === `${config.prefix}leave`) {
if(message.guild.me.voice.channel !== undefined) {
await message.guild.me.voice.channel.leave(); // disconnect();
await message.channel.send("Left");
}
}
});

How to get old message reactions

What I'm trying to do is to get username for users who reacts on that message. It's working good but when the bot restarts only new reactions work.
how to make it send all users reactions
client.on('ready', () => {
client.guilds.get('guild_id').channels.get('chnl_id').fetchMessage('msg_id');
});
client.on('messageReactionAdd', (reaction, user) => {
const { message} = reaction;
if(message.channel.id == 'chnl_id'){
if(reaction.emoji.name === "✅") {
message.guild.fetchMember(user.id).then(member => {
if(user.bot) return;
else {
message.channel.send(reaction.users.map(u => u.username.toString()))
}
})
}}});
If you have the message, then you can filter the reaction of that message by emojis:
const reaction = await message.reactions.cache.filter(r=> r.emoji.name === '✅').first().fetch();
Then you can fetch all reactions with that specific emoji:
await reaction.users.fetch();
Then you can filter from that if you want to (for example your own bot), with:
const filteredReactions = reaction.users.cache.filter(r=> !r.bot);
And don't forget to put these in an async function.

When I react to the message my discord bot sent, it is not being picked up until I've interacted in the discord server

I am making a ticket bot and it sends a message upon startup, but once the message has been sent, nothing happens when I react to it until I've done something like send a message in the discord server. I am using Discord.JS.
I want to know if there is any possible way to cache the message or something so that I do not have to interact with the server for the reaction event to pick up my reaction.
My Startup Code:
client.on('ready', () => {
console.log(`[AUTH] Authenticated with discord!`);
client.guilds.cache.forEach(async function(dguild) {
let channel1 = dguild.channels.cache.find(channel => channel.name === 'new-ticket')
if(!channel1) {
await dguild.createChannel("actions", { type: 'text' })
channel1 = dguild.channels.cache.find(channel => channel.name === 'new-ticket')
}
const fetched1 = await channel1.messages.fetch({ limit: 100 });
channel1.bulkDelete(fetched1);
let departments1 = "";
departments(deps => deps.forEach(dep => departments1 += '``'+dep.reactionEmoji +' '+ dep.name + '`` :: ' + dep.description + '\n\n'));
let embed1 = new Discord.MessageEmbed()
.setTitle(nte.title)
.setColor(nte.color)
.addField("\u200B", nte.header)
.addField("Departments: \n", departments1)
.addField("\u200B", nte.footer);
channel1.send(embed1).then(async m => {
await departments(deps => deps.forEach(dep => m.react(dep.reactionEmoji)));
console.log(m.id +":"+channel1.id);
dguild.channels.cache.get(channel1.id).message.cache.get(m.id);
})
});
});
My Reaction Event:
client.on('messageReactionAdd', async (reaction, user) => {
if(user.id == client.user.id) return;
const userReactions = reaction.message.reactions.cache.filter(reaction => reaction.users.cache.has(user.id));
try {
for (const reaction of userReactions.values()) {
await reaction.users.remove(user.id);
}
} catch (error) {
console.error('Failed to remove reactions.');
}
departments(deps => deps.forEach(dep => {
if (reaction.emoji.name == dep.reactionEmoji) {
try {
ticket.create(user.id, dep.id, reaction.message);
console.log(dep.name + ": Ticket Opened");
} catch {
console.log('Failed to generate ticket.');
}
}
}))
});
Cheers.

discord.js reaction for play function

I am pretty sure it means message is not defined but why I think I defined it does anyone know what is the problem? I tried everything I can. it sends this error (There was an error connecting to the voice channel: TypeError: Cannot read property 'react' of undefined)
function play(guild, song, client, message) {
const serverQueue = client.queue.get(guild.id)
const loop = client.loop.get(guild.id)
console.log(loop)
if (!song) {
serverQueue.voiceChannel.leave()
client.queue.delete(guild.id)
return
}
const dispatcher = serverQueue.connection.play(ytdl(song.url))
.on('finish', () => {
if (loop === undefined) {
serverQueue.songs.shift()
}
play(guild, serverQueue.songs[0], client, message)
})
.on('error', error => {
console.log(error)
})
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5)
if (loop === undefined) {
const reaction = (reaction) => reaction.emoji.name === '⏭️';
serverQueue.textChannel.send(`Playing: **${song.title}**`)
message.react('⏭️')
.then(console.log)
.catch(console.error);
message.awaitReactions((reaction) => (reaction.emoji.name == '⏭️'),
{ max: 1 }).then(collected => {
if (collected.first().emoji.name == '⏭️') {
if(!message.member.voice.channel) return message.channel.send("You need to be in a voice channel to skip the music")
if(!serverQueue) return message.channel.send("There is nothing to playing")
serverQueue.connection.dispatcher.end()
client.loop.delete(message.guild.id)
}
return undefined
})
}
}
You are right. Inside play(<args>){...} function you try to call .react() on undefined. Could you give more context to this problem? Like the calling context to see why play(<args>){} receives no value for its 4th parameter, message.

Categories