Firebase 警報觸發器

Firebase 為各種專案和應用程式管理事件提供警報。以下是 Firebase 何時可以向您發送此類警報的一些範例事件:

  • 對於 Crashlytics,如果您的應用程式崩潰次數急劇增加,我們可以向您發出警報。
  • 對於效能監控,如果您的應用程式的啟動時間超過您配置的閾值,我們可以向您發出警報。
  • 對於應用程式分發,如果您的一位測試人員註冊了新的 iOS 設備,我們可以提醒您。

根據警報和專案成員設定的首選項,Firebase 在 Firebase 控制台中顯示這些類型的警報或透過電子郵件發送它們。

本頁面介紹如何在 Cloud Functions for Firebase(第 2 代)中撰寫處理警報事件的函數。

它是如何運作的?

您可以觸發函數來回應這些來源發出的警報事件:

在典型的生命週期中,由警報事件觸發的函數會執行以下操作:

  1. 偵聽/等待 Firebase 發出特定警報類型。
  2. 發出警報時觸發,並接收包含有關事件的特定資訊的事件負載。
  3. 呼叫函數的程式碼來處理事件負載。

觸發警報事件的函數

使用firebase-functions/v2/alerts子包編寫處理警報事件的函數。以下特定於產品的範例示範了一個工作流程,其中當 Firebase 發出該產品的警報時,函數使用 Webhook 將訊息發佈到 Discord 頻道。

處理 Crashlytics 警報事件

對於以下 Crashlytics 範例,您使用 Cloud Functions for Firebase 來處理新的致命崩潰問題的警報事件。此功能將訊息中的警報訊息發佈到 Discord 頻道。

Discord 中的崩潰通知範例

新的致命崩潰問題的範例通知

此函數偵聽與 Firebase 發布新的致命問題相對應的事件:

Node.js

