🎙️

Discord.py で作る一時ボイスチャンネル Bot

に公開

Discord サーバーで「ロビー VC に入ると専用ルームが自動生成され、全員退出すると自動削除される」仕組みを見かけることがあるかと思います。

この記事では、そんな一時ボイスチャンネル Bot の作り方をまとめてみました。

完成イメージ

ユーザーがロビー VC に参加すると、専用の VC が自動作成され、コントロールパネル (名前変更・ロック・人数制限などのボタン) が送信されます。全員が退出すると VC が自動削除される、という流れです。

技術スタック

技術 用途
Python 3.12 言語
discord.py 2.x Discord Bot フレームワーク
SQLAlchemy 2.x 非同期 ORM
PostgreSQL データベース
pydantic-settings 環境変数管理

プロジェクト構成

src/
├── main.py              # エントリーポイント
├── bot.py               # Bot クラス
├── config.py            # 設定管理
├── cogs/
│   ├── admin.py         # /lobby コマンド
│   └── voice.py         # VC 自動作成・削除
├── database/
│   ├── engine.py        # DB エンジン
│   └── models.py        # テーブル定義
├── services/
│   └── db_service.py    # CRUD 操作
└── ui/
    └── control_panel.py # ボタン UI

Step 1: Bot の基本セットアップ

まずは Bot クラスを作成します。

src/bot.py
import discord
from discord.ext import commands

class EphemeralVCBot(commands.Bot):
    def __init__(self) -> None:
        intents = discord.Intents.default()
        intents.voice_states = True  # VC イベントを受け取るために必須
        intents.guilds = True

        super().__init__(
            command_prefix="!",
            intents=intents,
        )

    async def setup_hook(self) -> None:
        """Bot 起動時に Cog を読み込む"""
        await self.load_extension("src.cogs.admin")
        await self.load_extension("src.cogs.voice")

voice_states インテントを有効にしないと VC の参加・退出イベントを受け取れないので、忘れずに設定しておきます。

Step 2: データベース設計

ロビーと一時 VC の情報を保存するテーブルを定義します。

src/database/models.py
from sqlalchemy import BigInteger, Boolean, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

class Base(DeclarativeBase):
    pass

class Lobby(Base):
    """ロビー VC のテーブル"""
    __tablename__ = "lobbies"

    id: Mapped[int] = mapped_column(primary_key=True)
    channel_id: Mapped[str] = mapped_column(String(20), unique=True)
    guild_id: Mapped[str] = mapped_column(String(20))

class VoiceSession(Base):
    """一時 VC のテーブル"""
    __tablename__ = "voice_sessions"

    id: Mapped[int] = mapped_column(primary_key=True)
    channel_id: Mapped[str] = mapped_column(String(20), unique=True)
    owner_id: Mapped[str] = mapped_column(String(20))
    lobby_id: Mapped[int] = mapped_column(BigInteger)
    is_locked: Mapped[bool] = mapped_column(Boolean, default=False)
    is_hidden: Mapped[bool] = mapped_column(Boolean, default=False)

channel_id を String にしているのは、Discord の ID が 64bit 整数で、Discord API が JSON で返す際に文字列として扱われることがあるためです。

Step 3: VC 自動作成ロジック

VC の参加・退出イベントを監視して、自動作成・削除を行います。なお、_is_lobby や _is_temp_vc などのヘルパーメソッド、save_voice_session などの DB 操作関数は省略しています。

src/cogs/voice.py
import discord
from discord.ext import commands

