Reputation: 35
I try to make a discord bot with cogs that i woudn't need to restart the bot every time I'm changing the code. I have done this:
from Bot import bot
from checks import check_if_me
from cogs.tracking import Tracking
from discord.ext import commands
token = ''
@bot.event
async def on_ready():
bot.add_cog(Tracking(bot))
print(f'ready {bot.latency}')
@bot.command(name='reload')
@commands.check(check_if_me)
async def reload_cog(ctx):
bot.remove_cog('Tracking')
bot.add_cog(Tracking(bot))
bot.run(token)
but it's just load the same cog and not the new.
Upvotes: 1
Views: 4838
Reputation: 93
In order to do that, you would need to actually reload the extension rather than the class cog. An extension refers to the whole file.
Discord.py allows you to load an extension using bot.load_extension
to avoid users from importing the cog manually.
You can do this by defined a setup() function in your cog file, this will receive Bot
instance for you to add your cog. After that, you can use bot.load_extension
in the main file and use bot.reload_extension
to achieve your current problem.
Example:
cogs\tracking.py
import discord
from discord.ext import commands
class Tracking(commands.Cog):
def __init__(self, bot):
self.bot = bot # This is so you can access Bot instance in your cog
# You must have this function for `bot.load_extension` to call
def setup(bot):
bot.add_cog(Tracking(bot))
\main.py
import discord
from discord.ext import commands
bot = commands.Bot(...)
# "cogs.tracking" refers to "cogs\tracking.py" file
bot.load_extension("cogs.tracking")
# A command to call the reload
@bot.command()
async def reload(ctx):
# Reloads the file, thus updating the Cog class.
bot.reload_extension("cogs.tracking")
Upvotes: 2