#Missing API issues and no response issues

11 messages · Page 1 of 1 (latest)

tribal patrol
#

My code keeps reporting Missing API key but it have been added

#

import openai
import discord
import os
import sys

client = discord.Client()

Accessing API_KEY from the environment variable if not set then exits

try:
openai_key = os.environ[""]
except KeyError as e:
print("Missing API_KEY please provide API_KEY.")
sys.exit(-1)

conversation_sessions = {}

@client.event
async def on_ready():
print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
print(f"Received message: {message.content}")

# Check if the message author is the same as the client user
if message.author == client.user:
    return

# Check if the message content matches the start command
if message.content == '$chatgpt start':
    print("Starting new conversation...")

    # Check if the user is already in a conversation session and notify them if so
    if message.author.id in conversation_sessions:
        await message.channel.send('You are already in a conversation. Please end the current conversation with `$chatgpt end` before starting a new one.')
        return
    
    # Initializing Open AI Completion engine
    openai.api_key = openai_key
    completion = openai.Completion.create(
            engine="davinci",
            prompt="",
            temperature=0.5,
            max_tokens=1024,
            top_p=1,
            frequency_penalty=0,
            presence_penalty=0
        )
#

Create a new conversation session for the user

    conversation_sessions[message.author.id] = {
        'session': completion,
        'history': []
    }
    await message.channel.send('Hello! Let\'s start a conversation. Please enter your first message.')

# Check if the message content matches the end command
elif message.content == '$chatgpt end':
    print("Ending conversation...")

    # Check if the user is in a conversation session and notify them if not
    if message.author.id not in conversation_sessions:
        await message.channel.send('You are not currently in a conversation. Please start a conversation with `$chatgpt start` to begin.')
        return

    # Delete the user's conversation session
    del conversation_sessions[message.author.id]
    await message.channel.send('Your conversation has ended. Thank you for chatting with me!')

# Check if the user is in a valid conversation session
elif message.author.id in conversation_sessions:
    print("Continuing conversation...")
    # Continue conversation with user input
    user_input = message.content
    conversation_sessions[message.author.id]['history'].append(user_input)
    conversation_sessions[message.author.id]['session'].update(prompt='\n'.join(conversation_sessions[message.author.id]['history']) + '\nA:')

    # Generate and send back bot response
    response_text = conversation_sessions[message.author.id]['session'].choices[0].text
    conversation_sessions[message.author.id]['history'].append(response_text)
    try:
        response = await message.channel.send(response_text)
        if response != None:
            print(f'Response to user successful: {response_text}')
    except Exception as error:
        print(f'Response to user failed: {error}')
honest meteor
#

openai_key = os.environ[""] This line of code doesn't make any sense

#

This isn't retrieving any key and this isn't a valid way to get the value of an environment variable

#

try saving the key as siomething like OPENAI_TOKEN and then getting it with os.environ["OPENAI_TOKEN"]

tribal patrol
#

import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
import openai

bot = commands.Bot(command_prefix="!")
slash = SlashCommand(bot)

Set your OpenAI API key

openai.api_key = ""

history = ""

@slash.slash(name="start", description="Starts a conversation with the bot.")
async def start(ctx: SlashContext):

Send a welcome message and prompt the user for input

await ctx.send("Hello, I'm a friendly conversation bot powered by OpenAI. What do you want to talk about?")

global history
history = ""

@slash.slash(name="talk", description="Continues a conversation with the bot.")
async def talk(ctx: SlashContext, message: str):

Append the user's message to the history variable

global history
history += f"User: {message}\n"

response = openai.Completion.create(
engine="davinci",
prompt=history + "Bot:",
temperature=0.9,
max_tokens=100,
top_p=1,
frequency_penalty=0,
presence_penalty=0.6,
stop=["\n"]
)

text = response["choices"][0]["text"]

Append the bot's response to the history variable

history += f"Bot: {text}\n"

Send the bot's response to the user

await ctx.send(text)

@slash.slash(name="end", description="Ends a conversation with the bot.")
async def end(ctx: SlashContext):

Send a goodbye message and clear the history variable

await ctx.send("It was nice talking to you. Have a good day!")
global history
history = ""

#

I keep getting issues with the slash tho, Ive check to see if my interpretor is the correct verion that matches discord_slash imports but i keep getting an error

#

Import "discord_slash" could not be resolved

honest meteor
#

I think you might be using an outdated way of making a slash command