[英]I'm trying to create a discord.js command that grabs a line from a json file and then sends it in a users DM
So i have a discord bot that generates keys, which you can redeem by a command. 因此,我有一个不和谐的bot,它可以生成密钥,您可以通过命令进行赎回。 I want a command that grabs a line from a keys.txt and dms the sender of the command. 我想要一个可从keys.txt中抓取一行并命令发送者dms的命令。
I have tried doing it myself, without any luck. 我尝试自己做,没有任何运气。 I'm not that familiar with javascript so it's hard for me. 我对javascript不太熟悉,所以对我来说很难。
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 我希望它能将命令从key.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
. 用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.
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.