ホーム › 使い方ガイド › Discord Bot でデータを保存する方法|SQLite でポイント・レベル機能を作る
GUIDE

Discord Bot でデータを保存する方法|SQLite でポイント・レベル機能を作る

ポイント、レベル、警告回数、サーバーごとの設定など、Bot を再起動しても消えないデータを持たせるには、データを保存する仕組みが必要です。このページでは、追加のサーバーがいらず手軽に使える SQLite を使って、discord.py の Bot にデータを保存する方法を説明します。

なぜ変数や JSON ではダメなのか

保存方法向いている用途注意点
Python の変数一時的なデータ再起動すると消える
JSON ファイル少ない設定値同時に書き込むと壊れることがある・データが増えると遅い
SQLiteユーザーごとのデータ全般1ファイルで完結し、壊れにくい

SQLite は Python に最初から入っているので、追加のインストールなしで使えます。ただし Bot の処理を止めないために、非同期版の aiosqlite を使うのがおすすめです。

pip install aiosqlite

サーバーで動かす場合は requirements.txt に aiosqlite を追加しておきます。

テーブルを作る

import aiosqlite
import discord
from discord.ext import commands

DB = "data.db"

class MyBot(commands.Bot):
    async def setup_hook(self):
        async with aiosqlite.connect(DB) as db:
            await db.execute("""
                CREATE TABLE IF NOT EXISTS points (
                    guild_id INTEGER,
                    user_id  INTEGER,
                    point    INTEGER DEFAULT 0,
                    PRIMARY KEY (guild_id, user_id)
                )
            """)
            await db.commit()
        await self.tree.sync()

bot = MyBot(command_prefix="!", intents=discord.Intents.default())

guild_id と user_id の組み合わせで1行にすると、複数のサーバーに入れても混ざりません。

ポイントを増やす・見る

async def add_point(guild_id: int, user_id: int, amount: int):
    async with aiosqlite.connect(DB) as db:
        await db.execute("""
            INSERT INTO points (guild_id, user_id, point) VALUES (?, ?, ?)
            ON CONFLICT(guild_id, user_id) DO UPDATE SET point = point + excluded.point
        """, (guild_id, user_id, amount))
        await db.commit()

async def get_point(guild_id: int, user_id: int) -> int:
    async with aiosqlite.connect(DB) as db:
        async with db.execute(
            "SELECT point FROM points WHERE guild_id = ? AND user_id = ?",
            (guild_id, user_id),
        ) as cur:
            row = await cur.fetchone()
    return row[0] if row else 0

@bot.tree.command(name="daily", description="1日1回ポイントをもらう")
async def daily(interaction: discord.Interaction):
    await add_point(interaction.guild_id, interaction.user.id, 10)
    now = await get_point(interaction.guild_id, interaction.user.id)
    await interaction.response.send_message(f"10ポイント獲得! 合計 {now} ポイント")
値は必ず ? を使って渡します。f-string で SQL 文に直接埋め込むと、入力された文字によって SQL が壊れたり、意図しない操作をされたりする危険があります(SQL インジェクション)。

ランキングを表示する

@bot.tree.command(name="ranking", description="ポイントランキング")
async def ranking(interaction: discord.Interaction):
    async with aiosqlite.connect(DB) as db:
        async with db.execute(
            "SELECT user_id, point FROM points WHERE guild_id = ? ORDER BY point DESC LIMIT 10",
            (interaction.guild_id,),
        ) as cur:
            rows = await cur.fetchall()
    lines = [f"{i}. <@{uid}> — {pt}pt" for i, (uid, pt) in enumerate(rows, 1)]
    embed = discord.Embed(title="ランキング", description="\n".join(lines) or "まだデータがありません", color=0x22c55e)
    await interaction.response.send_message(embed=embed)

サーバーで動かすときの注意

  • 保存場所:data.db は Bot のフォルダの中に作られます。StellaHost ではパネルの「ファイル」から確認・ダウンロードできます。
  • バックアップ:大事なデータは、ときどき data.db をダウンロードして手元に保存しておきましょう。
  • 上書きに注意:ファイルをアップロードし直すときに、data.db まで手元の古いもので上書きしないようにします。

まとめ

  • 再起動しても残るデータは SQLite(aiosqlite)に保存する
  • guild_id と user_id の組み合わせで管理すると混ざらない
  • 値は ? で渡し、data.db はときどきバックアップする

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

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

ほかのガイド

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 から始められる手順を紹介します。読む → Python で作った Discord Bot をサーバーで動かす手順discord.py などで作った Bot を、main.py と requirements.txt を置くだけでサーバーで動かす手順を解説。トークンの安全な置き方や、よくあるエラーの対処も紹介します。読む →