I want bot to send first message only - javascript

I'm making a spam command. I want users to enter a message to spam but only the first message should be spam. No other message should be registered if 1 spam is already running.
My code -
else if (command === prefix + "spam" && args[0] !== undefined) {
message.reply("Quick tip: Use `stopspam` command to stop this")
spamInterval = setInterval(() => {
message.channel.send(`${args.slice(0).join(" ")}`);
}, 1500);
}

Define outside an status variable
let spamrunning=0
Then add the condition of that status variable, and the change of it.
else if (command === prefix + "spam" && args[0] !== undefined && spamrunning==0) {
message.reply("Quick tip: Use `stopspam` command to stop this")
spamrunning=1
spamInterval = setInterval(() => {
message.channel.send(`${args.slice(0).join(" ")}`);
}, 1500);
}
and change status again when you clear the interval
else if (command === prefix + "stopspam") {
...
spamrunning=0
}

Related

Having an issue with randomization in Discord JS

so i've been trying to make it so that every time the user sends a message there's a 50/50 chance that the bot reacts with an emoji, however the number is only picked every time i restart the bot. any ideas on how i can make it pick the number every time the command is triggered?
i tried to use setInterval but that didn't work so idk
here code;
const userID = "user id"
let random = Math.floor(Math.random()*2)
client.on('messageCreate', (message) => {
if(random === 1) {
if(message.author.id === userID) {
message.react('emoji');
}
}
});
Simply, define the random variable inside the messageCreate event.
Example:
const userID = "user id";
client.on('messageCreate', (message) => {
let random = Math.floor(Math.random() * 2);
if (random === 1) {
if (message.author.id === userID) {
message.react('emoji');
}
}
});
If you define random inside of the messageCreate event it means that a new random number is generated each time the even is called.
const userID = "user id"
client.on('messageCreate', (message) => {
let random = Math.floor(Math.random()*2)
if(random === 1) {
if(message.author.id === userID) {
message.react('emoji');
}
}
});
As Tyler2P has already shown an example, just wanted to explain why this works.
Thanks

How can you cancel your whole Discord Application

So I'm creating a Discord Application bot, Ban appeal Application that works within DM's only. I type the command p!apply and start the application, however whenever I try to cancel the application by typing cancel it only replies and does not actually cancel the whole form.
Here's my code:
let userApplications = {}
client.on("message", function(message) {
if (message.author.equals(client.user)) return;
let authorId = message.author.id;
if (message.content === prefix + "apply") {
if (!(authorId in userApplications)) {
userApplications[authorId] = { "step" : 1}
message.author.send("**__Team PhyZics Discord Ban Appeal Form__** \n If you're applying to get unbanned from our server, please fill this application out. We do not accept all applications, so take this application seriously and take your time when filling this out. \n \n - If you want to cancel this application please type `cancel`");
message.author.send("**Question 1: Which server did you get banned from?**");
}
} else {
if (message.channel.type === "dm" && authorId in userApplications) {
if (message.content.toLowerCase() === 'cancel') {
return message.author.send('Application Cancelled');
}
let authorApplication = userApplications[authorId];
if (authorApplication.step == 1 ) {
authorApplication.answer1 = message.content;
message.author.send("**Question 2: Why did you get banned/What reason did you get banned for?**");
authorApplication.step ++;
}
else if (authorApplication.step == 2) {
authorApplication.answer2 = message.content;
message.author.send("**Question 3: Why do you want to get unbanned?**");
authorApplication.step ++;
}
else if (authorApplication.step == 3) {
authorApplication.answer3 = message.content;
message.author.send("**Question 4: Any questions or concerns? If not, please type `no`.**");
authorApplication.step ++;
}
else if (authorApplication.step == 4) {
authorApplication.answer4 = message.content;
message.author.send("Your application has been submitted, please be patient and do not ask any staff member regarding to your ban appeal.");
client.channels.cache.get("790376360848785419")
.send(`**${message.author.tag}'s Application** \n **Q1**: ${authorApplication.answer1} \n **Q2:** ${authorApplication.answer2} \n **Q3:** ${authorApplication.answer3} \n **Q4:** ${authorApplication.answer4} `);
delete userApplications[authorId];
}
}
}
});
enter image description here
You're getting this problem because you're only returning a message Application cancelled without actually removing the user from your userApplications object.
To fix this, all you have to do is delete the entry from your object when the user cancels, like so:
if (message.content.toLowerCase() === 'cancel') {
delete userApplications[authorId];
return message.author.send('Application Cancelled');
}

I made this and my bot loops the "else" function. I'm confused cuz I don't think I have any intentions to make a looping function

