我一直在为一个discord机器人编写这段代码,它允许你打开和关闭被动模式。 启用时,它会将您的用户id添加到被动模式用户列表中,并在禁用时将其删除。 当我运行这个命令时,不会发生任何事情,文本文件也不会被覆盖。有人知道它怎么了吗
@client.command()
async def passive(ctx, value: bool):
user_id = str(ctx.author.id)
if value:
with open('passive.txt', 'w') as a:
if user_id in a.read():
await ctx.channel.send('You are already in passive mode!')
else:
a.write(f'{user_id}\n')
await ctx.channel.send('Passive mode successfully enabled!')
a.close()
else:
with open('passive.txt', 'r') as r:
lines = r.readlines()
r.close()
with open('passive.txt', 'w') as d:
for line in lines:
if line.strip('\n') != (user_id):
d.write(line)
await ctx.channel.send('No more passive mode for you')
else:
await ctx.channel.send('You are already not in passive mode!')
d.close()
这不是一个真正不和谐的问题。 首先,您应该学会在IDE或调试器中读取错误消息
并将
with open('passive.txt', 'w') as a:
更改为with open('passive.txt', 'w+') as a:
你不能用
'w'
同时读写,但是'w+'
可以做到我用w+测试了你的代码,它对文件I/O很好,但不能切换
我建议您首先测试文本IO,如果它有效,请将其放入您的机器人中。 也许您应该简化您的问题,并将其作为python问题发布(不包括discord.py部分)
这是I/O文档https://docs.python.org/3/library/io.html#text-i-o
相关问题 更多 >
编程相关推荐