How can a Discord bot reply to only certain users? - discord

I am looking for a way to make a Discord bot which either reacts or replies to only certain users. It can choose the user by either role or ID, but I can not seem to get it working. This is what I have tried:
if (message.author.id === 'myDiscordID') {
message.reply('hello!').then(r => {
});
}
I am coding in Discord JS, if that helps. This is the entire index.js file:
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if (message.author.id === 'myDiscordID') {
message.reply('hello!').then(r => {
});
}
});
client.login(token);
The file runs fine, the bot comes online, and then it prints 'Ready!' to the console, however, the rest of the code doesn't seem to work.

I`ts look like this must work.
Are you sure bot in your server and have permissions to read message ?
Try this ready block
client.once('ready', () => {
console.log('Ready!');
const guildList = client.guilds.cache.map(guild => guild.name)
console.join(`Bot go online in ${guildList.length}`)
console.log(guildList.join('\n'))
});
And some solutin to check user.id or roles includes:
console.log(message.content) for check is this event triggeret.
client.on('message', message => {
console.log(message.content)
if (message.author.id === '') {
message.reply('author contain')
}
if (message.member.roles.cache.has('ROLE ID')) {
message.reply('role contain')
}
if(message.member.roles.cache.some(role => ['ID1', 'ID2'].includes(role.id)) {
message.reply('some role contain')
}
});

I was also having a problem with that. Here is the solution that worked for me.
const userID = "The_user's_id";
bot.on("message", function(message) {
if(message.author.id === userID) {
message.react('emoji name or id');
}
});
Note: to find the id of a user, just right click him and press "copy ID".

Related

Discord js, Bot can only find itself until someone else send a message

I was trying to get all the members of a role but i can only get the bot until someone else send a message then i can see them too
here is my code
const matches = require("../differents-matches")
module.exports = (client) => {
setInterval(async () => {
/*const allmatch = await matches.
where('_notified').exists(false).
where('_startDate').lt(Date.now()).
where('_endDate').gt(Date.now())
allmatch.forEach(element => {
})*/
console.log(client.guilds.cache.get('1050150840813498401').roles.cache.get('1050889003110506516').members.map(m => m.user.id))
//
}, 5000)
}
i tried the solution proposed in this post but the problem is still here
i have all the intents needed :
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers], fetchAllMembers: true });
and i did activate the server member intent in the bot options, i can't find any other thing to try. If you have an idea of what is the problem please leave a message.
It is expected, actually the fetchAllMembers client option disappeared with Discord.js v13.
You should now fetch the guild members manually:
const matches = require("../differents-matches")
module.exports = (client) => {
setInterval(async () => {
/*const allmatch = await matches.
where('_notified').exists(false).
where('_startDate').lt(Date.now()).
where('_endDate').gt(Date.now())
allmatch.forEach(element => {
})*/
const guild = client.guilds.cache.get('1050150840813498401');
await guild.members.fetch(); // do what fetchAllMembers previously did
console.log(guild.roles.cache.get('1050889003110506516').members.map(m => m.user.id))
//
}, 5000)
}

DM Specific User ID on Discord.js Bot

i'm new to coding bots and i need help on how to add a command on messaging a certain person a customized message. this is what i have so far. what should i do?
const Discord = require('discord.js');
const config = require("./Data/config.json")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
client.once('ready', () => {
console.log('Ready!');
});
client.login('TOKEN');
client.on('message', async message => {
if (message.author.bot) return;
let prefix = '??'
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split("/ +/g");
let msg = message.content.toLowerCase();
let cmd = args.shift().toLowerCase();
if (msg.startsWith(prefix + 'ping')) {
message.channel.send('pong');
}
if (msg.startsWith(prefix + 'hello')) {
message.channel.send('hewwo uwu');
}
});
To fetch a user by id, you can use bot.users.fetch()
To direct message a user, you can use User.send():
const user = await client.users.fetch(userId);
user.send("This is a DM!");
This simple function will easily resolve the user (you can provide a user object or user ID so it’s very helpful)
async function DMUser(resolvable, content, client) {
const user = client.users.resolve(resolvable)
return user.send(content)
}
//returns: message sent, or error
//usage: DMUser(UserResolvable, "content", client)
Related links:
UserManager.resolve
User.send
UserResolvable

A bot that deletes all messages except for messeges saying "potato"

I have been trying to make a bot that only allows the messages saying, "potato" and deletes all other messages with different content. (I am very new to this stuff.)
Here is the code I've tried so far, created by a user here:
client.on("message", (message) => {
if(message.content != "potato") return message.delete()
});
When I input it into the code, I get an indent error and a semi-colon error. When I auto fix them, I get this code:
client.on("message", (message) => {
if(message.content != "potato") return message.delete();
});
The terminal repeats back the messages in the server (has no roles or perms), but doesn't delete them in discord if they aren't "potato". The bot has Admin perm.
Any edits or suggestions? (I do have a linter, not sure if relevant.)
Thanks, PM
Rest of code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.login('TOKEN');
client.on("message", (message) => {
if(message.content !== "potato") return message.delete();
});
You need to put await before the message.delete() otherwise it won't work.
It's also better for code readability to put client.login at the bottom of the code.
Your code should look like this:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on("message", async (message) => {
if(message.content !== "potato") {return await message.delete();}
});
client.login('TOKEN');

How do we make a kick command with userid?

So how do we detect the userID with the kick command below?
So below is my kick command and whenever I kick a person I need to mention them (?kick #test) I want to kick a user by their user id (?kick 354353) and their mentions.
const client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
// Ignore messages that aren't from a guild
if (!message.guild) return;
if (message.content.startsWith('?kick')) {
if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS']))
return;
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
message.reply("That user isn't in this guild!");
}
// Otherwise, if no user was mentioned
} else {
message.reply("You didn't mention the user to kick!");
}
}
});
client.login('TOKEN');
I recommend setting up Arguments if you plan to make more commands that take user input.
However if you're not interested in fully setting up arguments, you can just slice the message and grab the id. You will then need to fetch the member object, make sure to make your function is async for this, or use Promise#then if you prefer.
if (message.content.startsWith('?kick')) {
if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS']))
return;
const memberId = message.content.slice(' ')[1];
if (memberId) {
const memberToKick = await message.guild.members.cache.fetch(userId);
memberToKick.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
// Log the error
console.error(err);
});
}
}

Giving roles on discord

I'm making a discord murder mystery bot.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on("message", (message) => {
msg = message.content.toLowerCase();
if (message.author.bot) {
return;
}
mention = message.mentions.users.first();
if (msg.startsWith("kill")) {
if (mention == null) {
return;
}
message.delete();
mention.send('you are dead');
message.channel.send("now done");
}
});
client.login('my token');
What would I add to the code so after the person who was tagged got there role changed from alive to dead?
// First, make sure that you're in a guild
if (!message.guild) return;
// Get the guild member from the user
// You can also use message.mentions.members.first() (make sure that you check that
// the message was sent in a guild beforehand if you do so)
const member = message.guild.members.cache.get(mention.id);
// You can use the ID of the roles, or get the role by name. Example:
// const aliveRole = message.guild.roles.cache.find(r => r.name === 'Alive');
const aliveRole = 'alive role ID here';
const deadRole = 'dead role ID here';
// You can also use try/catch with await if you make the listener and async
// function:
/*
client.on("message", async (message) => {
// ...
try {
await Promise.all([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]);
} catch (error) {
console.error(error);
}
})
*/
Promise.all([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]).catch(console.error);
The Promise.all means that the promises for adding and removing the roles are started at the same time. A promise is an object that can resolve to a value or reject with an error, so the .catch(console.error) logs all errors. I recommend that you handle errors for message.delete(), mention.send('you are dead'), and message.channel.send("now done") as well.
For more information on member.roles.remove() and member.roles.add(), see the documentation for GuildMemberRoleManager.

Resources