実現したいこと
discord.pyのExtensionのリロード時にtaskもリロードする
前提
Discord.pyでbotを作っているのですが、/reloadコマンドが呼ばれたときにreloadするようにしたいです。
他コマンドのリロードはできているのですが、裏で動いている指定時間ごとにメッセージを送信するループをリロードさせたいです。
roop.restart()
や、roop.stop()
等の関数を呼び出したいのですが、どのように呼び出せば良いかわかりません。
extension内のteardown関数でどうにか呼び出そうとしてみましたが、できていないようです。
Cogが更新されたことを検知するイベントハンドラーなどあれば教えていただきたいです。
該当のソースコード
python
1# main.py 2from os import getenv 3 4import discord 5from discord.ext import commands 6 7intents = discord.Intents.default() 8intents.message_content = True 9 10bot = commands.Bot(command_prefix="!", case_insensitive=True, intents=intents) 11 12@bot.event 13async def on_ready(): 14 print("Bot is ready!") 15 await bot.tree.sync() 16 print("Synced") 17 18@bot.event 19async def setup_hook(): 20 await bot.load_extension("cogs.common") 21 print("added cog") 22 23@bot.tree.command(name="reload", description="extensionをreload") 24async def reload_all(ctx: discord.Interaction): 25 await bot.reload_extension("cogs.common") 26 embed = discord.Embed(title="Success*!*", description="リロードしました") 27 await ctx.response.send_message(embed=embed) 28 29if __name__ == "__main__": 30 bot.run(getenv("APP_TOKEN", "")) 31 print("closed")
python
1from discord.ext import commands, tasks 2from discord import app_commands 3 4class CommonComands(commands.Cog): 5 def __init__(self, bot: commands.Bot): 6 self.bot = bot 7 8 @commands.Cog.listener(name="on_ready") 9 async def task_starter(self): 10 print("roop") 11 self.roop.start() 12 13 async def stop_task(self): 14 self.roop.stop() 15 16 @tasks.loop(seconds=5) 17 async def roop(self): 18 print("roop started") 19 ch = self.bot.get_all_channels() 20 for i in ch: 21 if i.type == discord.ChannelType.text: 22 await i.send("Hello, World") 23 24async def setup(bot: commands.Bot): 25 await bot.add_cog(CommonComands(bot)) 26 27 28async def teardown(bot: commands.Bot): 29 bot.get_cog(CommonComands.__cog_name__).stop_task()
試したこと
・ bot.get_cog()
からの呼び出し
・bot.remove_cog
補足情報(FW/ツールのバージョンなど)
discord.py==2.3.2
Python 3.11.7

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。