exports.postfatalissuetodiscord = onNewFatalIssuePublished(async (event) => {

Python

@crashlytics_fn.on_new_fatal_issue_published(secrets=["DISCORD_WEBHOOK_URL"])
def post_fatal_issue_to_discord(event: crashlytics_fn.CrashlyticsNewFatalIssueEvent) -> None:
    """Publishes a message to Discord whenever a new Crashlytics fatal issue occurs."""

然後函數解析傳回的事件對象,從事件負載中解析有用資訊並建構一條訊息以發佈到 Discord 通道:

Node.js

  // construct a helpful message to send to Discord
  const appId = event.appId;
  const {id, title, subtitle, appVersion} = event.data.payload.issue;
  const message = `
🚨 New fatal issue for ${appId} in version ${appVersion} 🚨

**${title}**

${subtitle}

id: \`${id}\`
`;

Python

    # Construct a helpful message to send to Discord.
    app_id = event.app_id
    issue = event.data.payload.issue
    message = f"""
🚨 New fatal issue for {app_id} in version {issue.app_version} 🚨

# {issue.title}

{issue.subtitle}

ID: `{issue.id}`
""".strip()

最後,該函數將建構的訊息透過 HTTP 請求傳送到 Discord:

Node.js

const response = await postMessageToDiscord("Crashlytics Bot", message);
if (response.ok) {
  logger.info(
      `Posted fatal Crashlytics alert ${id} for ${appId} to Discord`,
      event.data.payload,
  );
} else {
  throw new Error(response.error);
}

Python

response = post_message_to_discord("Crashlytics Bot", message, DISCORD_WEBHOOK_URL.value)
if response.ok:
    print(f"Posted fatal Crashlytics alert {issue.id} for {app_id} to Discord.")
    pprint.pp(event.data.payload)
else:
    response.raise_for_status()

若要了解您可以擷取的所有 Crashlytics 警報事件,請前往Crashlytics 警報的參考文件。

處理效能監控警報事件

此範例匯出一個偵聽效能閾值警報事件的函數:

Node.js

exports.postperformancealerttodiscord = onThresholdAlertPublished(
    async (event) => {

Python

@performance_fn.on_threshold_alert_published(secrets=["DISCORD_WEBHOOK_URL"])
def post_performance_alert_to_discord(event: performance_fn.PerformanceThresholdAlertEvent) -> None:
    """Publishes a message to Discord whenever a performance threshold alert is fired."""

然後函數解析傳回的事件對象,從事件負載中解析有用資訊並建構一條訊息以發佈到 Discord 通道:

Node.js

      // construct a helpful message to send to Discord
      const appId = event.appId;
      const {
        eventName,
        metricType,
        eventType,
        numSamples,
        thresholdValue,
        thresholdUnit,
        conditionPercentile,
        appVersion,
        violationValue,
        violationUnit,
        investigateUri,
      } = event.data.payload;
      const message = `
    ⚠️ Performance Alert for ${metricType} of ${eventType}: **${eventName}** ⚠️
    
    App id: ${appId}
    Alert condition: ${thresholdValue} ${thresholdUnit}
    Percentile (if applicable): ${conditionPercentile}
    App version (if applicable): ${appVersion}
    
    Violation: ${violationValue} ${violationUnit}
    Number of samples checked: ${numSamples}
    
    **Investigate more:** ${investigateUri}
    `;

Python

    # Construct a helpful message to send to Discord.
    app_id = event.app_id
    perf = event.data.payload
    message = f"""
⚠️ Performance Alert for {perf.metric_type} of {perf.event_type}: **{perf.event_name}** ⚠️

App ID: {app_id}
Alert condition: {perf.threshold_value} {perf.threshold_unit}
Percentile (if applicable): {perf.condition_percentile}
App version (if applicable): {perf.app_version}

Violation: {perf.violation_value} {perf.violation_unit}
Number of samples checked: {perf.num_samples}

**Investigate more:** {perf.investigate_uri}
""".strip()

最後,該函數將建構的訊息透過 HTTP 請求傳送到 Discord:

Node.js

const response = await postMessageToDiscord(
    "Firebase Performance Bot", message);
if (response.ok) {
  logger.info(
      `Posted Firebase Performance alert ${eventName} to Discord`,
      event.data.payload,
  );
} else {
  throw new Error(response.error);
}

Python

response = post_message_to_discord("App Performance Bot", message,
                                   DISCORD_WEBHOOK_URL.value)
if response.ok:
    print(f"Posted Firebase Performance alert {perf.event_name} to Discord.")
    pprint.pp(event.data.payload)
else:
    response.raise_for_status()

若要了解您可以擷取的所有效能警報事件,請前往效能監控警報的參考文件。

處理應用程式分發警報事件

本節中的範例向您展示如何為新測試儀 iOS 裝置警報編寫函數。

在此範例中,此函數會偵聽每次測試人員註冊新 iOS 裝置時發送的事件。註冊新的 iOS 裝置時,您需要使用該裝置的 UDID 更新您的設定文件,然後重新分發應用程式。

Node.js

exports.postnewduuidtodiscord = onNewTesterIosDevicePublished(async (event) => {

Python

@app_distribution_fn.on_new_tester_ios_device_published(secrets=["DISCORD_WEBHOOK_URL"])
def post_new_udid_to_discord(event: app_distribution_fn.NewTesterDeviceEvent) -> None:
    """Publishes a message to Discord whenever someone registers a new iOS test device."""

然後函數解析傳回的對象,從事件負載中解析有用資訊並建構一條訊息以發佈到 Discord 通道:

Node.js

  // construct a helpful message to send to Discord
  const appId = event.appId;
  const {
    testerDeviceIdentifier,
    testerDeviceModelName,
    testerEmail,
    testerName,
  } = event.data.payload;
  const message = `
📱 New iOS device registered by ${testerName} <${testerEmail}> for ${appId}

UDID **${testerDeviceIdentifier}** for ${testerDeviceModelName}
`;

Python

    # Construct a helpful message to send to Discord.
    app_id = event.app_id
    app_dist = event.data.payload
    message = f"""
📱 New iOS device registered by {app_dist.tester_name} <{app_dist.tester_email}> for {app_id}

UDID **{app_dist.tester_device_identifier}** for {app_dist.tester_device_model_name}
""".strip()

最後,該函數將建構的訊息透過 HTTP 請求傳送到 Discord:

Node.js

const response = await postMessageToDiscord("AppDistribution Bot", message);
if (response.ok) {
  logger.info(
      `Posted iOS device registration alert for ${testerEmail} to Discord`,
  );
} else {
  throw new Error(response.error);
}

Python

response = post_message_to_discord("App Distro Bot", message, DISCORD_WEBHOOK_URL.value)
if response.ok:
    print(f"Posted iOS device registration alert for {app_dist.tester_email} to Discord.")
    pprint.pp(event.data.payload)
else:
    response.raise_for_status()

若要了解您可以擷取的所有 App Distribution 警報事件,請參閱App Distribution 警報的參考文件。

若要了解如何使用由App Distribution 的應用程式內回饋 Firebase 警報觸發的功能,請參閱向 Jira 傳送應用程式內回饋