You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Azure Communication Services Python发送带参数的WhatsApp消息

使用Azure Communication Services发送带参数的WhatsApp消息模板(Python)

核心实现逻辑

在Meta WhatsApp Business门户定义的带{{1}}、{{2}}这类占位符的模板,可通过Azure Communication Services(ACS)Python SDK的template_parameters字段填充参数值,参数顺序需与模板占位符的序号严格对应。

步骤示例

  1. 前置准备

    • 已完成ACS基础配置:获取资源连接字符串、绑定并验证WhatsApp号码
    • 在Meta侧创建并审核通过带参数的消息模板(比如示例中的"You made a purchase for {{1}} using a credit card ending in {{2}}.")
  2. 安装依赖SDK

    pip install azure-communication-messaging
    
  3. 发送带参数的模板消息代码

    from azure.communication.messaging import WhatsAppClient
    from azure.communication.messaging.models import WhatsAppTemplateMessage, WhatsAppTemplateComponent
    
    # 初始化ACS消息客户端
    connection_string = "你的ACS资源连接字符串"
    client = WhatsAppClient.from_connection_string(connection_string)
    
    # 按模板占位符顺序定义参数值
    template_parameters = [
        WhatsAppTemplateComponent(type="text", text="$99.99"),  # 对应模板中的{{1}}
        WhatsAppTemplateComponent(type="text", text="1234")     # 对应模板中的{{2}}
    ]
    
    # 构造模板消息
    template_msg = WhatsAppTemplateMessage(
        template_name="你的模板名称",  # 需与Meta门户的模板名称完全一致
        language="en_US",            # 匹配模板的语言代码(如zh_CN)
        template_parameters=template_parameters,
        to="+接收方WhatsApp号码(含国家代码)",
        from_="+你的ACS绑定WhatsApp号码"
    )
    
    # 发送消息并获取响应
    send_response = client.send(template_msg)
    print(f"消息发送成功,消息ID: {send_response.message_id}")
    

关键注意事项

  • template_name必须与Meta平台的模板名称完全匹配,包括大小写和特殊字符
  • language需严格对应Meta模板的语言代码,不匹配会导致发送失败
  • 如果模板包含媒体类参数(如图片、文档),需将WhatsAppTemplateComponent的type设为对应类型(如"image"),并补充url字段传入资源地址

内容的提问来源于stack exchange,提问作者Erfan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 08:08:10