discord.py编写Forest链接发送命令出现unexpected indent报错求助
问题原因
这个报错是Python的缩进规则触发的,Python通过缩进来划分代码块层级,同一层级的代码必须保持一致的缩进宽度,且不能混合使用空格和制表符进行缩进。你当前报错指向的sent = await ctx.send(embed=embed)行缩进宽度和它所属的代码层级不匹配。
定位方法
- 优先看报错信息指向的行号(你这里是main.py第49行),对比该行和上一行同级代码的缩进:
上一行embed = discord.Embed(...)的缩进是2个空格,而sent行你用了8个空格,属于和上一行同级的代码却多了缩进,就会触发unexpected indent报错。 - 同时还要检查其他代码块的缩进逻辑:
try块内部的代码需要比try多一级缩进,你写的if msg:现在和try是同级,也属于缩进错误。 - 额外逻辑问题:最后一行
await ctx.send("The link for forest session by" + msg.author + "is" msg.content)中,"is"和msg.content之间漏了拼接用的加号,msg.author是用户对象,直接拼接需要先转成字符串类型。
修正后的完整代码
(统一使用Python官方推荐的4空格缩进规则,同时补充了超时异常处理避免运行时报错)
# 需提前导入asyncio模块处理超时异常 import asyncio @client.command(aliases=['forest','forestcode','forest-code']) async def code(self, ctx): await ctx.message.delete() embed = discord.Embed( title="Forest code", description="Please send the link for the forest session" ) sent = await ctx.send(embed=embed) try: msg = await self.bot.wait_for( "message", timeout=60, check=lambda message: message.author == ctx.author and message.channel == ctx.channel ) if msg: await sent.delete() await msg.delete() await ctx.send("The link for forest session by" + str(msg.author) + "is" + msg.content) except asyncio.TimeoutError: await sent.delete() await ctx.send("Operation timeout, please try again later.", delete_after=10)
内容的提问来源于stack exchange,提问作者user15609381
相关产品推荐
相关产品推荐

