Discord bot only reacting to only a few commands - javascript

I've been trying to figure out how to make a discord bot for my server. I started out simple with just basic reactions, but its not reacting to the other half of the commands I have given it. here is the code if anyone would like to help me with this. Keep in mind that im just a beginner and this is my very first project ever. Also these are very funny commands so be warned.
const Discord = require('discord.js');
const bot = new Discord.Client();
const token = 'RETRACTED';
bot.on('ready', () =>{
console.log('Im alive whore');
bot.user.setActivity ("owo");
});
const PREFIX = '!';
bot.on ("message", (message => {
if (message.author.bot) return;
msg = message.content.toLowerCase();
if (msg.includes ("pp")) {
message.channel.sendMessage ("haha you said pp!")
}
msg = message.content.toLowerCase();
if (msg.startsWith ("good morning")) {
message.channel.send("Good morning! Remember to stay hydrated!")
}
if (msg.includes ("komaeda"))
message.react ('👀');
}
))
bot.on ("message", (message => {
if (message.author.bot) return;
msg = message.content.toLowerCase();
if (msg.includes ("eggs")) {
message.react ('👀');
message.channel.sendMessage ("SunnySideup please")
}
if (msg.includes ("Jojo good")) {
message.channel.sendMessage("Your opinion is WRONG!")
}
if (msg.startsWith ("Jojo")) {
message.channel.sendMessage("jojo is bad ah ha ha")
}
}))
bot.on ("message", (message => {
if (message.author.bot) return;
msg = message.content.toLowerCase();
if (msg.includes ("Like scoob what's your favorite thing to do on the weekened")) {
message.channel.sendMessage("Arururururururururu")
}
if (msg.includes ("Bathroom time")) {
message.channel.sendMessage("Piss? Yummy!")
}
if (msg.includes ("Bathroom time")) {
message.channel.sendMessage("Piss? Yummy!")
}
}))
bot.login (token);

You're registering three separate message event listeners when Client only recognizes one of these.
Combine all of your message event listeners into on .on("message", ...) command and it should work fine.

Related

Discordjs API error whilst trying to banning a user

I am attempting to program a ban command to be used by an administrator at a user who has broken the rules or has been naughty enough to be banned. When I ran the following code:
const Discord = require("discord.js");
const config = require("./config.json");
const { MessageAttachment, MessageEmbed } = require('discord.js');
const client = new Discord.Client({ intents: ["GUILDS","GUILD_MEMBERS", "GUILD_MESSAGES", "DIRECT_MESSAGES", "DIRECT_MESSAGE_REACTIONS", "DIRECT_MESSAGE_TYPING"], partials: ['CHANNEL',] })
const RichEmbed = require("discord.js");
const prefix = "!";
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "news") {
if (message.channel.type == "DM") {
message.author.send(" ");
}
}
if (command === "help") {
message.author.send("The help desk is avaliable at this website: https://example.com/");
}
});
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.channel.send(`Pong! ${timeTaken}ms.`);
}
if (command === "delete all messages") {
const timeTaken = Date.now() - message.createdTimestamp;
const code = Math.random(1,1000)
message.channel.send(`Executing command. Verification Required.`);
message.author.send(`Your code is the number ${code}.`)
message.channel.send(`Please confirm your code. The code has been sent to your dms. Confirm it in here.`)
}
if (command === "ban") {
const user = message.mentions.users.first().id
message.guild.members.ban(user).then(user => {
message.channel.send(`Banned ${user.id}`);
}).catch(console.error);
}
});
client.login(config.BOT_TOKEN)
I ran into the following error whilst trying to test the command on a dummy acc.
DiscordAPIError: Missing Permissions
at RequestHandler.execute (/home/runner/gwehuirw/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/runner/gwehuirw/node_modules/discord.js/src/rest/RequestHandler.js:51:14) {
method: 'put',
path: '/guilds/891083670314680370/bans/943680142004322326',
code: 50013,
httpStatus: 403,
requestData: { json: { delete_message_days: 0 }, files: [] }
Could someone please help me with this? Thanks.
PS: I already had the necessary permissions for the bot to ban users. I also added the necessary intents for it to work. But I still am stuck.
Try removing the .id when you are trying to get the user. Getting the id would be making you ban the string that is the id, not the user.
I realized that the user who was trying to ban a user needed to have certain permissions. I have finished working on the command. Thanks to everyone who had helped me through this mess!

discord.js give role when react - no reply error in the discord server

I wanted do a discord bot, and wanted it to give a role when someone reacts with an emoji, but it doesn't responsed.
My code, for now, looks like this:
client.on('messageReactionAdd', async (reaction, user) => { //here the bot adds the reaction
if (reaction.partial) {
try {
await reaction.fetch()
} catch (error) {
return console.error('error');
}
}
const guild = client.guilds.cache.get("server-id");
const role = guild.roles.cache.get("role-id");
const member = reaction.message.guild.member(user);
if (reaction.message.id !== 'text-message-id') return;
else if(reaction.emoji.name === "😎") {
if (member.roles.cache.has(fem)) return;
else
member.roles.add(role)
}
})
and
client.on('messageReactionRemove', async (reaction, user) => { //here the bot removes the reaction
if (reaction.partial) {
try {
await reaction.fetch()
} catch (error) {
console.error('error')
return
}
}
const guild = client.guilds.cache.get("server-id");
const role = guild.roles.cache.get("role-id")
const member = reaction.message.guild.member(user)
if (reaction.message.id !== 'text message id') return
else if (reaction.emoji.name === "😎") {
if (member.roles.cache.has(fem))
member.roles.remove(role)
}
});
I don't know what happened, but I thing has a version error (of
discord.js) Someone can help me?
I wanted to a RPG server, when the player reacts to a emoji, a role
of Wizard or Warrior is add...
I can't say for sure if it will fix your error, but here's a few things you should apply to your code:
Make sure you enabled partials in your startup file:
const { Client } = require('discord.js');
const client = new Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });
Check if user is partial:
if(user.partial) await user.fetch();
Restructure your try block:
try {
if(reaction.partial) await reaction.fetch();
if(user.partial) await user.fetch();
}
Await the role to be added:
if (reaction.message.id !== 'text-message-id') return;
else if(reaction.emoji.name === "😎") {
if (member.roles.cache.has(fem)) return;
else await member.roles.add(role);
}
You have to await this, because roles.add() returns a promise
Also...
if you're planning to add some more messages / reactions you can use a switch for this.
Example:
// Listen for messages
switch(reaction.message.id) {
case 'your message id':
if(reaction.emoji.name === '👍') {
// Your code, if the user reacted with 👍
}
break;
case 'another message id':
// if you want to listen for multiple reactions, you can add a switch for that
// too
switch(reaction.emoji.name) {
case '😂':
// your code if user reacted with 😂
break;
case '❌':
// your code if user reacted with ❌
break;
default:
break;
}
default:
break;
}
Note:
Of course you don't have to use a switch / switches because for some people it's a bit confusing / not clean. You can manage this with if / if else statements too, but if this is getting more and more I'd recommend using a switch
The rest of your code looks fine, so I hope this will fix your problem :)
You can also take a look at my code, handling this event

