
プッシュ通知サンプルスクリプト
前提条件
- FCMトークン: Flutter サンプルセットアップセクションでは、開発者のデバイスのFCMトークンをログに出力する実装を行っています。
- APIへのアクセス: サービスアカウントセクションで、APIへのアクセス権を持つサービスアカウントのJSONをダウンロードしました。
[サンプル] Pythonプッシュ通知送信スクリプト
以下のPythonスクリプトは、Firebase Cloud Messagingを使用してプッシュ通知を送信する方法を示しています:
# sender.py
# Refer to the Service Account section for the JSON key file creation.
# Refer to the Sample Flutter Setup section for FCM token creation.
import time
import firebase_admin
from firebase_admin import messaging, credentials
# Firebase service account JSON file (Replace with the correct path)
SERVICE_ACCOUNT_PATH = "path/to/file"
# Firebase Cloud Messaging (FCM) token of the target device (Replace with actual token)
FCM_TOKEN = "Get this token from the client device set up."
# Initialize Firebase Admin SDK if not already initialized
if not firebase_admin._apps:
cred = credentials.Certificate(SERVICE_ACCOUNT_PATH)
firebase_admin.initialize_app(cred)
# Create a notification message
message = messaging.Message(
notification=messaging.Notification(
title="Sample Title",
body="Sample Body."
),
data={"timestamp": str(time.time())},
token=FCM_TOKEN, # Target device token
)
# Send the notification
try:
response = messaging.send(message)
print("Successfully sent message:", response)
except Exception as e:
print("Failed to send message:", str(e))
完全な実装
Flutterの完全な実装については、Flutterサンプルセットアップをご参照ください。モバイルアプリケーションでプッシュ通知を受信および処理するために必要なすべてのコードが含まれています。
デバッグ
通知の受信とイベントログのデバッグには、ローカルデバッガーを使用できます。Firebaseは、Firebaseコンソールにデバッグビューを提供しており、イベントの発生をリアルタイムで確認できます。