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.
Related
Hey i need for a project a tool to delete all channsl on a Discordserver via a Discord.js Bot.
i got one with handlers and this is my "event code" but dosent work.
Discord.js v14
const client = require("../../index");
module.exports = {
name: "blacksheep"
};
client.on("ready", () => {
var server = Client.guilds.get('1045245227264397382');
for (var i = 0; i < server.channels.array().length; i++) {
server.channels.array()[i].delete();
}})
i dont find the right way to get it worked. thx <3
Then i start the bot all Channels should be deletet without any command.
You need to include error messages or what the results of running this code was for us to actually help you, but for now I'm going to assume that everything in your bot and bot event handlers is working except for the last three lines that loop through the channels and delete them. If that's the case, then you just need to change those lines to something like this (replace your for-loop block with this):
server.channels.cache.forEach((channel) => {
channel.delete();
});
This accesses the server's channel cache, which is a collection, and so it uses the collection's forEach function to loop through all the channels, and then calls each of the channels' delete() functions to delete them.
Note that you may experience severe ratelimiting when doing this, because Discord has heavy ratelimits on requests to server channels.
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
})
What I'm trying to do is make a log for my bot, (you know, something to record server events as they happen), and I've been doing alright so far, but I just can't seem to figure out how to get the reason for a ban/kick or whatever else can record reasons. I've checked the documentation, and I just can't really figure out what some of the stuff there means. There isn't really code to show off, because I have no clue where to start here, and it's about time I ask somewhere for help.
Edit: I do know where to start, I can find the audit log entry, but I can't get the reason for the entry
You can use guild.fetchAuditLogs()
const guild = client.guilds.cache.get('Guild_ID')
const fetchedBan = await guild.fetchAuditLogs({ user: 'User_ID), type: 'MEMBER_BAN_ADD' })
You can also use message.guild instead of const guild = client.guilds.cache.get('Guild_ID')
To get the reason for the latest ban of that member
const banReason = fetchedBan.entries.first().reason
I'm working on a bot, and wanted to know if there was a way to open dms from all people in a server, and see if any commands were in there. If so I want the commands to be completed, but only with certain key words. Please help!
You can loop through the Guild's members collection and access the GuildMember's DMchannel using GuildMember.user.dmChannel then fetch all the messages using dmChannel.messages.fetch() then use filter() to get the messages with the keywords you're looking for
message.guild.members.cache.forEach(async (member) => {
const fetchedMsgs = await member.user.dmChannel.messages.fetch()
const messages = fetchedMsgs.filter((message) => message.content.toLowerCase().includes('search term')) // make sure the search term is lowercase
messages.forEach((message) => console.log(`${message.author.username} (${message.author.id}): '${message.content}' # ${message.createdAt}`)
})
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.');
});
});
};