Discord.js | Making a message sniper command

I'm trying to make a bot log/snipe a message, when someone says 'zsnipe', I want to know how would i make 'zsnipe' a command but its not working, am I doing something wrong? here's the code:
bot.on('messageDelete', message => {
const embed8 = new Discord.MessageEmbed()
.setAuthor(`${message.author.username}#${message.author.discriminator}`, message.author.avatarURL({dynamic : true}))
.setDescription(message.content)
if (message.content === 'zsnipe'){
message.channel.send(embed8)
}
})
Your Help Will be Appreciated!
Here is some code that saves the last deleted message in a channel and allows it to be retrieved when someone says zsnipe.
Warning: the deleted messages will be lost if the bot restarts.
const deletedMessages = new Discord.Collection();
bot.on('message', async message => {
if (message.author.bot) return;
const args = message.content.trim().split(/\s+/g);
const command = args.shift().toLowerCase();
switch (command) {
case 'zsnipe':
const msg = deletedMessages.get(message.channel.id);
if (!msg) return message.reply('could not find any deleted messages in this channel.');
const embed = new Discord.MessageEmbed()
.setAuthor(msg.author.tag, msg.author.avatarURL({ dynamic: true }))
.setDescription(msg.content);
message.channel.send(embed).catch(err => console.error(err));
break;
});
bot.on('messageDelete', message => {
deletedMessages.set(message.channel.id, message);
});

Job Inquiry Bot for Discord.js

I am trying to create a bot that a user can DM to start a "job" inquiry.
Example:
A user messages the bot with !inquiry, then the bot asks questions about the job such as if it's a personal project or for a company, then what is the company or personal projects twitter, it will then ask what type of service they are requesting by supplying options and based on that option the bot will respond with "Please explain what you have in mind for your new xxx job"
Then once the user answers all those questions the bot sends an embed with what they answered.
I was thinking of using MessageCollector but I got stuck with how to do the logic. I have the bot responding to the user so I understand how to send messages through DM to a user. just don't quite understand how to implement the rest. I need a little push.
client.on("message", async (msg) => {
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
if (msg.channel.type === "dm") {
const args = msg.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
const discordUser = msg.author.tag;
if (command !== "order") {
try {
sendFailMessage(msg, "wrongCommand");
} catch (e) {
console.warn("Failed sending Fail Message");
}
} else {
msg.channel.startTyping(1);
msg.author.send();
I've made something similar before so incase you want the full code and context: https://github.com/karizma/ravenxi/blob/master/commands/showcase/apply.js
But here's it rewritten for your context:
(note it's def not optimized since idk your context code, and you are passing variables for every call, but if you know js decently which you should if you are gonna use a libary, it shouldn't be too hard to better the code)
function sendNexQuestion(index, channel, questions, replys) {
return channel.send(questions[index])
.then(() => channel.awaitMessages(() => true, { max: 1, time: 30000, errors: ["time"] }))
.then(reply => {
const content = reply.first().content;
if (content === prefix + "cancel") throw "Self-Cancel";
if (content === prefix + "redo") {
replys.length = 0;
return sendNextQuestion(0, channel, questions, replys);
}
replys.push(content);
return index >= questions.length - 1 ? new Promise(res => res(replys)) : sendNextQuestion(index + 1, channel, questions, replys);
}).catch(err => {
if (err === "Self-Cancel") {
//user canceled
}
channel.send("Application Canceled");
});
}
client.on("message", async (msg) => {
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
if (msg.channel.type === "dm") {
const args = msg.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
const questions = ["Why do you want this?", "Question 2"];
if (command === "inquiry") {
sendNexQuestion(0, msg.channel, questions, []).then(replys => {
//array of replys
})
}
}
});

Why doesn't my message.reply command not work?

My bot has connected to the server, it becomes online when I start the code, but i can't seem to figure out why the message.reply command doesnt work
Code:
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('Message', (message) => {
if(message.content == 'ping') {
message.reply('pong');
}
});
Am i missing something? i'm coding using visual studio code
Client's events are case-sensitive, therefore, "Message" and "message" are completely two different things.
Replace "Message" with "message" on line 5 to fix your code.
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('message', (message) => {
if (message.content == 'ping') {
message.reply('pong');
}
});

Categories