Delaying a delete event - discord.js

I have a ticket system on my discord.js bot, and when you close it, it instantly closes. I was curious if there was a way to delay it from deleting for 1 hour. Here's my code:
const Discord = require('discord.js');
module.exports.run = async (bot, message, args) => {
if (!message.channel.name.startsWith('ticket')) return message.channel.send('You are not in a ticket channel!');
let reason = args[0] | 'Ticket Closed!'
message.channel.delete(args[0])
}
module.exports.help = {
name: "close"
}

One easy way to do it is with a simple setTimeout function. E.g.:
module.exports.run = async (bot, message, args) => {
if (!message.channel.name.startsWith('ticket')) return message.channel.send('You are not in a ticket channel!');
let reason = args[0] | 'Ticket Closed!'
setTimeout(() => {
message.channel.delete(args[0]);
}, 60 * 60 * 1000); // Sets timeout for 1 hour
}

You could use
.then(m => m.delete(time in ms));
after the message.
Or, if you want to edit it before you delete it:
const msg = await message.channel.send("Edit message!")
msg.edit("It's edited now!")
msg.edit("You can do it multiple times!")
// You can use a setTimeout() here if you want a delay. Also, make sure that this is in an async function
msg.delete()

Related

How to configure the timer code more efficiently?

When using this code, the message is updated every second, and then suddenly moves slowly or quickly in every five seconds. I want to make a more stable timer. What should I do?
const { Client, GatewayIntentBits, Collection } = require('discord.js');
module.exports = {
name: "timer",
async execute(message, args) {
ggg=args.shift(1)
let timecc = ggg*60
const tic = await message.reply("⏳"+parseInt((timecc / 60)/60)+"h"+parseInt((timecc / 60)%60)+"m"+(timecc % 60)+"s")
var timer = setInterval(() => {
timecc --
tic.edit({ content: "⏳"+parseInt((timecc / 60)/60)+"h"+parseInt((timecc / 60)%60)+"m"+(timecc % 60)+"s" })
.catch(console.warn = () => {});
if (timecc === 0) {
clearInterval(timer);
tic.edit({ content: "⌛"+"#everyone time out!" })
.catch(console.warn = () => {});
}
}, 1000)
}
}
Discord limits the amount of messages any user can send (you can try this yourself by spamming messages in any channel; you should see the same 5-second-interval behavior as your bot if you do it enough).
Sadly, the only solution for this is to send messages less often.

Setting a timeout to delete a message embed on discord.js

