您只需要做两件事:为票创建一个新名称(如果之前的名称是“01-Ticket”,那么您需要将新名称命名为“02-Ticket”)并插入该票使用新名称进入对象。
解决方案
这里有一个完整的例子来说明如何做这样的事情:
let tickets = require('./tickets.json');
let newName = "01-Ticket";
if (msg.guild.id in tickets) {
let guildTickets = tickets[msg.guild.id];
let oldName = Object.keys(guildTickets).sort((a,b) => a.localeCompare(b)).pop();
let newNumber = Number(oldName.split("-")[0]) + 1;
let length = newNumber.toString().length;
newName = ("0" + newNumber).slice(-((length - 1) + Math.ceil(2 / length))) + "-Ticket";
}
else {
tickets[msg.guild.id] = {};
}
let ticket = {
User: msg.author.id,
Channel_ID: msg.channel.id
}
tickets[msg.guild.id][newName] = ticket;
fs.writeFileSync('tickets.json', JSON.stringify(tickets, null, 5))
说明
下面是相同的代码,但我对每一行都进行了注释,以便您更容易理解我在此示例中所做的一切的目的:
let tickets = require('./tickets.json');
let newName = "01-Ticket";
//Check if the guild has any tickets
if (msg.guild.id in tickets) {
//The guild does already have tickets
//Get the tickets for this guild
let guildTickets = tickets[msg.guild.id];
//Take all of the ticket names ("01-Ticket", "02-Ticket", etc.) via Object.keys(),
//sort them in ascending numerical order via .sort(),
//and get the last one (the largest number, or the name of the latest ticket) via .pop()
let oldName = Object.keys(guildTickets).sort((a,b) => a.localeCompare(b)).pop();
//Take the old ticket's name ("01-Ticket"), get its number ("01"), and increment
//it by one (so now it would be "2")
let newNumber = Number(oldName.split("-")[0]) + 1;
//The length of the new number (for "2", the length would be 1)
let length = newNumber.toString().length;
//Now add a single "0" to the start of the name (name so far: "0")
//then add the new number (name so far: "02")
//Then, from the end of the name go back as far as necessary to get the proper name (name so far: "02")
//This works with all amounts of digits (ex: 2 -> "02"; 12 -> "12")
newName = ("0" + newNumber).slice(-((length - 1) + Math.ceil(2 / length))) + "-Ticket";
}
else {
//No tickets have been made in this guild yet
//So set the guild's ticket list to an empty object
tickets[msg.guild.id] = {};
}
//Create the new ticket to add to the guild's ticket list
let ticket = {
User: msg.author.id,
Channel_ID: msg.channel.id
}
//Add the ticket to the guild's ticket list
tickets[msg.guild.id][newName] = ticket;
//Update the tickets.json with your updated 'tickets' object
fs.writeFileSync('tickets.json', JSON.stringify(tickets, null, 5))
首先我要检查公会的ID是否已经在tickets.json中。如果不是,我们将它作为一个空对象添加(并且我们使用默认名称添加新票:“01-Ticket”)。如果公会的 ID 已经在文件中,那么我们需要为我们的新票创建一个新名称。所以首先我得到代表公会门票的对象。然后我得到该对象中的所有键(即票的名称:“01-Ticket”、“02-Ticket”等)。我将这些键从最小到最大排序(因为所有票证名称都以数字开头,这实际上是按数字排序),并使用 .pop() 检索排序列表中的最后一个票证名称(这是票证名称以最大数)。然后我从该票名中取出号码,并在其中添加一个。然后我确保在新票名的开头添加一个“0”,如果它只有一位数的话;我正在使用一个复杂的公式和.slice() 来执行此操作,但您可以使用简单的if 语句来执行此操作。然后我自己创建票证,设置其用户 ID 和频道 ID 属性。最后,我通过更新tickets 变量将票添加到公会的票列表中,然后将tickets.json 更新为tickets 的新值。
此代码中的新名称创建已经过测试并且可以正常工作。其余代码未经测试,但与我自己的一些机器人的工作代码完全相同。如果此答案的任何部分没有意义,或者您发现错误,请随时发表评论。