Discord.py指定用户Embed随机推送功能报错求助
解决Discord.py机器人!bestpost命令的TypeError问题
错误原因
你遇到的TypeError: argument of type 'NoneType' is not iterable主要来自以下场景:
- 频道内部分消息没有Embed内容,直接取
message.embeds[0]会引发索引错误;或是存在Embed但title字段为None,此时执行poster in None会触发该错误。 - 未校验
client.get_channel(123)的返回值,若频道ID错误或机器人无访问权限,会返回None,后续遍历历史时出错。 - 当筛选后
best_posts为空列表时,random.choice会直接报错。
修正后的代码
import random from typing import Optional from discord.ext import commands @client.command() async def bestpost(ctx, poster: Optional[str] = None): # 统一将用户名参数转小写,避免类型注解语法错误 if poster is not None: poster = poster.lower() # 获取目标频道并校验有效性 channel = client.get_channel(123) if not channel: await ctx.send("目标频道不存在或无访问权限") return best_posts = [] async for message in channel.history(limit=None): # 跳过无Embed的消息 if not message.embeds: continue embed = message.embeds[0] # 跳过无标题的Embed if not embed.title: continue if poster is not None: # 不区分大小写检查标题是否包含目标用户名 if poster in embed.title.lower(): best_posts.append(embed) else: best_posts.append(embed) # 处理无匹配结果的情况 if not best_posts: tip = f"未找到标题包含`{poster}`的Embed内容" if poster else "目标频道中没有可推送的Embed内容" await ctx.send(tip) return random_bestpost = random.choice(best_posts) await ctx.send(embed=random_bestpost)
关键修改说明
- 移除类型注解里的
str.lower,改为在参数接收后统一转小写,修复语法错误。 - 增加频道存在性校验,提前返回错误提示。
- 遍历消息时过滤无Embed或无标题的内容,避免访问None对象。
- 用户名匹配改为不区分大小写,提升命令易用性。
- 增加空列表判断,避免
random.choice报错,给出友好提示。
内容的提问来源于stack exchange,提问作者jzb
相关产品推荐
相关产品推荐

