The code that appears in this article is provided for illustration purposes only and is not intended for production use. Please rewrite it appropriately according to your application.
I want to pass arguments to Task
Basically, I think that Tasks that are executed regularly often start when the bot starts. However, sometimes you want to control the start timing and destination channel with commands. For example, ** "I want you to mention the time signal on the specified channel every 5 minutes for 30 minutes from now" **.
However, there is currently no example in the discord.py document that Task (https://discordpy.readthedocs.io/ja/latest/ext/tasks/index.html) takes an argument.
First, add an argument to the Task you want to execute regularly.
For example, consider the case where a mention is sent to the person who sent the command in the channel in which the command is input.
In this case, if you receive Context
as an argument when entering the command, it seems that you can identify the channel and sender.
from discord.ext import tasks, commands
class MyCog(commands.Cog):
def __init__(self):
pass
def cog_unload(self):
self.reminder.cancel()
@tasks.loop(minutes=5.0, count=6)
async def reminder(self, ctx, content):
await ctx.send("<@{0}> {1}".format(ctx.author.id, content))
If you define reminder like this, you will be reminded just by starting it.
So how do you pass this argument ctx
?
As the title says. You can pass it to start ()
which is used when the task starts. The * args
and ** kawrgs
passed to start ()
are passed as they are as arguments of the corresponding Task.
So, for example, you can define the following reminder command.
from discord.ext import tasks, commands
class MyCog(commands.Cog):
def __init__(self):
pass
def cog_unload(self):
self.reminder.cancel()
@tasks.loop(minutes=5.0, count=6)
async def reminder(self, ctx, content):
await ctx.send("<@{0}> {1}".format(ctx.author.id, content))
@commands.command()
async def set_reminder(self, ctx, content):
self.reminder.start(ctx, content) #Important here
await ctx.send("I set a reminder")
Now, if you send the set_reminder
command to the chat, the pre-specified content will be mentioned every 5 minutes.
The point is self.reminder.start (ctx, content)
, and it's OK as long as the argument passed to start ()
is passed to the argument of Task started by that start ()
.
As I wrote at the beginning, this code itself is not intended for production. I'm curious about what happens if another person hits set_reminder within 30 minutes after entering set_reminder.
Please be aware that this is just a pseudo code for explaining how to pass arguments to Task. (But please let me know if there are any fatal mistakes such as grammatical mistakes)
Recommended Posts