简体   繁体   English

用户设置 [discord.py]

[英]User settings [discord.py]

I've been working on this code for a discord bot that allows you toggle passive mode on and off.我一直在为一个不和谐的机器人编写这段代码,它允许你打开和关闭被动模式。 When you enable it, it adds your user id to a list of passive mode users and removes it when disabled.当您启用它时,它会将您的用户 ID 添加到被动模式用户列表中,并在禁用时将其删除。 When I run this command, nothing happens, and the text file isn't overwritten.当我运行这个命令时,什么也没有发生,文本文件也没有被覆盖。 Does anyone know what's wrong with it?有谁知道它有什么问题?

@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()

That isn't really a discord.py questions.这不是一个真正的 discord.py 问题。 first you should learn to read the err message in your IDE or debugger.首先,您应该学习阅读 IDE 或调试器中的 err 消息。

and change with open('passive.txt', 'w') as a: to with open('passive.txt', 'w+') as a:with open('passive.txt', 'w') as a:更改为with open('passive.txt', 'w+') as a:

You can't read and write at the same time with 'w' , but 'w+' will do it 'w'不能同时读写,但'w+'可以

I tested your code with w+, it's work fine for file I/O but not the toggle.我用 w+ 测试了你的代码,它适用于文件 I/O,但不适用于切换。

I suggest you test the text IO first , if it work, put it into your bot.我建议您先测试文本 IO ,如果有效,请将其放入您的机器人中。 Maybe you should simplify your question and post it as a python question (without the part of discord.py)也许您应该简化您的问题并将其发布为 python 问题(没有 discord.py 的部分)

IO模式

here's the I/O doc https://docs.python.org/3/library/io.html#text-io这是 I/O 文档https://docs.python.org/3/library/io.html#text-io

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM