client.event 不会向 JSON 文件on_guild_add (discord.py) 添加前缀



我尝试在 json bot 中添加机器人时创建事件会添加一个前缀:

@client.event
async def on_guild_join(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = '//'
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)

但我不明白为什么会出现此错误:

Traceback (most recent call last):
File "c:/projects/bots/textjson.py", line 14, in <module>
@client.event
NameError: name 'client' is not defined

我的代码有问题吗???

也是导入脚本

import discord
import json
from discord.ext import commands

错误说它找不到名为client的变量。你给下面起了什么名字?

... = commands.Bot(command_prefix=...

通常人们会用clientbot来命名,所以只需仔细检查您引用的是您认为的名称。


出现此问题的另一个原因是,如果您将事件放在定义client变量的行上方

@client.event
async def on_guild_join(.....
client = commands.Bot(.....

应该像这样重新排序:

client = commands.Bot(.....
@client.event
async def on_guild_join(.....