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

使用pyfcm的async_notify_multiple批量发通知失效,求正确方法

PyFCM 向多个令牌发送通知的正确流程

首先说明:PyFCM最新版本中并没有官方推荐的async_notify_multiple函数,大概率是你混淆了函数名称,官方支持的异步多设备通知函数为async_notify_multiple_devices。如果该函数或你提到的函数无法正常工作,可按以下流程操作:

1. 基础初始化校验

确保正确初始化异步FCM服务,且服务器密钥有效:

from pyfcm.async_fcm import AsyncFCMNotification

# 替换为你的FCM服务器密钥
push_service = AsyncFCMNotification(api_key="YOUR_FCM_SERVER_KEY")

2. 官方推荐的异步批量发送方式

使用async_notify_multiple_devices直接批量发送,这是官方原生支持的多令牌通知方法:

import asyncio

async def batch_send_notifications():
    # 目标令牌列表
    target_tokens = ["TOKEN_1", "TOKEN_2", "TOKEN_3"]
    # 构造通知内容
    message = {
        "message_title": "批量通知标题",
        "message_body": "批量通知内容",
        # 可选:自定义数据字段
        "data_message": {"key": "value"}
    }
    
    # 执行批量发送
    response = await push_service.async_notify_multiple_devices(
        registration_ids=target_tokens,
        **message
    )
    
    # 解析返回结果
    print(f"成功发送: {response['success']} 条")
    print(f"失败发送: {response['failure']} 条")
    # 可进一步处理失败的令牌(如过期令牌)
    if response.get('results'):
        for idx, result in enumerate(response['results']):
            if 'error' in result:
                print(f"令牌 {target_tokens[idx]} 发送失败: {result['error']}")

# 运行异步函数
asyncio.run(batch_send_notifications())

3. 替代方案:异步循环单令牌发送

如果批量函数仍有问题,可通过异步任务并发调用单令牌发送函数,灵活性更高:

import asyncio

async def send_single_notification(token):
    try:
        response = await push_service.async_notify_single_device(
            registration_id=token,
            message_title="单条通知标题",
            message_body="单条通知内容"
        )
        return (token, True, response)
    except Exception as e:
        return (token, False, str(e))

async def bulk_send_via_tasks():
    target_tokens = ["TOKEN_1", "TOKEN_2", "TOKEN_3"]
    # 创建异步任务列表
    tasks = [send_single_notification(token) for token in target_tokens]
    # 并发执行任务
    results = await asyncio.gather(*tasks, return_exceptions=False)
    
    # 处理结果
    for token, success, res in results:
        if success:
            print(f"令牌 {token} 发送成功")
        else:
            print(f"令牌 {token} 发送失败: {res}")

asyncio.run(bulk_send_via_tasks())

4. 常见问题排查

  • 确认令牌列表无空值、无效格式或过期令牌
  • 检查FCM服务器密钥是否拥有Cloud Messaging API的发送权限
  • 捕获并打印具体异常信息,定位问题根源(如网络问题、权限错误)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 16:14:59