Discord.js - Getting information after Prefix and command - arrays

I'm now working in a new command, a poll command.
For that, I need a way of get the arguments after the prefix and the command itself.
Example: +Poll Do you like puppies?
And, it'd ignore the "+Poll", and get only the question itself, for then create a poll.
To get the arguments, I'm using:
var Args = message.content.split(/\s+/g)

You probably want to try creating the poll with a command, store the question in your database, and then use a separate command to display current polls that are open. Then the users would select the poll via command and the bot would await the response to the question.
I won't go into detail about storing the question in a database, because that's a totally different question. If you need help setting up a local database and store the polls, link to another question and I'll be happy to give more examples.
To go with your question, I would suggest using subStr to save each word after the command in an array, so you can later use those parts in the code. Something like this will store everything after !poll in the variable poll:
if (message.content.startsWith("!poll ")) {
var poll = message.content.substr("!poll ".length);
// Do something with poll variable //
message.channel.send('Your poll question is: ' + poll);
});
For the user answering the poll, you can try using awaitMessage to ask the question, and give a set number of responses. You would want to wrap this in a command that queries your database for the available polls first, and use that identifier to actually get the right question and possible reponses. The example below just echos the response that is collected, but you would want to store the response in the database instead of sending it in a message.
if (message.content === '!poll') {
message.channel.send(`please say yes or no`).then(() => {
message.channel.awaitMessages(response => response.content === `yes` || response.content === 'no', {
max: 1, // number of responses to collect
time: 10000, //time that bot waits for answer in ms
errors: ['time'],
})
.then((collected) => {
var pollRes = collected.first().content; //this is the first response collected
message.channel.send('You said ' + pollRes);
// Do something else here (save response in database)
})
.catch(() => { // if no message is collected
message.channel.send('I didnt catch that, Try again.');
});
});
};

Related

How to check if message contains emojis discord.js

