我部署了以下 Python Firebase 云函数,该函数应该在集合约会中对文档进行更改时触发,然后相应地向关联用户发送 FCM。
# The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
from firebase_functions import firestore_fn, https_fn
# The Firebase Admin SDK to access Cloud Firestore.
from firebase_admin import initialize_app, firestore, messaging
import google.cloud.firestore
app = initialize_app()
db = firestore.client
@firestore_fn.on_document_updated(document="Appointments/{appointmentId}")
def send_appointment_notification(event: firestore_fn.Event[firestore_fn.DocumentSnapshot | None]):
# Get the updated data after the update operation
updated_data = event.after.data()
# Access the status field from the updated data
status = updated_data.get("status")
if status in ['Approved', 'Declined']:
# Get the clientId from the appointment document
client_id = updated_data.get("clientId")
# Retrieve user document to get the fcmtoken
user_ref = db.collection('Users').document(client_id)
user_doc = user_ref.get()
if user_doc.exists:
user_data = user_doc.to_dict()
if 'fcmToken' in user_data:
fcmtoken = user_data['fcmToken']
# Compose notification message
if status == 'Approved':
notification_title = f'Appointment Approved'
elif status == 'Declined':
notification_title = f'Appointment Declined'
message = messaging.Message(
data={
'appointmentId': updated_data.get("appointmentId")
},
notification={
'title': notification_title,
'body': f'Appointment on {updated_data.get("startDateTime")} has been {status.lower()}'
},
token=fcmtoken
)
# Send the notification
response = messaging.send(message)
print('Notification sent successfully:', response)
else:
print('No fcmtoken found for the user.')
else:
print(f'User document with ID {client_id} does not exist.')
else:
print(f'Status {status} is not Approved or Declined.')
触发时,我的日志中出现以下错误
Traceback (most recent call last):
File "/layers/google.python.pip/pip/lib/python3.12/site-packages/flask/app.py", line 1473, in wsgi_app
response = self.full_dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/layers/google.python.pip/pip/lib/python3.12/site-packages/flask/app.py", line 882, in full_dispatch_request
rv = self.handle_user_exception(e)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/layers/google.python.pip/pip/lib/python3.12/site-packages/flask/app.py", line 880, in full_dispatch_request
rv = self.dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^
File "/layers/google.python.pip/pip/lib/python3.12/site-packages/flask/app.py", line 865, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/layers/google.python.pip/pip/lib/python3.12/site-packages/functions_framework/execution_id.py", line 106, in wrapper
return view_function(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/layers/google.python.pip/pip/lib/python3.12/site-packages/functions_framework/__init__.py", line 188, in view_func
function(event)
File "/layers/google.python.pip/pip/lib/python3.12/site-packages/firebase_functions/firestore_fn.py", line 255, in on_document_updated_wrapped
return _firestore_endpoint_handler(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/layers/google.python.pip/pip/lib/python3.12/site-packages/firebase_functions/firestore_fn.py", line 176, in _firestore_endpoint_handler
func(database_event)
File "/workspace/main.py", line 35, in send_appointment_notification
updated_data = event.after.data()
^^^^^^^^^^^
AttributeError: 'Event' object has no attribute 'after'
以前我会使用even.data.get(“status”),我会得到
status = event.data.get("status") ^^^^^^^^^^^^^^ AttributeError: 'Change' object has no attribute 'get'
查看文档中的示例。 查找文档“之后”内容的正确方法是这样的:
@on_document_updated(document="users/{userId}")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:
# Get an object with the current document values.
new_value = event.data.after.to_dict()
您似乎没有正确输入
event
参数,并且您没有使用 data
的 event
属性。