How to react on a specific message? - javascript

Hey I have an Embed and I want that my Bot reacts with a Custom Emoji to it, but when I try it with my example of Code The bBot will react to every message that is send. Here's my Code:
bot.on("message", (message) => {
if (message.content.startsWith(prefix + "set")) {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('React to gain acess to the Role "Test"')
.setAuthor('Name')
.setThumbnail('123')
.setTimestamp()
.setFooter('Name');
message.channel.send(exampleEmbed);
if (message.channel.send(exampleEmbed)) {
message.react('123')
}
}
})
The last part is very confusing I know but I tried everything, even this :-)

There is something that you should note. When you are attempting to react, you don't define a message. This will give you an error because the bot's trying to react to a message that doesn't exist (To the bot) and isn't defined. I've added some code below that takes the sent message and reacts on it
message.channel.send(exampleEmbed)
.then(m => m.react('123'));
This method takes the Message Promise given from the sent message and reacts to said message

Related

Getting the channel name in discord.js

I'm trying to specify the channel my discord bot is posting in using the following code:
client.on("message", message => {
if message.content.includes("?chan") {
const channel = client.channels.cache.get('CHANNEL_ID_HERE')
console.log(channel)
channel.send("pong")
}
})
Upon sending the message "?chan", I want the discord bot to print whatever "channel" contains into the console, as well as send the message "pong" to the specified channel. It does neither of these things, and I'm not sure why. Also the rest of the code runs fine, including the parts with code from discord.js.

Discord.js bot Cannot read property 'send' of undefined

I am trying to implement for my discord server and my discord bot a possibility to send a PM message to a lot of users.
I created something like this:
client.on("message", message => {
mentiondm = message.mentions.users.first();
mentionMessage = message.content.slice(22)
mentiondm.send(mentionMessage);
console.log('Message Sent!')
})
It's working for first mentioned user, message is sending but there are several problems:
after sending first message bot is crashing down with this error Cannot read property 'send' of undefined
I tried to change message.mentions.users to message.mentions.roles but then message is not sending.
There is a way to do my functionality better or at least upgrade this what I have here to working properly?
It's because it tries to get the first mentioned user from the bot's message too. Check if the message author is a bot and if it is, don't send the message.
Also, try to check if there is someone mentioned and if not, simply return.
client.on('message', (message) => {
if (message.author.bot) return;
let mentionDM = message.mentions.users.first();
if (!mentionDM)
return console.log('No mentioned user');
let mentionMessage = message.content.slice(22);
mentionDM.send(mentionMessage);
console.log('Message Sent!');
});

Discord bot log

