Firebase 提醒触发器

Firebase 会针对各种项目和应用管理事件提供提醒。下方列出了一些示例提醒事件:

  • 对于 Crashlytics,我们可以在应用的崩溃次数剧增时向您发送提醒。
  • 对于 Performance Monitoring,我们可以在应用的启动时间超过配置的阈值时向您发送提醒。
  • 对于 App Distribution,我们可以在有测试人员注册了新的 iOS 设备时向您发送提醒。

根据项目成员设定的提醒和偏好设置,Firebase 可能会在 Firebase 控制台中显示此类提醒,也可能会通过电子邮件发送提醒。

本页介绍了如何在 Cloud Functions for Firebase(第 2 代)中编写用于处理提醒事件的函数。

工作原理

您可以触发函数来响应以下来源发出的提醒事件:

在典型生命周期中,提醒事件触发的函数会执行以下操作:

  1. 监听/等待从 Firebase 发出特定类型的提醒。
  2. 在有提醒发出时触发,并接收包含事件特定信息的事件载荷。
  3. 调用函数的代码来处理事件载荷。

在发生提醒事件时触发函数

使用 firebase-functions/v2/alerts 子软件包编写用于处理提醒事件的函数。以下产品专用示例演示了一个工作流,在 Firebase 发出有关该产品的提醒时,函数会使用网络钩子将消息发布到一个 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 提醒事件,请参阅 CrashlyticsCrashlytics 提醒参考文档。

处理 Performance Monitoring 提醒事件

下面的示例会导出一个函数来监听性能阈值提醒事件:

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 提醒参考文档。

处理 App Distribution 提醒事件

本部分中的示例展示了如何编写针对新注册的测试人员 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 DistributionCrashlytics 提醒参考文档。

如需了解如何使用由 App Distribution 中的 Firebase 应用内反馈提醒触发的函数,请参阅向 Jira 发送应用内反馈