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
})
Related
First I create an object
var queue = {1:{},2:{},3:{}};
And then I store the message based on QueueKey, or edit if it's already created
if (typeof queue[QueueKey].messageOBJ == 'undefined')
{
queue[QueueKey].messageOBJ = await configChannel.send({ embeds: [getEmbedFloor(QueueKey)] });
}
else
{
queue[QueueKey].messageOBJ = await queue[QueueKey].messageOBJ.edit({ embeds: [getEmbedFloor(QueueKey)] });
}
everything starts working well but after sometime(1~2 hours) bot stops editing the already created message, looks like it lose object reference.
It not pops any error message or code break, seems like the message was edited sucessfully but the real message in discord still the same
I'm thinking in store the messageID instead the whole object and search for the message ID with .fetch() but this will lead to other problems
is there any way to store message Objects properly?
I discovered my problem, actually bot was editing the message to frequently, so after some time discord "auto ban" my bot for some time, something like a cooldown, só it starts to get slower and slower, up to seems like it is stuck.
My solution was check message before edit, to compare if the changes in message are really necessary, before edit or not
I'm using Node and Discord.JS, trying to see if there's a way to differentiate between types of edits whenever a message is edited so a bot can tease the user for editing their message. The function works well so far, and is as follows:
let responses = ["some", "responses"];
bot.on('messageUpdate', ( message ) => {
let result = responses[Math.floor(Math.random()*(responses.length)-1)]
message.channel.send(result);
})
However, this detects all message updates, including say a link updating to have an embed. Is there any way to differentiate between a deliberate user edit and a message being updated with an embed through event listeners, or will I need to make a workaround with an if..else statement?
To check when message is edited, You'll be required to use the messageUpdate event listener.
In the messageUpdate event, there is 2 parameters. (oldMessage, newMessage) Learn More
Then, you can check the content of the oldMessage & newMessage parameters by using the .content property.
Example of code:
client.on("messageUpdate", (oldMessage, newMessage) => {
if(oldMessage.content === newMessage.content) return // Will do nothing if the content of oldMessage is equals to newMessage's content
// Do here your stuff
})
I hope I helped you!
Ignore this, i have not found an answer as I had hoped ;(
I have a message edit log but I want to stop sending the log if a mobs message was updated, I tried a few codes like
if(bot.oldMessage.content.edit()){
return;
}
It showed and error
cannot read property 'edit' of undefined
I then removed edit then content was undefined. The code for the message update is below.
The Code
module.exports = async (bot, oldMessage, newMessage) => {
let channels = JSON.parse(
fs.readFileSync('././database/messageChannel.json', 'utf8')
);
let channelId = channels[oldMessage.guild.id].channel;
let msgChannel = bot.channels.cache.get(channelId);
if (!msgChannel) {
return console.log(`No message channel found with ID ${channelId}`);
}
if (oldMessage.content === newMessage.content){
return;
}
let mEmbed = new MessageEmbed()
.setAuthor(oldMessage.author.tag, oldMessage.author.displayAvatarURL({dynamic: true}))
.setColor(cyan)
.setDescription(`**Message Editied in <#${oldMessage.channel.id}>**`)
.addField(`Before`, `${oldMessage.content}`)
.addField(`After`, `${newMessage.content}`)
.setFooter(`UserID: ${oldMessage.author.id}`)
.setTimestamp()
msgChannel.send(mEmbed)
}
How would I stop it from sending the embed if a bots message was updated.
Making a really simple check will resolve this issue. In Discord.js there is a user field that tells you if the user is a bot or not.
In fact, it is really recommended you add this in the "onMessage" part of your code as it stops other bots from using your bot, this is to make sure things are safe and no loopbacks/feedbacks happen, either way, you don't want a malicious bot taking advantage of your bot, which can get your bot in trouble too.
Here is what you want to do;
if (message.author.bot) return;
What this code specifically does is check if the message's author is a bot, if it returns true, it will break the code from running, if it returns a false, the code continues running.
You can do the same if you want to listen to bots ONLY by simply adding a exclamation mark before the message.author.bot like this;
if (!message.author.bot) return;
It is also possible to see what other kinds of information something holds, you can print anything to your console. For example, if you want to view what a message object contains, you can print it into your console with;
console.log(message) // This will show everything within that object.
console.log(message.author) // This will show everything within the author object (like ID's, name, discriminators, avatars, etc.)
Go ahead and explore what you can do!
Happy developing! ^ -^
That is really easy to do. All you need to do is check if the author of the message ist a bot and then return if true. You do that like this
if (oldMessage.author.bot) return;
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.
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.');
});
});
};