Discord.py图片搜索命令优化求助:样式不符与Embed失效问题
Discord.py图片搜索命令修复方案
问题分析
- 异常开头内容:爬取Google图片时,
soup.find_all('img')会返回页面所有图片,其中第一个是Google搜索logo,导致每次搜索开头都会发送该logo。 - Embed样式未生效:仅创建了
discord.Embed对象,但未将其传入ctx.send()方法,无法触发Embed展示逻辑。
修复步骤
1. 解决异常开头内容问题
修改图片链接提取逻辑,过滤掉非目标图片(如Google logo),同时优先提取真实缩略图链接(Google图片搜索的缩略图通常存在data-src属性):
# 替换原url_list生成代码 url_list = [] for image in image_elements: # 优先取data-src,过滤Google logo的短链接 img_url = image.get('data-src') or image.get('src') if img_url and not img_url.startswith('https://www.google.com/images'): url_list.append(img_url) # 空列表判断,避免索引错误 if not url_list: await ctx.send("未找到相关图片") return
2. 修复Embed样式未生效问题
创建Embed后需通过ctx.send(embed=embed)发送,后续编辑消息时也要更新Embed内容:
# 替换原发送消息的代码 current_index = 0 # 初始化Embed embed = discord.Embed(title=f"图片搜索结果:{query}", color=0x00ff00) embed.set_image(url=url_list[current_index]) message = await ctx.send(embed=embed) await message.add_reaction('◀️') await message.add_reaction('▶️') # 修改循环内的编辑逻辑 while True: reaction, user = await client.wait_for('reaction_add', check=lambda reaction, user: user == ctx.author and reaction.message.id == message.id) if str(reaction.emoji) == '▶️': current_index = (current_index + 1) % len(url_list) elif str(reaction.emoji) == '◀️': current_index = (current_index - 1) % len(url_list) # 更新Embed图片链接 embed.set_image(url=url_list[current_index]) await message.edit(embed=embed) await message.remove_reaction(reaction, user)
3. 额外优化建议
- 支持多关键词搜索:将命令参数改为
async def image(ctx, *, query),允许用户输入带空格的搜索词。 - 添加超时机制:在
wait_for中设置timeout参数,避免无限等待用户反应。 - 异常捕获:处理网络请求失败、解析错误等情况,防止命令崩溃。
完整修复后代码
import requests from bs4 import BeautifulSoup import discord @client.command() async def image(ctx, *, query): try: response = requests.get(f"https://www.google.com/search?tbm=isch&q={query}") response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') image_elements = soup.find_all('img') url_list = [] for image in image_elements: img_url = image.get('data-src') or image.get('src') if img_url and not img_url.startswith('https://www.google.com/images'): url_list.append(img_url) if not url_list: await ctx.send("未找到相关图片") return current_index = 0 embed = discord.Embed(title=f"图片搜索结果:{query}", color=0x00ff00) embed.set_image(url=url_list[current_index]) message = await ctx.send(embed=embed) await message.add_reaction('◀️') await message.add_reaction('▶️') while True: reaction, user = await client.wait_for( 'reaction_add', check=lambda reaction, user: user == ctx.author and reaction.message.id == message.id, timeout=60 ) if str(reaction.emoji) == '▶️': current_index = (current_index + 1) % len(url_list) elif str(reaction.emoji) == '◀️': current_index = (current_index - 1) % len(url_list) embed.set_image(url=url_list[current_index]) await message.edit(embed=embed) await message.remove_reaction(reaction, user) except requests.exceptions.RequestException: await ctx.send("网络请求失败,请稍后重试") except Exception as e: await ctx.send(f"命令执行出错:{str(e)}")
内容的提问来源于stack exchange,提问作者sigma skibidi
相关产品推荐
相关产品推荐

