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

如何通过代码发送WhatsApp状态(Stories)?开发者寻求解决方案

通过代码发送WhatsApp状态的实现方案

一、官方WhatsApp Business Platform(生产环境推荐)

这是WhatsApp官方提供的合规API方案,稳定性高,适合正式项目使用。前置准备:

  1. 注册WhatsApp Business账号,获取AccessToken、Phone Number ID等API凭证
  2. 完成账号验证并开通状态发布权限

TypeScript代码示例(基于Axios)

import axios from 'axios';
import fs from 'fs';

// 替换为你的实际凭证
const ACCESS_TOKEN = 'your-access-token';
const PHONE_NUMBER_ID = 'your-phone-number-id';
const API_BASE_URL = `https://graph.facebook.com/v18.0/${PHONE_NUMBER_ID}`;

// 上传状态媒体(图片/视频)
async function uploadStatusMedia(filePath: string, mimeType: string) {
  const formData = new FormData();
  formData.append('file', fs.createReadStream(filePath));
  formData.append('type', mimeType);
  formData.append('messaging_product', 'whatsapp');

  const response = await axios.post(`${API_BASE_URL}/media`, formData, {
    headers: {
      'Authorization': `Bearer ${ACCESS_TOKEN}`,
      ...formData.getHeaders()
    }
  });
  return response.data.id;
}

// 发布状态
async function publishStatus(mediaId: string, caption?: string) {
  const payload = {
    messaging_product: 'whatsapp',
    status: {
      media: {
        id: mediaId,
        caption: caption
      }
    }
  };

  await axios.post(`${API_BASE_URL}/status`, payload, {
    headers: {
      'Authorization': `Bearer ${ACCESS_TOKEN}`,
      'Content-Type': 'application/json'
    }
  });
}

// 调用示例
(async () => {
  const mediaId = await uploadStatusMedia('./status.jpg', 'image/jpeg');
  await publishStatus(mediaId, '通过官方API发布的状态');
})();

二、基于whatsapp-web.js(测试/非生产场景)

该库模拟网页版WhatsApp交互,无需官方API,但存在账号被限制的风险,仅适合测试或个人项目。

TypeScript代码示例

import { Client, LocalAuth, MessageMedia } from 'whatsapp-web.js';

const client = new Client({
  authStrategy: new LocalAuth() // 保存登录状态,避免重复扫码
});

client.on('ready', async () => {
  console.log('客户端已登录');

  // 设置个人静态状态(显示在资料栏)
  await client.setStatus('这是静态个人状态');

  // 发布24小时动态状态
  const media = MessageMedia.fromFilePath('./status-image.jpg');
  // 发送到状态专属广播聊天
  const statusChatId = 'status@broadcast';
  await client.sendMessage(statusChatId, media, {
    caption: '通过代码发布的动态状态'
  });
});

client.initialize();

三、Python快速实现方案

使用pywhatkit第三方库,操作简单,依赖网页版WhatsApp,适合快速验证功能。

Python代码示例

import pywhatkit

# 发送文本动态状态
pywhatkit.sendwhatmsg_to_group_instantly("status", "Python发送的文本状态", wait_time=15, tab_close=True, close_time=2)

# 发送带图片的动态状态
pywhatkit.sendwhats_image("status", "status-image.jpg", caption="带图片的状态")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 23:37:38