discord.py经济系统开发报错:TypeError: 'bool'类型不可迭代
Discord机器人经济系统TypeError问题修复
我正在为自有服务器开发经济系统机器人,运行时触发如下错误:
File "c:\Users\trace\Desktop\MU LFG\lfg bot\main.py", line 303, in open_account if str(user.id) in users : TypeError: argument of type 'bool' is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\trace\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 1350, in invoke await ctx.command.invoke(ctx) File "C:\Users\trace\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 1023, in invoke await injected(*ctx.args, **ctx.kwargs) # type: ignore File "C:\Users\trace\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 238, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: argument of type 'bool' is not iterable
问题根源
报错核心是open_account函数中,users变量被赋值为布尔值False,但in操作符需要字典、列表这类可迭代对象才能判断成员关系。
查看代码逻辑后发现,get_bank_data函数在文件不存在或读取失败时,错误返回了False而非空字典,导致后续调用该函数得到的users是布尔类型,无法执行in判断。
修复方案
- 修改
get_bank_data函数,当文件不存在或解析出错时返回空字典:
def get_bank_data(): try: with open("bank.json", "r") as f: return json.load(f) except (FileNotFoundError, json.JSONDecodeError): return {}
- 可选:在
open_account函数开头增加校验,确保users是有效字典:
def open_account(user): users = get_bank_data() if not isinstance(users, dict): users = {} # 原函数后续逻辑...
内容的提问来源于stack exchange,提问作者Kacie Anderson
相关产品推荐
相关产品推荐

