You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已安装discord、openai模块仍报ModuleNotFoundError问题求助

Discord + ChatGPT 机器人运行报错:ModuleNotFoundError

机器人代码

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)

报错信息

运行时提示no module named 'discord'、no module named 'openai',完整报错栈:

Traceback (most recent call last):
  File "C:\Users\My Computer\PycharmProjects\pythonProject\.venv\Scripts\Discord_bot.py", line 1, in <module>
    import discord
ModuleNotFoundError: No module named 'discord'

已尝试的操作

  • 执行pip install discord和pip install openai安装模块
  • 重启电脑
  • 更换VS Code运行代码
  • CMD和PyCharm终端均显示模块已安装,但问题未解决

解决方案

1. 确认PyCharm的项目解释器

  • 点击PyCharm右下角的Python版本图标,选择Interpreter Settings
  • 检查当前项目使用的解释器路径是否为项目目录下的.venv\Scripts\python.exe,确保激活的是项目专属虚拟环境

2. 在虚拟环境终端安装正确的模块

  • 打开PyCharm底部的Terminal,确认终端前缀显示(.venv)(表示虚拟环境已激活)
  • 执行以下命令安装正确的依赖包:
pip install discord.py openai

注意:Discord官方Python库的包名是discord.py,而非discord,之前的pip install discord安装的是无关包

3. 验证安装结果

在终端执行pip list,查看输出中是否存在discord.py和openai,确认模块已成功安装到当前虚拟环境

4. 重新运行代码

回到代码编辑界面,点击右上角运行按钮,或右键代码文件选择Run 'Discord_bot'

内容的提问来源于stack exchange,提问作者Mark Balmonte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 10:18:11