Looking for someone to review my code with me

Hi everyone, I was not sure the best place to start looking so I thought may as well here. I was wondering if there were any developers that could lend 30-60 minutes of their time reviewing my code with me. I am trying to develop a simple ChatGPT powered discord bot for an internal company wiki that draws data from a google drive folder. I have gone through the majority of the process, but I have seem to hit a road block and cannot figure out why my code is not working. Thank you!

Welcome to the community!

Feel free to share the code and what you’re having trouble with, and we’ll try to help if we can.

Thanks! should I hyperlink the code or paste directly in here?

1 Like

if you use the ``` (3 tilda’s or backticks) wrapped around your code (before and after it) then it will format it as code

#This is some code
#this is some more
    #indented etc.
    print("yay")
1 Like

Okay, I think I got it formatted for you!

What error are you getting?

Sweet, thank you. So I activate the code, it shows that the code accessed the google drive and fetched the correct file, and finally it shows the bot initialized correctly. So everything seems good until I try to talk to the bot in the discord chat.

In the discord chat where the bot and I are the only participants, I send “!ask How is the weather today?”

Here is the error I receive

‘’’
(myvenv) jordan@Jordans-MacBook-Pro-2 discordbot % python3 bot.py
/Users/jordan/discordbot/myvenv/lib/python3.9/site-packages/urllib3/init.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the ‘ssl’ module is compiled with ‘LibreSSL 2.8.3’.
Starting Google Drive authentication…
Checking for existing token.json file…
Found existing token.json file. Loading credentials…
Credentials are expired. Refreshing token…
Saving credentials to token.json
Google Drive authentication completed.
Checking for existing token.json file…
Found existing token.json file. Loading credentials…
2024-09-05 18:33:25 INFO discord.client logging in using static token
2024-09-05 18:33:27 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: fac9647ee976d439e76e510eecf5846c).
Found FAQ file: faq with ID: 1zfttX7nA3V_Xi2Qjp8EHZ5mrDm91xPRLd8W7ea30EzI
Download 100%.
FAQ Content Loaded:
WONDERFLY ARENA
FREQUENTLY ASKED QUESTIONS

  1. Do you offer open play or walk-ins or drop-ins?
    1. We do not offer any walk-in events. We have scheduled Open Play nights for Adult participants only 18+. For more information on those, see our Open Play page here.
  2. How many people can I bring? What’s the difference between “players” and “spectators”.
    1. The number of people you bring is dependent on your event type, please look at our event guide for full information. Party packages st
      We have logged in as Wonder Bot#1310
      2024-09-05 18:33:41 ERROR discord.client Ignoring exception in on_message
      Traceback (most recent call last):
      File “/Users/jordan/discordbot/myvenv/lib/python3.9/site-packages/discord/client.py”, line 449, in _run_event
      await coro(*args, **kwargs)
      File “/Users/jordan/discordbot/bot.py”, line 110, in on_message
      response = generate_conversational_response(user_input)
      File “/Users/jordan/discordbot/bot.py”, line 75, in generate_conversational_response
      response = OpenAI.completions.create(engine=“text-davinci-003”,
      AttributeError: type object ‘OpenAI’ has no attribute ‘completions’
      ‘’’
1 Like

Are you using latest OpenAI library?

Also, text-davinci-003 is deprecated. A quick replacement would be gpt-3.5-instruct, I believe…

https://platform.openai.com/docs/models/model-endpoint-compatibility

I’d try swapping the model then try updating the library… There’s been quite a few changes with the library, though!

Hmmmm I am getting this error now with that change:

(myvenv) jordan@Jordans-MBP-2 discordbot % pip install --upgrade openai
Requirement already satisfied: openai in ./myvenv/lib/python3.9/site-packages (1.43.0)
Collecting openai
  Downloading openai-1.44.1-py3-none-any.whl.metadata (22 kB)
Requirement already satisfied: anyio<5,>=3.5.0 in ./myvenv/lib/python3.9/site-packages (from openai) (4.4.0)
Requirement already satisfied: distro<2,>=1.7.0 in ./myvenv/lib/python3.9/site-packages (from openai) (1.9.0)
Requirement already satisfied: httpx<1,>=0.23.0 in ./myvenv/lib/python3.9/site-packages (from openai) (0.27.2)
Requirement already satisfied: jiter<1,>=0.4.0 in ./myvenv/lib/python3.9/site-packages (from openai) (0.5.0)
Requirement already satisfied: pydantic<3,>=1.9.0 in ./myvenv/lib/python3.9/site-packages (from openai) (2.8.2)
Requirement already satisfied: sniffio in ./myvenv/lib/python3.9/site-packages (from openai) (1.3.1)
Requirement already satisfied: tqdm>4 in ./myvenv/lib/python3.9/site-packages (from openai) (4.66.5)
Requirement already satisfied: typing-extensions<5,>=4.11 in ./myvenv/lib/python3.9/site-packages (from openai) (4.12.2)
Requirement already satisfied: idna>=2.8 in ./myvenv/lib/python3.9/site-packages (from anyio<5,>=3.5.0->openai) (3.8)
Requirement already satisfied: exceptiongroup>=1.0.2 in ./myvenv/lib/python3.9/site-packages (from anyio<5,>=3.5.0->openai) (1.2.2)
Requirement already satisfied: certifi in ./myvenv/lib/python3.9/site-packages (from httpx<1,>=0.23.0->openai) (2024.8.30)
Requirement already satisfied: httpcore==1.* in ./myvenv/lib/python3.9/site-packages (from httpx<1,>=0.23.0->openai) (1.0.5)
Requirement already satisfied: h11<0.15,>=0.13 in ./myvenv/lib/python3.9/site-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai) (0.14.0)
Requirement already satisfied: annotated-types>=0.4.0 in ./myvenv/lib/python3.9/site-packages (from pydantic<3,>=1.9.0->openai) (0.7.0)
Requirement already satisfied: pydantic-core==2.20.1 in ./myvenv/lib/python3.9/site-packages (from pydantic<3,>=1.9.0->openai) (2.20.1)
Downloading openai-1.44.1-py3-none-any.whl (373 kB)
Installing collected packages: openai
  Attempting uninstall: openai
    Found existing installation: openai 1.43.0
    Uninstalling openai-1.43.0:
      Successfully uninstalled openai-1.43.0
Successfully installed openai-1.44.1
(myvenv) jordan@Jordans-MBP-2 discordbot % python3 bot.py
/Users/jordan/discordbot/myvenv/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
  warnings.warn(
Starting Google Drive authentication...
Checking for existing token.json file...
Found existing token.json file. Loading credentials...
Credentials are expired. Refreshing token...
Saving credentials to token.json
Google Drive authentication completed.
Checking for existing token.json file...
Found existing token.json file. Loading credentials...
2024-09-09 16:11:52 INFO     discord.client logging in using static token
2024-09-09 16:11:54 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 55021055dd942eb72702c0abaa125aa5).
Found FAQ file: faq with ID: 1zfttX7nA3V_Xi2Qjp8EHZ5mrDm91xPRLd8W7ea30EzI
Download 100%.
FAQ Content Loaded:
WONDERFLY ARENA
FREQUENTLY ASKED QUESTIONS
1. Do you offer open play or walk-ins or drop-ins?
   1. We do not offer any walk-in events. We have scheduled Open Play nights for Adult participants only 18+. For more information on those, see our Open Play page here.
2. How many people can I bring? What's the difference between “players” and “spectators”.
   1. The number of people you bring is dependent on your event type, please look at our event guide for full information. Party packages st
We have logged in as Wonder Bot#1310
2024-09-09 16:12:11 ERROR    discord.client Ignoring exception in on_message
Traceback (most recent call last):
  File "/Users/jordan/discordbot/myvenv/lib/python3.9/site-packages/discord/client.py", line 449, in _run_event
    await coro(*args, **kwargs)
  File "/Users/jordan/discordbot/bot.py", line 110, in on_message
    response = generate_conversational_response(user_input)
  File "/Users/jordan/discordbot/bot.py", line 75, in generate_conversational_response
    response = OpenAI.completions.create(engine="gpt-3.5-turbo-instruct",
AttributeError: type object 'OpenAI' has no attribute 'completions'```

