0

I created a python chat discord bot. However when asking it a question in direct messages it replies multiple times. Sometimes it replies (highlighted messages) other times it just posts a normal message not surrounded by ``` and I can't for the life of me figure out why and would really appreciate some help on this matter. Example conversation

This is the python code with comments:

import openai
import discord

# Set up the OpenAI API key
openai.api_key = "<api key>"

# https://discordpy.readthedocs.io/en/stable/intents.html
intents = discord.Intents.default()
intents.message_content = True
# Set up the Discord client
client = discord.Client(intents=intents)

@client.event
async def on_message(message):
    # Only respond to messages starting with !ai
    if message.content.startswith("!ai"):
        # Use the GPT-3 API to generate a response
        response = openai.Completion.create(
            engine="text-davinci-002",
            prompt=message.content,
            #no of tokens in response 4097 max that is promt+response length 
            max_tokens=2048,
            #no of responses
            n=1,
            #randomness of response 0-1
            temperature=0.3
        )

         # Get the response text
        text = response["choices"][0]["text"]

        # Split the response into multiple messages if it's longer than 1500 characters
        if len(text) > 1500:
            messages = [text[i:i+1500] for i in range(0, len(text), 1500)]
        else:
            messages = [text]


        # Send the response messages to the Discord channel
        for text in messages:
            await message.reply("```"+text+"```")


# Run the Discord client
client.run("<discordtoken>")

I'd be very grateful for any help

I suspect this is the problem:

        # Send the response messages to the Discord channel
        for text in messages:
            await message.reply("```"+text+"```")

but I'm unsure why

Nomad
  • 11
  • 3
  • Probe your code to see the journey the response takes. Add print(text) in between the responses like so: # Send the response messages to the Discord channel for text in messages: print(text) await message.reply("```"+text+"```") – Toakley Dec 06 '22 at 22:34

0 Answers0