I have the following code
const Discord = require("discord.js"),
{ MessageEmbed } = Discord,
ms = require("ms"),
module.exports.run = async (client, message) => {
async function awaitMessages(func) {
let output;
const m = await message.channel.awaitMessages({ filter: m => m.author.id === message.author.id, time: 60000 });
if (m.content !== "cancel") output = await func(m);
else return await message.channel.send("cancelled") && null;
if (typeof output === "function") return await output() && awaitMessages(func);
else return output;
}
function makeWaitArg(argName, description) {
const embeds = [new MessageEmbed()
.setTitle(`Giveaway ${argName}`)
.setDescription(description + " within the next 60 seconds.")
.setColor("#2F3136")
.setTimestamp()
.setFooter("Create A Giveaway! | Type cancel to cancel.", message.author.displayAvatarURL())];
return () => message.channel.send({ embeds: embeds })
};
function makeError(title, desc) {
const embeds = [new MessageEmbed().setFooter("type cancel to cancel")];
return () => message.channel.send({ embed: embeds })
}
const channel = await awaitMessages(makeWaitArg("Channel", "Please type the channel you want the giveaway to be in."), ({content}) => {
if (message.guild.channels.cache.has(content) || message.guild.channel.cache.get(content)) return content;
else return makeError("Channel", "That channel doesn't exist. Try Again.");
}),
prize = await awaitMessages(makeWaitArg("Prize.", "Please send what you would like the giveaway prize to be"), ({ content }) => {
if (content.length > 256) return makeError("Giveaway Prize Too Long.", "Please ensure the giveaway prize is less than 256 characters. Try again.");
else return content;
}),
// ill do those just be quick with logic
winnerCount = await awaitMessages(makeWaitArg("Winner Count.","Please send how many winners you would like the giveaway to have"), ({ content }) => {
if (isNaN(content)) return makeError("Invalid Winner Count.", "Please provide valid numbers as the winner count. Try again.");
else if (parseInt(content) > 15) return makeError("You can not have more than 15 winners per giveaway!")
else return content;
}),
time = await awaitMessages(makeWaitArg("Time.", "Please send how long you would like the giveaway to last"), ({ content }) => {
if (!ms(content)) return makeError("Invalid Time.", "Please provide a valid time. Try again.");
else return ms(content);
})
if (!channel || !prize || !winnerCount || !time) return;
// Start the giveaway
};
Recursion is being used to appropriately ask for multiple inputs upon failure to provide a correct input, according to my logic everything should work fine and from what I observe is that I face a massive latency between two of the steps which might be due to unnecessary load on the system while performing recursion, I need to know where that is originating and would like to rectify it.
Related
EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
Code:
const discord = require('discord.js')
const newEmbed = require('embedcord')
const randomHex = require('random-hex')
module.exports = (client, message, options) => {
let links = require('./links.json')
let foundLink = false
let banReason = (options && options.banReason) || 'Sent a phishing link.'
let logs = (options && options.logs)
let member = message.mentions.members.first()
for(var i in links) {
if(message.content.toLowerCase().includes(links[i])) foundLink = true
}
if(foundLink) {
if(message.author.hasPermission('ADMINISTRATOR'))
return
message.delete()
member.ban({reason: banReason})
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
)
logs.send(embed)
}
}
Your return position might be preventing anything below if from running try changing this
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) return;
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
Or this if you want if/else
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) {
return;
} else {
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
}
EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
foundLink variable is unnecessary, you can move your code inside the loop.
Use message.member.hasPermission() instead of message.author.hasPermission().
Example code for v12.5.3(Message Event):
client.on('message', (message) => {
if (message.author.bot) return; // Ignore bot messages
const { member, channel, guild } = message; // Get the message author, channel, and guild
if (!member || !channel || !guild) return; // Ignore messages without a member, channel or guild
const { links } = require('./links.json'); // Get links from json file
for (let i = 0; i < links.length; i++) { // Check if the message contains a link in the links.json file
if (message.content.toLowerCase().includes(links[i])) { // If the message contains a link
if (member.hasPermission('ADMINISTRATOR')) return; // If the member has the administrator permission, don't ban them
const banReason = 'Sent a phishing link'; // Reason for the ban
message.delete(); // Delete the message
guild.member(member).ban({ reason: banReason }); // Ban the member
channel.send(`${member.displayName} has been banned for sending a phishing link.`) // Send a message to the channel
break;
}
}
})
So I'm messing around with creating a discord bot that repeatedly pings a user until they respond/say anything in the chat (annoying, right?). The amount of times to ping the user and the time between each ping can also be adjusted if necessary. However, I can't seem to find a way to detect if the pinged user actually says something in the chat, and a way to stop the loop.
The actual pinging part of the code is in this for loop:
const ping = async () => {
for(var i = 1; i <= pingAmount; i++){
//the wait() command
await new Promise(r => setTimeout(r, pingTime * 1000));
//the actual ping
message.channel.send(`hey <#${userID}> let\'s play minecraft`);
}
//sends a message once pinging is finished
message.channel.send("Pinging Complete.");
};
I've tried nesting the following code inside that loop, but I get no results.
client.on('message', message =>{
if(message.author == taggedUser) {
message.channel.send('User has replied. Stopping pings.')
return;
}
});
Any help is appreciated!
full code below:
module.exports = {
name: 'Ping',
description: "Pings specified user until they appear",
execute(message, args, Discord){
//initialize variables
const client = new Discord.Client();
const taggedUser = message.mentions.users.first();
const userID = message.mentions.users.first().id;
//splits the command
const slicedString = message.content.split(' ');
//grabs specific numbers from command as input
const pingAmount = slicedString.slice(4,5);
const pingTime = slicedString.slice(5);
//display confirmation info in chat
message.channel.send(`So, ${message.author.username}, you want to annoy ${taggedUser.username}? Alright then lol`);
message.channel.send(`btw ${taggedUser.username}\'s user ID is ${userID} lmao`);
message.channel.send(`amount of times to ping: ${pingAmount}`);
message.channel.send(`time between pings: ${pingTime} seconds`);
//checks to make sure pingTime isnt too short
if(pingTime < 5){
if(pingTime == 1){
message.channel.send(`1 second is too short!`);
return;
} else {
message.channel.send(`${pingTime} seconds is too short!`);
return;
}
}
//timer and loop using pingAmount and pingTime as inputs
const ping = async () => {
for(var i = 1; i <= pingAmount; i++){
//the wait() command
await new Promise(r => setTimeout(r, pingTime * 1000));
//the actual ping
message.channel.send(`hey <#${userID}> let\'s play minecraft`);
const pingedUsers = [taggedUser];
// doodle message
const msg = {author: {id:1}};
// message event
const onMessage = (message) => {
if (pingedUsers.indexOf(message.author.id) != -1) {
console.log("user replied");
}
}
onMessage(msg); // nothing
pingedUsers.push(msg.author.id); // push the author id
onMessage(msg); // he replied!
}
//sends a message once pinging is finished
message.channel.send("Pinging Complete.");
};
//runs the ping function
ping();
}
}
You should be comparing the author's snowflake (id) in this case.
You can put the pinged users in a list and see if the message author is in that list.
const pingedUsers = [];
// doodle message
const msg = {author: {id:1}};
// message event
const onMessage = (message) => {
if (pingedUsers.indexOf(message.author.id) != -1) {
console.log("user replied");
}
}
onMessage(msg); // nothing
pingedUsers.push(msg.author.id); // push the author id
onMessage(msg); // he replied!
This is my purge command, I want my purge to ignore pins, anyone knows how could I do it?
This is what I got for now:
} else if (message.content.toLowerCase().startsWith(`${PREFIX}purge`)) {
if (!message.member.hasPermission('MANAGE_MESSAGES')) return message.channel.send("You don\'t have permissions to do this command")
if (!message.guild.me.hasPermission('MANAGE_MESSAGES')) return message.channel.send("I don\'t have permissions to do this command")
if (!args[1]) return message.channel.send("You need to specify a number of messages to purge")
if (isNaN(args[1])) return message.channel.send("That isn\'t a valid amount of messages to purge")
if (args[1] > 100 || args[1] < 2) return message.channel.send("Make sure that your amount is ranging 2 - 100")
try {
await message.channel.bulkDelete(fetch(message).filter(message => !message.pinned)).size
} catch {
return message.channel.send("You can only bulk delete messages within 14 days of age")
}
var embed = new Discord.MessageEmbed()
.setAuthor(`${message.author.username} - (${message.author.id})`, message.author.displayAvatarURL())
.setThumbnail(message.author.displayAvatarURL())
.setColor('#FFAE00')
.setDescription(`
**Deleted:** ${args[1]}
**Action:** Purge
**Channel:** ${message.channel}
**Time:** ${moment().format('llll')}
`)
const channel = message.guild.channels.cache.find(c => c.name === "audit-log")
channel.send(embed)
}
})
await message.channel.bulkDelete(fetch(message).filter(message => !message.pinned)).size
BTW this last line doesn't work but it is what I think I need to modify
Use this:
await message.channel.bulkDelete(
(await message.channel.messages.fetch({limit: args[1]}))
.filter(m => !m.pinned)
)
Note that if there are pinned messages, it will delete less messages than args[1].
How would i create a help command that displays all the commands when people do !help as i have no idea how to do a help command in the index.js file or would it be easir to put the help would be mutch apreated. its using the dicord econmy code but it dosnt have a help command to display all the commands
const eco = require("discord-economy");
//Create the bot client
const client = new Discord.Client();
//Set the prefix and token of the bot.
const settings = {
prefix: '!',
token: 'token'
}
//Whenever someone types a message this gets activated.
//(If you use 'await' in your functions make sure you put async here)
client.on('message', async message => {
//This reads the first part of your message behind your prefix to see which command you want to use.
var command = message.content.toLowerCase().slice(settings.prefix.length).split(' ')[0];
//These are the arguments behind the commands.
var args = message.content.split(' ').slice(1);
//If the message does not start with your prefix return.
//If the user that types a message is a bot account return.
if (!message.content.startsWith(settings.prefix) || message.author.bot) return;
if (command === 'balance') {
var output = await eco.FetchBalance(message.author.id)
message.channel.send(`Hey ${message.author.tag}! You own ${output.balance} coins.`);
}
if (command === 'daily') {
var output = await eco.Daily(message.author.id)
//output.updated will tell you if the user already claimed his/her daily yes or no.
if (output.updated) {
var profile = await eco.AddToBalance(message.author.id, 100)
message.reply(`You claimed your daily coins successfully! You now own ${profile.newbalance} coins.`);
} else {
message.channel.send(`Sorry, you already claimed your daily coins!\nBut no worries, over ${output.timetowait} you can daily again!`)
}
}
if (command === 'resetdaily') {
var output = await eco.ResetDaily(message.author.id)
message.reply(output) //It will send 'Daily Reset.'
}
if (command === 'leaderboard') {
//If you use discord-economy guild based you can use the filter() function to only allow the database within your guild
//(message.author.id + message.guild.id) can be your way to store guild based id's
//filter: x => x.userid.endsWith(message.guild.id)
//If you put a mention behind the command it searches for the mentioned user in database and tells the position.
if (message.mentions.users.first()) {
var output = await eco.Leaderboard({
filter: x => x.balance > 50,
search: message.mentions.users.first().id
})
message.channel.send(`The user ${message.mentions.users.first().tag} is number ${output} on my leaderboard!`);
} else {
eco.Leaderboard({
limit: 3, //Only takes top 3 ( Totally Optional )
filter: x => x.balance > 50 //Only allows people with more than 100 balance ( Totally Optional )
}).then(async users => { //make sure it is async
if (users[0]) var firstplace = await client.fetchUser(users[0].userid) //Searches for the user object in discord for first place
if (users[1]) var secondplace = await client.fetchUser(users[1].userid) //Searches for the user object in discord for second place
if (users[2]) var thirdplace = await client.fetchUser(users[2].userid) //Searches for the user object in discord for third place
message.channel.send(`My leaderboard:
1 - ${firstplace && firstplace.tag || 'Nobody Yet'} : ${users[0] && users[0].balance || 'None'}
2 - ${secondplace && secondplace.tag || 'Nobody Yet'} : ${users[1] && users[1].balance || 'None'}
3 - ${thirdplace && thirdplace.tag || 'Nobody Yet'} : ${users[2] && users[2].balance || 'None'}`)
})
}
}
if (command === 'transfer') {
var user = message.mentions.users.first()
var amount = args[1]
if (!user) return message.reply('Reply the user you want to send money to!')
if (!amount) return message.reply('Specify the amount you want to pay!')
var output = await eco.FetchBalance(message.author.id)
if (output.balance < amount) return message.reply('You have fewer coins than the amount you want to transfer!')
var transfer = await eco.Transfer(message.author.id, user.id, amount)
message.reply(`Transfering coins successfully done!\nBalance from ${message.author.tag}: ${transfer.FromUser}\nBalance from ${user.tag}: ${transfer.ToUser}`);
}
if (command === 'coinflip') {
var flip = args[0] //Heads or Tails
var amount = args[1] //Coins to gamble
if (!flip || !['heads', 'tails'].includes(flip)) return message.reply('Please specify the flip, either heads or tails!')
if (!amount) return message.reply('Specify the amount you want to gamble!')
var output = await eco.FetchBalance(message.author.id)
if (output.balance < amount) return message.reply('You have fewer coins than the amount you want to gamble!')
var gamble = await eco.Coinflip(message.author.id, flip, amount).catch(console.error)
message.reply(`You ${gamble.output}! New balance: ${gamble.newbalance}`)
}
if (command === 'dice') {
var roll = args[0] //Should be a number between 1 and 6
var amount = args[1] //Coins to gamble
if (!roll || ![1, 2, 3, 4, 5, 6].includes(parseInt(roll))) return message.reply('Specify the roll, it should be a number between 1-6')
if (!amount) return message.reply('Specify the amount you want to gamble!')
var output = eco.FetchBalance(message.author.id)
if (output.balance < amount) return message.reply('You have fewer coins than the amount you want to gamble!')
var gamble = await eco.Dice(message.author.id, roll, amount).catch(console.error)
message.reply(`The dice rolled ${gamble.dice}. So you ${gamble.output}! New balance: ${gamble.newbalance}`)
}
if (command == 'delete') { //You want to make this command admin only!
var user = message.mentions.users.first()
if (!user) return message.reply('Please specify a user I have to delete in my database!')
if (!message.guild.me.hasPermission(`ADMINISTRATION`)) return message.reply('You need to be admin to execute this command!')
var output = await eco.Delete(user.id)
if (output.deleted == true) return message.reply('Successfully deleted the user out of the database!')
message.reply('Error: Could not find the user in database.')
}
if (command === 'work') { //I made 2 examples for this command! Both versions will work!
var output = await eco.Work(message.author.id)
//50% chance to fail and earn nothing. You earn between 1-100 coins. And you get one out of 20 random jobs.
if (output.earned == 0) return message.reply('Awh, you did not do your job well so you earned nothing!')
message.channel.send(`${message.author.username}
You worked as a \` ${output.job} \` and earned :money_with_wings: ${output.earned}
You now own :money_with_wings: ${output.balance}`)
var output = await eco.Work(message.author.id, {
failurerate: 10,
money: Math.floor(Math.random() * 500),
jobs: ['cashier', 'shopkeeper']
})
//10% chance to fail and earn nothing. You earn between 1-500 coins. And you get one of those 3 random jobs.
if (output.earned == 0) return message.reply('Awh, you did not do your job well so you earned nothing!')
message.channel.send(`${message.author.username}
You worked as a \` ${output.job} \` and earned :money_with_wings: ${output.earned}
You now own :money_with_wings: ${output.balance}`)
}
if (command === 'slots') {
var amount = args[0] //Coins to gamble
if (!amount) return message.reply('Specify the amount you want to gamble!')
var output = await eco.FetchBalance(message.author.id)
if (output.balance < amount) return message.reply('You have fewer coins than the amount you want to gamble!')
var gamble = await eco.Slots(message.author.id, amount, {
width: 3,
height: 1
}).catch(console.error)
message.channel.send(gamble.grid)//Grid checks for a 100% match vertical or horizontal.
message.reply(`You ${gamble.output}! New balance: ${gamble.newbalance}`)
}
});
//Your secret token to log the bot in. (never show this to anyone!)
client.login(settings.token) ```
The easiest way to do it would be to add something like this
if (command === 'help') {
message.reply('here are my commands: commamd1 commamd2')
}
however, you could use an embed to make it look nicer, see here fore some info about them
I want to code a game for a Discord bot and I have a little problem with this code:
(async function() {
if (command == "rps") {
message.channel.send("**Please mention a user you want to play with.**");
var member = message.mentions.members.first()
if (!member) return; {
const embed = new Discord.RichEmbed()
.setColor(0xffffff)
.setFooter('Please look in DMs')
.setDescription(args.join(' '))
.setTitle(`<#> **Do you accept** <#>**'s game?**`);
let msg = await message.channel.send(embed);
await msg.react('✅');
await msg.react('❎');
}
}
})();
I want to EmbedMessage return after mention member. Like this:
User: rps
Bot: Please mention a user
User: mention user
Bot: embed
You can use TextChannel.awaitMessages():
(async function() {
if (command == "rps") {
message.channel.send("**Please mention a user you want to play with.**");
let filter = msg => {
if (msg.author.id != message.author.id) return false; // the message has to be from the original author
if (msg.mentions.members.size == 0) { // it needs at least a mention
msg.reply("Your message has no mentions.");
return false;
}
return msg.mentions.members.first().id != msg.author.id; // the mention should not be the author itself
};
let collected = await message.channel.awaitMessages(filter, {
maxMatches: 1,
time: 60000
});
// if there are no matches (aka they didn't reply)
if (collected.size == 0) return message.edit("Command canceled.");
// otherwise get the member
let member = collected.first().mentions.members.first();
const embed = new Discord.RichEmbed()
.setColor(0xffffff)
.setFooter('Please look in DMs')
.setDescription(args.join(' '))
.setTitle(`<#> **Do you accept** <#>**'s game?**`);
let msg = await message.channel.send({
embed
});
await msg.react('✅');
await msg.react('❎');
}
})();