简体   繁体   中英

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. 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. first you should learn to read the err message in your IDE or debugger.

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

You can't read and write at the same time with 'w' , but 'w+' will do it

I tested your code with w+, it's work fine for file I/O but not the toggle.

I suggest you test the text IO first , if it work, put it into your bot. Maybe you should simplify your question and post it as a python question (without the part of discord.py)

IO模式

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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