1
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?

Discord Botの作り方③CI/CD編

Posted at

はじめに

以前の記事の続きです

無事にDiscord BotをLightsailにデプロイしましたが、
改修が発生すると、一々、git pullするのが面倒ですね
今回は、GitHub Actionsを使って、mainブランチにpushした後、自動で再デプロイするようにします

手順

まずは、Lightsailで作成したサーバーにアクセスしよう
以前の記事と同じです。

ssh -i ~/.ssh/LightsailDefaultKey-ap-northeast-1.pem ubuntu@インスタンスのIP

次はGitHubActions用の鍵を作ります

ssh-keygen -t ed25519 -C "github-actions" -f ~/.ssh/github-actions

作成した公開鍵をauthorized_keysに登録

cat ~/.ssh/github-actions.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

作成した秘密鍵をGitHubに登録

GitHub → リポジトリ →
Settings → Secrets and variables → Actions → New repository secret
にて、以下のコマンドで取得した文字列を貼り付けてください

cat ~/.ssh/github-actions

GitHub Actionsの設定ファイルを作ります
リポジトリの直下に .github/workflows/deploy.ymlを作成します

name: Deploy to Lightsail

on:
  push:
    branches: ["main"]

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Deploy to Lightsail
        uses: appleboy/ssh-action@v0.1.10
        with:
          # サーバーIP、ユーザー名はマネジメントコンソールのLightsailから見れます
          host: '作成したサーバーのIP'
          username: '作成したサーバーのユーザー名'
          # 'LIGHTSAIL_SSH_KEY'を、先程GitHubに秘密鍵を登録した際に付けたNameに置き換えてください
          key: ${{ secrets.LIGHTSAIL_SSH_KEY }}
          # 自分の環境に応じて、ディレクトリ名とサービス名を置き換えてください
          script: |
            cd ~/discord-bot-test
            git pull
            sudo systemctl restart bot

サービス名を忘れた人は、以下コマンドで出てきます

ls /etc/systemd/system

これで完了です
後はpushしてください
GitHub → リポジトリ → Actions
で、ワークフローが緑色(Success)になれば成功です

動作確認

Botのソースコードを変更しましょう
現在のソースだと、チャンネルで/helloと打つと、Botが「こんにちは!」と返してくれる状態です
返答を変えてみましょう

main.py
@tree.command(name="hello", description="挨拶します")
async def start_command(interaction: discord.Interaction):
    await interaction.response.send_message("CI/CD成功です!")

変更したらpush
GitHub → リポジトリ → Actions
にて、新しいワークフローが作成されます
緑色(Success)になれば成功です。

チャンネルで「/hello」と打って、返答が「CI/CD成功です!」となれば無事完了です!

最後に

これにてDiscord Botの作り方に関する記事は終わりです

1
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
1
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?