简体   繁体   English

在 discord.py 上重新加载齿轮

[英]reload cogs on discord.py

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.我尝试使用齿轮制作 discord 机器人,每次更改代码时我都不需要重新启动机器人。 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.但它只是加载相同的齿轮而不是新的。

In order to do that, you would need to actually reload the extension rather than the class cog.为此,您需要实际重新加载扩展而不是 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. Discord.py 允许您使用bot.load_extension加载扩展,以避免用户手动导入 cog。

You can do this by defined a setup() function in your cog file, this will receive Bot instance for you to add your cog.您可以通过在 cog 文件中定义 setup() function 来执行此操作,这将接收Bot实例供您添加 cog。 After that, you can use bot.load_extension in the main file and use bot.reload_extension to achieve your current problem.之后,您可以在主文件中使用bot.load_extension并使用bot.reload_extension来解决您当前的问题。

Example:例子:

cogs\tracking.py齿轮\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 \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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM