Discord Bot 個人制作手順(Python)
開発に必要なソフトウェアのインストール
Python
プログラミング言語(プログラムを実行する環境)
3.11 推奨(3.10 / 3.9 / 3.8 でも可)(3.12 は非推奨)
インストール方法解説 https://www.python.jp/install/install.html
VSCode
プログラムを書くためのコードエディタ(すごいメモ帳)
https://azure.microsoft.com/ja-jp/products/visual-studio-code
Bot アカウントの作成
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))
VSCode のターミナルを開く
表示 -> ターミナル
Windows/Macの方法に合わせてコマンドを打つ
python3 だったり python だったり py -3 だったり
確認 -> https://tutorial.djangogirls.org/ja/python_introduction/
discord.py をインストール
$ 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からサーバー上に移す
Botを稼働できるサービス(PaaS)
無料だったけど5$/月に😭
Railway にプログラムをアップロード(デプロイ)する際に経由する
参考リンク/ツール
英語情報に立ち向かうための翻訳ツール(DeepL)
Python によるプログラムの書き方の解説サイト:
discord.py リファレンス