discord bot does not get message for command - javascript

I'm watching a video (https://www.youtube.com/watch?v=ovIQqlXllWw&ab_channel=AnsontheDeveloper) to see how to make a discord poll bot. now Im at the point where the bot doesnt respond to some code and i cant find out the issue.
const { ContextMenuCommandBuilder } = require("discord.js");
const Discord = require("discord.js");
const client = new Discord.Client({intents: ['Guilds', 'MessageContent', 'GuildMessages', 'GuildMembers']});
const token = "token";
//Login with token
client.login(token);
const userCreatedPolls = new Map();
client.on('ready', () => console.log("The bot is online!"));
client.on('messageCreate', async message => {
if(message.author.bot) return;
if(message.content.toLowerCase() === '!createpoll') {
message.channel.send("Enter games to add");
let filter = msg => {
if(msg.author.id === message.author.id) {
console.log("test");
if(msg.content.toLowerCase() === 'done'){ collector.stop();}
else return true;
}
else return false;
}
let collector = message.channel.createMessageCollector(filter, { maxMatches: 20 });
let pollOptions = await getPollOptions(collector);
let embed = new discord.RichEmbed();
embed.setTitle("Poll");
embed.setDescription(pollOptions.join("\n"));
let confirm = await message.channel.send(embed);
I can turn the bot on and when i do !createpoll the bot show the correct message but when i type 'done' nothing happens. I found out the the bot cant access the if ( if(msg.author.id === message.author.id) ) but i dont know why it doesnt work.

Related

Bot sends embed message but doesn't send mp4 attachment

New to coding and recently started making a discord bot using JS. It's a bot where a certain mp4 plays with a specific snippet.
I'm having trouble with the fact that the mp4 doesn't send when I input the command, just the embed message. Basically if I do -snip kratos the bot sends the embed message but not the mp4.
Here's what I have so far:
const fs = require('fs');
const { Client, MessageAttachment } = require('discord.js');
const config = require('./config.json');
const { prefix, token } = require('./config.json');
const client = new Client();
client.commands = new Discord.Collection();```
And here are the command events:
``` client.on('message', message => {
if (message.content === `${prefix}snip kratos`) {
if (message.author.bot) return
const kratos = new Discord.MessageEmbed()
.setColor('#ffb638')
.setTitle('Kratos')
.setDescription('Sending 1 snippet(s)...')
.setTimestamp()
.setFooter('SkiBot');
message.channel.send(kratos);
client.on('message', message => {
if (message.content === `${prefix}snip kratos`) {
if (message.author.bot) return
const attachment = new MessageAttachment('./snippets/kratos/Kratos.mp4');
message.channel.send(attachment);
}
});
}
});
client.on('message', message => {
if (message.content === `${prefix}snip johnny bravo`) {
if (message.author.bot) return
const kratos = new Discord.MessageEmbed()
.setColor('#ffb638')
.setTitle('Johnny Bravo')
.setDescription('Sending 1 snippet(s)...')
.setTimestamp()
.setFooter('SkiBot');
message.channel.send(kratos);
client.on('message', message => {
if (message.content === `${prefix}snip johnny bravo`) {
if (message.author.bot) return
const attachment = new MessageAttachment('./snippets/Johnny_Bravo/Johnny_Bravo.mp4');
message.channel.send(attachment);
}
});
}
});```
The issue is that you are nesting event listeners. Remove the nested client.on('message', ...) part and send the message attachment after sending the embed.
client.on('message', (message) => {
if (message.author.bot) {
return
}
if (message.content === `${prefix}snip kratos`) {
const kratos = new MessageEmbed()
.setColor('#ffb638')
.setTitle('Kratos')
.setDescription('Sending 1 snippet...')
.setTimestamp()
.setFooter('SkiBot')
message.channel.send(kratos)
const attachment = new MessageAttachment('./snippets/kratos/Kratos.mp4')
message.channel.send(attachment)
}
})
And you don't need multiple message event listeners. You can simplify the code by creating an object with the valid commands.
client.on('message', (message) => {
const { content, author, channel } = message
if (author.bot) {
return
}
const embeds = {
[`${prefix}snip kratos`]: {
title: 'Kratos',
attachmentPath: './snippets/kratos/Kratos.mp4',
},
[`${prefix}snip johnny bravo`]: {
title: 'Johnny Bravo',
attachmentPath: './snippets/Johnny_Bravo/Johnny_Bravo.mp4',
},
}
const embed = embeds[content]
if (embed) {
const { title, attachmentPath } = embed
channel.send(
new MessageEmbed()
.setColor('#ffb638')
.setTitle(title)
.setDescription('Sending 1 snippet...')
.setTimestamp()
.setFooter('SkiBot')
)
channel.send(new MessageAttachment(attachmentPath))
}
})
The above solution should be enough if you don't have a lot of commands. Check this guide to learn how to create individual command files to keep your code organized.
You should be able to do
message.channel.send({
files: [
"./snippets/kratos/Kratos.mp4"
]})
As referred to here https://discord.js.org/#/docs/main/stable/class/TextChannel?scrollTo=send
Also right here client.commands = new Discord.Collection(); right here you are calling Discord but Discord was not defined

When i enter my discord bot token in visualstudiocode and i run it in command prompt it doesent work

My token for my discord bot isn't working.
When I go into the command prompt and I type node ., it says:
Syntax Error: Invalid or unexpected token
I'm pretty sure nothing is wrong with my code.
Heres my code:
const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = "?";
client.once("ready", () => {
console.log("KeyBot is online!");
});
client.on("message", (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === "ping") {
message.channel.send("pong!");
}
});
const args = message.content.split(" ").slice(1);
const user = message.mentions.users.first();
const banReason = args.slice(1).join(" ");
if (!user) {
try {
if (!message.guild.members.get(args.slice(0, 1).join(" ")))
throw new Error("Couldn't get a Discord user with this userID!");
user = message.guild.members.get(args.slice(0, 1).join(" "));
user = user.user;
} catch (error) {
return message.reply("Couldn' get a Discord user with this userID!");
}
}
if (user === message.author)
return message.channel.send("You can't ban yourself");
if (!reason) return message.reply("You forgot to enter a reason for this ban!");
if (!message.guild.member(user).bannable)
return message.reply(
"You can't ban this user because you the bot has not sufficient permissions!"
);
await message.guild.ban(user);
const Discord = require("discord.js");
const banConfirmationEmbed = new Discord.RichEmbed()
.setColor("RED")
.setDescription(`✅ ${user.tag} has been successfully banned!`);
message.channel.send({
embed: banConfirmationEmbed,
});
const modlogChannelID = "";
if (modlogChannelID.length !== 0) {
if (!client.channels.get(modlogChannelID)) return undefined;
const banConfirmationEmbedModlog = new Discord.RichEmbed()
.setAuthor(
`Banned by **${msg.author.username}#${msg.author.discriminator}**`,
msg.author.displayAvatarURL
)
.setThumbnail(user.displayAvatarURL)
.setColor("RED")
.setTimestamp().setDescription(`**Action**: Ban
**User**: ${user.username}#${user.discriminator} (${user.id})
**Reason**: ${reason}`);
client.channels.get(modlogChannelID).send({
embed: banConfirmationEmbedModlog,
});
}
const args = message.content.split(" ").slice(1);
const amount = args.join(" ");
if (!amount)
return msg.reply(
"You haven't given an amount of messages which should be deleted!"
);
if (isNaN(amount)) return msg.reply("The amount parameter isn`t a number!");
if (amount > 100)
return msg.reply("You can`t delete more than 100 messages at once!");
if (amount < 1) return msg.reply("You have to delete at least 1 message!");
await msg.channel.messages
.fetch({
limit: amount,
})
.then((messages) => {
msg.channel.bulkDelete(messages);
});
client.login("token");

Discord.js command that gives a role

so I'm trying to make a command that where you type $test and it gives you, for example, a "Test" role. This is my current code but I keep getting an error: "Cannot read property 'addRole' of undefined"
const Discord = require("discord.js");
const { send } = require("process");
const { clear } = require("console");
const client = new Discord.Client();
var prefix = "$";
client.login("token");
//TEST COMMAND
client.on("message", message => {
if (message.content.startsWith(prefix + "test")) {
message.channel.send("You have been given `Need to be tested` role! You will be tested shortly!")
client.channels.get("701547440310059059").send(` please test ${message.author}!`)
const member = message.mentions.members.first();
let testRole = message.guild.roles.find(role => role.id == "609021049375293460")
member.addRole(testRole)
}})
client.on('ready',()=>{
console.log(`[READY] Logged in as ${client.user.tag}! ID: ${client.user.id}`);
let statuses = [
" status "
]
setInterval(function(){
let status = statuses[Math.floor(Math.random() * statuses.length)];
client.user.setActivity(status, {type:"WATCHING"})
}, 3000) //Seconds to Random
});
Please let me know how I can do this easily or something.
In discord.js v12, GuildMember does not have a function .addRole, you need to use GuildMemberRoleManager's .add, also you need to add .cache when getting roles from server, like this:
const member = message.mentions.members.first();
let testRole = message.guild.roles.cache.find(role => role.id == "609021049375293460")
member.roles.add(testRole)
Okay, you are getting the error Cannot read property 'addRole' of undefined.
This means that the member variable is undefined, which could be caused by the fact that you didn't mention a member.
In this line, you put const member = message.mentions.members.first(); which means when you run the command, you have to mention someone to add the role to.
Hope this helps.
In newest version of discord.js you can try the following code:
// Where '799617378904178698' is your role id
message.guild.roles.fetch('799617378904178698')
.then(role => {
console.log(`The role color is: ${role.color}`);
console.log(`The role name is: ${role.name}`);
let member = message.mentions.members.first();
member.roles.add(role).catch(console.error);
})
.catch(console.error);
Works in case you're trying to add a certain role. You ought to call it like that:
(prefix)commandName #member
Found one more solution in case you want to give any role to any user (except bot)
main.js (or index.js whatever you have):
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '+';
const fs = require("fs");
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);
}
client.once('ready', () => {
console.log('Bot is online');
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
console.log(args);
const command = args.shift().toLowerCase();
if (command == 'giveany') {
const role = args[1].slice(3, args[1].length - 1);
client.commands.get('giveany').execute(message, args, role);
}
});
client.login('token');
giveany.js :
module.exports = {
name: 'giveany',
description: 'adds any role to a member',
execute(message, args, role) {
console.log(role);
message.guild.roles.fetch(role)
.then(r => {
console.log(`The role color is: ${r.color}`);
console.log(`The role name is: ${r.name}`);
let member = message.mentions.members.first();
if (member != undefined) {
console.log('member=' + member);
member.roles.add(r).catch(console.error);
} else {
message.channel.send('You cannot give a role to a user that is either bot or undefined');
}
}).catch( (error) => {
console.error(error);
message.channel.send('Could not find given role: ' + args[1]);
});
}
}
Calling: +giveany #Username #Role