I made a bot with purpose to manage discord roles and here's my code briefly
bot.on('message', (message) => {
const parts = message.content.split(' ');
if (parts[0] == 'Platform' || 'platform') {
if (parts[1] == 'iOS') {
message.channel.send(`thx, ${message.author}`)
message.member.roles.add(iOS);
}
else {
message.channel.send(`nooo`)
}
}
}
Why my else command keeps going over and over? How am I supposed to do in order to stop it?
Your code should read:
if (parts[0] == 'Platform' || parts[0] == 'platform') {

How to fix ReferenceError

After some modification, instead of message is not defined, it is receivedMessage.channel.bulkdelete(args[0].then (() => {
ReferenceError: receivedmessage is not defined. I am not really sure myself what does that mean because im new to node.js and javascript. If there is any mistakes I made please tell me!
client.on('message', (receivedMessage) => {
if (receivedMessage.author == client.user) { // Prevent bot from responding to its own messages
return
}
if (receivedMessage.content.startsWith("?")) {
processCommand(receivedMessage)
}
})
function processCommand(receivedMessage) {
let fullCommand = receivedMessage.content.substr(1) // Remove the leading exclamation mark
let splitCommand = fullCommand.split(" ") // Split the message up in to pieces for each space
let primaryCommand = splitCommand[0] // The first word directly after the exclamation is the command
let arguments = splitCommand.slice(1) // All other words are arguments/parameters/options for the command
console.log("Command received: " + primaryCommand)
console.log("Arguments: " + arguments) // There may not be any arguments
if (primaryCommand == "help") {
helpCommand(arguments, receivedMessage)
} else if (primaryCommand == "multiply") {
multiplyCommand(arguments, receivedMessage)
} else if(primaryCommand == "clear") {
clearCommand(arguments, receivedMessage)
} else {
receivedMessage.channel.send("I don't understand the command. Try `?help`, `?multiply` or '?clear'")
}
function helpCommand(arguments, receivedMessage) {
if (arguments.length > 0) {
receivedMessage.channel.send("It looks like you might need help with " + arguments + ".Try `!multiply 2 4 10` or `!multiply 5.2 7`")
} else {
receivedMessage.channel.send("I'm not sure what you need help with. Try `?help [topic]`")
}
}
function multiplyCommand(arguments, receivedMessage) {
if (arguments.length < 2) {
receivedMessage.channel.send("Not enough values to multiply. Try `!multiply 2 4 10` or `!multiply 5.2 7`")
return
}
let product = 1
arguments.forEach((value) => {
product = product * parseFloat(value)
})
receivedMessage.channel.send("The product of " + arguments + " multiplied together is: " + product.toString())
}
}
function clearCommand (arguments, receivedMessage) {
if (!recievedMessage.member.hasPermission("MANAGE_MESSAGES"))
return receivedmessage.reply("You have no permission to use this command.Sad.");
if (!args[0])
return receivedMessage.channel.send("Please specify a number.")
}
receivedmessage.channel.bulkDelete(args[0]).then(() => {
receivedMessage.channel.send(`Cleared ${args[0]} messages.`).then(msg => msg.delete(5000));
}
,)
You need to use receivedMessasge instead of message, as thats the name you choose in that function.
It kinda seems like you dont really have much experience and I would recommend you to read the offical discord.js guide: https://discordjs.guide . It will teach you how to write Discord Bots without needing to copy a lot of weired stuff into your Code!
1) You have defined receivedMessage instead of messsage
2) The code for clear command is not in any function and it executes once, before any messages.
You need to use receivedMessage instead of message and insert the code in the processCommand function
if (primaryCommand == "help") {
helpCommand(arguments, receivedMessage)
} else if (primaryCommand == "multiply") {
multiplyCommand(arguments, receivedMessage)
} else if(primaryCommand == "clear") {
if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.reply("You have no permission to use this command.Sad.");
if (!args[0]) return message.channel.send("Please specify a number.")
message.channel.bulkDelete(args[0]).then(() => {
message.channel.send(`Cleared ${args[0]} messages.`).then(msg => msg.delete(5000));
});
// or create a function for this command
} else {
receivedMessage.channel.send("I don't understand the command. Try `?help` or `?multiply`")
}

how to make a menu in discord.js?

I am currently making a discord bot using discord.js and i am trying to make a menu command so when a user types [prefix]menu it sends a picture of the menu
i can do that easily but i am trying to make it multipaged, i know i could just make a menu1, menu2 and menu3 command but id like to have a command saying nextpage and previouspage this is what i have so far but it doesn't work and there is no errors
if (command === "menu") {
output()
message.channel.send({file: './images/menu1.png'});
curPage = 1;
}
if (command === "next page") {
output()
curPage++;
if(curPage >= 3) {
output()
curPage = 3; message.channel.send("You're on the last page!");
}
} else if (command === "previous page") {
output()
curPage--;
if(curPage <= 0) {
output()
curPage = 1; message.channel.send("You're on the first page!");
}
message.channel.send({file: `./images/menu${curPage}.png`});
}
Use a ReactionCollector instead.
A collect event would be emitted when a user reacts to the targeted message.
Example:
const collector = message.createReactionCollector((reaction, user) =>
user.id === message.author.id &&
reaction.emoji.name === "◀" ||
reaction.emoji.name === "▶" ||
reaction.emoji.name === "❌"
).once("collect", reaction => {
const chosen = reaction.emoji.name;
if(chosen === "◀"){
// Prev page
}else if(chosen === "▶"){
// Next page
}else{
// Stop navigating pages
}
collector.stop();
});
Docs: Message, ReactionCollector, Reaction, User
I think the best way to achieve this, would be with .awaitMessages?
https://discord.js.org/#/docs/main/stable/class/TextChannel?scrollTo=awaitMessages
It might be worth trying something along these lines, however I'm not 100% sure about how to await multiple times for paging back and forth... I'd be interested in seeing someone elses solution for this.
For example:
if (command === "menu") {
message.channel.send({file: './images/menu1.png'});
.then(() => {
message.channel.awaitMessages(response => response.content === 'next', {
max: 1,
time: 30000,
errors: ['time'],
})
.then((collected) => {
message.channel.send({file: './images/menu2.png'});
})
.catch(() => {
// Do something with error
});
});
}

Categories

Resources