Here is the current code: 

```import discord
from openai import OpenAI
import os
from dotenv import load_dotenv
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from google_drive_auth import authenticate_google_drive  # Import Google Drive authentication
import io

# Load environment variables from .env file
load_dotenv()

# Set your API keys from environment variables
  # Load OpenAI API key from environment variable
discord_token = os.getenv('DISCORD_TOKEN')    # Load Discord bot token from environment variable
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))

# Authenticate with Google Drive
creds = authenticate_google_drive()

# Function to list files in a specific Google Drive folder and find the FAQ file
def find_faq_file_in_folder(folder_id, creds):
    service = build('drive', 'v3', credentials=creds)

    # Query for files in the specified folder
    query = f"'{folder_id}' in parents"
    results = service.files().list(q=query, pageSize=100, fields="files(id, name, mimeType)").execute()
    files = results.get('files', [])

    faq_file_id = None

    # Search for the FAQ file by name (case-insensitive)
    for file in files:
        if "faq" in file['name'].lower():  # Customize to match part of your FAQ file name
            faq_file_id = file['id']
            print(f"Found FAQ file: {file['name']} with ID: {file['id']}")
            break

    return faq_file_id

# Function to download the FAQ file from Google Drive
def download_faq_file(file_id, creds):
    service = build('drive', 'v3', credentials=creds)

    # Export the file as a plain text file (for Google Docs/Sheets)
    request = service.files().export_media(fileId=file_id, mimeType='text/plain')

    fh = io.BytesIO()
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while not done:
        status, done = downloader.next_chunk()
        print(f"Download {int(status.progress() * 100)}%.")

    # Return the file content as a string
    return fh.getvalue().decode('utf-8')

# Function to search the FAQ document for an answer
def search_faq(question, faq_content):
    question = question.lower()
    lines = faq_content.split('\n')  # Split the FAQ content into lines
    answer = None

    # Search for the question in the FAQ content
    for i, line in enumerate(lines):
        if question in line.lower():
            # Get the answer (next line after the question)
            answer = lines[i + 1] if i + 1 < len(lines) else "Sorry, I can't find the answer to that."
            break

    return answer

# Function to generate a conversational response using OpenAI
def generate_conversational_response(user_input):
    response = OpenAI.completions.create(engine="gpt-3.5-turbo-instruct",
    prompt=f"Respond to this in a conversational tone: {user_input}",
    max_tokens=150)
    return response.choices[0].text.strip()

# Start of the bot
intents = discord.Intents.default()  # Create a new instance of the default intents
intents.message_content = True       # Enable the bot to read the message content

client = discord.Client(intents=intents)

# On bot startup, search the folder for the FAQ file and load it
@client.event
async def on_ready():
    folder_id = '1HtBcRQm1tiVVZyLpOPsXxFM0JwFLuqYM'  # Replace with your actual folder ID
    faq_file_id = find_faq_file_in_folder(folder_id, creds)

    if faq_file_id:
        global faq_content
        faq_content = download_faq_file(faq_file_id, creds)
        print(f"FAQ Content Loaded:\n{faq_content[:500]}")  # Print the first 500 characters of the FAQ
    else:
        print("FAQ file not found in the specified folder.")

    print(f'We have logged in as {client.user}')

# Handle incoming messages
@client.event
async def on_message(message):
    if message.author == client.user:
        return

    # General conversational response using OpenAI
    if message.content.startswith('!ask'):
        user_input = message.content[len('!ask '):].strip()
        response = generate_conversational_response(user_input)
        await message.channel.send(response)

    # Search FAQ for employee question
    if message.content.startswith('!faq'):
        question = message.content[len('!faq '):].strip()
        answer = search_faq(question, faq_content)
        await message.channel.send(answer)

# Run the bot
client.run(discord_token)```