samyyc.dev
LOC::Macau, China

..UTC+8

samyyc.dev

-- BPM

Sun Jun 25 2023

Hooking a Discord Bot Up to GPT 3.0

#134

/

samyyc

/

795 words

/

Updated 1258 days ago

/

[中文]

Hooking a Discord Bot Up to GPT 3.0

Since GPT 3.0 has no restrictions and can be used for NSFW stuff and long-form writing, I decided to hook it up to Discord.

This thing is seriously expensive. After I hooked it up, I messed around for a bit and burned through a lot of money, so I don't dare play with it anymore.

Applying for an API Key

Just apply on the official site. My proxy had been banned by OpenAI before; no idea why it got unbanned recently.

First, log in to openai.com

Then go to this page

Click Create new secret key to apply for an API key. The API key should start with sk-.

Setting Up the Environment

First, install the official OpenAI library with pip.

pip install openai

Then set the API key in the code.

import openai

openai.api_key = "sk-XXXXXX" # your API key

Writing the Main Code

Refer to the earlier post Discord Bot

Here I want to implement a message-listener-style reply: when a user @s the bot, it automatically generates a reply.

First, write a function that handles the main logic.

Generating the Request Content

Because I'm going to use this bot in multiple group chats, I need to keep each conversation's context separate by channel ID.

The message listener in the interactions library gives us the channel ID, so I just need to add a parameter to this function to receive it.

# This dictionary stores the context for interactions with the AI
completion_prompts = {}
# completion_prompts: {'{channel id}': XXX}

id = str(channel_id)
if id not in messages:
    completion_prompts[id] = "" # initialize
# content is the parameter passed in, the user's input. It needs a little formatting here to make the output more stable.
# Append content directly at the end. Sometimes a single conversation has too much context and may use a lot of tokens.
completion_prompts[id]+=f"\n用户: {content}\nAI: "

# Next is the time-consuming API request, so send a message first to remind the user.
# event is the parameter passed in, provided by the message listener.
# Send a message directly here and store it in a variable, preparing for later edits.
message = await event.message.channel.send("处理中...")

Requesting the API and Streaming the Response

Since GPT 3.0 is a large language continuation model, a single generation can get pretty long, so this is when you should use the streaming feature OpenAI provides.

First, request the API.

resp = openai.Completion.create(
        model = "text-davinci-003",
        prompt = completion_prompts[id],
        max_tokens = 700, # max number of tokens per generation
        stream = True # enable streaming
    )

Next, receive the streamed content and edit the message.

completion = ""
buffer = 0
for chunk in resp:
    buffer += 1
    completion += chunk['choices'][0]['text'] # append the returned content
    if buffer % 10 == 0: # update the Discord message every 10 generated chunks
        completion = completion.replace("AI: ","")  # sometimes it outputs multiple "AI: " itself, so remove them
        await message.edit(content = completion) # edit the message
# do one final update
await message.edit(content = completion)
# add the AI's reply to the context
completion_prompts[id] += f"\nAI: {completion}"

That wraps up the whole request function. Here's what it looks like overall:

import openai
import interactions

openai.api_key = "sk-XXXXX"

async def getCompletionReply(channel_id: int, content: str, event: interactions.events.MessageCreate):
    id = str(channel_id)
    if id not in completion_prompts:
        completion_prompts[id] = ""
    completion_prompts[id]+=f"\n用户: {content}\nAI: "

    message = await event.message.channel.send("处理中...")

    resp = openai.Completion.create(
        model = "text-davinci-003",
        prompt = completion_prompts[id],
        max_tokens = 700,
        stream = True
    )

    completion = ""
    buffer = 0
    for chunk in resp:
        buffer += 1
        completion += chunk['choices'][0]['text']
        if buffer % 10 == 0:
            completion = completion.replace("AI: ","")
            await message.edit(content = completion)

    await message.edit(content = completion)

    completion_prompts[id] += f"\nAI: {completion}"
    

Registering the Discord Listener and Command

Next, I need to use a listener from the interactions library to listen for user messages.

Listener

I want it to reply only when a user @s the bot. In Discord, an @ mention is written as <@[bot id]>. For example, my bot ID is 1114511148474179624, so the mention is <@1114511148474179624>.

Here's the implementation:

@interactions.listen()
async def on_message_create(event: interactions.events.MessageCreate):
    if event.message.content and event.message.contains_mention('<@1114511148474179624>'): # check whether the bot is @-mentioned
        message = event.message.content.replace('<@1114511148474179624>', '') # remove the @ mention text
        id = str(event.message.channel.id)
        await Chat.getCompletionReply(event.message.channel.id, message, event); # call the function we just wrote

Put this code right in the bot registration code.

Command

Here I need to register a command to reset the conversation content (that is, clear the context variable).

@interactions.slash_command(
    name = "openai",
    description = "控制OpenAI对话选项",
    scopes = scopes
)
async def chat(ctx: interactions.SlashContext):
    pass

@chat.subcommand(
    sub_cmd_name = "reset",
    sub_cmd_description = "重置当前对话内容"
)
async def chat_reset(ctx: interactions.SlashContext):
    await ctx.defer()
    completion_prompts[str(ctx.channel_id)] = ""
    await ctx.send('**已重置对话内容**')

This registers a /openai reset command for resetting the conversation.