如何在Python脚本中为Discord embed消息添加两个带URL链接的按钮
实现方案
你当前使用的是discord-webhook库,该库原生支持添加跳转链接的按钮组件,按以下步骤修改即可:
步骤1:导入所需组件类
在文件头部补充导入按钮、行组件对应的类:
from discord_webhook import DiscordComponent, ActionRow
步骤2:创建链接按钮组件
在你构造完embed对象之后、执行webhook请求之前,添加代码创建两个按钮:
# 第一个跳转按钮,自行修改label显示文字和url跳转地址 btn1 = DiscordComponent( type=2, # 固定值2,代表组件类型为按钮 style=5, # 固定值5,代表按钮为跳转链接类型 label="按钮1显示文字", url="https://替换为你要跳转的第一个链接" ) # 第二个跳转按钮 btn2 = DiscordComponent( type=2, style=5, label="按钮2显示文字", url="https://替换为你要跳转的第二个链接" ) # 将两个按钮放到同一行容器中 row = ActionRow(components=[btn1, btn2])
步骤3:将组件添加到webhook请求
在webhook.add_embed(embed)代码之后,补充一行添加行组件的代码:
webhook.add_component(row)
额外修正:原有代码逻辑BUG
你当前的域名判断写法存在逻辑错误,无论content中是否包含亚马逊域名,都会触发消息发送:
# 错误写法,永远返回True if 'amazon.fr' or 'amazon.de' or 'amazon.es' or 'amazon.co.uk' in content:
修改为正确的多域名匹配逻辑:
amazon_domains = ['amazon.fr', 'amazon.de', 'amazon.es', 'amazon.co.uk'] if any(domain in content for domain in amazon_domains):
修改后完整代码示例
from discord_webhook import DiscordEmbed, DiscordWebhook, DiscordComponent, ActionRow # 原有变量定义部分保持不变:author、content、link_img、link_edp、webhook等变量按你原有逻辑声明即可 embed = DiscordEmbed(title='> :incoming_envelope: __Posté par '+(author)+'__', description=content, color='03b2f8') embed.set_author(name='DEALABS (Topic EDP)', url='https://www.dealabs.com/discussions/le-topic-des-erreurs-de-prix-1056379?page=999', icon_url='https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Flag_of_France.svg/langfr-225px-Flag_of_France.svg.png') embed.set_thumbnail(url=link_img) #embed.set_image(url=link_img) embed.set_footer(text='DEALABS (Topic EDP)') embed.set_timestamp() embed.add_embed_field(name='> :pushpin: __Lien erreur de prix:__', value=link_edp) embed.add_embed_field(name='> :bell: __Tag:__', value=':orange_circle: [@here](https://7e01f9c8.eu.jeedom.link/core/api/jeeApi.php?apikey=e6FZdh5wGTreFrUnW0REfnaVdb5W57GB&type=scenario&id=6&action=start) - :red_circle: [@everyone](https://7e01f9c8.eu.jeedom.link/core/api/jeeApi.php?apikey=e6FZdh5wGTreFrUnW0REfnaVdb5W57GB&type=scenario&id=6&action=start)') # 新增按钮构造逻辑 btn1 = DiscordComponent( type=2, style=5, label="按钮1显示文字", url="https://替换为你要跳转的第一个链接" ) btn2 = DiscordComponent( type=2, style=5, label="按钮2显示文字", url="https://替换为你要跳转的第二个链接" ) row = ActionRow(components=[btn1, btn2]) webhook.add_embed(embed) webhook.add_component(row) # 新增添加组件代码 # 修正后的域名判断逻辑 amazon_domains = ['amazon.fr', 'amazon.de', 'amazon.es', 'amazon.co.uk'] if any(domain in content for domain in amazon_domains): response = webhook.execute() driver.close();
内容的提问来源于stack exchange,提问作者JohnDoe
相关产品推荐
相关产品推荐

