Discord.py生成token时重复输出历史token是什么原因?
问题根因
你定义的tkn是全局作用域的列表,每次调用createtoken命令执行tkn.append(tok)操作时,都会把新生成的token追加到全局列表中,后续使用'\n'.join(tkn)拼接输出内容时,自然会携带所有历史生成过的token。
修复方案
可根据需求选择对应优化方式:
- 若每次调用命令仅生成1个token(你当前代码中循环次数固定为1),可直接省略列表变量,直接使用当前生成的token输出
- 若后续可能调整为批量生成多个token,可将
tkn列表移到createtoken函数内部,每次调用命令时重新初始化空列表,避免历史数据残留
修改后代码示例(适配单token生成场景,最简化)
import random # 若你原代码已导入random可忽略此行 tokenOpts = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".lower() def GenToken(): t1 = ''.join((random.choice(tokenOpts)) for x in range(5)) t2 = ''.join((random.choice(tokenOpts)) for x in range(3)) t3 = ''.join((random.choice(tokenOpts)) for x in range(7)) t4 = ''.join((random.choice(tokenOpts)) for x in range(5)) return f"{t1}-{t2}-{t3}-{t4}" @bot.command() async def createtoken(ctx, planDays=0): if ctx.message.author.id in config.OWNERS: with open(path, "r") as data: tokens = json.load(data) with open(path, "w") as output: tok = GenToken() tokens[0]['Unused'].append({"Days": planDays, "Level": "None", "Token": str(tok)}) output.write(json.dumps(tokens, sort_keys=False, indent=4)) embed = discord.Embed( title="Verification", color= discord.Color.dark_theme() ) embed.add_field(name="Token Status: Created <:white_check_mark:886940376127131689>", value=f"Token: `{tok}`") embed.set_footer(text="YoursTruly.exe") await ctx.send(embed=embed)
修改后代码示例(适配后续可能批量生成的场景)
import random # 若你原代码已导入random可忽略此行 tokenOpts = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".lower() def GenToken(): t1 = ''.join((random.choice(tokenOpts)) for x in range(5)) t2 = ''.join((random.choice(tokenOpts)) for x in range(3)) t3 = ''.join((random.choice(tokenOpts)) for x in range(7)) t4 = ''.join((random.choice(tokenOpts)) for x in range(5)) return f"{t1}-{t2}-{t3}-{t4}" @bot.command() async def createtoken(ctx, planDays=0, generate_count=1): # 可自定义传入生成token的数量 if ctx.message.author.id in config.OWNERS: tkn = [] # 每次调用命令初始化空列表,清除历史数据 with open(path, "r") as data: tokens = json.load(data) with open(path, "w") as output: for i in range(generate_count): tok = GenToken() tkn.append(tok) tokens[0]['Unused'].append({"Days": planDays, "Level": "None", "Token": str(tok)}) output.write(json.dumps(tokens, sort_keys=False, indent=4)) o = '\n'.join(tkn) embed = discord.Embed( title="Verification", color= discord.Color.dark_theme() ) embed.add_field(name="Token Status: Created <:white_check_mark:886940376127131689>", value=f"Token: `{o}`") embed.set_footer(text="YoursTruly.exe") await ctx.send(embed=embed)
内容的提问来源于stack exchange,提问作者UnknownKachal
相关产品推荐
相关产品推荐

