Discord Python Bot: List of players in json

Viewed 112

What i'm trying to achive is to make three simple commands:

!add nick

!delete nick

!list (of nicknames)

This is my not-so-well-working script:

import json
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!')



def add(name):
    list.append( name )

@bot.command()
async def dele(ctx, *args):
    with open('list.json', 'r') as f:
        lines = json.loads(f.read())

    for name in args:
        lines.remove(name)

    with open('list.json', 'w') as f:
        f.write(json.dumps(lines))

@bot.command()
async def add(ctx, *args):
    with open('list.json', 'r') as f:
        lines = json.loads(f.read())

    for name in args:
        lines.append(name)

    with open('list.json', 'w') as f:
        f.write(json.dumps(lines))


@bot.command()
async def list(ctx):
    with open('list.json', 'r') as f:
     
        list = json.loads(f.read())
        await ctx.channel.send(f"List {list}")

bot.run("MY TOKEN HERE")



Command !list output:

command !list output

list.json ["test1", "test2", "test3", "test", "4", "test4", "name", "name", "test", "5", "test", "6"]

So... adding and deleting nicknames works fine (except that when i'm trying to add nickname with spaces its adding two separate keys).

But the biggest problem i got with the list command. Don't know how to format this to some kind of list with \n nicknames showing one by one or even with discord embed thing. Please help.

1 Answers

Spaces


(except that when i'm trying to add nickname with spaces its adding two separate keys)

Remember that when you write two words separated by space, the commands.command takes them as two arguments. You must write them without spaces.

One parameter function


You can solve your problem editing your functions like this:

@Bot.command()
async def add(ctx, member: str):
    with open('list.json', 'r') as f:
    lines = json.loads(f.read())

    lines.append(member)

    with open('list.json', 'w') as f:
        f.write(json.dumps(lines))

Embed


You can do something like this:

description = ""
for i in list:
    description += f'{i}\n'

Or

description = '\n'.join (list)

Then,

    emb = discord.Embed(title="List", description=description, color=discord.Color.random())
    await ctx.send(embed=emb)
Related