【问题标题】:Audit log problems with Discord.pyDiscord.py 的审核日志问题
【发布时间】:2021-02-24 14:38:36
【问题描述】:

我正在为我的经济创建审计日志。此时,只要有人使用经济命令,我就会让它向频道发送消息。

async def audit_log(ctx, bot, action, stats=None, new_bank=None, new_money=None):
        audit_channel = bot.get_channel(813610020943953920)
        old_stats = stats
        new_stats = stats
        if new_bank is not None:
            new_stats['bank'] = new_bank
        if new_money is not None:
            new_stats['money'] = new_money

        await audit_channel.send(f'{ctx.author} did {action},\nprev-bank: {old_stats["bank"]}, prev-cash: {old_stats["money"]}\nnew-bank: {new_stats["bank"]}, new-cash: {new_stats["money"]}')

Stats 是一个字典,分配给数据库中某人的文档。其中两个值是货币和银行。并非每个命令都会更新银行和货币,如果命令更新其中任何一个,它就会通过它。现在我已经描述了代码,我将描述问题。当我收到不和谐的消息时,它既有新的,也有旧的,等于新的。当我做了一些打印时,我最终发现它改变了 if 语句中的 old_stats 。它改变了货币中的货币和银行中的银行。

我花了大约 5 个小时试图弄清楚这一点,任何帮助将不胜感激。

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    这里的错误是你将old_statsnew_stats 都分配给了stats,并且由于字典是可变的,python 使得old_statsnew_stats 保持相同的字典,所以如果你更新一个你更新“两个都”。要解决此问题,您可以使用复制模块复制功能:copy.copy(stats)

    这就是你的代码看起来固定的样子:

    # imports
    import copy
    
    # ... other code
    async def audit_log(ctx, bot, action, stats=None, new_bank=None, new_money=None):
            audit_channel = bot.get_channel(813610020943953920)
            old_stats = copy.copy(stats)
            new_stats = copy.copy(stats)
            if new_bank is not None:
                new_stats['bank'] = new_bank
            if new_money is not None:
                new_stats['money'] = new_money
    
            await audit_channel.send(f'{ctx.author} did {action},\nprev-bank: {old_stats["bank"]}, prev-cash: {old_stats["money"]}\nnew-bank: {new_stats["bank"]}, new-cash: {new_stats["money"]}')
    

    说明

    1. 导入副本
    2. new_stats 分配给stats 的副本,并将old_stats 分配给stats 的副本。

    【讨论】:

    • 非常感谢您的帮助。这个答案解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2018-03-04
    • 1970-01-01
    • 2021-12-12
    相关资源
    最近更新 更多