class VoiceCog(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @commands.Cog.listener()
    async def on_voice_state_update(
        self,
        member: discord.Member,
        before: discord.VoiceState,
        after: discord.VoiceState,
    ) -> None:
        # ロビーへの参加を検知
        if after.channel and await self._is_lobby(after.channel.id):
            await self._create_voice_channel(member, after.channel)

        # VC からの退出を検知
        if before.channel and await self._is_temp_vc(before.channel.id):
            await self._cleanup_if_empty(before.channel)

    async def _create_voice_channel(
        self,
        member: discord.Member,
        lobby: discord.VoiceChannel,
    ) -> None:
        """一時 VC を作成してユーザーを移動"""
        # オーナーの権限オーバーライド
        overwrites = {
            member: discord.PermissionOverwrite(
                connect=True,
                manage_channels=True,  # チャンネル設定の変更
                move_members=True,     # メンバーのキック
            ),
        }

        # VC を作成
        new_channel = await lobby.guild.create_voice_channel(
            name=f"{member.display_name}'s VC",
            category=lobby.category,
            overwrites=overwrites,
        )

        # ユーザーを移動
        await member.move_to(new_channel)

        # DB に保存
        await save_voice_session(new_channel.id, member.id, lobby.id)

        # コントロールパネルを送信
        await self._send_control_panel(new_channel, member)

    async def _cleanup_if_empty(self, channel: discord.VoiceChannel) -> None:
        """誰もいなくなった VC を削除"""
        if len(channel.members) == 0:
            await channel.delete()
            await delete_voice_session(channel.id)

イベントフロー

Step 4: コントロールパネル (ボタン UI)

discord.py の View と Button を使ってボタン操作を実装しています。なお、RenameModal や UserLimitSelectView の実装は省略しています。

src/ui/control_panel.py
import discord
from discord import ui

class ControlPanelView(ui.View):
    def __init__(self, session_id: int, is_locked: bool, is_hidden: bool):
        super().__init__(timeout=None)  # タイムアウト無効
        self.session_id = session_id

        # ロック状態に応じてラベルを切り替え
        lock_label = "🔓 アンロック" if is_locked else "🔒 ロック"
        self.lock_button.label = lock_label

    @ui.button(label="🏷️ 名前変更", style=discord.ButtonStyle.secondary)
    async def rename(self, interaction: discord.Interaction, button: ui.Button):
        """名前変更モーダルを表示"""
        modal = RenameModal()
        await interaction.response.send_modal(modal)

    @ui.button(label="🔒 ロック", style=discord.ButtonStyle.secondary)
    async def lock_button(self, interaction: discord.Interaction, button: ui.Button):
        """VC をロック/アンロック"""
        channel = interaction.channel
        if not isinstance(channel, discord.VoiceChannel):
            return

        # @everyone の接続権限を切り替え
        overwrite = channel.overwrites_for(channel.guild.default_role)
        is_locked = overwrite.connect is False

        overwrite.connect = None if is_locked else False
        await channel.set_permissions(channel.guild.default_role, overwrite=overwrite)

        # ボタンのラベルを更新
        button.label = "🔒 ロック" if is_locked else "🔓 アンロック"
        await interaction.response.edit_message(view=self)

    @ui.button(label="👥 人数制限", style=discord.ButtonStyle.secondary)
    async def user_limit(self, interaction: discord.Interaction, button: ui.Button):
        """人数制限セレクトメニューを表示"""
        view = UserLimitSelectView()
        await interaction.response.send_message(
            "人数制限を選択してください",
            view=view,
            ephemeral=True,
        )

永続化について

Bot を再起動してもボタンが動作するように、custom_id を設定しておきます。

@ui.button(
    label="🔒 ロック",
    style=discord.ButtonStyle.secondary,
    custom_id="control_panel:lock",  # これを追加
)
async def lock_button(self, interaction, button):
    ...

あわせて、Step 1 の setup_hook に View の登録を追加しておきます。

async def setup_hook(self) -> None:
    # Cog の読み込み
    await self.load_extension("src.cogs.admin")
    await self.load_extension("src.cogs.voice")
    # View の登録
    self.add_view(ControlPanelView(session_id=0, is_locked=False, is_hidden=False))

Step 5: /lobby コマンド (管理者用)

ロビー VC を作成するスラッシュコマンドです。

src/cogs/admin.py
import discord
from discord import app_commands
from discord.ext import commands

class AdminCog(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @app_commands.command(name="lobby", description="ロビー VC を作成します")
    @app_commands.default_permissions(administrator=True)
    async def lobby(self, interaction: discord.Interaction) -> None:
        """ロビー VC を作成"""
        guild = interaction.guild
        if not guild:
            return

        # カテゴリを作成
        category = await guild.create_category("🎙️ ボイスチャンネル")

        # ロビー VC を作成
        lobby_channel = await guild.create_voice_channel(
            name="➕ VC を作成",
            category=category,
        )

        # DB に保存
        await save_lobby(lobby_channel.id, guild.id)

        await interaction.response.send_message(
            f"ロビーを作成しました: {lobby_channel.mention}",
            ephemeral=True,
        )

Step 6: 権限の設計

Step 3 の _create_voice_channel で設定している権限についての補足です。

権限 用途
connect=True オーナーは常に接続可能
manage_channels=True チャンネル名や設定の変更
move_members=True 他のメンバーをキック

ロック機能の仕組み

# ロック: @everyone の connect を False に
await channel.set_permissions(
    channel.guild.default_role,
    connect=False,
)

# 特定ユーザーを許可: そのユーザーの connect を True に
await channel.set_permissions(
    allowed_user,
    connect=True,
)

デプロイ

依存パッケージと環境変数の例です。

requirements.txt
discord.py~=2.6.0
SQLAlchemy~=2.0.0
asyncpg~=0.30.0
pydantic-settings~=2.0
環境変数 説明
DISCORD_TOKEN Bot トークン
DATABASE_URL PostgreSQL 接続 URL

おわりに

discord.py は View や Button など UI 周りの機能が充実しているので、何かの参考になれば幸いです。

発展として、VC の名前変更回数制限 (レートリミット対策) やブロックリスト機能、テンプレート機能 (よく使う設定を保存) なども考えられるかもしれません。

参考

Discussion