Discord JS - If user sends DM to bot with specific string - discord

The code below works and send a DM to the user when he/she reacts to a message.
The goal is then to add a role - or do something - if the user replies with the correct string.
if (reaction.emoji.name === theDoor) {
await reaction.message.guild.members.cache.get(user.id).roles.add(treasure);
const reactUser = await reaction.message.guild.members.cache.get(user.id);
reactUser.send('Enter the code. Hint: *Yumi Zouma*.');
} else {
return;
}
How can I make the bot handle DM from other users? Google seems to only provide how to send a DM to a user.

What you need to use then is a Message Collector.
Docs
For example,
const dm = await reactUser.send("Enter code")
const collector = dm.channel.createMessageCollector({filter, max: 5, time: 30000}); //We're creating the collector, allowing for a max of 5 messages or 30 seconds runtime.
collector.on('collect', m => {
console.log(m.content)
}
collector.on('end', (collected, reason) => {
await dm.channel.send({content: `Collector ended for reason: ${reason} reached! I collected ${collected.size} messages.`})
}

Related

Check The Status Of Another Discord Bot

So i need a bot that tracks another bot's status. like if its online it will say in a channel (with an embed) "The Bot Is Online" And The Same if it goes offline and whenever someone does !status {botname} it shows the uptime/downtime of the bot and 'last online' date
if someone can make it happen i will really appricate it!
also i found this github rebo but it dosen't work, it just says the bot is online and whenever i type !setup {channel} it turns off
The Link to the Repo: https://github.com/sujalgoel/discord-bot-status-checker
Also uh it can be any language, i don't really want to add anything else πŸ˜….
Again, Thanks!
First of all, you would need the privileged Presence intent, which you can enable in the Developer Portal.
Tracking the bot's status
In order to have this work, we have to listen to the presenceUpdate event in discord.js. This event emits whenever someone's presence (a.k.a. status) updates.
Add this in your index.js file, or an event handler file:
// put this with your other imports (and esm equivalent if necessary)
const { MessageEmbed } = require("discord.js");
client.on("presenceUpdate", async (oldPresence, newPresence) => {
// check if the member is the bot we're looking for, if not, return
if (newPresence.member !== "your other bot id here") return;
// check if the status (online, idle, dnd, offline) updated, if not, return
if (oldPresence?.status === newPresence.status) return;
// fetch the channel that we're sending a message in
const channel = await client.channels.fetch("your updating channel id here");
// create the embed
const embed = new MessageEmbed()
.setTitle(`${newPresence.member.displayName}'s status updated!`)
.addField("Old status", oldPresence?.status ?? "offline")
.addField("New status", newPresence.status ?? "offline");
channel.send({ embeds: [embed] });
});
Now, whenever we update the targeted bot's status (online, idle, dnd, offline), it should send the embed we created!
!status command
This one will be a bit harder. If you don't have or want to use a database, we will need to store it in a Collection. The important thing about a Collection is that it resets whenever your bot updates, meaning that even if your bot restarts, everything in that Collection is gone. Collections, rather than just a variable, allows you to store more than one bot's value if you need it in the future.
However, because I don't know what you want or what database you're using, we're going to use Collections.
In your index.js file from before:
// put this with your other imports (and esm equivalent if necessary)
const { Collection, MessageEmbed } = require("discord.js");
// create a collection to store our status data
const client.statusCollection = new Collection();
client.statusCollection.set("your other bot id here", Date.now());
client.on("presenceUpdate", async (oldPresence, newPresence) => {
// check if the member is the bot we're looking for, if not, return
if (newPresence.member !== "your other bot id here") return;
// check if the status (online, idle, dnd, offline) updated, if not, return
if (oldPresence?.status === newPresence.status) return;
// fetch the channel that we're sending a message in
const channel = await client.channels.fetch("your updating channel id here");
// create the embed
const embed = new MessageEmbed()
.setTitle(`${newPresence.member.displayName}'s status updated!`)
.addField("Old status", oldPresence?.status ?? "offline")
.addField("New status", newPresence.status ?? "offline");
channel.send({ embeds: [embed] });
// add the changes in our Collection if changed from/to offline
if ((oldPresence?.status === "offline" || !oldPresence) || (newPresence.status === "offline")) {
client.statusCollection.set("your other bot id here", Date.now());
}
});
Assuming that you already have a prefix command handler (not slash commands) and that the message, args (array of arguments separated by spaces), and client exists, put this in a command file, and make sure it's in an async/await context:
// put this at the top of the file
const { MessageEmbed } = require("discord.js");
const bot = await message.guild.members.fetch("your other bot id here");
const embed = new MessageEmbed()
.setTitle(`${bot.displayName}'s status`);
// if bot is currently offline
if ((bot.presence?.status === "offline") || (!bot.presence)) {
const lastOnline = client.statusCollection.get("your other bot id here");
embed.setDescription(`The bot is currently offline, it was last online at <t:${lastOnline / 1000}:F>`);
} else { // if bot is not currently offline
const uptime = client.statusCollection.get("your other bot id here");
embed.setDescription(`The bot is currently online, its uptime is ${uptime / 1000}`);
};
message.reply({ embeds: [embed] });
In no way is this the most perfect code, but, it does the trick and is a great starting point for you to add on. Some suggestions would be to add the tracker in an event handler rather than your index.js file, use a database rather than a local Collection, and of course, prettify the embed messages!

Count reactions to a message after certain time has passed

So I made a bot that has a vote command, where you ask it to say a votable thing and people can only react with tick, cross or N/A in discord.js
What I need to make work now, is a response (either by command or automated over-time, but preferably automated over the time period of 24hrs).
So far, I've tried many different methods and looked all over the Discord.js Docs, but nothing has quite worked out at all. Here's how the code ended up, although it doesn't work:
var textToEcho = args.join(" ");
Client.channels.cache.get('channel ID').send(textToEcho).then(async m => {
await m.react('βœ…');
await m.react('❎');
await m.react('801426534341541919');
});
message.channel.fetchMessage(textToEcho).then(msg => {
let downVoteCollection = msg.reactions.filter(rx => rx.emoji.name == 'βœ…');
console.log(downVoteCollection.first().count);
}).catch(console.error);
Note: This ONLY checks for the tick response.
It appears that you're trying to get all of the reactions directly after the message has been sent, this will only return the bots reactions, if any at all.
To accurately get the reactions after a certain about of time you'll have to add a .setTimeout(...) function.
var textToEcho = args.join(" ");
Client.channels.cache.get('channel ID').send(textToEcho).then(async m => {
await m.react('βœ…');
await m.react('❎');
await m.react('801426534341541919');
});
setTimeout(() => {
message.channel.messages.fetch(message.id).then(msg => {
let downVoteCollection = msg.reactions.filter(rx => rx.emoji.name == 'βœ…'); // Filter the reactions
msg.author.send(`You have received **${downVoteCollection.first().count}** votes on your latest poll!`); // Sends the poll owner how many votes they recieved
}).catch(console.error);
}, 86400000); // This will wait 24 hours after the message has been sent to count reactions

Discord.js Forward DM message to specific channel

So, I need a way to forward a message sent in the bot's dm to a specific channel in my server.
this is the code that I got so far:
execute(message, args) {
if(message.channel.type == "dm"){
let cf = args.join(' ')
const cfAdm = message.guild.channels.cache.get('767082831205367809')
let embed = new discord.MessageEmbed()
.setTitle('**CONFISSÃO**')
.setDescription(cf)
.setColor('#000000')
const filter = (reaction, user) => ['πŸ‘', 'πŸ‘Ž'].includes(reaction.emoji.name);
const reactOptions = {maxEmojis: 1};
cfAdm.send(embed)
.then(function (message) {
message.react('πŸ‘')
.then(() => message.react('πŸ‘Ž'))
/**** start collecting reacts ****/
.then(() => message.awaitReactions(filter, reactOptions))
/**** collection finished! ****/
.then(collected => {
if (collected.first().emoji.name === 'πŸ‘') {
const cfGnr = message.guild.channels.cache.get('766763882097672263')
cfGnr.send(embed)
}
})
});
}
else {
message.delete()
message.channel.send('Send me this in the dm so you can stay anon')
.then (message =>{
message.delete({timeout: 5000})
})
}
}
But for some reason that I can't seem to understand, it gives me this error:
TypeError: Cannot read property 'channels' of null
If anyone can help me, that would be greatly apreciated.
Thanks in advance and sorry for the bad english
The error here is that you are trying to call const cfAdm = message.guild.channels.cache.get('ID') on a message object from a Direct Message channel ( if(message.channel.type == "dm"){)
DMs don't have guilds, therefore message.guild is null and message.guild.channels does not exist.
You will need to first access the channel some other way. Luckily, Discord.js has a way to access all channels the bot can work with* (you don't need to muck around with guilds because all channels have unique IDs):
client.channels.fetch(ID) or client.channels.cache.get(ID)
(I have not tested this but it seems fairly straight forward)
*See the link for caveats that apply to bots in a large amount of servers.

Discord.js - How do you move a user that reacts to an embed?

I am new to Discord js and I am trying to make my bot move all users that react to an embed into a certain voice channel. Currently, it takes whoever wrote the message and moves them to the specified voice channel.I tried many combinations of user.id, guild.member, etc. What would I put before the .setVoiceChannel? I am confused as to what message.member is other than the person that wrote the message. Thank you!
collector.on('collect', (reaction, user) => {
if (reaction.emoji.name == reactionControls.VOID) {
const channel = message.guild.channels.find('name', 'Void 1');
message.member.setVoiceChannel(channel);
}
});
message.member does refer to the user who execute the command, if you want the member who reacted you will have to convert user using <GuildMember>.fetchMember, the only issue now is that the collect event doesn't give the parameter of user in v11.5.1 so you will need to just use collector.users.last() to get the last reactor
collector.on('collect', async (reaction) => {
if (reaction.emoji.name == reactionControls.VOID) {
const channel = message.guild.channels.find('name', 'Void 1');
const user = collector.users.last();
const member = await message.guild.fetchMember(user);
member.setVoiceChannel(channel);
}
});

How do you make some bot commands only work in some discord channels

This is my first time using js. I need to ban a certain word in a certain channel. I don't want the message to be deleted if it is not in the specific channel.
For Example:
I want to ban the word "goodbye" in the #greeting channel
BUT
I don't want to ban the word "goodbye" In the #farewell channel
How would I go about this?
Thanks.
By the way I wanted to use example code, but none of it made any sense.
I wrote a simple example for you on how to achieve this:
const Discord = require("discord.js");
const Client = new Discord.Client();
const ForbiddenWords = {
"ChannelID": ["goodbaye", "bye"] // Greeting channel
};
Client.on("ready", () => {
console.log(`${Client.user.tag} is ready!`);
});
Client.on("message", (message) => { // Fired when the bot detects a new message.
if (message.author.bot) {return false}; // Checking if the message author is a bot.
if (ForbiddenWords[message.channel.id]) { // Checking if the current channel has any forbidden words in the ForbiddenWords Object
if (ForbiddenWords[message.channel.id].some(word => message.content.toString().toLowerCase().includes(word))) { // Checking if the message contains any forbidden words
message.delete(); // Deleting the message.
};
};
});
Client.login(process.env.DISCORD_AUTH_TOKEN);

Resources