如何使用Python Telegram Bot发送带自定义预览的消息?
使用Python Telegram Bot实现带文字预览的消息
可以实现这个功能,核心是利用Telegram的网页预览机制,结合自定义网页的元标签来控制预览内容,具体操作如下:
实现步骤
- 准备一个自定义网页,在页面中添加Open Graph(OG)元标签,用来定义预览的标题、描述和图片:
<meta property="og:title" content="你的预览标题"> <meta property="og:description" content="你的预览描述文本"> <meta property="og:image" content="https://你要显示的预览图片链接"> - 使用Python Telegram Bot的
send_message方法发送包含该网页链接的文本消息,Telegram会自动抓取OG标签生成预览效果。
代码示例
from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes async def send_preview(update: Update, context: ContextTypes.DEFAULT_TYPE): # 构造带链接的消息文本 msg_text = "点击查看详情:https://你的自定义网页链接.com" # 发送消息,默认开启网页预览(disable_web_page_preview=False可省略) await context.bot.send_message( chat_id=update.effective_chat.id, text=msg_text ) if __name__ == '__main__': # 替换为你的机器人Token app = ApplicationBuilder().token("YOUR_BOT_TOKEN").build() # 添加命令处理器,发送/preview触发消息 app.add_handler(CommandHandler("preview", send_preview)) app.run_polling()
额外说明
如果不想依赖外部网页,也可以通过InlineQueryResultArticle实现类似的内嵌预览效果,但这种方式需要通过内联查询触发,操作相对复杂。最贴近你需求的还是OG标签+网页预览的方案。
内容的提问来源于stack exchange,提问作者Yousif Ahmed elbalaa
相关产品推荐
相关产品推荐

