discord.py公告命令优化:将缩略图URL输入设为可选的实现方法
代码修改方案
核心修改逻辑
- 拆分原有统一的异常捕获块:将必填的标题、描述输入环节保留在外层全局捕获中,这两个环节超时仍会终止命令
- 把可选的缩略图URL输入环节单独嵌套一层独立的try-except块,仅捕获该环节的超时异常,超时后自动提示并跳过该环节继续执行
- 生成Embed时新增判断逻辑,仅当用户输入了有效URL时才添加缩略图
修改后的完整代码
@bot.command(pass_context = True, aliases=[ 'a', 'announce' ]) async def announce_command(ctx): await ctx.send(f"**{ctx.author}**, send a title in 60 seconds, to begin embed builder!",delete_after=45) def check(m: discord.Message): return m.author.id == ctx.author.id and m.channel.id == ctx.channel.id try: # 必填环节:标题输入 titlemsg = await bot.wait_for(event = 'message', check = check, timeout= 10 ) await ctx.send(f"**{ctx.author}**, State a description.", delete_after=45) # 必填环节:描述输入 msg= await bot.wait_for(event = 'message', check = check, timeout= 40) await ctx.send(f"**{ctx.author}**, State a Url, if you want a thumbnail added.",delete_after=45) # 可选环节:缩略图URL输入,单独捕获超时 UrlThmsg = None try: UrlThmsg = await bot.wait_for(event= 'message', check = check, timeout= 10) except asyncio.TimeoutError: await ctx.send(f"**{ctx.author}**,将不添加缩略图", delete_after=45) except asyncio.TimeoutError: await ctx.send(f"**{ctx.author}**, you didn't send any message that meets the check in this channel for 60 seconds..", delete_after=45) return else: embed = d.Embed(title = f"{titlemsg.content}", description = f"{msg.content}", color = 0xFFFFFF) # 仅当获取到缩略图URL时才添加缩略图 if UrlThmsg: embed.set_thumbnail(url = f"{UrlThmsg.content}") embed.set_footer(text = f'Annouced By {ctx.author}') await ctx.send('@everyone', embed = embed)
内容的提问来源于stack exchange,提问作者Spooky Hmm
相关产品推荐
相关产品推荐

