【问题标题】:Discord Python Bot: List of players in jsonDiscord Python Bot:json 中的玩家列表
【发布时间】:2021-11-12 12:50:30
【问题描述】:

我想要实现的是创建三个简单的命令:

!添加昵称

!删除昵称

!list(昵称)

这是我不太好的脚本:

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 昵称一一显示,甚至嵌入不和谐的东西。 请帮忙。

【问题讨论】:

    标签: python json discord command


    【解决方案1】:

    空间


    (除了当我尝试添加带有空格的昵称时,它会添加两个单独的键)

    请记住,当您编写两个以空格分隔的单词时,commands.command 会将它们作为两个参数。您必须将它们写成不带空格的。

    一个参数函数


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

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

    【讨论】:

    • 但是如果commands.command装饰器下的异步函数有*作为函数参数,你仍然可以传递无限参数,并且还请使用f-strings
    • @GhostOps,我知道,但他的问题是用空格写的昵称,而不是参数的数量。
    • i.imgur.com/mI71HCK.png 有点工作,但不是只得到一个列表(最后一个看起来不错),我为每个键得到三个。如何修复?
    • 关于我应该使用key.replace(" ","_") 的空格,所以它会用下划线保存昵称,然后在列表命令中我应该用key.replace("_"," ") 将下划线更改为空格@ 我猜......我只是不知道如何在代码中做到这一点。
    • @Martin 用下划线保存昵称是什么意思?你打算将用户的用户名作为参数传递给命令吗?
    猜你喜欢
    • 2020-09-06
    • 1970-01-01
    • 2016-01-08
    • 2023-03-06
    • 2019-08-10
    • 2022-06-17
    • 1970-01-01
    • 2021-12-05
    • 2015-09-09
    相关资源
    最近更新 更多