为什么这个错误一直显示,我错过了什么? wait message.channel.send(f"Answer: {bot_response}") IndentationError: 意外缩进

问题描述 投票:0回答:1

所以我的代码基本上是从 walktrough 复制的,用于使不和谐机器人使用 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']**:

每行带有“消息”的行都被标记为错误,并建议从“电子邮件”导入....

我尝试了各种方法,检查我的代码是否有错误,进行拼写检查,看看我是否遗漏了步行槽中的某些内容。但这也是我第一次尝试 python 项目,所以我可能只是缺乏经验,甚至不知道在哪里寻找错误。enter image description here

python discord artificial-intelligence openai-api
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}")
© www.soinside.com 2019 - 2024. All rights reserved.