Discord Bot 個人制作手順(Python)

開発に必要なソフトウェアのインストール

Bot アカウントの作成

  • https://discord.com/developers/applications

  • Bot -> Privileged Gateway Intents -> 3つ全てONに

  • Bot -> TOKEN -> Reset Token -> Copy

    • ↓のプログラムで必要なので保存しておく

  • OAuth2 -> URL Generator

    • bot と applications.commands にチェック

    • 招待用URLをコピー

  • 招待用URLを開いて自分のサーバーに導入する

Bot プログラムの作成と起動

  • まずBotプログラム用のフォルダを作成

  • VSCode でそのフォルダを開く

    • メニュー -> ファイル -> フォルダを開く

  • 以下のプログラムを作成して保存

  • main.py として保存

import discord
from discord.ext import commands

TOKEN = '↑で保存したTOKENをここに書く'

extensions = (
    'fortune',
)

class MyBot(commands.Bot):
    def __init__(self):
        super().__init__(
            command_prefix=commands.when_mentioned,
            intents=discord.Intents.all(),
        )

    async def setup_hook(self):
        for extension in extensions:
            await self.load_extension(extension)

if __name__ == '__main__':
    MyBot().run(TOKEN)
  • fortune.py として保存

from discord.ext import commands
from random import choice

class FortuneCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return
        if message.content == '占い':
            fortunes = ['超大吉', '大吉', '吉']
            fortune = choice(fortunes)
            await message.channel.send(f'今日の運勢は {fortune} です!')

async def setup(bot):
    await bot.add_cog(FortuneCog(bot))
$ python3 -m pip install discord.py
  • main.py を実行(Botを起動)

$ python3 main.py
  • Mac で SSLCertVerificationError が表示されたら↓を打って実行し直し

    • Pythonのバージョンに合わせて 3.11 の部分を変更

$ /Applications/Python\ 3.11/Install\ Certificates.command
  • サーバー上で Bot がオンラインになってるのが確認できたら「占い」とメッセージを送信して確認

稼働場所を自宅PCからサーバー上に移す

  • https://railway.app/

    • Botを稼働できるサービス(PaaS)

      • 無料だったけど5$/月に😭

  • https://github.com/

    • Railway にプログラムをアップロード(デプロイ)する際に経由する

参考リンク/ツール


この記事が気に入ったらサポートをしてみませんか?