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

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');

Related

Discord bot not coming online despite no error messages?

I have recently spent a long time making a discord ticket bot, and all of a sudden now, it isnt turning on. There are no error messages when I turn the bot on, and the webview says the bot is online. I am hosting on repl.it
Sorry for the long code, but any genius who could work this out would be greatly appreciated. Thanks in advance.
const fs = require('fs');
const client = new Discord.Client();
const prefix = '-'
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles){
const command = require(`./commands/${file}`)
client.commands.set(command.name, command);
}
require('./server.js')
client.on("ready", () => {
console.log('Bot ready!');
client.user.setActivity('-help', { type: "LISTENING"} ).catch(console.error)
})
client.on("message", async (message) => {
if (message.author.bot) return;
const filter = (m) => m.author.id === message.author.id;
if (message.content === "-ticket") {
let channel = message.author.dmChannel;
if (!channel) channel = await message.author.createDM();
let embed = new Discord.MessageEmbed();
embed.setTitle('Open a Ticket')
embed.setDescription('Thank you for reaching out to us. If you have a question, please state it below so I can connect you to a member of our support team. If you a reporting a user, please describe your report in detail below.')
embed.setColor('AQUA')
message.author.send(embed);
channel
.awaitMessages(filter, {max: 1, time: 1000 * 300, errors: ['time'] })
.then ( async (collected) => {
const msg = collected.first();
message.author.send(`
>>> ✅ Thank you for reaching out to us! I have created a case for your inquiry with out support team. Expect a reply soon!
❓ Your question: ${msg}
`);
let claimEmbed = new Discord.MessageEmbed();
claimEmbed.setTitle('New Ticket')
claimEmbed.setDescription(`
New ticket created by ${message.author.tag}: ${msg}
React with ✅ to claim!
`)
claimEmbed.setColor('AQUA')
claimEmbed.setTimestamp()
try {
let claimChannel = client.channels.cache.find(
(channel) => channel.name === 'general',
);
let claimMessage = await claimChannel.send(claimEmbed);
claimMessage.react('✅');
const handleReaction = (reaction, user) => {
if (user.id === '923956860682399806') {
return;
}
const name = `ticket-${user.tag}`
claimMessage.guild.channels
.create(name, {
type: 'text',
}).then(channel => {
console.log(channel)
})
claimMessage.delete();
}
client.on('messageReactionAdd', (reaction, user) => {
const channelID = '858428421683675169'
if (reaction.message.channel.id === channelID) {
handleReaction(reaction, user)
}
})
} catch (err) {
throw err;
}
})
.catch((err) => console.log(err));
}
})
client.login(process.env['TOKEN'])
Your problem could possibly be that you have not put any intents. Intents look like this:
const { Client } = require('discord.js');
const client = new Client({
intents: 46687,
});
You can always calculate your intents with this intents calculator: https://ziad87.net/intents/
Side note:
If you are using discord.js v14 you change client.on from message to messageCreate.

How to Pin a Message in Discord

I am trying to make a discord bot for a small server that I am in, and I want it to pin a certain message to the channel that it was sent in. I have done a few bots before, but it seems that the syntax has changed since I last used it, and code that I was going to reuse no longer works. I have managed to get around some of those changes (like the intents,) but when I try to check for a sent message, it just does nothing. My current code
const { Client, Intents } = require("discord.js");
const { token } = require("./config.json");
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
if (msg.content == "something goes here") {
msg.pin()
}
});
client.login(token);
I have tried supplementing messageCreate for message like I have seen a few people recommend, but it still seems to do nothing. Even changing the msg.pin() to console.log(msg) still shows nothing in the console
client.on("messageCreate", (msg) => {
if (msg.content == "something goes here") {
console.log(msg)
}
});
I do have the privileged intent toggle enabled, so I don't think that that is the problem
[privileged toggles]
Does anybody know what the problem here is, and how I could fix it? Any help is appreciated, thanks!
First of all, you have not enabled the GUILD_MESSAGES intent in your client so you need to add that by doing this:
const client = new Client({
intents: [
Intents.FLAGS.GUILDS
Intents.FLAGS.GUILD_MESSAGES
]
});
Other than that, the .pin() function is still there and there is no change in it. You can provide a reason as well. The .pin() function also returns a promise, so you will have to use .then() or await, so your final code might look like this:
const { Client, Intents } = require("discord.js");
const { token } = require("./config.json");
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.once("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
if (msg.content == "something goes here") {
msg.pin().then(() => console.log)
}
});
client.login(token);
You can learn more about the .pin() function here => pin | discord.js
For Discord.js v13 use the following:
const { Client } = require("discord.js");
const { token } = require("./config.json");
const client = new Client({
intents: new Intents(32767)
});
client.login(token)
client.on("message", (ctx) => {
if (ctx.content == "something goes here") {
ctx.pin(ctx.id, "Pinned")
}
});

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

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.

How can a Discord bot reply to only certain users?

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".

Resources