Hello I am trying to use a discord bot to wait for a message from an admin of my server and then check the following messages from users. My code waits for the admin message however it somehow caches it ?? At least it doesnt check the users messages. I made my bot write the message where it got triggered to make it more understandable:
const Discord = require("discord.js");
const bot = new Discord.Client();
const bot_config = require("./settings.json")
var token = bot_config.usertoken
var userid = bot_config.userid
var channel = "940800688219369483"; //
bot.on("ready", () => {
console.log(`SUCCESSFULLY LOGGED IN AS ${bot.user.tag}!`);
});
let counter = 0
bot.on("message", (msg) => {
//Waiting for mesage from specific admin
if(msg.author == "1011983215650672781"){
if(counter == 0){ // check if message has already been send
if (msg.channel.id != channel) return; // Checks valid Channel ID
if (msg.author == userid && msg.author == "703629528454660106" && msg.authot == "255396012045238222" && msg.authot == "142772377047199744" && msg.authot == "235748962103951360") { //CHECK IF NEXT MESSAGE IS NOT AN ADMIN
console.log("ADMIN MESSGAE");
}
else{
let answer = msg.content
bot.channels.cache.get(channel).send(answer)
counter ++
console.log("SUCCESSFULLY SENT MESSAGE")
}
}
else{
console.log("ALREADY SENT MESSAGE - CLOSE BOT")
}
}
})
bot.login(usertoken)
The problem is, the bot still writes the first admin message in the channel and not the onw from the first user
You might kick yourself for this, but you have used msg.authot instead of msg.author.id.
You may want to check out the docs, they come in handy when you need to know how to access properties.
I want to create a command to send DM to users who reacted (all reactions) to a message from ID. I want to filter the bots and don't send two messages for one user if they reacted twice.
if (command === 'gopv') {
message.channel.messages.fetch("806866144597770280").then((reactionMessage) => {
console.log(
reactionMessage.reactions.cache
.each(async(reaction) => await reaction.users.fetch())
.map((reaction) => reaction.users.cache.filter((user) => !user.bot))
.flat()
);
});
}
I would probably create a dmSent object with the user IDs as keys, so I could easily check if a DM was already sent to them. When you loop over the users reacted to the message, you can check if the ID already exists or if the user is a bot. If the user is not found in the dmSent object, you can send a message and add the user ID to the object.
I've just checked it, the following sends only one message to each user who reacted at least to the message:
if (command === 'gopv') {
const dmSent = {};
try {
const { reactions } = await message.channel.messages.fetch('806866144597770280');
reactions.cache.each(async (reaction) => {
const usersReacted = await reaction.users.fetch();
usersReacted.each((user) => {
if (dmSent[user.id] || user.bot) return;
dmSent[user.id] = true;
user.send('You sent at least one reaction, so here is a DM.');
});
});
} catch (err) {
console.log(err);
}
}
I want the user to input !fn maxtl and the bot would reply by putting out this link
https://fortnitetracker.com/profile/all/maxtl/event
This is what I am thinking it would look like. Can someone provide me with any suggestions on how to improve this Discord bot API usage?
bot.on("message", (msg) => {
if (msg.content === `!fn ${Username}`) {
msg.reply(`https://fortnitetracker.com/profile/all/${Username}/events`);
}
});
Assuming you aren't doing any other processing of the message, this is what you'll probably need to do.
bot.on("message", (msg) => {
if (!msg.content.startsWith('!')) return;
const arguments = msg.content.split(' ');
const command = arguments.shift();
if (command === '!fn') {
msg.reply(`https://fortnitetracker.com/profile/all/${arguments[0]}/events`);
}
});
This will
Check and see that the message begins with your command identifier (assuming it's "!")
Split the message in to an array of arguments;
Remove and store the command in a command variable
Check to see if the command is equal to "!fn"
Reply with a url that includes argument[0] which at this point would be equal to the username if one was provided.
I think this block of code is something you are looking for, I am not 100% because I don't know what the rest of your bot is doing.
This code will
Listen for a message
The bailout of the code execution if the message doesn't start with !fn
Attempts to find the message with mentioned Username (your snippet shows this variable
available so I assume it's known beforehand, if not we can figure that out too)
The Bot tries to post the message
bot.on('message', async (msg) => {
if (!msg.content.startsWith('!fn')) return;
const commandFound = msg.content.find(mentioned => mentioned === `!fn ${Username}`)
const arguments = commandFound.split(' ');
const userName = arguments.shift();
if (userName) {
try {
await msg.reply(`https://fortnitetracker.com/profile/all/${userName}/events`);
} catch (err) {
console.warn('Failed to respond to mention.');
console.warn(err);
}
}
});
Ok, I know that there are similar questions out there but no matter what I try I get the same result. I have been trying for 2 days now to figure out how to check if I had the "OverBot-Admin" role for a ban command. But whenever I run the command it spams the chat! Here is my code:
if (command === "ban") {
if(message.member.roles.has(role => role.name === "OverBot-Admin")) {
let reason = args.slice(1).join(" ");
if (!reason) reason = "No reason provided";
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.ban({ reason: "They were being bad." })
.then(() => {
message.reply(
":white_check_mark: Successfully banned " +
message.user.id +
"for " +
reason
);
const embed = new Discord.RichEmbed()
.setTitle("Ban")
.addField("Member:", message.user.id)
.addField("Reason:", reason)
.setTimestamp()
.setFooter(
"Created by OverThrow, OverBot SE",
"https://cdn.discordapp.com/avatars/649431468254429224/0b63291c1e7342c2320ca5c3cce806ca.png?size=2048"
);
})
.catch(err => {
message.reply(":x: I was unable to ban that member!");
console.error(err);
});
} else {
message.reply(":x: That user isn't a member to this guild!");
}
} else {
message.reply(":x: You didn't mention a member to ban!");
}
}
} else {
message.reply(":x: I couldn't ban this user, please make sure you have the OverBot-Admin role!")
}
message.member.roles.has() requires a role ID as an argument, whereas here, you are passing in a function. The method I think you are looking for is Collection.exists (although this method is deprecated, if anyone can figure out a different way to go about this, please let me know).
Looking at the message.reply in the then function after banning, I see a message.user.id. However, message.user does not seem to be a valid property of the message object according to the docs. I assume that you would be referring to the user who was just banned, in which case you can reuse the user or member variable you previously defined.
If you have further problems, feel free to comment back.
So I have been search far and wide over the internet, trying to find a possible way to make a purge command. Now I have found quite a lot of different ways to make one, but none of them either suited me in the way I wanted, or simply worked for me.
SO to start off, here is my code
const Discord = require("discord.js"); // use discord.js
const BOT_TOKEN = "secret bot token :)" // bot's token
const PREFIX = "*" // bot's prefix
var eightball = [ // sets the answers to an eightball
"yes!",
"no...",
"maybe?",
"probably",
"I don't think so.",
"never!",
"you can try...",
"up to you!",
]
var bot = new Discord.Client(); // sets Discord.Client to bot
bot.on("ready", function() { // when the bot starts up, set its game to Use *help and tell the console "Booted up!"
bot.user.setGame("Use *info") // sets the game the bot is playing
console.log("Booted up!") // messages the console Booted up!
});
bot.on("message", function(message) { // when a message is sent
if (message.author.equals(bot.user)) return; // if the message is sent by a bot, ignore
if (!message.content.startsWith(PREFIX)) return; // if the message doesn't contain PREFIX (*), then ignore
var args = message.content.substring(PREFIX.length).split(" "); // removes the prefix from the message
var command = args[0].toLowerCase(); // sets the command to lowercase (making it incase sensitive)
var mutedrole = message.guild.roles.find("name", "muted");
if (command == "help") { // creates a command *help
var embedhelpmember = new Discord.RichEmbed() // sets a embed box to the variable embedhelpmember
.setTitle("**List of Commands**\n") // sets the title to List of Commands
.addField(" - help", "Displays this message (Correct usage: *help)") // sets the first field to explain the command *help
.addField(" - info", "Tells info about myself :grin:") // sets the field information about the command *info
.addField(" - ping", "Tests your ping (Correct usage: *ping)") // sets the second field to explain the command *ping
.addField(" - cookie", "Sends a cookie to the desired player! :cookie: (Correct usage: *cookie #username)") // sets the third field to explain the command *cookie
.addField(" - 8ball", "Answers to all of your questions! (Correct usage: *8ball [question])") // sets the field to the 8ball command
.setColor(0xFFA500) // sets the color of the embed box to orange
.setFooter("You need help, do you?") // sets the footer to "You need help, do you?"
var embedhelpadmin = new Discord.RichEmbed() // sets a embed box to the var embedhelpadmin
.setTitle("**List of Admin Commands**\n") // sets the title
.addField(" - say", "Makes the bot say whatever you want (Correct usage: *say [message])")
.addField(" - mute", "Mutes a desired member with a reason (Coorect usage: *mute #username [reason])") // sets a field
.addField(" - unmute", "Unmutes a muted player (Correct usage: *unmute #username)")
.addField(" - kick", "Kicks a desired member with a reason (Correct usage: *kick #username [reason])") //sets a field
.setColor(0xFF0000) // sets a color
.setFooter("Ooo, an admin!") // sets the footer
message.channel.send(embedhelpmember); // sends the embed box "embedhelpmember" to the chatif
if(message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.channel.send(embedhelpadmin); // if member is a botadmin, display this too
}
if (command == "info") { // creates the command *info
message.channel.send("Hey! My name is cookie-bot and I'm here to assist you! You can do *help to see all of my commands! If you have any problems with the Minecraft/Discord server, you can contact an administrator! :smile:") // gives u info
}
if (command == "ping") { // creates a command *ping
message.channel.send("Pong!"); // answers with "Pong!"
}
if (command == "cookie") { // creates the command cookie
if (args[1]) message.channel.send(message.author.toString() + " has given " + args[1].toString() + " a cookie! :cookie:") // sends the message saying someone has given someone else a cookie if someone mentions someone else
else message.channel.send("Who do you want to send a cookie to? :cookie: (Correct usage: *cookie #username)") // sends the error message if no-one is mentioned
}
if (command == "8ball") { // creates the command 8ball
if (args[1] != null) message.reply(eightball[Math.floor(Math.random() * eightball.length).toString(16)]); // if args[1], post random answer
else message.channel.send("Ummmm, what is your question? :rolling_eyes: (Correct usage: *8ball [question])"); // if not, error
}
if (command == "say") { // creates command say
if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!");
var sayMessage = message.content.substring(4)
message.delete().catch(O_o=>{});
message.channel.send(sayMessage);
}
if(command === "purge") {
let messagecount = parseInt(args[1]) || 1;
var deletedMessages = -1;
message.channel.fetchMessages({limit: Math.min(messagecount + 1, 100)}).then(messages => {
messages.forEach(m => {
if (m.author.id == bot.user.id) {
m.delete().catch(console.error);
deletedMessages++;
}
});
}).then(() => {
if (deletedMessages === -1) deletedMessages = 0;
message.channel.send(`:white_check_mark: Purged \`${deletedMessages}\` messages.`)
.then(m => m.delete(2000));
}).catch(console.error);
}
if (command == "mute") { // creates the command mute
if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!"); // if author has no perms
var mutedmember = message.mentions.members.first(); // sets the mentioned user to the var kickedmember
if (!mutedmember) return message.reply("Please mention a valid member of this server!") // if there is no kickedmmeber var
if (mutedmember.hasPermission("ADMINISTRATOR")) return message.reply("I cannot mute this member!") // if memebr is an admin
var mutereasondelete = 10 + mutedmember.user.id.length //sets the length of the kickreasondelete
var mutereason = message.content.substring(mutereasondelete).split(" "); // deletes the first letters until it reaches the reason
var mutereason = mutereason.join(" "); // joins the list kickreason into one line
if (!mutereason) return message.reply("Please indicate a reason for the mute!") // if no reason
mutedmember.addRole(mutedrole) //if reason, kick
.catch(error => message.reply(`Sorry ${message.author} I couldn't mute because of : ${error}`)); //if error, display error
message.reply(`${mutedmember.user} has been muted by ${message.author} because: ${mutereason}`); // sends a message saying he was kicked
}
if (command == "unmute") { // creates the command unmute
if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!"); // if author has no perms
var unmutedmember = message.mentions.members.first(); // sets the mentioned user to the var kickedmember
if (!unmutedmember) return message.reply("Please mention a valid member of this server!") // if there is no kickedmmeber var
unmutedmember.removeRole(mutedrole) //if reason, kick
.catch(error => message.reply(`Sorry ${message.author} I couldn't mute because of : ${error}`)); //if error, display error
message.reply(`${unmutedmember.user} has been unmuted by ${message.author}!`); // sends a message saying he was kicked
}
if (command == "kick") { // creates the command kick
if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!"); // if author has no perms
var kickedmember = message.mentions.members.first(); // sets the mentioned user to the var kickedmember
if (!kickedmember) return message.reply("Please mention a valid member of this server!") // if there is no kickedmmeber var
if (!kickedmember.kickable) return message.reply("I cannot kick this member!") // if the member is unkickable
var kickreasondelete = 10 + kickedmember.user.id.length //sets the length of the kickreasondelete
var kickreason = message.content.substring(kickreasondelete).split(" "); // deletes the first letters until it reaches the reason
var kickreason = kickreason.join(" "); // joins the list kickreason into one line
if (!kickreason) return message.reply("Please indicate a reason for the kick!") // if no reason
kickedmember.kick(kickreason) //if reason, kick
.catch(error => message.reply(`Sorry #${message.author} I couldn't kick because of : ${error}`)); //if error, display error
message.reply(`${kickedmember.user.username} has been kicked by ${message.author.username} because: ${kickreason}`); // sends a message saying he was kicked
}
});
bot.login(BOT_TOKEN); // connects to the bot
It is the only file in my bot folder except the package.json, package-lock.json and all the node_modules.
What I'm trying to do is type in discord *purge [number of messages I want to purge] and get the bot to delete the amount of the messages I asked it to delete, PLUS the command I entered (for example, if I ask the bot to delete 5 messages, he deletes 6 including the *purge 5 message.
Any help would be much appreciated, thanks!
What you are looking for is this (bulkDelete()) method for Discord.js.
It bulk deletes a message, just simply pass in a collection of message in the method and it will do the job for you.
(You can use messages property from channel, otherwise if you prefer promises, then try fetchMessages() method. )
Just make sure that the channel is not a voice channel, or a DM channel. And finally, your bot needs to have permission too.
You can get your own bot's permission for the guild using message.guild.member(client).permissions, or you can just directly use message.guild.member(client).hasPermission(permission), which returns a boolean that determines if your bot have a desired permission.
(The method docs for hasPermission() is here)
note sure if this is still relevant but this what i use in my bots
if (!suffix) {
var newamount = "2";
} else {
var amount = Number(suffix);
var adding = 1;
var newamount = amount + adding;
}
let messagecount = newamount.toString();
msg.channel
.fetchMessages({
limit: messagecount
})
.then(messages => {
msg.channel.bulkDelete(messages);
// Logging the number of messages deleted on both the channel and console.
msg.channel
.send(
"Deletion of messages successful. \n Total messages deleted including command: " +
newamount
)
.then(message => message.delete(5000));
console.log(
"Deletion of messages successful. \n Total messages deleted including command: " +
newamount
);
})
.catch(err => {
console.log("Error while doing Bulk Delete");
console.log(err);
});
basic function is to specify number of messages to purge and it will delete that many plus the command used, the full example is here