WhatsAppTools 使 Agent 能够与 WhatsApp Business API 进行交互,从而可以发送文本消息和模板消息。

先决条件

本指南演示了如何将 WhatsApp 与 Agno 集成。在运行此示例之前, 您需要完成以下设置步骤:

  1. 创建 Meta 开发者账户

  2. 设置 WhatsApp Business API 您可以从 Business Settings 获取您的 WhatsApp Business Account ID

  3. 配置环境

    • 设置以下环境变量:
      export WHATSAPP_ACCESS_TOKEN=your_access_token          # 访问令牌
      export WHATSAPP_PHONE_NUMBER_ID=your_phone_number_id    # 手机号码 ID
      export WHATSAPP_RECIPIENT_WAID=your_recipient_waid      # 收件人 WhatsApp ID (例如 1234567890)
      export WHATSAPP_VERSION=your_whatsapp_version           # WhatsApp API 版本 (例如 v22.0)
      

重要提示:

  • 首次联系时,必须使用预先批准的消息模板 此处
  • 测试消息只能发送到在您的测试环境中注册的号码

下面的示例展示了如何使用 Agno 的 WhatsApp 工具发送模板消息。 有关更复杂的用例,请查看 WhatsApp Cloud API 文档: 此处

示例

以下 Agent 将使用 WhatsApp 发送模板消息:

cookbook/tools/whatsapp_tool.py
from agno.agent import Agent
from agno.models.google import Gemini
from agno.tools.whatsapp import WhatsAppTools

agent = Agent(
    name="whatsapp",
    model=Gemini(id="gemini-2.0-flash"),
    tools=[WhatsAppTools()],
    show_tool_calls=True
)

# 示例:发送模板消息
# 注意:将 '''hello_world''' 替换为您的实际模板名称
# 并将 +91 1234567890 替换为收件人的 WhatsApp ID
agent.print_response(
    "Send a template message using the '''hello_world''' template in English to +91 1234567890"
)

工具包参数

参数类型默认值描述
access_tokenOptional[str]NoneWhatsApp Business API 访问令牌。如果未提供,则使用 WHATSAPP_ACCESS_TOKEN 环境变量。
phone_number_idOptional[str]NoneWhatsApp Business Account 手机号码 ID。如果未提供,则使用 WHATSAPP_PHONE_NUMBER_ID 环境变量。
versionstr"v22.0"要使用的 API 版本。如果未提供,则使用 WHATSAPP_VERSION 环境变量或默认为 “v22.0”。
recipient_waidOptional[str]None默认收件人 WhatsApp ID(例如,“1234567890”)。如果未提供,则使用 WHATSAPP_RECIPIENT_WAID 环境变量。
async_modeboolFalse为发送消息启用异步方法。

工具包函数

函数描述
send_text_message_sync将文本消息发送给 WhatsApp 用户(同步)。 参数:text (str), recipient (Optional[str]), preview_url (bool), recipient_type (str)。
send_template_message_sync将模板消息发送给 WhatsApp 用户(同步)。 参数:recipient (Optional[str]), template_name (str), language_code (str), components (Optional[List[Dict[str, Any]]])。
send_text_message_async将文本消息发送给 WhatsApp 用户(异步)。 参数:text (str), recipient (Optional[str]), preview_url (bool), recipient_type (str)。
send_template_message_async将模板消息发送给 WhatsApp 用户(异步)。 参数:recipient (Optional[str]), template_name (str), language_code (str), components (Optional[List[Dict[str, Any]]])。

开发者资源