discord.ext.tasks -- asyncio.Task ヘルパー

バージョン 1.1.0 で追加.

ボットを作成するときの最も一般的な操作の1つは、指定した間隔でバックグラウンドでループを実行させることです。このパターンは非常に一般的ですが、注意すべきことがたくさんあります。

  • asyncio.CancelledError はどのように処理するべきですか?

  • インターネット接続が切れた場合はどうするべきですか?

  • スリープできる最大時間は何秒ですか?

The goal of this ndiscord.py extension is to abstract all these worries away from you.

レシピ

Cog におけるシンプルなバックグラウンドタスク:

from discord.ext import tasks, commands

class MyCog(commands.Cog):
    def __init__(self):
        self.index = 0
        self.printer.start()

    def cog_unload(self):
        self.printer.cancel()

    @tasks.loop(seconds=5.0)
    async def printer(self):
        print(self.index)
        self.index += 1

再接続中に処理する例外を追加します:

import asyncpg
from discord.ext import tasks, commands

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.data = []
        self.batch_update.add_exception_type(asyncpg.PostgresConnectionError)
        self.batch_update.start()

    def cog_unload(self):
        self.batch_update.cancel()

    @tasks.loop(minutes=5.0)
    async def batch_update(self):
        async with self.bot.pool.acquire() as con:
            # batch update here...
            pass

特定の回数ループさせる:

from discord.ext import tasks

@tasks.loop(seconds=5.0, count=5)
async def slow_count():
    print(slow_count.current_loop)

@slow_count.after_loop
async def after_slow_count():
    print('done!')

slow_count.start()

ループが始まる前に、Botの準備が整うまで待機する:

from discord.ext import tasks, commands

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.index = 0
        self.bot = bot
        self.printer.start()

    def cog_unload(self):
        self.printer.cancel()

    @tasks.loop(seconds=5.0)
    async def printer(self):
        print(self.index)
        self.index += 1

    @printer.before_loop
    async def before_printer(self):
        print('waiting...')
        await self.bot.wait_until_ready()

キャンセルする場合、その間に何らかの処理を行う:

from discord.ext import tasks, commands
import asyncio

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot= bot
        self._batch = []
        self.lock = asyncio.Lock()
        self.bulker.start()

    async def do_bulk(self):
        # bulk insert data here
        ...

    @tasks.loop(seconds=10.0)
    async def bulker(self):
        async with self.lock:
            await self.do_bulk()

    @bulker.after_loop
    async def on_bulker_cancel(self):
        if self.bulker.is_being_cancelled() and len(self._batch) != 0:
            # if we're cancelled and we have some data left...
            # let's insert it to our database
            await self.do_bulk()

APIリファレンス

class discord.ext.tasks.Loop

ループと再接続処理を抽象化するバックグラウンドタスクのヘルパー。

loop() はこれを作成するための主要なインタフェースです。

@after_loop

A decorator that register a coroutine to be called after the loop finished running.

The coroutine must take no arguments (except self in a class context).

注釈

This coroutine is called even during cancellation. If it is desirable to tell apart whether something was cancelled or not, check to see whether is_being_cancelled() is True or not.

パラメータ

coro (coroutine) -- The coroutine to register after the loop finishes.

例外

TypeError -- The function was not a coroutine.

@before_loop

A decorator that registers a coroutine to be called before the loop starts running.

This is useful if you want to wait for some bot state before the loop starts, such as discord.Client.wait_until_ready().

The coroutine must take no arguments (except self in a class context).

パラメータ

coro (coroutine) -- The coroutine to register before the loop runs.

例外

TypeError -- The function was not a coroutine.

@error

A decorator that registers a coroutine to be called if the task encounters an unhandled exception.

The coroutine must take only one argument the exception raised (except self in a class context).

By default this prints to sys.stderr however it could be overridden to have a different implementation.

バージョン 1.4 で追加.

パラメータ

coro (coroutine) -- The coroutine to register in the event of an unhandled exception.

例外

TypeError -- The function was not a coroutine.

property seconds: Optional[float]

Read-only value for the number of seconds between each iteration. None if an explicit time value was passed instead.

バージョン 2.0 で追加.

Type

Optional[float]

property minutes: Optional[float]

Read-only value for the number of minutes between each iteration. None if an explicit time value was passed instead.

バージョン 2.0 で追加.

Type

Optional[float]

property hours: Optional[float]

Read-only value for the number of hours between each iteration. None if an explicit time value was passed instead.

バージョン 2.0 で追加.

Type

Optional[float]

property time: Optional[List[datetime.time]]

Read-only list for the exact times this loop runs at. None if relative times were passed instead.

バージョン 2.0 で追加.

Type

Optional[List[datetime.time]]

