I need a bot to react to a message above the user who sent the command. Right now the bot only reacts to the user who sent the command.
client.on('message', (msg) => {
if (msg.content === 'Boo Hoo') {
const reactionEmoji = msg.guild.emojis.cache.find(
(emoji) => emoji.name === 'BooHoo'
);
msg.react(reactionEmoji);
}
});
how would I modify/rewrite this code to make it react to a message above the user who sent the command? I'm thinking it might have something to do with MessageManager, and fetching messages but I don't know.
Here, use the .fetch() method:
message.channel.messages
.fetch({ limit: 2 }) // get the two latest messages in that channel (cmd and the one aaobve it)
.then((messages) => messages.last().react(reactEmoji)); // get last (second) entry and react to it
Related
I made a bot and made a command which should give a button when triggered, then when the button is clicked, the original message from the bot should be updated to "button was clicked". it does give the button but it says interaction failed. but when I click it again it then works.
and then when I run the command again, sometimes the bot just crashes, while sometimes it gives the button, after which it crashes.
I'm using discord.js V14
I've tried to make the command triggered by text and the first part works fine, but when it gets to the button part, it gets messed up. I'm still fairly new to discord.js v14 so the code is a bit of a mess.
This is the code:
client.on('messageCreate', (message) => {
if (message.author.bot) return;
if (message.content === 'test') {
let row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('test')
.setLabel('testing')
.setStyle(ButtonStyle.Primary),
);
message.channel.send({
content: 'hey there!',
components: [row]
});
}
client.on('interactionCreate', (interaction) => {
if (!interaction.isButton()) {
message.channel.send('hello gringo');
};
if (interaction.customId)
console.log(interaction);
const filter = i => i.customId === 'test' && i.user.id === '877466540679786536';
const collector = interaction.channel.createMessageComponentCollector({
filter,
time: 15000
});
collector.on('collect', async i => {
await i.update({
content: 'Button was clicked!',
components: []
});
});
collector.on('end', collected => console.log(`Collected ${collected.size} items`));
})
});
and this is the error I get:
rawError: {
message: 'Interaction has already been acknowledged.',
code: 40060
},
code: 40060,
status: 400,
method: 'POST',
url: 'https://discord.com/api/v10/interactions/1064212307045003315/aW50ZXJhY3Rpb246MTA2NDIxMjMwNzA0NTAwMzMxNTpJOGxpUEttZ2U3ZERIaW9iRXg4VkxiN2ZpREZJN2RRV2d6WW9uMUE3dXR2RFpNckI4SnliMEpCZGFEWm9qUVg0R2duS3ZTWk1UVkMyM015SWlKYk94cjU0Q3FWMVhCUFA5UDQzeWJVTzZPU09YNmZBR2NwS3MxZjRXeGgzOVAzSA/callback'
}
This is a common error in Discord.JS that occurs when you already replied to an interaction and you attempt to reply again.
From the discord.js discord server:
You have already replied to the interaction.
• Use .followUp() to send a new message
• If you deferred reply it's better to use .editReply()
• Responding to slash commands / buttons / select menus
To fix this error, you can use .followUp() to send another message to the channel or .editReply() to edit the reply as shown above.
You can see the documentation on a command interaction here
I've been working on this code for a discord bot that tracks a the voice channels of a server until a specific person joins which then the bot joins and then plays an audio. However whenever I start up my file, it keeps on saying
[nodemon] starting `node index.js`
[nodemon] clean exit - waiting for changes before restart
I have no clue why, I've looked online and I haven't seen any other people having the same issue as me, and if they did the answer didn't help.
Here is my code.
const { Client, GatewayIntentBits } = require('discord.js');
const { Lavalink } = require('discord.js-lavalink');
class MyBot {
// The Discord.js client object that represents our bot
client;
// The ID of the specific person we want to track
userIdToTrack;
// The audio file to play when the specific person joins
audioFile;
constructor(client, userIdToTrack, audioFile) {
// Save the client object and user ID and audio file for later use
this.client = "[bot token]";
this.userIdToTrack = '[discord id]';
this.audioFile = '[file name]';
}
onGuildVoiceJoin(event) {
// Get the member who just joined the voice channel
const member = event.member;
// If the member is the specific person we want to track...
if (member.id === this.userIdToTrack) {
// Get the voice channel that the member joined
const voiceChannel = event.channel;
// Join the voice channel with the bot
voiceChannel.guild.voice.channel.join();
// Play the audio file using Lavalink
lavalink.play(voiceChannel, {
track: '[file name]',
});
const client = new Client({
token: 'bot token]',
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
],
});
// Create a new instance of the Lavalink class and connect to the Lavalink nodes
const lavalink = new Lavalink({
client: client,
nodes: [
{ host: 'ratio-w', port: 2334, password: 'youshallnotpass' },
],
});
lavalink.connect();
client.on('ready', () => {
console.log('The bot is ready');
// Create a new instance of the bot, passing in the client object, user ID, and audio file
const bot = new MyBot("bot token", "user id", "file name");
// Listen for voice state update events, which are triggered when a user joins or leaves a voice channel
client.on('voiceStateUpdate', (oldState, newState) => {
// Check if the user we want to track has just joined a voice channel
if (newState.member.id === userIdToTrack && newState.channel) {
// Get the voice channel the user joined
const voiceChannel = newState.channel;
// Join the voice channel with the bot
voiceChannel.join().then(connection => {
// Play the audio file using Lavalink
lavalink.play(voiceChannel, {
track: audioFile,
});
});
}
});
client.on('messageCreate', message => {
if (message.content === 'ping') {
message.reply('hey <#user id>, you STINK!!!!111!');
}
});
client.on('messageCreate', message => {
if (message.content === 'shut up [redacted]') {
message.reply('yeah <#user id> shut up smelly');
}
});
client.on('messageCreate', message => {
if (message.content === 'stop being a nerd [redacted]') {
message.reply('<#user id> be like :nerd:');
}
});
});
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', reason.stack || reason)
// Recommended: send the information to sentry.io
// or whatever crash reporting service you use
})
client.login('[bot id]');}}}
I tried fixing any possible syntax errors, I've tried looking online but no help was found, I've properly started lavalink (I think), I've edited some of the code so that all possible parts are fixed. I've downloaded all possible directories like updating discord.js, node.js, lavalink.js, and more I think.
I want to have my Discord bot in 2 servers and I want that if someone wants to create a ticket it should create it in the category: Ticket
How can I do that?
You can get a list of all channels the client is currently handling with client.channels. On the cache of channels (which is a collection) you can use the .find() method to find the channel by its name:
client.on('message', async (message) => {
// check command, etc.
const channel = await client.channels.cache.find(
(ch) => ch.name === 'ticket',
);
console.log(channel.id);
});
I would like to know how to integrate reaction roles in my discord.js bot. I have tried the traditional methods of messageReactionAdd but it seem's very hard to make it extendable and editable, and it just became unusuable after having my bot in many guilds...
I have been trying to search for node modules that make this possible, but the only thing i found was this, and when trying to integrate it in my bot, it just made my commands and stuff no longer work, i have tried to read how to make reaction roles using that package, but at no avail, nothing worked...
I did try this:
const ReactionRole = require("reaction-role");
const system = new ReactionRole("my-token");
let option1 = system.createOption("x:697809640147105878", "697809380137107478");
let option2 = system.createOption("emoji-1:720843460158698152", "708355720436777033");
let option3 = system.createOption("pepe:720623437466435626", "703908514887761930");
system.createMessage("725572782157898450", "702115562158948432", 2, null, option1, option2, option3);
system.init();
But as i said, it made all my commands unusable...
Hope someone can help me!
You can easily implement this using the discord.js-collector package, it supports MongoDB, which is a database, so you'll no longer have to edit your bot manually!
Here's how to do it:
const { ReactionRoleManager } = require('discord.js-collector'); //We import the discord.js-collector package that'll make reaction roles possible
const { Client } = require('discord.js'); // We import the client constructor to initialize a new client
const client = new Client(); //We create a new client
const reactionRoleManager = new ReactionRoleManager(client, {
//We create a reaction role manager that'll handle everything related to reaction roles
storage: true, // Enable reaction role store in a Json file
path: __dirname + '/roles.json', // Where will save the roles if store is enabled
mongoDbLink: 'url mongoose link', // See here to see how setup mongoose: https://github.com/IDjinn/Discord.js-Collector/tree/dev/examples/reaction-role-manager/Note.md & https://medium.com/#LondonAppBrewery/how-to-download-install-mongodb-on-windows-4ee4b3493514
});
client.on('ready', () => {
console.log('ready');
});
client.on('message', async (message) => {
const client = message.client;
const args = message.content.split(' ').slice(1);
// Example
// >createReactionRole #role :emoji: MessageId
if (message.content.startsWith('>createReactionRole')) {
const role = message.mentions.roles.first();
if (!role)
return message
.reply('You need mention a role')
.then((m) => m.delete({ timeout: 1_000 }));
const emoji = args[1];
if (!emoji)
return message
.reply('You need use a valid emoji.')
.then((m) => m.delete({ timeout: 1_000 }));
const msg = await message.channel.messages.fetch(args[2] || message.id);
if (!role)
return message
.reply('Message not found!')
.then((m) => m.delete({ timeout: 1_000 }));
reactionRoleManager.addRole({
message: msg,
role,
emoji,
});
message.reply('Done').then((m) => m.delete({ timeout: 500 }));
}
});
client.login('Token');
And here's a live preview:
You can also use this package to do some other really cool stuff! Like embed paginator, questions, Yes/No Questions...
You can find them all here!
Every time I try to do that, the emoji just changes into a question mark. Here's my code:
client.on("message", async (msg) => {
if (msg.content == "*verify check") {
msg.member.setNickname(`${msg.member.displayName} ✅`);
message.react(`✅`);
}
});
Your message variable in the above code is inconsistent. You used 'msg' to catch the return value but used 'message' to react. Keep it consistent, otherwise, you might face errors. Also, a bot cannot change the nickname of the owner of the server, so if you want to test this code, make sure you are not the owner of the server where you are testing it.
bot.on('message', async message => {
if (message.content == "*verify check") {
message.member.setNickname(`${message.member.displayName} ✅`)
.catch(err => console.log(err));
message.react(`✅`);
}
});