Message not defined discord.js chatbot

So I'm trying to get my bot to work but the code says message not defined. I have tried everything I know to do:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('ready!');
});
if (message.content === '!ping') {
message.channel.send('Pong.');
}
if (command === "!hug") {
let user = message.mentions.users.first();
message.channel.send("You have been hugged " + user);
}
client.login('my-bot-token');
You forgot to add a event listener for a message, I think.
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('ready!');
});
client.on("message", (message) => {
if (message.content === '!ping') {
message.channel.send('Pong.');
}
if (command === "!hug") {
let user = message.mentions.users.first();
message.channel.send("You have been hugged " + user);
}
}
client.login('my-bot-token');

Working on a Discord bot with discord.js, tempmute won't work

making a discord bot in javascript with visual studio code but for some reason getting an error. I'll show you the code that is relevant first.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
classes I'm working with
Here is the index.js:
const { Client, Collection } = require("discord.js");
const { config } = require("dotenv");
const fs = require("fs");
const client = new Client({
disableEveryone: true
});
client.commands = new Collection();
client.aliases = new Collection();
client.categories = fs.readdirSync("./commands/");
config({
path: __dirname + "/.env"
});
["command"].forEach(handler => {
require(`./handlers/${handler}`)(client);
});
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setPresence({
status: "online",
game: {
name: "you get boosted❤️",
type: "Watching"
}
});
});
client.on("message", async message => {
const prefix = "!";
if (message.author.bot) return;
if (!message.guild) return;
if (!message.content.startsWith(prefix)) return;
if (!message.member) message.member = await message.guild.fetchMember(message);
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd);
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (command)
command.run(client, message, args);
});
client.login(process.env.TOKEN);
Here is tempmute:
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'mute':
var person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]));
if(!person) return message.reply("I CANT FIND THE USER " + person)
let mainrole = message.guild.roles.find(role => role.name === "Newbie");
let role = message.guild.roles.find(role => role.name === "mute");
if(!role) return message.reply("Couldn't find the mute role.")
let time = args[2];
if(!time){
return message.reply("You didnt specify a time!");
}
person.removeRole(mainrole.id)
person.addRole(role.id);
message.channel.send(`#${person.user.tag} has now been muted for ${ms(ms(time))}`)
setTimeout(function(){
person.addRole(mainrole.id)
person.removeRole(role.id);
console.log(role.id)
message.channel.send(`#${person.user.tag} has been unmuted.`)
}, ms(time));
break;
}
});
Here is the help.js which lists all commands
const { RichEmbed } = require("discord.js");
const { stripIndents } = require("common-tags");
module.exports = {
name: "help",
aliases: ["h"],
category: "info",
description: "Returns all commands, or one specific command info",
usage: "[command | alias]",
run: async (client, message, args) => {
if (args[0]) {
return getCMD(client, message, args[0]);
} else {
return getAll(client, message);
}
}
}
function getAll(client, message) {
const embed = new RichEmbed()
.setColor("RANDOM")
const commands = (category) => {
return client.commands
.filter(cmd => cmd.category === category)
.map(cmd => `- \`${cmd.name}\``)
.join("\n");
}
const info = client.categories
.map(cat => stripIndents`**${cat[0].toUpperCase() + cat.slice(1)}** \n${commands(cat)}`)
.reduce((string, category) => string + "\n" + category);
return message.channel.send(embed.setDescription(info));
}
function getCMD(client, message, input) {
const embed = new RichEmbed()
const cmd = client.commands.get(input.toLowerCase()) || client.commands.get(client.aliases.get(input.toLowerCase()));
let info = `No information found for command **${input.toLowerCase()}**`;
if (!cmd) {
return message.channel.send(embed.setColor("RED").setDescription(info));
}
if (cmd.name) info = `**Command name**: ${cmd.name}`;
if (cmd.aliases) info += `\n**Aliases**: ${cmd.aliases.map(a => `\`${a}\``).join(", ")}`;
if (cmd.description) info += `\n**Description**: ${cmd.description}`;
if (cmd.usage) {
info += `\n**Usage**: ${cmd.usage}`;
embed.setFooter(`Syntax: <> = required, [] = optional`);
}
return message.channel.send(embed.setColor("GREEN").setDescription(info));
}
ERROR:
Error message, bot not defined.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
I think the tempmute simply doesn't work because you use bot.on() instead of client.on(), which was defined in the index.js. I can't help you for the rest but everything is maybe related to this.

Categories

Resources