Firebase 快訊觸發條件

Firebase 針對多種專案和應用程式管理服務提供快訊 事件。以下是幾個事件範例,可用來瞭解 Firebase 何時可傳送這項要求 警示類型:

  • 使用 Crashlytics 之後,如果應用程式的用量大幅增加 當機。
  • 對於 Performance Monitoring,我們可以在您應用程式的啟動時間超過 您設定的閾值
  • 針對應用程式發布,如有測試人員註冊新的 iOS 裝置,我們會向您發出快訊 裝置。

取決於快訊和專案設定的偏好設定 成員 Firebase 會在 Firebase 控制台顯示或傳送這類快訊 像是您可以測量運作時間及健康狀態檢查 並設定透過電子郵件傳送快訊

本頁面說明如何在 Cloud Functions for Firebase (第 2 代) 中寫入函式 處理快訊事件

運作原理

您可以觸發函式,回應下列來源產生的警示事件:

在一般生命週期中,由快訊事件觸發的函式會執行以下動作: 包括:

  1. 監聽/等待由 Firebase 發出特定快訊類型。
  2. 發出快訊時觸發,並接收 包含事件的特定資訊
  3. 叫用函式的程式碼來處理事件酬載。

在發生快訊事件時觸發函式

使用 firebase-functions/v2/alerts 子套件編寫會符合下列條件的函式: 處理快訊事件以下示範產品的具體範例 函式:函式使用 Webhook 將訊息發布至 Discord 頻道 系統從 Firebase 發送該產品快訊時,就會觸發這個事件。

處理 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()

最後,函式會將建構的訊息傳送至 Discord HTTP 要求:

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()

如要瞭解所有可擷取的成效快訊事件,請前往 參考文件 Performance Monitoring 快訊

處理應用程式發布快訊事件

本節中的範例說明如何為新的測試人員 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()

如要瞭解可擷取的所有「應用程式發布」快訊事件,請前往 查看 應用程式發布快訊

如要瞭解如何使用由 應用程式發布中的應用程式內意見回饋 Firebase 快訊, 請參閱「在應用程式中傳送意見回饋給 Jira」。