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

如何用Node.js结合WhatsApp Cloud API实现Typing输入状态模拟?

使用Node.js结合WhatsApp Cloud API实现Typing输入状态指示器

WhatsApp Cloud API本身提供了官方支持的Typing状态发送接口,不需要用空消息这类非常规手段。核心是通过messages端点发送presence类型的请求,指定状态为typing。

实现代码示例

可以在现有代码基础上新增一个发送输入状态的函数:

const axios = require('axios');

// 发送Typing状态指示器
const sendTypingIndicator = async (recipient) => {
    const url = 'https://graph.facebook.com/v16.0/{your_phone_number_id}/messages';
    const data = {
        messaging_product: 'whatsapp',
        recipient_type: 'individual',
        to: recipient,
        type: 'presence',
        presence: 'typing'
    };
    const headers = {
        'Authorization': 'Bearer {your_access_token}',
        'Content-Type': 'application/json'
    };

    try {
        await axios.post(url, data, { headers });
        console.log('Typing indicator sent successfully');
    } catch (error) {
        console.error('Error sending typing indicator', error);
    }
};

// 原有发送消息函数
const sendMessage = async (recipient, message) => {
    const url = 'https://graph.facebook.com/v16.0/{your_phone_number_id}/messages';
    const data = {
        messaging_product: 'whatsapp',
        to: recipient,
        text: { body: message }
    };
    const headers = {
        'Authorization': 'Bearer {your_access_token}',
        'Content-Type': 'application/json'
    };

    try {
        const response = await axios.post(url, data, { headers });
        console.log('Message sent successfully', response.data);
    } catch (error) {
        console.error('Error sending message', error);
    }
};

// 使用示例:先发送Typing状态,延迟1.5秒后发送消息
const sendMessageWithTyping = async (recipient, message) => {
    await sendTypingIndicator(recipient);
    // 模拟输入时长,可根据消息长度调整
    await new Promise(resolve => setTimeout(resolve, 1500));
    await sendMessage(recipient, message);
};

sendMessageWithTyping('recipient_number', 'Hello, this is a test message!');

关于你之前思路的说明

  • 空消息触发:不可行,WhatsApp Cloud API会拒绝空消息请求,返回参数错误,无法触发输入状态。
  • 设置延迟:单独的延迟不会显示输入状态,必须配合官方的typing状态请求,延迟只是模拟真实输入的时间,提升用户体验。

注意事项

  • 替换代码中的{your_phone_number_id}和{your_access_token}为你的实际配置。
  • Typing状态会在约10秒后自动消失,如果需要持续显示,可每隔8秒左右重新发送一次typing请求(不过一般单次发送配合消息发送前的延迟足够)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 16:40:06