ホーム › 使い方ガイド › discord.py で定期実行する方法|tasks.loop で毎日・毎時の自動投稿
GUIDE

discord.py で定期実行する方法|tasks.loop で毎日・毎時の自動投稿

「毎朝9時にお知らせを投稿する」「10分ごとにステータスを更新する」といった定期的な処理は、discord.py の tasks.loop で簡単に作れます。このページでは、一定間隔での実行、決まった時刻での実行、開始・停止の方法と、よくある失敗を説明します。

一定間隔で実行する

import discord
from discord.ext import commands, tasks

bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())
CHANNEL_ID = 123456789012345678

@tasks.loop(minutes=30)
async def reminder():
    channel = bot.get_channel(CHANNEL_ID)
    if channel:
        await channel.send("30分たちました。休憩しましょう!")

@reminder.before_loop
async def before_reminder():
    await bot.wait_until_ready()  # ログインが終わるまで待つ

@bot.event
async def setup_hook():
    reminder.start()

seconds=・minutes=・hours= で間隔を指定します。before_loop で wait_until_ready() を待たないと、起動直後に get_channel が None を返して失敗します。

毎日決まった時刻に実行する

import datetime

JST = datetime.timezone(datetime.timedelta(hours=9))
times = [
    datetime.time(hour=9, minute=0, tzinfo=JST),
    datetime.time(hour=21, minute=0, tzinfo=JST),
]

@tasks.loop(time=times)
async def daily_post():
    channel = bot.get_channel(CHANNEL_ID)
    await channel.send("おはようございます!今日も一日がんばりましょう。")
tzinfo を付けないと UTC(日本時間の9時間前)として扱われます。サーバーは日本時間で動いているとは限らないので、必ず日本時間(JST)を指定しましょう。

曜日を限定する

tasks.loop には曜日の指定がないので、関数の中で判定します。

@tasks.loop(time=datetime.time(hour=12, tzinfo=JST))
async def weekly():
    if datetime.datetime.now(JST).weekday() != 0:  # 0=月曜日
        return
    await bot.get_channel(CHANNEL_ID).send("今週もよろしくお願いします!")

コマンドで開始・停止する

@bot.tree.command(name="reminder_on", description="リマインダーを開始")
async def reminder_on(interaction: discord.Interaction):
    if not reminder.is_running():
        reminder.start()
    await interaction.response.send_message("開始しました", ephemeral=True)

@bot.tree.command(name="reminder_off", description="リマインダーを停止")
async def reminder_off(interaction: discord.Interaction):
    reminder.cancel()
    await interaction.response.send_message("停止しました", ephemeral=True)

途中の処理を待ってから止めたいときは cancel() の代わりに stop() を使います。

途中でエラーが起きたとき

ループの中でエラーが起きると、そのループは止まってしまいます。止まってほしくない処理は try で囲むか、エラー時の処理を書いておきます。

@reminder.error
async def reminder_error(error):
    print(f"リマインダーでエラー: {error}")
    reminder.restart()

よくある失敗

RuntimeError: Task is already launched

on_ready で start() していると、再接続のたびに呼ばれてこのエラーになります。setup_hook で開始するか、is_running() を確認してから開始します。

間隔が短すぎて制限される

数秒ごとのメッセージ編集やチャンネル名の変更は、Discord のレート制限にかかります。詳しくは「レート制限(429)の原因と対処法」を見てください。

パソコンを閉じたら投稿されなかった

定期実行は Bot が動いている間しか行われません。毎日の自動投稿を確実に続けるには、24時間動くサーバーで動かす必要があります。StellaHost なら月額 ¥180 から使えます。

まとめ

  • @tasks.loop(minutes=...) で一定間隔、time= で決まった時刻
  • 時刻指定は日本時間の tzinfo を必ず付ける
  • before_loop で wait_until_ready()、開始は setup_hook で

Discord Bot を、月 ¥180 で24時間。

支払い後およそ2分で、日本のサーバーが自動で用意されます。 プランを見る →

ほかのガイド

Discord Bot でデータを保存する方法|SQLite でポイント・レベル機能を作る再起動しても消えないデータを、SQLite(aiosqlite)で Discord Bot に保存する方法を解説。ポイント機能・ランキングのサンプルコードと、サーバーでの注意点を紹介します。読む → discord.py でチケット(お問い合わせ)機能を作る方法ボタンを押すと本人とスタッフだけが見える専用チャンネルが作られる、チケット機能の作り方を discord.py のサンプルコード付きで解説します。読む → discord.py で NG ワード削除・スパム対策・タイムアウトを作る方法discord.py で NG ワードを含むメッセージの自動削除、連投スパムの検知、タイムアウトを作る方法と、Discord 標準の AutoMod との使い分けを解説します。読む → Discord Bot のステータス(プレイ中・視聴中)を表示・変更する方法discord.py で Bot の「○○をプレイ中」などのステータスを設定する方法、オンライン状態の変え方、導入サーバー数を表示して定期的に切り替える方法を解説します。読む → Discord Bot がメッセージを読めない?Message Content Intent の設定方法コマンドに反応しない・message.content が空になる原因は Message Content Intent。Discord Developer Portal とコード(discord.py)の両方で有効にする手順を解説します。読む → Discord Bot を24時間動かす方法|PCを閉じても止まらないPC を閉じると止まってしまう Discord Bot を、24時間動かし続ける方法を解説。自分の PC・無料ホスティング・Bot 用サーバーの違いと、月額 ¥180 から始められる手順を紹介します。読む →