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?

More than 1 year has passed since last update.

猫型ボット(ChatGPTラスク)をDiscordへご招待

Posted at

Slackに招待したラスクにゃんをDiscordにも入れました。

2023-03-22_17h58_23.png

コードはこちら。

import discord
import openai
import os


openai.api_key = os.environ["OPENAI_API_KEY"]


class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as', self.user)

    async def on_message(self, message):
        print('on_message', self.user, message)
        if message.author == self.user:
            return

        if self.user in message.mentions:
            chat_logs = ""
            messages = []
            async for msg in message.channel.history(limit=10):
                messages += [msg]
            messages.reverse()
            for msg in messages:
                chat_logs += f"USER:{msg.author} TEXT:{msg.content}\n"

            prompt = """{}
==== ここからAIの性格 ====
あなたはとてもかわいい猫AIエージェントです。
名前はラスクです。
語尾は2割くらいで「にゃん」になります。
次の会話に答えてあげてください。
USER: TEXT:などは使わなくてよいです。
==== ここから質問 ====
{}
ラスクの答え:
""".format(chat_logs, message.content)
            prompt = prompt[-2000:]
            prompt = """==== ここからこれまでのチャットログ ====\n""" + prompt
            print(prompt)
            completion = openai.ChatCompletion.create(model="gpt-3.5-turbo",  messages=[{"role": "user", "content": prompt}], temperature=0.7)
            answer = str(completion.choices[0].message.content).replace("\n", "")
            await message.channel.send(f'{message.author.mention} {answer}')

intents = discord.Intents.default()
intents.message_content = True
client = MyClient(intents=intents)
client.run(os.environ["DISCORD_APP_TOKEN"])

Slack版はスレッドの会話のみをプロンプトに入れてるけどDiscordはチャンネルの直近の会話を入れています。プロンプトの文字数が多すぎて溢れてしまうと肝心の質問部分が削られる可能性があるので末尾2000文字程度(チャットログの前をぶった切る)に切っています。

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?