So, I created a discord.js bot and added the following into index.js:
client.on("guildCreate", guild = {
const logsServerJoin = client.channels.get('757945781352136794');
console.log(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`);
client.channels.cache.get('channel id paste here').send(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`);
var guildMSG = guild.channels.find('name', 'general');
if (guildMSG) {
guildMSG.send(` Hello there! My original name is \`Bryant\`!\n\ This bot created by **R 1 J 4 N#7686**\n\ For more info
type \`/help\`!\n\ \`Bryant - Official Server:\`
https://discord.gg/UsQFpzy`);
} else {
return;
}
});
// Logs of the bot leaves a server and changed the game of the bot
client.on("guildDelete", guild = {
client.channels.cache.get('757945781352136794').send(`The bot just
left ${guild.name}, Owned by ${guild.owner.user.tag}`);
console.log(`The bot has been left ${guild.name}, Owned by ${guild.owner.user.tag}`);
logsServerLeave.send(`The bot has been left ${guild.name}, Owned by ${guild.owner.user.tag}`);
});
It does not show any error in the terminal. It is supposed to log me where the bot joined and left in the mentioned channel but does not 🤷‍♂️. Can anyone help me out with this?
If you are getting no console log and no message in the channel / an error telling you that the channel could not be found, the issue is most likely in how you are registering the events, make sure client is an instance of the discord.js Client, below is a minimal working example
const { Client } = require("discord.js")
const client = new Client()
client.on("guildCreate", guild => {
console.log(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`)
})
client.login("yourtoken")
If you are trying to get the logs from your bot alert you in your home discord server you can do this multiple ways: Getting the channel from cache, Constructing the channel or Using webhooks. Currently you are trying to fetch the channel from cache. Although a decent solution it can fall down when using sharding later down the line. Personally I prefer webhooks as they are the easiest and most isolated.
Channel from cache
This technique is very similar to the way you were doing it.
const channel = client.channels.cache.get('757945781352136794')
channel.send('An Event occurred')
Just place this code anywhere you want to log something and you'll be fine.
Constructing the channel
const guild = new Discord.Guild(client, { id: '757945781352136794' });
const channel = new Discord.TextChannel(guild, { id: '757945781352136794' });
channel.send('An Event occurred')
This method is similar to fetching the channel from cache except it will be faster as you are constructing your home guild and channel and then sending to it. Mind you will need a client which you can get from message.client
Webhooks
My Favourite method uses webhooks. I recommend you read up on how discord webhooks work in both Discord and Discord.js
You will also need to create a webhook. This is very easy. Go into the channel you want the webhooks to be sent to and then go to integrations and create a new webhook. You can change the name and profile as you wish but copy the url and it should look something like this:
https://discord.com/api/webhooks/757945781352136794/OkMsuUHwdStR90k7hrfEi5*********
The last part of the path is the webhook token and the bit before is the channel ID
I recommend you create a helper function that can be called like this:
sendWebhook('An event occurred');
And then write the function to create and then send to the webhook
function sendWebhook(text) {
const webhook = new Discord.WebhookClient('757945781352136794', 'OkMsuUHwdStR90k7hrfEi5*********');
webhook.send(text);
webhook.destroy();
}
This will not be very dynamic and will be a pain to change the channel but for constant logging ( like guild joins and leaves ) I think it is the best solution
The problem is probably that you don't have "Privileged Gateway Intents" enabled. To turn them on, go to https://discord.com/developers, click on your application, then on "Bot" then scroll down and enable "PRESENCE INTENT" and "SERVER MEMBERS INTENT" and save. It should probably work for you now.

how to detect an embed and then resend it (discord.js)

so what i am trying to do is detect when a bot sends an embed in a channel, and when it does detect this, to take that embed and resend it the same as it was sent as.
For example, if the bot detects an embed sent in one channel, it will send that exact same embed in another channel. But the reason for this is because I want to take the embeds from multiple bots.
in discordjs.guide it says to use this code:
const receivedEmbed = message.embeds[0];
const exampleEmbed = new Discord.MessageEmbed(receivedEmbed).setTitle('New title');
channel.send(exampleEmbed);
but this has not worked for me
You need to replace channel in the line channel.send(exampleEmbed); with an actual reference to a channel. Since you will be using the message event handler, you can get the channel the message was sent in using message.channel.
I have also added in a check to ensure that the message was sent by a bot and contains an embed.
client.on('message', message => {
// check to ensure message was sent by bot and contains embed
if (!message.author.bot || !message.embeds[0]) return;
const receivedEmbed = message.embeds[0];
const exampleEmbed = new Discord.MessageEmbed(receivedEmbed).setTitle('New title');
// send in same channel
message.channel.send(exampleEmbed);
// send in different channel
client.channels.fetch(/* Channel ID */).then(channel => {
channel.send(exampleEmbed);
});
// alternatively, you can use this (but the function must be asynchronous)
const channel = await client.channels.fetch(/* Channel ID */);
channel.send(exampleEmbed);
});
For more information on valid properties and methods, read the Discord.js docs.
The following code will check if the message has any embeds and will resend the first one.
if (message.embeds) {
message.channel.send({ embed: message.embeds.first() || message.embeds[0] })
};
const embed = message.embeds[0];
const editedEmbed = embed
.setTitle('Edited!')
.addField('Test Field!', 'This is a test', true);
message.channel.send(editedEmbed);
This worked perfectly fine for me.
The problem will be that you don't have a TextChannel selected. (message.channel)

How to remove a message after a specific period of time in DiscordJS?

I have a question demanding DiscordJS.
It is, how to properly delete a Discord message that the bot sent?
I know it's a newbie question, but I'm new to DiscordJS.
I'm very thankful for all the responses I get, no matter if helpful or not.
You have to use the .delete method for the message object in order to delete the message. Just wait until the message is sent and then delete it after a certain period of time.
For (Rich)embeds, use the following code:
const Discord = require('discord.js');
const RichEmbed = new Discord.RichEmbed()
.setAuthor('test');
const message = await message.channel.send({ embed: RichEmbed }).then(r => r.delete('time in milliseconds'));
For normal messages, use the following code:
const message = await message.channel.send('Hello').then(r => r.delete('time in milliseconds'))

Categories

Resources