Discord“bruh”计数Bot运行提示load_counters未定义报错求助
报错原因
你在代码中直接调用了load_counters()、save_counters()两个自定义函数,但没有实现这两个函数的对应逻辑,Python运行时无法找到函数定义,因此触发未定义报错。
修复方案
步骤1:补充两个工具函数的实现
在代码中counters = load_counters()语句的前面,添加以下两个函数的定义:
def load_counters(): # 计数文件不存在时初始化默认数据 if not os.path.exists("counters.json"): init_data = {"bruh": 0} with open("counters.json", "w", encoding="utf-8") as f: json.dump(init_data, f) return init_data # 读取现有计数文件内容 with open("counters.json", "r", encoding="utf-8") as f: return json.load(f) def save_counters(counters): # 将最新计数写入文件 with open("counters.json", "w", encoding="utf-8") as f: json.dump(counters, f, indent=4)
步骤2:优化冗余代码和配置
- 你代码中定义的
setup函数是Cog扩展开发时才会用到的逻辑,当前没有对应的Cog类实现,可以直接删除避免冗余。 - 你现有的json计数文件里最后一个键值对后多余的逗号可以删除,避免低版本Python解析JSON时报语法错误,修改后内容如下:
{ "bruh": 0 }
修复后完整代码
import discord from discord.ext import commands import os import json # 工具函数定义 def load_counters(): if not os.path.exists("counters.json"): init_data = {"bruh": 0} with open("counters.json", "w", encoding="utf-8") as f: json.dump(init_data, f) return init_data with open("counters.json", "r", encoding="utf-8") as f: return json.load(f) def save_counters(counters): with open("counters.json", "w", encoding="utf-8") as f: json.dump(counters, f, indent=4) client = discord.Client() @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return counters = load_counters() if "bruh" in message.content: counters["bruh"] += 1 await message.channel.send(str(counters["bruh"])) save_counters(counters) client.run(os.getenv('TOKEN'))
内容的提问来源于stack exchange,提问作者PyroKyro128
相关产品推荐
相关产品推荐

