So i have a discord bot that generates keys, which you can redeem by a command. I want a command that grabs a line from a keys.txt and dms the sender of the command.
I have tried doing it myself, without any luck. I'm not that familiar with javascript so it's hard for me.
I don't have any code yet.
I expect it to DM the sender of the command the key that it grabbed from the keys.json
Reading and handling the file...
const fs = require('fs'); // Included in Node.js
const keysPath = './keys.txt'; // Change to the relative path of the txt file
try {
// The next line reads the file and returns an array containing each line
const keys = fs.readFileSync(keysPath).replace(/\r/g, '').split(/\n/);
} catch(err) {
console.error(err);
}
Sending and handling a key...
message.author.send(`Here's your key: ||${keys[0]}||`)
.then(() => {
keys.splice(0, 1); // Removes the first key that was just given out
try {
fs.writeFileSync(keys.join('\n')); // Puts the updated 'keys' array back into the file
} catch(err) {
console.error(err);
}
})
.catch(console.error);
For this you need "line-reader". Install it with npm i line-reader
.
const lineReader = require("line-reader")
lineReader.eachLine("path/to/file.txt", (line) => {
// This will be executed for each line in the file
})
// client is your Discord.Client()
client.on("message", (message) => {
if (message.content === "YOUR_COMMAND") {
message.author.send("YOUR_MESSAGE")
}
})
const lineReader = require("line-reader")
var keys = []
lineReader.eachLine("path/to/file.txt", (line) => {
keys.push(line)
})
client.on("message", (message) => {
if (message.content === "YOUR_COMMAND") {
message.author.send("Key: " + keys[0]) // This will send the user the first key/line in the list.
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.