Audit log problems with Discord.py



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

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是一个字典,它被分配给数据库中某人的文档。其中两种价值是货币和银行。并不是每个命令都更新bank和money,如果命令更新其中一个,它就传递它。现在我已经描述了代码,我将描述问题。当我得到不和谐的信息时,它的新和旧都等于新的。当我做一些打印时,我最终发现它改变了if语句中的old_stats。它把钱换成钱,把银行换成银行。

我花了大约5个小时来解决这个问题,任何帮助都将是非常感激的。

这里的错误是您将old_statsnew_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. 进口副本/gh>
  2. new_stats分配给stats的副本,将old_stats分配给stats的副本。

最新更新