property name: str

The name of the task

バージョン 2.0 で追加.

Type

str

property current_loop: int

The current iteration of the loop.

Type

int

property next_iteration: Optional[datetime.datetime]

When the next iteration of the loop will occur.

バージョン 1.3 で追加.

Type

Optional[datetime.datetime]

await __call__(*args, **kwargs)

This function is a coroutine.

Calls the internal callback that the task holds.

バージョン 1.6 で追加.

パラメータ
  • *args -- The arguments to use.

  • **kwargs -- The keyword arguments to use.

start(*args, **kwargs)

Starts the internal task in the event loop.

パラメータ
  • *args -- The arguments to use.

  • **kwargs -- The keyword arguments to use.

例外

RuntimeError -- A task has already been launched and is running.

戻り値

タスクが作成されました。

戻り値の型

asyncio.Task

stop()

Gracefully stops the task from running.

Unlike cancel(), this allows the task to finish its current iteration before gracefully exiting.

注釈

If the internal function raises an error that can be handled before finishing then it will retry until it succeeds.

If this is undesirable, either remove the error handling before stopping via clear_exception_types() or use cancel() instead.

バージョン 1.2 で追加.

cancel()

Cancels the internal task, if it is running.

restart(*args, **kwargs)

A convenience method to restart the internal task.

注釈

Due to the way this function works, the task is not returned like start().

パラメータ
  • *args -- The arguments to use.

  • **kwargs -- The keyword arguments to use.

add_exception_type(*exceptions)

Adds exception types to be handled during the reconnect logic.

By default the exception types handled are those handled by discord.Client.connect(), which includes a lot of internet disconnection errors.

This function is useful if you're interacting with a 3rd party library that raises its own set of exceptions.

パラメータ

*exceptions (Type[BaseException]) -- An argument list of exception classes to handle.

例外

TypeError -- An exception passed is either not a class or not inherited from BaseException.

clear_exception_types()

Removes all exception types that are handled.

注釈

This operation obviously cannot be undone!

remove_exception_type(*exceptions)

Removes exception types from being handled during the reconnect logic.

パラメータ

*exceptions (Type[BaseException]) -- An argument list of exception classes to handle.

戻り値

Whether all exceptions were successfully removed.

戻り値の型

bool

get_task()

Optional[asyncio.Task]: Fetches the internal task or None if there isn't one running.

is_being_cancelled()

Whether the task is being cancelled.

failed()

bool: Whether the internal task has failed.

バージョン 1.2 で追加.

is_running()

bool: Check if the task is currently running.

バージョン 1.4 で追加.

change_interval(*, seconds=0, minutes=0, hours=0, time=...)

Changes the interval for the sleep time.

バージョン 1.2 で追加.

パラメータ
  • seconds (float) -- The number of seconds between every iteration.

  • minutes (float) -- The number of minutes between every iteration.

  • hours (float) -- The number of hours between every iteration.

  • time (Union[datetime.time, Sequence[datetime.time]]) --

    The exact times to run this loop at. Either a non-empty list or a single value of datetime.time should be passed. This cannot be used in conjunction with the relative time parameters.

    バージョン 2.0 で追加.

    注釈

    Duplicate times will be ignored, and only run once.

例外
  • ValueError -- An invalid value was given.

  • TypeError -- An invalid value for the time parameter was passed, or the time parameter was passed in conjunction with relative time parameters.

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=..., loop=...)

A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a Loop.

パラメータ
  • seconds (float) -- The number of seconds between every iteration.

  • minutes (float) -- The number of minutes between every iteration.

  • hours (float) -- The number of hours between every iteration.

  • time (Union[datetime.time, Sequence[datetime.time]]) --

    The exact times to run this loop at. Either a non-empty list or a single value of datetime.time should be passed. Timezones are supported. If no timezone is given for the times, it is assumed to represent UTC time.

    This cannot be used in conjunction with the relative time parameters.

    注釈

    Duplicate times will be ignored, and only run once.

    バージョン 2.0 で追加.

  • count (Optional[int]) -- The number of loops to do, None if it should be an infinite loop.

  • reconnect (bool) -- Whether to handle errors and restart the task using an exponential back-off algorithm similar to the one used in discord.Client.connect().

  • name (str) --

    The name of the loop, used for debugging purposes. If you don't provide it, it will use the function/callback/coro name.

    バージョン 2.0 で追加.

  • loop (asyncio.AbstractEventLoop) -- The loop to use to register the task, if not given defaults to asyncio.get_event_loop().

例外
  • ValueError -- An invalid value was given.

  • TypeError -- The function was not a coroutine, an invalid value for the time parameter was passed, or time parameter was passed in conjunction with relative time parameters.