簡體   English   中英

為什么 discord.py 無法識別“on_message()”之外的變量?

[英]Why is discord.py not recognizing variables outside “on_message()”?

我的 discord.py 腳本給了我一個意外錯誤。 它基本上將我在async def on_message():之外定義的所有變量標記為“未定義”。

好吧,您也可以通過在on_message()下定義它們來輕松修復它。 我試過了。 但是,問題來了:每次發送消息時,變量都會被設置回您定義的值,即使您確實添加了,就像一行說如果發生這種情況,請將其更改為另一個值。 (例如前綴,正如您在下面的代碼中看到的那樣,我想使用名為“changeprefix”的命令更改機器人的前綴並且它可以工作,但是當使用該前綴發送另一條消息時,它不會識別它;因為在開始時定義變量的行再次運行,一切都被重置了。

除了刪除on_message()並使用discord.ext.commands或其他方法之外,還有其他方法嗎? 我更熟悉on-message()系統,而且如果我切換到它,我會更改整個腳本。

import discord

client = discord.Client()
token= "some nice token"
#defining here results in "UnboundLocalError: local variable 'prefix' referenced before assignment", in the first line using the variable defined here

@client.event

async def on_message(message):
     #defining here results variables being refreshed each time a message is sent

我相信您正在尋找的是global的,這是一個關於如何使用它的簡單示例。

something = 1

@client.event
async def on_message(message):
    global something
    something = something + 1
    print(something) # 2 at first iteration

#outside of on_message
print(something) # 2 it is the same

如果您想將其與前綴一起使用,請將其設置為以guild.id為鍵的字典,值為前綴。

順便說一句,使用命令會更容易做到這一點。

注意:如果您重新啟動機器人,您將丟失此信息

如果我正確理解了您的問題,您想要一個每次調用命令時都會更改其值的變量,您可以使用全局變量(我不推薦它)或 bot var。 也使用commands.Bot這樣你就可以使用命令系統

bot = commands.Bot(command_prefix='.')
# Using a global variable
my_var = 'my value'

@bot.command()
async def foo(ctx, arg):
    global my_var
    my_var = arg
    await ctx.send(f"Changed `my_var` value to `arg`")
# Using a bot var
bot.my_var = 'my value'

@bot.command()
async def foo(ctx, arg):
    bot.my_var = arg
    await ctx.send(f"Changed `bot.my_var` value to `arg`")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM