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

开发Discord自定义状态修改器出现IndentationError缩进错误如何解决

错误原因

你遇到的IndentationError是Python最常见的语法错误之一,由代码缩进层级不匹配导致,你的代码中存在多处缩进和语法问题,触发报错的直接原因是choice判断块的缩进层级混乱:

  • MyClient类下的on_ready异步方法内部代码缩进错误,time.sleep(5)、打印登录信息的语句完全没有缩进进方法体内
  • 所有自定义的状态设置函数(playing/streaming/listening/watching)内部的await语句没有缩进进函数体,且这些函数没有加async关键字声明为异步函数,await只能在异步函数内使用
  • 末尾的choice判断块缩进完全混乱,第一个if choice == "playing"块内定义了空的playing函数后没有正确闭合代码块,导致下一行if choice == ("watching"):的缩进和外层层级不匹配,直接触发报错
  • 额外存在其他语法问题:缺失discord模块导入、调用函数时多加了冒号(如listening():)、变量名拼写错误(playing函数内引用了不存在的变量a5)、逻辑顺序错误(在客户端登录前就执行状态设置逻辑)
修复方案
  1. 统一缩进规则,全程使用4个空格缩进,禁止混用空格和制表符
  2. 修正所有类、函数的缩进层级,函数内部代码必须缩进进对应代码块
  3. 给所有用到await的函数添加async关键字
  4. 修正choice判断块的逻辑,删除多余的空函数定义,直接调用对应功能函数,修正函数调用语法
  5. 调整逻辑顺序,将用户输入状态、修改状态的逻辑放到客户端登录完成后的on_ready方法内执行
  6. 补全缺失的模块导入,修正变量名拼写错误

修正后的可运行代码如下:

import os
import time
import discord
import colorama
from colorama import Fore

colorama.init()
print("可选状态类型: playing, streaming, listening, watching ")
token = input(Fore.GREEN + "请输入账号Token: ")


class MyClient(discord.Client):
    async def on_ready(self):
        print(Fore.CYAN + "等待初始化完成...")
        time.sleep(5)
        print(Fore.GREEN + "登录成功,当前账号为", self.user)

        # 状态设置函数定义
        async def playing():
            a = input("请输入要显示的内容: ")
            await self.change_presence(activity=discord.Game(name=a))

        async def streaming():
            a4 = input("请输入要显示的内容: ")
            u1 = input("请输入Twitch直播间链接: ")
            await self.change_presence(activity=discord.Streaming(name=a4, url=u1))

        async def listening():
            a3 = input("请输入要显示的内容: ")
            await self.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=a3))

        async def watching():
            a2 = input("请输入要显示的内容: ")
            await self.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=a2))

        choice = input("请输入要设置的状态类型: ").strip().lower()
        os.system("cls")
        if choice == "playing":
            await playing()
        elif choice == "watching":
            await watching()
        elif choice == "listening":
            await listening()
        elif choice == "streaming":
            await streaming()
        else:
            print(Fore.RED + "输入的状态类型无效")


client = MyClient(intents=discord.Intents.default())
client.run(token, bot=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:24:04