I'm trying to create a "help" command for my Discord bot, but it seems like I can't figure out why. THe purge command also doesn't work, but the rest of them are working. The kick, ping, ban and say commands are all working at the moment. And I'm also trying to figure out how to let the bot log command usage to the console. Any help would be appreciated !
client.on("message", async message => {
// This event will run on every single message received, from any channel or DM.
// It's good practice to ignore other bots. This also makes your bot ignore itself
// and not get into a spam loop (we call that "botception").
if(message.author.bot) return;
// Also good practice to ignore any message that does not start with our prefix,
// which is set in the configuration file.
if(message.content.indexOf(config.prefix) !== 0) return;
// Here we separate our "command" name, and our "arguments" for the command.
// e.g. if we have the message "+say Is this the real life?" , we'll get the following:
// command = say
// args = ["Is", "this", "the", "real", "life?"]
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
// Let's go with a few common example commands! Feel free to delete or change those.
if(command === "ping") {
// Calculates ping between sending a message and editing it, giving a nice round-trip latency.
// The second ping is an average latency between the bot and the websocket server (one-way, not round-trip)
const m = await message.channel.send("Ping?");
m.edit(`Pong! Latency is ${m.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ping)}ms`);
}
if(command === "say") {
// makes the bot say something and delete the message. As an example, it's open to anyone to use.
// To get the "message" itself we join the `args` back into a string with spaces:
const sayMessage = args.join(" ");
// Then we delete the command message (sneaky, right?). The catch just ignores the error with a cute smiley thing.
message.delete().catch(O_o=>{});
// And we get the bot to say the thing:
message.channel.send(sayMessage);
}
if (command === "kick") {
let modRole = message.guild.roles.find("name", "[Owner]");
if(message.member.roles.has(modRole.id)) {
let kickMember = message.guild.member(message.mentions.users.first());
message.guild.member(kickMember).kick();
message.channel.sendMessage("Member Kicked.");
} else {
return message.reply("You dont have the perms to kick members. scrub.");
}
}
if(command === "ban") {
let modRole = message.guild.roles.find("name", "[Owner]");
if(message.member.roles.has(modRole.id)) {
let banMember = message.guild.member(message.mentions.users.first());
message.guild.member(banMember).ban();
message.channel.sendMessage("Member banned.");
} else {
return message.reply("You dont have the perms to ban members. scrub.");
}
if(command === "purge") {
// This command removes all messages from all users in the channel, up to 100.
// get the delete count, as an actual number.
const deleteCount = parseInt(args[0], 10);
// Ooooh nice, combined conditions. <3
if(!deleteCount || deleteCount < 2 || deleteCount > 100)
return message.reply("Please provide a number between 2 and 100 for the number of messages to delete");
// So we get our messages, and delete them. Simple enough, right?
const fetched = await message.channel.fetchMessages({count: deleteCount});
message.channel.bulkDelete(fetched)
.catch(error => message.reply(`Couldn't delete messages because of: ${error}`));
}
if(command === "help") {
message.channel.send({embed: {
color: 3447003,
author: {
name: client.user.username,
icon_url: client.user.avatarURL
},
title: "Help",
description: "This message contains all the info of the bot's commands",
fields: [{
name: "d!help",
value: "This command can be used by everyone; displays this message"
},
{
name: "d!ping",
value: "This command can be used by everyone; it's tells the latency of the bot and the Discord API"
},
{
name: "d!kick <user>",
value: "This command can be used by [Owner]; it kicks a user"
},
{
name: "d!ban <user>",
value: "This command can be used by [Owner]; it bans a user"
},
{
name: "d!purge",
value: "This command isn't working correctly for as far as we know"
}
],
timestamp: new Date(),
footer: {
text: "© DeltBot Team"
}
}
Your fetched variable and bulkDelete needs to be in a async function since you're using await.
Related
I have been having some problems with my image cooldown script recently. It's intent, when it works, is to let users post images in between a set time limit, in order to prevent spamming. In Discord.JS v12, it was working perfectly. However, after installing v13.6, it does not do its job anymore. Here's the code.
On line 6, there is a line that excludes some channels from the cooldown. The rest of the channels in the server are subject to it though. I would appreciate some help with this code, as it is pretty important.
FYI: All intents have been enabled and listed in the index.js file. Everything else works, but not this script.
Here's the raw paste code, if you want to test the code out:
const talkedRecently = new Set();
client.on('messageCreate', async message => {
if (!message.guild) return;
if (message.author.bot) return;
if (!message.channel.type === 'dm') return;
if (!message.channel.id === 'channel1' || 'channel2' || 'channel3' || 'channel4' || 'channel5' || 'channel6' || 'channel7' || 'channel8') {
if (message.attachments.size > 0) {
if (talkedRecently.has(message.author.id)) {
setTimeout(()=> message.delete(), 5000).catch(err => console.log(err))
message.channel.send("You must wait 30 seconds before sending another attachment - " + message.author.username).then(msg => {
setTimeout(() => message.delete(), 10000)
}).catch(/*Your Error handling if the Message isn't returned, sent, etc.*/)
}
}
}
});
There are 5 issues with this code.
You are strict-comparing boolean to a string, which of course... will always return false
// DON'T DO THIS
if (!thing === 'one') {
// DO THIS
if (thing !== 'one') {
That's not how we compare multiple values in JS
// DON'T DO THIS
if (thing === "one" || "two" || "three")
// DO THIS
if ([ "one", "two", "three" ].includes(thing)) {
The channel IDs must be changed, there are no channels IDs such as channelN
You are deleting the same message 2 times
// Right here
setTimeout(()=> message.delete(), 5000).catch(err => console.log(err))
// ...
// And here
.then(msg => { setTimeout(() => message.delete(), 10000) }).catch(/*Your Error handling if the Message isn't returned, sent, etc.*/)
Your code is outdated and requires an update
See the update guide here.
As i said in the title i am getting this error, and I don't know how to fix it, but tutorials use the same thing and don't get this error. Pls help me i dont know what to do.
error:
"Cannot read property 'start' of undefined"
const ms = require('ms')
const { MessageEmbed } = require('discord.js')
module.exports = {
name : 'giveaway',
execute : async(message, args ,client) => {
if(!message.member.hasPermission('MANAGE_MESSAGES')) return message.channel.send('You dont have manage messages permission.')
const channel = message.mentions.channels.first()
if(!channel) return message.channel.send('Please specify a channel')
const duration = args[1]
if(!duration) return message.channel.send('please enter a valid duration')
const winners = args[2]
if(!winners) return message.channel.send('Please specify an amount of winners')
const prize = args.slice(3).join(" ")
if(!prize) return message.channel.send('Please sepcify a prize to win')
client.giveaways.start(channel, {
time : ms(duration),
prize : prize,
winnerCount: winners,
hostedBy: message.author,
messages: {
giveaway: "Giveaway \#everyone",
giveawayEnd: "Giveaway Ended \#everyone",
timeRemaining: "Time Remaining **{duration}**",
inviteToParticipate: "React with 🎉 to join the giveaway",
winMessage: "Congrats {winners}, you have won the giveaway",
embedFooter: "Giveaway Time!",
noWinner: "Could not determine a winner",
hostedBy: 'Hosted by {user}',
winners: "winners",
endedAt: 'Ends at',
units: {
seconds: "seconds",
minutes: "minutes",
hours: 'hours',
days: 'days',
pluralS: false
}
},
})
message.channel.send(`Giveaway is starting in ${channel}`)
}
}
error line code: client.giveaways.start(channel, {
index.js:
client.giveaways = new GiveawaysManager(client, {
storage : './giveaways.json',
updateCountdownEvery : 5000,
embedColor: '#D03600',
reaction: '🎉'
})
giveaways.json: []
Execute:
try{
command.execute(message,args, cmd, client, Discord);
} catch (err){
message.reply("There was an error trying to execute this command!");
console.log(err);
}
}
In your command.execute() call, you are passing in client as the fourth parameter. But in your command file, where you export the giveaway command, client is the third parameter.
module.exports = {
name : 'giveaway',
// Add cmd parameter here, so client is passed in correctly as the fourth parameter
execute : async(message, args, cmd, client) => { ... }
}
Yes I know TLDR but I would appreciate the help
Ok I have this wall of code below I use for applications
It uses a button to start the application (asking questions)
and after the application is filled in it sends that application to a specified applicationChannelId
is there any way I could add buttons to the application that was sent to the applicationChannelId to accept or deny members?
Accept would add a role by id and sends a message to the original applicant
//Not the code I tried using just an example for what the Accept button would do
//
let teamRole = message.guild.roles.cache.find(role => role.id == "761996603434598460")
member.roles.add(teamRole)
member.send("You have been accepted into the team")
Deny would send a message to the original applicant
I have tried doing this for the past few days but just can't get it to work it either does nothing or breaks everything
I have removed some info from the code below to make it shorter
Code for my button I already use to start the application for an applicant
client.on("message", async (message) => {
const reqEmbed = {
color: 0xed5181,
title: 'Blind Spot Team Requirements',
url: 'link',
author: {
name: '',
icon_url: '',
url: '',
},
description: '',
thumbnail: {
url: '',
},
fields: [{
"name": `Read through these Requirements`,
"value": `- requirments will go here`,
}, ],
image: {
url: '',
},
footer: {
text: 'Blind Spot est 2019',
icon_url: 'link',
},
};
//
// Don't reply to bots
let admins = ['741483726688747541', '741483726688747541'];
if (message.content.startsWith(`#blindspot`)) {
message.delete();
const amount = message.content.split(" ")[1];
if (!admins.includes(message.author.id)) {
message.reply("You do not have permission to do that!");
return;
}
// Perform raw API request and send a message with a button,
// since it isn't supported natively in discord.js v12
client.api.channels(message.channel.id).messages.post({
data: {
embeds: [reqEmbed],
components: [{
type: 1,
components: [{
type: 2,
style: 4,
label: "Apply",
// Our button id, we can use that later to identify,
// that the user has clicked this specific button
custom_id: "send_application"
}]
}]
}
});
}
});
Rest of code that handles questions and sends application to applicationChannelId when complete
// Channel id where the application will be sent
const applicationChannelId = "652099170835890177";
// Our questions the bot will ask the user
const questions = ["These are the questions but have deleted them to make this shorter",];
// Function that will ask a GuildMember a question and returns a reply
async function askQuestion(member, question) {
const message = await member.send(question);
const reply = await message.channel.awaitMessages((m) => {
return m.author.id === member.id;
}, {
time: 5 * 60000,
max: 1
});
return reply.first();
}
client.ws.on("INTERACTION_CREATE", async (interaction) => {
// If component type is a button
if (interaction.data.component_type === 2) {
const guildId = interaction.guild_id;
const userId = interaction.member.user.id;
const buttonId = interaction.data.custom_id;
const member = client.guilds.resolve(guildId).member(userId);
if (buttonId == "send_application") {
// Reply to an interaction, so we don't get "This interaction failed" error
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: "I have started the application process in your DM's.",
flags: 64 // make the message ephemeral
}
}
});
try {
// Create our application, we will fill it later
const application = new MessageEmbed()
.setTitle("New Application")
.setDescription(`This application was submitted by ${member}/${member.user.tag}`)
.setFooter("If the #Username doesn't appear please go to general chat and scroll through the member list")
.setColor("#ED4245");
const cancel = () => member.send("Your application has been canceled.\n**If you would like to start your application again Click on the Apply button in** <#657393981851697153>");
// Ask the user if he wants to continue
const reply = await askQuestion(member, "Please fill in this form so we can proceed with your tryout.\n" + "**Type `yes` to continue or type `cancel` to cancel.**");
// If not cancel the process
if (reply.content.toLowerCase() != "yes") {
cancel();
return;
}
// Ask the user questions one by one and add them to application
for (const question of questions) {
const reply = await askQuestion(member, question);
// The user can cancel the process anytime he wants
if (reply.content.toLowerCase() == "cancel") {
cancel();
return;
}
application.addField(question, reply);
}
await askQuestion(member, "Would you like to submit your Application?\n" + "**Type `yes` to get your Application submitted and reviewed by Staff Members.**");
// If not cancel the process
if (reply.content.toLowerCase() != "yes") {
cancel();
return;
}
// Send the filled application to the application channel
client.channels.cache.get(applicationChannelId).send(application);
} catch {
// If the user took too long to respond an error will be thrown,
// we can handle that case here.
member.send("You took too long to respond or Something went wrong, Please contact a Staff member\n" + "The process was canceled.");
}
}
}
});
at this point I just feel like not even doing this and keep it as is because its driving me insane
You very well can! just send it as you send your normal buttons!
const {
MessageButton,
MessageActionRow
} = require("discord.js"),
const denybtn = new MessageButton()
.setStyle('DANGER')
.setEmoji('❌')
.setCustomId('deny')
const acceptbtn = new MessageButton()
.setStyle('SUCCESS')
.setEmoji('✔')
.setCustomId('accept')
client.channels.cache.get(applicationChannelId).send({
embeds: [application],
components: [new MessageActionRow().addComponents["acceptbtn", "denybtn"]]
});
const collector = msg.createMessageComponentCollector({
time: 3600000,
errors: ["time"],
});
await collector.on("collect", async (r) => {
if (r.user.id !== message.author.id)
return r.reply({
content: "You may not accept/ deny this application",
ephemeral: true,
});
if (r.customId === "acceptbtn") {
let teamRole = message.guild.roles.cache.find(role => role.id == "761996603434598460")
member.roles.add(teamRole)
member.send("You have been accepted into the team")
}
if (r.customId === "denybtn") {
member.send("You have been rejected");
}
});
NOTE: Please be mindful that since your question lacks the functions / method definitions you are using I have used discord.js v13's methods, you may update your discord.js version and the code will work as intended ALTHOUGH the component collector's functions have been directly copy pasted from your question and in some instances such as member#send member is not defined, so please take this as an example and I urge you to write the code instead of copy pasting directly!
I'm trying to make a discord bot on, when pinging the owner, auto bans the author that pinged the player. The issue is, it bans the player for saying anything, how would I make it that it'd only ban if they pinged the owner?
Here's the code.
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '<#329005206526361610>'
client.once('ready', () => {
console.log("Wary's Defender Bot is up");
});
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
if (mention.startsWith('<#329005206526361610') && mention.endsWith('>')) return {
// mention = mention.slice(2, -1),
return: client.users.cache.get(mention)
}
}
client.on('message', _message => {
// if(!_message.content.users.has('#warycoolio')) return;
const user = getUserFromMention(_message.content);
if(user) return;
console.log('found target')
var member = _message.author
var rMember = _message.guild.member(_message.author)
// ban7, 'lol.'
rMember.ban({ days: 7, reason: 'They deserved it'}); {
// Successmessage
console.log('target dead.')
}
});
You can do this by checking _message.mentions.users with .has() and passing in the guild owner's id.
Use .has() instead of checking message content, this will automatically check the Message#mentions collection.
Dynamically get the guild owner's id using Guild#ownerID.
client.on('message', _message => {
if (_message.mentions.users.has(_message.guild.ownerID)) {
_message.author.ban({ days: 7, reason: 'They deserved it'});
}
});
You could just do a quick check to see if the mentions include a mention to the owner of the server, and then ban the user.
client.on("message", _message => {
if (_message.mentions.users.first().id === "owner id") {
message.author.ban()
}
})
My bot is not responding to any commands except for the .purge command.
Here is my code.
const { Client, MessageEmbed } = require('discord.js');
const client = new Client();
const { prefix, token } = require('./config.json');
client.on('ready', () => {
client.user.setStatus('invisible');
console.log('Bot ready!');
client.user.setActivity('Bot is in WIP Do not expect stuff to work', {
type: 'STREAMING',
url: "https://www.twitch.tv/jonkps4"
});
console.log('Changed status!');
});
client.on('message', message => {
if (message.content.startsWith(".") || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (message === 'apply') {
message.reply("The Small Developers Application form link is:")
message.reply("https://forms.gle/nb6QwNySjC63wSMUA")
}
if (message === 'kick') {
const user = message.mentions.users.first();
// If we have a user mentioned
if (user) {
// Now we get the member from the user
const member = message.guild.member(user);
// If the member is in the guild
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
// We let the message author know we were able to kick the person
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member \n Maybe due to I having missing permissions or My role is not the higher than the role the person to kick has');
// 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!");
}
}
if (command === 'purge') {
const amount = parseInt(args[0]) + 1;
if (isNaN(amount)) {
return message.reply('Not a valid number');
} else if (amount > 100) {
return message.reply('Too many messages to clear. \n In order to clear the whole channel or clear more please either ```1. Right click on the channel and click Clone Channel``` or ```2. Execute this command again but more times and a number less than 100.```');
} else if (amount <= 1) {
return message.reply('Amount of messages to clear **MUST** not be less than 1 or more than 100.')
}
message.channel.bulkDelete(amount, true).catch(err => {
console.error(err);
message.channel.send('**There was an error trying to prune messages in this channel!**');
});
}
});
client.login(token);
I need a specific command to work which is the .apply command
and i would like to know why my embeds do not work.
I tried this embed example It didn't work.
const embed = new MessageEmbed()
// Set the title of the field
.setTitle('A slick little embed')
// Set the color of the embed
.setColor(0xff0000)
// Set the main content of the embed
.setDescription('Hello, this is a slick embed!');
.setThumbnail('https://tr.rbxcdn.com/23e104f6348dd71d597c3246990b9d84/420/420/Decal/Png')
// Send the embed to the same channel as the message
message.channel.send(embed);
What did I do wrong? I am quite new to Discord.JS Any help would be needed.
You used the message parameter instead of command. Instead of message === 'xxx' put command === 'xxx'. Simple mistake, I think that was what you meant anyways. Of course the purge command worked because you put command === 'purge' there