-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: update cogs guide, and few touch ups in other guides
- Loading branch information
1 parent
6c7e9f5
commit 4064673
Showing
11 changed files
with
622 additions
and
139 deletions.
There are no files selected for viewing
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,36 +1,73 @@ | ||
# Tasks | ||
|
||
[Tasks](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html) in discord.py are helpers | ||
for [asyncio.Task](https://docs.python.org/3/library/asyncio-task.html#task-object) | ||
One of the most common things you will often find yourself needing is some sort of background task. This could be anything from updating a counter every minute to updating some leaderboard every hour or posting daily reminders. | ||
To handle these tasks, discord.py provides a `tasks` extension that makes it easy to create and manage background tasks. | ||
|
||
They are used for having a loop run in the background at a specified interval/time. | ||
The `tasks` extension is a wrapper around the [`asyncio.Task`](https://docs.python.org/3/library/asyncio-task.html#task-object) class that allows you to run a coroutine in the background at a specified interval, with a lot of additional features like error handling, reconnect logic, exponential backoff, and more. | ||
|
||
## Creating a task | ||
|
||
To create a task you need to make an `async` function that you want to run in the task and apply `tasks.loop` decorator on it. | ||
|
||
You can read about its parameters in [discord.py documentation](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#discord.ext.tasks.loop) | ||
It takes the following arguments: | ||
|
||
```python | ||
from discord.ext import tasks | ||
- `seconds`: The number of seconds between each iteration. | ||
- `minutes`: The number of minutes between each iteration. | ||
- `hours`: The number of hours between each iteration. | ||
- `time`: A `datetime.time` or a list of `datetime.time` objects representing the time(s) of day to run the task. | ||
- `count`: The number of times to run the task. If `None`, the task will run indefinitely. | ||
- `reconnect`: Whether to handle errors and restart the task using an exponential backoff strategy. Defaults to `True`. For more information see [here](https://github.com/Rapptz/discord.py/blob/ff638d393d0f5a83639ccc087bec9bf588b59a22/discord/backoff.py#L41-L108). | ||
- `name`: The name of the task. If `None`, the function name will be used. | ||
|
||
Then you can start it by using it's `start` method. This will schedule the task to run in the background. | ||
|
||
@tasks.loop(seconds=10) | ||
async def my_task(): | ||
print("Hello!") | ||
``` | ||
=== "Using a Cog" | ||
```python | ||
from discord.ext import commands, tasks | ||
|
||
Then you can start it by using it's `start` method. For example in `setup_hook`: | ||
class MyCog(commands.Cog): | ||
def __init__(self, bot): | ||
self.bot = bot | ||
|
||
```python | ||
@bot.event | ||
async def setup_hook(): | ||
my_task.start() | ||
``` | ||
# you can start the task when the cog is loaded | ||
async def cog_load(self): | ||
self.my_task.start() | ||
|
||
# you can stop the task when the cog is unloaded | ||
async def cog_unload(self): | ||
self.my_task.stop() | ||
|
||
@tasks.loop(seconds=10) | ||
async def my_task(self): | ||
print("Hello!") | ||
|
||
async def setup(bot): | ||
bot.add_cog(MyCog(bot)) | ||
``` | ||
=== "Standalone" | ||
```python | ||
from discord.ext import tasks | ||
|
||
@tasks.loop(seconds=10) | ||
async def my_task(): | ||
print("Hello!") | ||
|
||
@bot.event | ||
async def setup_hook(): # setup_hook is called before the bot is started | ||
my_task.start() | ||
|
||
@my_task.before_loop | ||
async def before_my_task(): | ||
await bot.wait_until_ready() # wait until the bot is ready | ||
``` | ||
!!! note "Note" | ||
The only requirement to schedule a task is to call the `start` method which you can call at an appropriate place in your code. A thing to note is that the task may start running before the bot is ready, so you may want to use `before_loop` to wait until the bot is ready if you are fetching any data from the discord API. | ||
|
||
## Utility Decorators | ||
|
||
### before_loop | ||
--- | ||
|
||
### @before_loop | ||
|
||
A decorator that registers a coroutine to be called before the loop starts running. | ||
|
||
|
@@ -48,9 +85,9 @@ async def before_my_task(): | |
print("preparing!") | ||
``` | ||
|
||
### after_loop | ||
### @after_loop | ||
|
||
A decorator that registers a coroutine to be called after the loop finishes running. | ||
A decorator that registers a coroutine to be called after the loop finishes running. You can use this to perform cleanup tasks. | ||
|
||
```python | ||
from discord.ext import tasks | ||
|
@@ -66,7 +103,7 @@ async def after_my_task(): | |
print("finished!") | ||
``` | ||
|
||
### error | ||
### @error | ||
|
||
A decorator that registers a coroutine to be called if the task encounters an unhandled exception. | ||
|
||
|
@@ -121,9 +158,22 @@ my_task.restart() | |
Adds exception types to be handled during the reconnect logic. | ||
|
||
By default the exception types handled are those handled by `Client.connect()`, which includes a lot of internet disconnection errors. | ||
This method is useful if you want to handle custom exceptions that are either raise by you or some third-party libraries. | ||
This comment has been minimized.
Sorry, something went wrong.
Snipy7374
Collaborator
|
||
|
||
```python | ||
my_task.add_exception_type(SomeCustomError, AnotherCustomError) | ||
class SomeCustomError(Exception): | ||
pass | ||
|
||
@tasks.loop(seconds=10) | ||
async def my_task(): | ||
connection = await some_third_party_library.connect() | ||
print(connection) | ||
if not connection: | ||
raise SomeCustomError("Connection failed!") | ||
# do something with connection | ||
connection.close() | ||
|
||
my_task.add_exception_type(SomeCustomError) # now SomeCustomError will be handled during the reconnect logic | ||
``` | ||
|
||
### clear_exception_types | ||
|
@@ -162,4 +212,4 @@ my_task.change_interval(seconds=15) | |
|
||
## Examples | ||
|
||
Check out [discord.py tasks recipes](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#recipes). There you can find a lot of examples | ||
Check out [discord.py tasks recipes](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#recipes) for some examples on how to use tasks in your bot. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
from discord.ext import commands | ||
|
||
|
||
class SubCog(commands.Cog): | ||
... | ||
|
||
|
||
async def setup(bot: commands.Bot): | ||
await bot.add_cog(SubCog()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import discord | ||
from discord import app_commands | ||
from discord.ext import commands | ||
|
||
|
||
class SuperCog(commands.GroupCog, name="foo", description="A super cog"): | ||
_bar = app_commands.Group(name="bar", description="A bar group") | ||
|
||
@app_commands.command() | ||
async def foo(self, inter: discord.Interaction): | ||
await inter.response.send_message("foo") | ||
|
||
@_bar.command() | ||
async def baz(self, inter: discord.Interaction): | ||
await inter.response.send_message("baz") | ||
|
||
|
||
async def setup(bot: commands.Bot): | ||
await bot.add_cog(SuperCog()) |
Oops, something went wrong.
Idk why github is not letting me create a code suggestion, anyway