問題描述
我目前正在使用 discord.py 開發(fā)一個機器人,在這種情況下使用 JSON 文件來存儲它所在的每個服務器的機器人前綴.(+ 是機器人的默認前綴)使用前綴,我正在做 4 件事:在公會加入時:向 JSON 文檔添加前綴On guild remove:從 JSON 文檔中刪除此公會的前綴+更改前綴當提到機器人時,它會輸出一條消息,說明:'你好,這個服務器的前綴是+'
I am currently developing a bot using discord.py and in this case using a JSON file to store the bots prefixes for each server that it is in. ( + is the bots default prefix ) With prefixes, there is 4 things I am doing: On guild join: Adds a prefix to the JSON document On guild remove: Removes the prefix for this guild from the JSON document +changeprefix and when the bot is mentioned, it outputs a message stating: 'Hello, the prefix for this server is +'
前 3 部分工作正常.但是,當提到該機器人時,它會輸出錯誤:
The first 3 parts work correctly. However, when the bot is mentioned it outputs the error:
await message.channel.send(f'Hi my prefix for this server is **{prefix}**)
NameError: name 'prefix' is not defined
我已經(jīng)做了一些研究,并就這個問題詢問了多個幫助服務器,但是我發(fā)現(xiàn) python 沒有在這種情況下有用的常量,幫助服務器上的人不確定這個問題的答案.
I have done some research and asked multiple help servers about this issue however what I have found is that python does not have constants which would be useful in this situation and people on help servers were unsure of the answer to this question.
前綴設置的所有部分的代碼是這樣的:
The code for all parts of the prefix setup is this:
@bot.event
async def on_guild_join(guild):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = '+'
prefixes = prefix
with open('prefix.json', 'w') as f:
json.dump(prefixes, f, indent=4)
# REMOVES PREFIX FROM JSON FILE
@bot.event
async def on_guild_remove(guild):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
prefixes.pop(str(guild.id))
with open('prefix.json', 'w') as f:
json.dump(prefixes, f, indent=4)
# COMMAND TO CHANGE THE PREFIX
@bot.command()
@commands.has_permissions(manage_messages=True)
async def changeprefix(ctx, prefix):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
prefix = prefix
with open('prefix.json', 'w') as f:
json.dump(prefixes, f, indent=4)
await ctx.send(f'Prefix changed to **{prefix}**')
錯誤來自的on_message
是這樣的:
@bot.event
async def on_message(message):
if message.content.startswith("<@bot ID>"):
await message.channel.send(f'Hi my prefix for this server is **{prefix}**')
await bot.process_commands(message)
這在代碼中比其他部分更靠后
and this is further down in the code than the other parts of this
任何幫助將不勝感激.預期的輸出是,當它標記的機器人時,它會發(fā)送一條消息,說明服務器的當前前綴.
Any help would be appreciated. The expected output is so when the bot it tagged, it sends a message saying the current prefix for the server.
更新正如下面評論中提到的,我已經(jīng)更新了我的代碼,以便它讀取 JSON 文件并檢索前綴.這是 on_message
event
Update
As mentioned in a comment below, I have updated my code so it reads the JSON file and retrieves the prefix. This is the updated code in the on_message
event
if message.content.startswith("<bot ID>"):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
await message.channel.send(f'Hi my prefix for this server is **{prefix}**')
但是,這仍然顯示
NameError: name 'prefix' is not defined
我嘗試過的其他方法我也嘗試像這樣定義 prefix
:
Other things I have tried
I also tried defining prefix
like this:
if message.content.startswith("<@850794452364951554>"):
with open('prefix.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
prefix = prefix
await message.channel.send(f'Hi my prefix for this server is **{prefix}**')
我在 prefixes[str(ctx.guild.id)] = prefix
在這兩種情況下,它都會輸出以下錯誤:
In both those cases, it outputs this error:
UnboundLocalError: local variable 'prefix' referenced before assignment
推薦答案
你的代碼在很多地方對我來說毫無意義,因為你在 message
事件中使用了 ctx
, 這起初是不可能的.此外,在復制代碼時,prefixes = prefix
出現(xiàn)錯誤,因此值得懷疑的是為什么這對您有效.
Your code makes no sense to me in many places, because you use ctx
in a message
event, which is not possible at first. Also, when copying the code, I get an error with prefixes = prefix
, so it is questionable why this supposedly works for you.
您的 on_guild_join
對我來說也毫無意義,因為每個人都有默認前綴.該事件可能與您的 changeprefix
命令相關,但可以做得更好.
Your on_guild_join
also makes no sense to me, because everyone has the default prefix. The event may be relevant for your changeprefix
command, but that can be done better.
我稍微重寫了您的 changeprefix
命令并調整了您的 on_message
事件.
I rewrote your changeprefix
command a bit and adjusted your on_message
event.
看看下面的代碼:
@bot.event
async def on_message(message):
if message.content.startswith("What is the prefix for this guild?"):
with open('prefix.json', 'r', encoding='utf-8') as fp:
custom_prefixes = json.load(fp)
try:
prefix = custom_prefixes[f"{message.guild.id}"]
await message.channel.send(f'Hi my prefix for this server is **{prefix}**')
except KeyError:
return await message.channel.send("You have not set a new prefix.") # No JSON entry
await bot.process_commands(message)
@bot.command()
async def setprefix(ctx, prefixes: str):
with open('prefix.json', 'r', encoding='utf-8') as fp:
custom_prefixes = json.load(fp)
try:
custom_prefixes[f"{ctx.guild.id}"] = prefixes # If the guild.id already exists
except KeyError: # If there is no JSON entry
new = {ctx.guild.id: prefixes} # New prefix with command input
custom_prefixes.update(new) # Add guild.id and prefix
await ctx.send(f"Prefix set to: `{prefixes}`")
with open('prefix.json', 'w', encoding='utf-8') as fpp:
json.dump(custom_prefixes, fpp, indent=2)
由于您的 on_guild_join
事件也包含錯誤,我們必須以不同的方式確定前綴.如果我們將集合 prefix
附加到默認值,我們可以實現(xiàn)這一點.
As your on_guild_join
event also contains errors we have to determine the prefix in a different way. We can achieve that if we append the set prefix
to the default one.
看看下面的代碼:
def determine_prefix(bot, msg):
guild = msg.guild
base = [DEFAULT_PREFIX]
with open('prefix.json', 'r', encoding='utf-8') as fp: # Open the JSON
custom_prefixes = json.load(fp) # Load the custom prefixes
if guild: # If the guild exists
try:
prefix = custom_prefixes[f"{guild.id}"] # Get the prefix
base.append(prefix) # Append the new prefix
except KeyError:
pass
return base
[...](command.prefix = determine_prefix) # Where you defined your bot
這篇關于Discord.py 變量在整個代碼中不是恒定的的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!