首页 > 解决方案 > 如何制作警告命令和警告列表 discord.py

问题描述

我正在使用 discord.py rewrite 并希望创建一个命令~warn <user> <reason>来警告用户并~warns <user>显示用户拥有的警告数量。我一直在寻找有关此的教程,但几乎所有教程都在 discord.js 中,而 discord.py 中的教程都是异步的。有人可以帮我编码吗?

标签: discorddiscord.pydiscord.py-rewrite

解决方案


你可以使用JSON 模块,我会发出命令,

async def update_data(users, user):
    if not f'{user.id}' in users:
        users[f'{user.id}'] = {}
        users[f'{user.id}']['warns'] = 0

async def add_warns(users, user, warns):
    users[f'{user.id}']['warns'] += 1

@client.command()
async def remove_warn(ctx, user: discord.Member, amount: int=None):
    with open('warns.json', 'r') as f:
        users = json.load(f)

    amount = amount or 1

    await update_data(users, user)
    await add_warns(users, user, -amount)

    if users[f'{user.id}']['warns'] <= 0:
        with open('warns.json', 'w') as f:
            del users[f'{user.id}']['warns']
            del users[f'{user.id}']
            f.write(json.dumps(users, indent=4))
        return

    else:

        with open('warns.json', 'w') as f:
            json.dump(users, f, sort_keys=True, ensure_ascii=False, indent=4)

        await ctx.send(f'Removed {amount} warn for {user}')
        return

@client.command()
async def warns(ctx, user: discord.Member=None):
    user = user or ctx.author
    try:
        with open('warns.json', 'r') as f:
            users = json.load(f)

        warns = users[f'{user.id}']['warns']

        await ctx.send(f'{user} has {warns} warnings')
    except:
        await ctx.send(f'{user} dont have any warnings.')

推荐阅读