skip to Main Content

I am trying to integrate CHATGPT by open ai to my discord server.

this is the code:

import discord
import openai

intents = discord.Intents.default()
intents.message_content = True

# Discord and Openai
DISCORD_TOKEN = "key"
openai.api_key = "key"

# Initialize a client object for Discord bot
client = discord.Client(intents=intents)

# Function that sends message to OpenAI API and gets response
async def ask_gpt(message):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "user", "content": message.content}
        ]
    )
    answer = response.choices[0].message.content
    return answer

# Listener that checks for messages in Discord
@client.event
async def on_message(message):
    # Ignore messages from the bot itself
    if message.author == client.user:
        return
    # Sends message to OpenAI API
    response = await ask_gpt(message)
    # Sends response back to channel
    await message.channel.send(response)


# Start the bot
client.run(DISCORD_TOKEN)

I’m using pycharm.

IT has errors:
no module named ‘discord’
no module named ‘openai’

When I try to run it the terminal says:

Traceback (most recent call last):
  File "C:UsersMy ComputerPycharmProjectspythonProject.venvScriptsDiscord_bot.py", line 1, in <module>
    import discord
ModuleNotFoundError: No module named 'discord'

I already installed the modules using "pip install discord" and "pip install openai"
I even restarted my pc in hoping that it would be fixed but no luck :V. I’m an absolute beginner in programming in fact I just copy and pasted this from a video on youtube.

[enter image description here](https://phpout.com/wp-content/uploads/2024/04/lyBUH.png)

Tried restarting my pc.
Tried using Visual Code Studio.
Checked if the modules are installed. CMD and pyCharm terminal says it is installed.

2

Answers


  1. Did you activated your env?

    try

    source env/bin/activate for linux

    and windows .envbinactivate.bat

    Login or Signup to reply.
  2. I had this problem sometimes because pip wasn’t using the right Python (e.g. I had 3.12 as python3 and pip installed it into the 3.11 site-packages directory).

    Instead of using your current aliases, you can be extremely explicit:

    • Instead using the pip or pip3 command, use python3 -m pip.
    • Use which python3 to find the absolute path for your desired Python installation. In my case it’s /usr/bin/python3 (I don’t use venvs), but if it’s in a venv in might be something like .venv/bin/python3. Pass this as the --python argument to pip (before install). This will force pip to use that Python.
    • If pip complains “normal site-packages is not writable”, try again with sudo.

    For example:

    sudo python3 -m pip --python .venv/bin/python3 install openai discord
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search