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?

chatGPT APIとdiscord.pyでBOTを作ってデプロイまでしてみた。

Posted at

はじめに

前々からdiscordBOTを作ってみたかったので、今回chatGPTに質問ができるdiscordBOTを作成してfly.ioでデプロイまでしてみました。

実装

discord側の設定

botを作成する設定はこちらの記事にわかりやすくまとまっていたのでこちらを参考に設定しました。

必要なライブラリのインストール

pip install openai
pip install discor.py
pip install python-dotenv

chatGPTのAPIを利用するためのclass

main.py
from openai import OpenAI

class GPT():
    def __init__(self, API_KEY):
        self.client = OpenAI(api_key=API_KEY)
        self.messages = [
            {'role': "system", "content": "あなたはプロのプログラミング初心者の講師となります。プログラミング学習初心者からの質問を簡潔に返答することが求められます。また、回答は文字数で200文字以下である必要があります。"}
        ]

    def response(self, message: str):
        self.messages.append({"role": "user", "content": message})
        completion = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=self.messages,
            temperature=0.5
        )
        response = completion.choices[0].message.content
        self.messages.remove({"role": "user", "content": message})
        return response

プログラミングの講師としての役割付を事前に行います。またtemperatureの値を0~1の範囲で変更すれば出力の多様性が変化します(0の方が確率のたかい出力が、1に近いほうが低い確率の単語が選ばれます)。

また、このclassのインスタンスを作成するタイミングでAPI_KEYが必要になります。.envを作成して以下のようにopenAIのAPI_KEYを設定しておいてください。

.env
CHAT_GPT_API_KEY = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

discordの実装

main.py
from discord import app_commands
import discord
from dotenv import load_dotenv
import os

from openai import OpenAI


load_dotenv()

# 略

intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)


@client.event
async def on_ready():
    print('ログインしました')

    new_activity = f"Be ready to response commands"
    await client.change_presence(activity=discord.Game(new_activity))

    await tree.sync()


@tree.command(name='gpt', description='Get Response by ChatGPT API')
async def gpt(interaction: discord.Interaction, prompt:str):
    await interaction.response.defer()
    gpt = GPT(os.getenv('CHAT_GPT_API_KEY'))
    answer =  gpt.response(prompt)
    response = f"`You >>>`\n{prompt}\n`ぴょえGPT >>>`\n{answer}\n"
    await interaction.followup.send(response)


client.run(os.getenv('TOKEN'))

treeはdiscordの/コマンドを実現することができるようです。
今回は/gptというコマンドを作成しています。
このコマンドでは promptで引数をもらい、その部分がAPIへの入力となっています。

また、discordBotのtokenも.envに追記しておきましょう!

.env
TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
CHAT_GPT_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

これで実行できると思います!

最後に

discordBOTはかなり難しいものと思っていましたが、簡単に実装できました!
デプロイに関してはこちらの記事の通りに進めると問題なくできたので、ホスティングまでしてみたい人はこちらを参考にしてみてください。

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?