1

I have defined a variable called 'prefix' within my bot.py file which can be used in commands later, such as be displayed to the user. It's purpose is to simply store the bots prefix. However, I can't figure out how to use this variable in other cog files.

bot.py file: Variable Defined.

prefix = '!'

a cog file: Variable Tried to be used. (Final Line)

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')

How would I retrieve the variable I defined in the bot.py file and use it in the cog file?

SamNuttall
  • 11
  • 1
  • 2

3 Answers3

2

You can access Context.prefix to get the prefix used to invoke the command:

@commands.command()
async def help(self, ctx):
    await ctx.send(f'For commands, use {ctx.prefix}commands')
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
1

Assuming the bot.py file is in the same package:

from bot import prefix
Asad
  • 209
  • 1
  • 4
  • Yup, after testing, this is exactly what I needed thanks. Having said that, I would like to put my cogs in a seperate folder. So cogs/cog.py for example. Would it be possible to import from a specific directory? – SamNuttall Nov 11 '19 at 22:35
  • That will depend on how you have structured your project and modules. See [this](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time/14132912#14132912) post for some guidelines and best practices for imports. – Asad Nov 12 '19 at 10:30
1

After some testing, I found that you can add your variable to the client or bot obj by simply doing this client.the_variable_name. And you can access it by self.client.ur_variable in your cog.

The Code

The main.py or bot.py

client = commands.Bot(command_prefix=".", intents=intents)
my_var = "Hello from the other side..."
client.main_myVar = my_var

The cog file

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))
BalaRohan
  • 65
  • 1
  • 2
  • 9