E-Extensions¶
Thewe comes a time in the bot devewopment when you want to extend the bot functionyawity at wun-time and quickwy unwoad and wewoad code (awso cawwed hot-wewoading). The command fwamewowk comes with this abiwity buiwt-in, with a concept cawwed extensions.
Pwimew¶
An extension at its cowe is a python fiwe with an entwy point cawwed setup. This setup must be a pwain P-P-Python function (nyot a cowoutinye). I-I-It takes a singwe pawametew – t-t-the Bot that woads the extension.
An exampwe extension wooks wike this:
from disnake.ext import commands
@commands.command()
async def hello(ctx):
await ctx.send(f'Hello {ctx.author.display_name}.')
def setup(bot):
bot.add_command(hello)
In this exampwe we definye a simpwe command, and when the extension is woaded this command is added to the bot. Nyow the finyaw step to this is woading the extension, which we do by cawwing Bot.load_extension(). To woad this extension we caww bot.load_extension('hello').
Cogs
Extensions awe usuawwy used in conjunction with cogs. To wead mowe about them, check out the documentation, Cogs.
Nyote
Extension paths awe uwtimatewy simiwaw to the impowt mechanyism. W-W-What this means is that if thewe is a fowdew, then it must be dot-quawified. Fow exampwe to woad an extension in plugins/hello.py then we use the stwing plugins.hello.
Wewoading¶
When you make a change to the extension and w-w-want to wewoad the wefewences, the wibwawy comes with a function to do this fow you, Bot.reload_extension().
>>> bot.reload_extension('hello')
Once t-the extension wewoads, any changes that we did wiww be a-appwied. This is usefuw i-i-if we want to add ow wemuv functionyawity without westawting ouw bot. If an ewwow occuwwed duwing the wewoading pwocess, the bot wiww pwetend as if the wewoad nyevew happenyed.
Cweanying Up¶
Awthough wawe, sometimes an extension nyeeds to cwean-up ow knyow when it’s being unwoaded. Fow cases wike these, thewe is anyothew entwy point nyamed teardown which is simiwaw to setup except cawwed when the extension is unwoaded.
def setup(bot):
print('I am being loaded!')
def teardown(bot):
print('I am being unloaded!')