Message not defined discord.js chatbot - javascript

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

Related

discord bot does not get message for command

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.

discord.js Running a command sends a duplicate text

Here is my code, whenever I run the $dm command it runs it but also runs the $help command.
I know its probably a newbie question but if someone could help me out it will be appreciated
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
const { MessageEmbed } = require('discord.js');
client.once('ready', () => { client.user.setActivity('Use $help for a list of commands!', { type: "PLAYING" }); });
console.log('Ready!');
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
if (message.content.startsWith(`${prefix}ping`)) {
message.channel.send('Pong.');
} else if (message.content.startsWith(`${prefix}beep`)) {
message.channel.send('Boop.');
} else if (message.content === `${prefix}server`) {
message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
} else if (message.content === `${prefix}user-info`) {
message.channel.send(`Your username: ${message.author.username}\nYour ID: ${message.author.id}`);
console.log(message.content);
} else if (message.content === (`${prefix}dm`)) {
message.author.send("string");
} else if (message.content === "$help") {}
let embed = new MessageEmbed()
.setTitle("Command List")
.setDescription("$help, $ping, $beep, $server, $user-info, $dm")
.setColor("RANDOM")
message.channel.send(embed)
}
,
)
client.login(token)
else if (message.content === "$help") {} <- The issue
You're closing the curly braces too early and so the execution of your code below isn't actually dependant on the if statement.
It should look like this
else if (message.content === "$help") {
let embed = new MessageEmbed()
.setTitle("Command List")
.setDescription("$help, $ping, $beep, $server, $user-info, $dm")
.setColor("RANDOM")
message.channel.send(embed)
}
You must place this code:
let embed = new MessageEmbed()
.setTitle("Command List")
.setDescription("$help, $ping, $beep, $server, $user-info, $dm")
.setColor("RANDOM")
message.channel.send(embed)
within these curly braces:
} else if (message.content === "$help") {}
Tip: Use switch statements instead

How do I make a discord bot welcome command and leave command

I want to create an embedded welcome command and leave command. I would like an embedded DMS message for the person who joined the server.
This is the code I have so far:
const fs = require('fs');
const Discord = require('discord.js');
const {
prefix,
token
} = require('./config.json');
const client = new Discord.Client();
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);
}
const cooldowns = new Discord.Collection();
client.on('guildMemberAdd', member => {
if (!member.guild) return;
let guild = member.guild
let channel = guild.channels.cache.find(c => c.name === "welcome");
let membercount = guild.members
if (!channel) return;
let embed = new Discord.MessageEmbed().setColor("GREEN").setTitle("New Server Member!").setDescription(`Welcome, ${member.user.tag} to **${guild.name}!**`).setThumbnail(member.user.displayAvatarURL()).setFooter(`You are the ${membercount}th member to join`);
message.guild.channels.cache.find(i => i.name === 'sp').send(embed)
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setPresence({
status: "idle", //You can show online, idle.... activity: {
name: "with lower lifeforms!", //The message shown type: "PLAYING", // url: "" //PLAYING: WATCHING: LISTENING: STREAMING:
}
});
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName) || client.commands.find.Discord(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 3) * 1000;
if (timestamps.has(message.author.id)) {
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
}
}
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
Now on Discord, you will need to enable intents. To do this, go to the Discord Developer Portal, select your application, and go onto the Bot tab. If you scroll about half way down, you'll see a section called Privileged Gateway Intents. You need to tick Server Members Intent under that title. For what you're doing, Presence Intent shouldn't be required, but you can tick it in case you do ever need it.

How to add timed mute to discord.js

I'm making a discord bot and i want to add a timed mute function like in other moderation bots where you can say who you want to mute and for how long. I have done muting in general but now need the timed mute stuff so please help me. I am also not very good with Javascript so please tell me where i implement the code if you give me some. The mute file:
module.exports = {
name: "mute",
description: "mutes the mentioned user",
execute(message, args) {
const mutedRole = message.guild.roles.cache.find(
(role) => role.name === "muted"
);
const target = message.mentions.members.first();
if (!mutedRole) {
message.channel.send("Cannot find mute role.");
} else {
target.roles.add(mutedRole);
message.channel.send("Muted " + target + " ✅");
}
},
};
i want it that its -mute {user} {time}
an example is: -mute #ani 10s
if you want the main file here you go:
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("Ani Bot is online!");
client.user.setActivity("with depression");
});
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 === "test") {
client.commands.get("test").execute(message, args);
} else if (command === "mute") {
client.commands.get("mute").execute(message, args);
} else if (command === "unmute") {
client.commands.get("unmute").execute(message, args);
} else if (command === "join") {
client.commands.get("join").execute(message, args);
} else if (command === "leave") {
client.commands.get("leave").execute(message, args);
}
});
You can use the function setTimeout() right after you mute a user.
//you call the function unmuteUser after 10000 milliseconds
setTimeout(unmuteUser(user), 10000);
function unmuteUser(user){
//code that unmute
...
}

Discord bot kick

I started building a Discord bot and the first function I made was kicking members. This is the code
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.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
});
client.login(token);
If someone without the kick and ban permission tries it nothing happens so this part is working. If an admin types eg. :kick #someone then someone will be kicked. But if an Admin types :kick (without someone's username) I get an error and the bot stops working until I restart it manually. This is the error:TypeError: Cannot read property 'kick' of undefined. What can I do to make this fully working?
You'll need to check if that user exists.
Try is like this:
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if(!member) return message.channel.send('Cannot find this member');
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
And if you want to handle even more possible errors you'll need to use a try-catch block:
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if(!member) return message.channel.send('Cannot find this member');
try {
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
} catch (error) {
console.log(error);
message.channel.send('An error has occured');
}
}
}
Check if the user mentioned another user before kicking the member:
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.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if (!member)
return;
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
});
client.login(token);
You can't kick undefined.

Categories

Resources