I need to check if a message sent by user contains emojis because my database can't store this type of data. So I thought that I'll use a message.content.match() or message.content.includes() but when I use it, it still is not enough. I was thinking about making something like blacklist but for emojis and then I realized that I need to save a blacklist of all emojis so I gave up on that. My question for you is, do you know any easier way to make this? I was searching for solution to my problem but I didn't find anything.
Thank you a lot for any help.
if(message.author.id!='botid' && message.author.id===userdbId && message.content.match(/<a?:.+?:\d+>/)){
const name = args.join(" ");
const username = name.slice(0);
conn.query(`UPDATE users SET ignick='`+username+`' WHERE userID='${message.author.id}'`);
console.log(username);
message.channel.send("success message");
conn.end(err => {
if(err){
throw error;
}
console.log('Disconnected from database');
})
}
else{
console.log('bot has been stopped from adding his message to database');
}```
At top of this code i made a connect function and two constructors to pull from database userId
Whenever an emote is used in a message, it follows this format: <:OmegaStonks:723370807308582943>, where the name of the emote is "OmegaStonks" and the id links to the link to the image, like so: https://cdn.discordapp.com/emojis/723370807308582943.png
Detecting this pattern is pretty easy using regex.
<a?:.+?:\d+>
which takes any character from the first : to the second : (and I used a ? to make the wildcard . stop as soon as possible). You also can't have colons in emote names, so it won't abruptly stop there.
Source
Here is how you could do it
client.on('message', msg => {
if(msg.content.match(/<a?:.+?:\d+>/)) return; //or whatever action(s) you want to do
})

I want a discord bot send a dm to somebody by their id

if (message.content === "!test"){
client.users.cache.get('id').send('message');
console.log("message sent")
}
This method doesn't work and I wasn't able to find any other methods that worked
Is there a spelling mistake or this method is outdated?
I've actually encountered this error myself once. There are two problems you might be facing here:
The user isn't cached by discord.js yet
There isn't a DMChannel open for that user yet
To solve the first one, you have to fetch the user before doing anything with it. Remember this is a Promise, so you'll have to either await for it to complete or use .then(...).
const user = await client.users.fetch('id')
Once you've fetched your user by their ID, you can then create a DMChannel which, again, returns a promise.
const dmChannel = await user.createDM()
You can then use your channel like you normally would
dmChannel.send('Hello!')
Try to create a variable like this:
var user = client.users.cache.find(user => user.id === 'USER-ID')
And then do this:
user.send('your message')

How to log custom status updates using discord.js?

I've been working on a blacklisted words option, along with logging when a member of a guild sets a custom status containing a blacklisted word. However, I've run into a problem that I sometimes get the old status same as the new status (only for some guilds tho, others are fine). My code it here:
client.on("presenceUpdate", (oldPresence, newPresence) => {
const newCustomStatus = newPresence.activities[0].state
const oldCustomStatus = oldPresence.activities[0].state
console.log('old status: ' + oldCustomStatus)
console.log('new status: ' + newCustomStatus)
})
oldCustomStatus is sometimes same as newCustomStatus in some guilds, which makes it impossible to log the old status. It only happens in like a half of the guilds the member and bot share.
I thought about making a cache of all statuses on bots start and only toggling the event once, which would allow me to read both the new and old status, since there was always at least one guild with correct info. However, I couldn't then run a per-guild check for blacklisted words, since I don't know a way of reading guild IDs from a user object.
Any way of fixing the broken old and new status? Or a way to get a list of guild IDs the user and bot share?
Thanks
I found out it fires more than once by also logging the guild ID. That seems to solve half of the issue since the next fire takes the new status as both the old and new status. Not sure why it fires more than once tho.A simple solution for the logger is to use an if statement and compare the new and old statuses, and only log them if they are different:
client.on("presenceUpdate", (oldPresence, newPresence) => {
const newCustomStatus = newPresence.activities[0].state
const oldCustomStatus = oldPresence.activities[0].state
if(newCustomStatus != oldCustomStatus) {
console.log('old status: ' + oldCustomStatus)
console.log('new status: ' + newCustomStatus)
}
})
Not sure why it fires more than once, this solution is 100% working for me tho.

Discord.js - Getting multiple reactions to execute a command through awaitReactions method

I'm currently in the process of making a little game of TicTacToe, and the idea I had in mind is to make it so instead of the channel being spammed with constant embeds asking for the person's next move, is to simply make it reaction-based, where you get to pick 1 out of 9 reactions (And of course, you wont be able to pick it again if the other player has already picked it).
I have never really worked with requiring multiple reactions, therefore I'd like to ask your help on how exactly to make it so that the message command execution isn't a one-time thing, but will go on until there's eventually a winner.
So far, with the code I have written, this does work 2 times, but then it randomly stops and no longer works.
In addition, when I'm trying to declare a spot as an x or a circle, the spot turns completely blank.
Please help!
The code I have so far:
https://sourceb.in/S7cayfoYjp
Edit: I have now also found that the bot at first kind of skips the whole awaitReactions code. I used 'console.log(i)' for this, so that every time it loops it prints out 'i', and it seemed to be printing out the numbers 0-8 immediately, meaning it's not properly going through the code.
I think what you can use best there is a reactionCollector. It's a temporary reaction listener, attached to a message. A sample code for that would be:
const msg = await message.channel.send('tic tac toe test');
const acceptedEmojis = ['↖️', '⬆️', '↗️', '⬅️', '⏺️', '➡️', '↙️', '⬇️', '↘️']
const filter = (reaction, user) => {
return acceptedEmojis.includes(reaction.emoji.name) && user.id === turnId;
}
//here you create the collector. It has following attributes: it stops after 10 minutes or after 2 minutes of not collecting anything.
const collector = msg.createReactionCollector(filter, { time: 600000, idle: 120000});
//here you start the listener
collector.on('collect', (reaction, user) => {
if (reaction.emoji.name === '↖️') {
//remove the reaction
await msg.reactions.resolve('↖️')
acceptedEmojis.splice(acceptedEmojis.indexOf('↖️'), 1);
//rest of your code...
} else if (reaction.emoji.name === '⬆️') {
...
}
});

How to save some variables

ABOUT ME:
This question is aimed at using for a Discord bot using Discord.js
I'm used to doing coding in older coding languages like C++, C#, Batch, and Game Maker Studio, but I'm still new to Discord.js
THE INTENT:
I want to store some basic variables. Such as "Server Rupees" which is shared by everyone.
And maybe a couple others. Nothing individual. Not a database. Not an array.
THE QUESTION:
I've heard this can be done with a json file. How do I save one variable to a place I can get it back when the bot goes online again?
And once I have it saved. How do I get that variable back?
WHAT I KNOW:
Not a lot for Discord.js . My bot has about 20 different commands, like adding roles, recognizing a swear and deleting that message, kick/ban a user, bulk delete messages, etc.
Yes it can be done with a json file or database,
If you are gonna go with json:
Store the value inside of a json file to start of with, for example:
./my-data.json
{ "Server-Rupees": 200 }
You would get the result by requiring the file
const data = require("path-to-json.json");
console.log(data["Server-Rupees"])
// => 200
If you want to update the value, just update the property value and use fs.writeFile
const { writeFile } = require("fs");
const data = require("path-to-json.json");
data["Server-Rupees"] += 20;
//JSON.striginfy makes the object into a string, `null, 6` makes it prettier
writeFile("path-to-json.json", JSON.stringify(data, null, 6), err => {
if(err) console.error(err);
})
Note: writeFile's path won't always be the same as require's path even for the same file.

Resources