I have a basic ticketing system for a suggestions channel.
Ideally, when a user does .exesuggest <whatever suggestion they want> (.exe is the bot prefix), I want the bot to reply that the ticket has been sent to staff, i want the bot to delete the user's message, and to delete it's own message after 5 seconds. At the same time, the bot will send a message with the suggestion's author and the suggestion itself into a staff channel.
At the moment everything is working except for the bot deleting it's own message after 5 seconds.
Here is my code:
const Discord = require("discord.js")
const channelId = '873769980729106442'
const check = '✅'
let registered = false
const registerEvent = client => {
if (registered) {
return
}
registered = true
client.on('messageReactionAdd', (reaction, user) => {
if (user.bot) {
return
}
const { message } = reaction
if (message.channel.id === channelId) {
message.delete()
}
})
}
module.exports = {
commands: ['ticket', 'suggest', 'suggestion'],
minArgs: 1,
expectedArgs: '<message>',
callback: (userMessage, arguments, text, client) => {
const { guild, member } = userMessage
registerEvent(client)
const channel = guild.channels.cache.get(channelId)
const newTicketEmbed = new Discord.MessageEmbed()
.setAuthor(userMessage.author.username)
.setTitle('Created a new ticket.')
.setDescription(`"${text}"`)
.setFooter(`Click the ${check} icon to delete this message.`)
channel.send(newTicketEmbed).then(ticketMessage => {
ticketMessage.react(check)
const replyEmbed = new Discord.MessageEmbed()
.setDescription(`<#${member.id}> Your ticket has been created! Expect a reply soon!`)
userMessage.channel.send(replyEmbed)
})
}
}
I have a working command base handler in another file that makes the command work.
I just need to know exactly how to make that bot's reply in replyEmbed to be deleted after 5 seconds.
You can use a setTimeout function to delay the <message>.delete() function from executing.
Example:
setTimeout(function() { // Setup a timer
userMessage.delete(); // Deletes the users message
ticketMessage.delete(); // Deletes the ticket message
}, 5000); // 5 seconds in milliseconds
Full example:
const Discord = require("discord.js")
const channelId = '873769980729106442'
const check = '✅'
let registered = false
const registerEvent = client => {
if (registered) return;
registered = true
client.on('messageReactionAdd', (reaction, user) => {
if (user.bot) return;
const { message } = reaction
if (message.channel.id === channelId)
message.delete()
});
}
module.exports = {
commands: ['ticket', 'suggest', 'suggestion'],
minArgs: 1,
expectedArgs: '<message>',
callback: (userMessage, arguments, text, client) => {
const { guild, member } = userMessage
registerEvent(client)
const channel = guild.channels.cache.get(channelId)
const newTicketEmbed = new Discord.MessageEmbed()
.setAuthor(userMessage.author.username)
.setTitle('Created a new ticket.')
.setDescription(`"${text}"`)
.setFooter(`Click the ${check} icon to delete this message.`)
channel.send(newTicketEmbed).then(ticketMessage => {
ticketMessage.react(check)
const replyEmbed = new Discord.MessageEmbed()
.setDescription(`<#${member.id}> Your ticket has been created! Expect a reply soon!`)
userMessage.channel.send(replyEmbed);
setTimeout(function() { // Setup a timer
userMessage.delete(); // Deletes the users message
ticketMessage.delete(); // Deletes the ticket message
}, 5000); // 5 seconds in milliseconds
});
}
}
In Discord.js v13 you have to use setTimeout.
You can implement what you want like this:
userMessage.channel.send(replyEmbed).then(msg => {
setTimeout(() => msg.delete(), 5000);
});// It will delete after 5 seconds
It might work.
Message.delete has an options argument which is an object, and you can set the timeout there (v13 doesn’t have this!):
userMessage.delete({timeout: 5000}) //deletes after 5000 ms
v13 must use setTimeout since the feature was removed
setTimeout(() => userMessage.delete(), 5000) //deletes after 5000 ms

How do I update the presence of my Discord bot every like 5 minutes?

