Discord Python 机器人:json 中的玩家列表

Discord Python Bot: List of players in json

我想要实现的是发出三个简单的命令:

!添加昵称

!删除昵称

!列表(昵称)

这是我不太好用的脚本:

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")



命令 !list 输出:

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

所以...添加和删除昵称工作正常(除了当我尝试添加带空格的昵称时它添加了两个单独的键)。

但我遇到的最大问题是 list 命令。不知道如何将其格式化为某种列表,其中 \n 昵称一一显示,甚至嵌入了不和谐的东西。 请帮忙。

空间


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

请记住,当您编写由 space 分隔的两个单词时,commands.command 会将它们作为两个参数。您必须在没有 space 的情况下编写它们。

一个参数函数


您可以像这样编辑函数来解决问题:

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

嵌入


你可以这样做:

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

description = '\n'.join (list)

然后,

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