0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[生成AI出力バージョン]GoogleCloudのVMを用いて、DiscordのBOTを構築する

Posted at

※本記事は学習用途(高校生・専門学生・大学生向け)に限りご利用ください。商用利用は禁止です。

はじめに

Google Cloud とは?

検索すれば詳細は出てきますが、一言で言うと 「クラウド上のインフラとマネージドサービスの集合」 です。
≠ VM なので注意してください。VM は無数にあるサービスの一つで、正式には Compute Engine に含まれる VM インスタンス 機能として提供されています。

Discord とは?

無料で使えるチャット & 通話プラットフォームです。近年はゲーマーだけでなく、社会人サークルや技術コミュニティでも広く利用されています。
Bot を開発する際は Discord Developer Portal を使用します。
https://discord.com/developers/docs/intro


Google Cloud で VM を準備する

  1. プロジェクトの作成
  2. Compute Engine に移動
  3. VM インスタンスを作成
  4. SSH でログイン

以降の手順では東京リージョン(asia-northeast1)、マシンタイプ e2‑micro(共有 vCPU × 2、1 GiB RAM)を例に説明します。2025‑04 現在、常時起動で月額約 USD 7 程度です。
実際の価格はリージョン・構成・為替で変動するため、必ずコンソール右側の「概算コスト」を確認してください。

1. プロジェクトの作成

  1. https://console.cloud.google.com/ にアクセス
  2. 画面左上の Google Cloud アイコン右の▼新しいプロジェクト
  3. プロジェクト名を入力し 作成
    (完了まで ~30 秒)

2. Compute Engine へ移動

左側ナビゲーションの検索窓で「compute」と入力 → Compute Engine を選択
※ピン留め(📌)すると以降アクセスが楽になります。初回は 「Compute Engine API を有効化」 する画面が出るので 有効にする を押してください。

3. VM インスタンスを作成

設定項目 推奨値(例)
名前 discord-bot-vm
リージョン asia‑northeast1 (東京)
マシンシリーズ E2
マシンタイプ e2‑micro
ブートディスク Ubuntu 22.04 LTS (default 10 GB)
外部 IP エフェメラル (固定化しない)

VS Code Remote SSH を常用したい場合は e2‑standard‑2 以上を検討してください。

4. SSH でログイン

4‑1. ブラウザ SSH

インスタンス一覧の SSH ボタンからブラウザで接続し、シェルが開いたら自分の Linux ユーザー名をメモしておきます。

4‑2. ローカルマシンに鍵を作成

ssh-keygen -t rsa -f ~/.ssh/gcp_key -C "<GCP_USERNAME>"

公開鍵を VM に登録します。
コンソール → インスタンス詳細 → 編集SSH 認証鍵cat ~/.ssh/gcp_key.pub の内容を貼り付け → 保存

4‑3. ローカルから接続

ssh -i ~/.ssh/gcp_key <GCP_USERNAME>@<EXTERNAL_IP>

接続できれば準備完了です。


Discord Bot を作る

1. Python 仮想環境の構築

sudo apt update && sudo apt install -y python3 python3-venv git
mkdir ~/discord-bot && cd ~/discord-bot
python3 -m venv venv
source venv/bin/activate
pip install -U pip discord.py

2. サンプル Bot

bot.py

import os
import discord
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()                          # .env から環境変数を読み込む
TOKEN = os.getenv("DISCORD_BOT_TOKEN") # トークンはコードに直書きしない!

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    print(f"ログイン成功: {bot.user}")

@bot.command()
async def ping(ctx):
    await ctx.reply("Pong!")

bot.run(TOKEN)

.env

DISCORD_BOT_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

3. Discord Developer Portal の設定

  1. New Application でアプリを作成
  2. 左側 BotReset Token → コピーして .env に貼り付け
  3. Privileged Gateway IntentsMESSAGE CONTENT INTENT を ON
  4. OAuth2 → URL Generator
    • Scopes: bot
    • Bot Permissions: Send Messages, Read Message History
      生成された URL でサーバーに Bot を招待

4. Bot を起動

source ~/discord-bot/venv/bin/activate
python bot.py

「!ping」と送信すると Pong! と返ります。

常時稼働させる

nohup python bot.py > bot.log 2>&1 &
tail -f bot.log            # ログ監視

停止は pkill -f bot.py


クリーンアップ(課金停止)

使い終わったら プロジェクトを削除 するのが最も確実です。
コンソール → IAM と管理 › 設定シャットダウン

注意: プロジェクトは 30 日間保留状態となり、その間は請求が発生しませんが復元可能です。


おわりに

お疲れさまでした!
この記事がクラウド & Bot 開発の一歩目になれば幸いです。


0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?