我在bot.py文件中定义了一个名为'prefix'的变量,该变量可在以后的命令中使用,例如显示给用户。目的是仅存储bots前缀。 但是,我不知道如何在其他齿轮文件中使用此变量。
bot.py文件:变量已定义。
prefix = '!'
cog文件:变量尝试使用。 (最后一行)
def setup(bot):
bot.add_cog(CogName(bot))
class CogName(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def help(self, ctx):
await ctx.send(f'For commands, use {prefix}commands')
如何检索bot.py文件中定义的变量并将其用于cog文件?
答案 0 :(得分:1)
您可以访问Context.prefix
以获得用于调用命令的前缀:
@commands.command()
async def help(self, ctx):
await ctx.send(f'For commands, use {ctx.prefix}commands')
答案 1 :(得分:0)
假设bot.py文件位于同一软件包中:
from bot import prefix
答案 2 :(得分:0)
经过一些测试,我发现您只需执行此 client.the_variable_name
即可将变量添加到客户端或机器人 obj。您可以通过齿轮中的 self.client.ur_variable
访问它。
main.py 或 bot.py
client = commands.Bot(command_prefix=".", intents=intents)
my_var = "Hello from the other side..."
client.main_myVar = my_var
齿轮文件
from discord.ext import commands
class Test(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def test(self, ctx):
print(self.client.main_myVar)
def setup(client):
client.add_cog(Test(client))