I am making a Discord bot using Discord.js V12, and I want to get it to display how many members (as a status/presence) are in a server but I can't get it to update how many members are in the server. How would I go about doing that? Here is the code I have so far:
It just won't detect when someone else joins the server unless I restart the bot.
const guild = client.guilds.cache.get('848109201901617193');
const activities = [
`over ${guild.memberCount - 7} members.`,
`over ${guild.memberCount - 7} members.`
]
setInterval(() => {
const randomIndex = Math.floor(Math.random() * (activities.length - 1));
const newActivity = activities[randomIndex];
client.user.setActivity(newActivity, { type: 'WATCHING' });
}, 10000);
client.on("ready", () => {
console.log("ready");
//...
client.user.setActivity(); //... put activity
});
client.on("guildMemberAdd", member => {
client.user.setActivity() //... same thing
})
//and do the same with guild member remove
The string needs to be updated each time you want to set the status.
setInterval(async () => {
const guild = await client.guilds.fetch('848109201901617193', true, true);
const newActivity = `over ${guild.memberCount - 7} members.`;
client.user.setActivity(newActivity , { type: 'WATCHING' });
}, 5 * 60 * 1000);
Note: If you have the Guild members intent client.guilds.fetch('848109201901617193') or ..cache.get(.. is fine too!
Alternative you could update the Status on the guildMemberAdd Event.
Your guild details are cache so that memberCount even discord API updated it. Add discord also slow update on this properties not update immediately when member join guild. And there is no need to random activities there.
So you need to fetch new guild details code will be:
setInterval(async () => {
const guild = await client.guilds.fetch('848109201901617193', true, true);
const newActivity = `over ${guild.memberCount - 7} members.`;
client.user.setActivity(newActivity , { type: 'WATCHING' });
}, 10000);
Docs for fetch new guild here

How can I fix my code for my discord bot?

I am trying to make a discord bot to spam #everyone and troll my friends, but I can't seem to get it to loop. What am I doing wrong?
const Discord = module.require("discord.js");
module.exports.run = async (bot, message, args) => {
try {
message.channel.send('#everyone listen to this man.');
message.delete(1000);
} catch(e) {
console.log(e.stack);
}
}
module.exports.help = {
name: "servernotgood",
desc: "Mentions everyone?.",
personalThoughts: "Its a command that mentions everyone.)"
}
I can't fix what you did but i can give you about what you want.
setInterval(() => {
message.channel.send("#everyone listen to this man.");
message.delete(1000); //if you want the message get deleted.
},1500);

How to make a bot that deletes a message and posts it in another channel based on reactions

I'm trying to make it so when my bot picks up a reaction in a specific channel, it'll see if it hit 10 reactions on a specific reaction. Then it'll delete the reacted message and post it into another specific channel with a message attached to it.
Here's the code
doopliss.on('message', message => {
if (message.channel.id === "587066921422290953") {
setTimeout(function(){
message.react(message.guild.emojis.get('587070377696690177'))
}, 10)
setTimeout(function(){
message.react(message.guild.emojis.get('587071853609353256'))
}, 50)
setTimeout(function(){
message.react(message.guild.emojis.get('587070377704816640'))
}, 100)
}
});
const message = require("discord.js");
const emoji = require("discord.js");
const reaction = require("discord.js");
doopliss.on('message', message => {
if (message.channel.id === "587066921422290953") {
let limit = 2; // number of thumbsdown reactions you need
if (message.reaction.emoji.name == message.guild.emojis.get('587070377696690177')
&& reaction.count >= limit) message.reaction.message.delete();
let tcontent = message.reaction.message.content
let accept = message.guild.channels.get('587097086256873483')
accept.send(`${tcontent} \`\`\`This server suggestion has been accepted by the community! Great job! Now a staff member just needs to forward it to username.\`\`\``)
}})
Can't figure out how to do this.
Expected Result: Bot sees if post has 10 reactions, then delete it and take the same message to a different channel
Actual Result: An error occurs Cannot read 'channel' property
First I want to say that some question here like this one have what you search.
Moreover, the discord documentation and the guide provide an awaiting reactions section.
There is some other question that refer to the subject or the function used in the guide and by searching a bit you can even find question like this one which is almost the same thing as you.
However, here is a complete example of what you want to do. You can add a timer to the promise instead of just waiting. I didn't use the reaction collector because promise are a bit faster, but you can also create a management system of multiple collector , or use the client.on('messageReactionAdd').
const Discord = require('discord.js');
const config = require('./config.json');
const channelSuggestion = '<channelID>';
const channelSend = '<channelID>';
const emojiReact = '<emojiID>';
const prefixSuggestion = '!';
const reactionMax = 11;
const client = new Discord.Client();
client.on('ready', () => {
console.log('Starting!');
client.user.setActivity(config.activity);
});
client.on('message', (msg) => {
if ((msg.content[0] === prefixSuggestion) && (msg.channel.type === 'dm')){
sendSuggestion(msg);
}
});
function filter(reaction) {
return reaction.emoji.id === emojiReact;
}
function moveSuggestion(msg) {
client.channels.get(channelSend).send(msg.content)
.then(() => msg.delete()).catch(err => console.log(error));
}
function sendSuggestion(msg){
client.channels.get(channelSuggestion).send(msg.content.substr(1))
.then((newMsg) => newMsg.react(emojiReact))
.then((newMsgReaction) =>
newMsgReaction.message
.awaitReactions(filter, {max: reactionMax})//, time: 15000, errors: ['time']})
.then(collected => {
moveSuggestion(newMsgReaction.message);
})
// .catch(collected => {
// console.log(`After a minute, only ${collected.size} out of 10 reacted.`);
// })
);
}
client.login(config.token)
.then(() => console.log("We're in!"))
.catch((err) => console.log(err));
The bot will listen to dm message (I don't know how you want your bot to send the suggestion message, so I made my own way) which start with a !.
Then the bot will send a message to a specific channel, wait for N person to add a reaction, and then will send the message to another channel.

Resources