You need to enable JavaScript to run this app. 添加newUser变量后Python Firestore事件监听器失效求助
优惠活动
大模型
产品
解决方案
定价
更多

添加newUser变量后Python Firestore事件监听器失效求助

问题排查与修复建议

核心问题梳理

  • 监听查询条件错误:你用了where(u'main', u'array_contains', u'newUser'),但main是存储newUser的映射(字典),不是数组,这个查询根本匹配不到任何文档,导致快照回调永远不会触发后续逻辑。
  • 重复读取文档浪费资源:每次获取newUser、firstName、userPhone都重新调用get(),其实change.document已经包含了当前文档的所有数据,直接用它就行。
  • 文档更新路径错误:更新时写了document(u'{usersId}'),这是个固定字符串,不是动态的文档ID,应该用change.document.id;而且newUser在main映射下,更新字段要写main.newUser,不是直接newUser。
  • 类型判断可能不匹配:如果注册流程中newUser存的是布尔值True(不是字符串'True'),那么new_user == 'True'的判断永远不成立,不会执行后续逻辑。

修改后的完整代码

# Required Libraries
import time
import json 
import requests 
import firebase_admin
from firebase_admin import firestore, credentials, threading

# Connection Details
cred = credentials.Certificate("bondupProd.json")
firebase_admin.initialize_app(cred)
print("Connection Established Successfully!")

# Access to Firestore
db = firestore.client()
print("Connection to Firestore DB Successfully!")

# Create an event for notifying main thread
callback_done = threading.Event()

# Create function to check if newUser is True
def on_snapshot(col_snapshot, changes, read_time):
    for change in changes:
        if change.type.name in ('ADDED', 'MODIFIED'):
            doc = change.document
            doc_data = doc.to_dict()
            
            # 先确认main和newUser字段存在,避免KeyError
            if 'main' not in doc_data or 'newUser' not in doc_data['main']:
                continue
            
            new_user = doc_data['main']['newUser']
            # 兼容布尔值和字符串两种情况,根据实际存储类型调整
            if new_user is True or new_user == 'True':
                # 直接从文档数据中提取字段,无需重复查询
                info_data = doc_data.get('info', {})
                firstName = info_data.get('firstName', '')
                userPhone = info_data.get('phone', '')
                
                if not firstName or not userPhone:
                    print("缺少姓名或手机号字段")
                    continue
                
                print(firstName, userPhone)

                msgBird = "https://flows.messagebird.com/flows/...."  # 替换为实际Webhook地址
                data = {"firstName": firstName, "userPhone": userPhone}
                
                try:
                    # 捕获请求异常,方便排查Webhook问题
                    response = requests.post(
                        msgBird,
                        data=json.dumps(data),
                        headers={
                            "MessageBird-Signature-JWT": "sl9zzUwEAVgJlu0qhDIP8gzu0iKy9amR",
                            "Content-Type": "application/json"
                        }
                    )
                    response.raise_for_status()
                    print("Webhook发送成功")
                except requests.exceptions.RequestException as e:
                    print(f"Webhook发送失败: {str(e)}")
                
                # 更新newUser为False,注意字段路径是main.newUser
                try:
                    doc.update({'main.newUser': False})
                    print("newUser状态更新成功")
                except Exception as e:
                    print(f"更新newUser失败: {str(e)}")

# 修正监听查询:监听所有users文档的变化,或者根据需求调整条件
col_query = db.collection(u'users')
query_watch = col_query.on_snapshot(on_snapshot)

while True:
    time.sleep(1)
    print("Script running!")

额外优化建议

  • 添加异常捕获:对Webhook请求和Firestore更新操作增加异常处理,方便排查执行过程中的问题。
  • 字段存在性检查:提前判断info、firstName等字段是否存在,避免触发KeyError导致回调中断。
  • 调试日志:增加关键步骤的打印日志,方便跟踪代码执行流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:51:11