为什么这个错误一直出现,我漏掉了什么?await message.channel.send(f"Answer: {bot_response}") IndentationError: 意外缩进

0 投票
1 回答
18 浏览
提问于 2025-04-12 05:50

我的代码基本上是从一个教程上复制过来的,目的是让一个Discord机器人使用ChatGPT。

我在用Pycharm来做这个项目。

这是主要的代码:

from typing import Final
import os
import discord
from dotenv import load_dotenv
from chatgpt_ai.openai import chatgpt_response

load_dotenv()
TOKEN: Final[str] = os.getenv('DISCORD_TOKEN')

class MyClient(discord.Client):
    async def on_ready(self):
        print("Successfully logged in as: ", self.user)

    async  def on_message(self, message):
        print(message.content)
        if message.author == self.user:
            return
        command, user_message=None, None

    **for text in ['/ai', '/bot', 'chatgpt']:**
        if message.content.startswith(text):
            command = message.content.split('')[0]
            user_message = message.content.replace(text, '')
            print(command, user_message)

        if command == '/ai' or command == '/bot' or command == '/chatgpt':
            bot_response = chatgpt_response(prompt=user_message)
            await message.channel.send(f"Answer: {bot_response}")

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

    client = MyClient(intents=intents)




Terminal error code: 

File "C:\Users\Flavi\PycharmProjects\discord_flavio_bot\discord_bot\main.py", line 28
    await message.channel.send(f"Answer: {bot_response}")
IndentationError: unexpected indent

还有一点奇怪的是,从这一行**for text in ['/ai', '/bot', 'chatgpt']**:开始,

每一行包含“message”的地方都被标记为错误,并且建议从“email”导入东西……

我尝试了各种方法,检查了我的代码有没有错误,拼写检查,也看看我在教程中是否漏掉了什么。不过这也是我第一次尝试做Python项目,所以我可能太没有经验了,甚至不知道该从哪里找错误。点击这里查看图片描述

1 个回答

0

看起来你在for循环的缩进上出了点问题。Python的缩进决定了代码的作用范围,也就是说,代码在哪些地方可以运行。如果缩进不对,就会找不到某些信息,因为它超出了作用范围(因为缺少了一层缩进)。

我觉得把20到28行的缩进调整一下,然后把其他行的缩进减少,应该能解决你的问题。

async def on_message(self, message):
    print(message.content)
    if message.author == self.user:
        return
    command, user_message=None, None

    for text in ['/ai', '/bot', 'chatgpt']:**
        if message.content.startswith(text):
            command = message.content.split('')[0]
            user_message = message.content.replace(text, '')
            print(command, user_message)

        if command == '/ai' or command == '/bot' or command == '/chatgpt':
            bot_response = chatgpt_response(prompt=user_message)
            await message.channel.send(f"Answer: {bot_response}")

撰写回答