מופעלות של התראות Firebase

Firebase מספקת התראה עבור מגוון רחב של אירועי ניהול פרויקטים ואפליקציות. הנה כמה אירועים לדוגמה שבהם Firebase יכול לשלוח לך התראה מסוג זה:

  • עבור Crashlytics, אנו יכולים להתריע אם לאפליקציה שלך יש עלייה דרמטית בקריסות.
  • לניטור ביצועים, נוכל להתריע אם זמן ההפעלה של האפליקציה שלך חוצה את הסף שהוגדר.
  • עבור הפצת אפליקציות, נוכל להתריע אם אחד מהבודקים שלך רושם מכשיר iOS חדש.

בהתאם להתראה ולהעדפות שנקבעו על ידי חבר הפרויקט , Firebase מציג את סוגי ההתראות האלה במסוף Firebase או שולח אותן בדוא"ל.

דף זה מתאר כיצד לכתוב פונקציות ב-Cloud Functions for Firebase (דור שני) המטפלות באירועי התראה.

איך זה עובד?

אתה יכול להפעיל פונקציות בתגובה לאירועי התראה הנפלטים ממקורות אלה:

במחזור חיים טיפוסי, פונקציה המופעלת על ידי אירוע התראה עושה את הדברים הבאים:

  1. מקשיב/ממתין לסוג התראה ספציפי שנפלט מ-Firebase.
  2. מופעל כאשר ההתראה נפלטה, ומקבל את מטען האירוע המכיל מידע ספציפי על האירוע.
  3. מפעיל את הקוד של הפונקציה שלך כדי לטפל במטען האירוע.

הפעל פונקציה באירועי התראה

השתמש בתת-חבילת firebase-functions/v2/alerts כדי לכתוב פונקציה שמטפלת באירועי התראות. הדוגמאות הספציפיות למוצר הבאות מדגימות זרימת עבודה שבה פונקציה משתמשת ב-webhook כדי לפרסם הודעה לערוץ Discord כאשר נפלטת התראה עבור אותו מוצר מ-Firebase.

טפל באירוע התראת Crashlytics

עבור הדוגמה הבאה של Crashlytics, אתה משתמש ב-Cloud Functions for Firebase כדי לטפל באירוע התראה על בעיית קריסה קטלנית חדשה. פונקציה זו מפרסמת את מידע ההתראה בהודעה לערוץ Discord.

הודעת קריסה לדוגמה בדיסקורד

הודעה לדוגמה על בעיית קריסה קטלנית חדשה

הפונקציה מאזינה לאירוע המתאים לפרסום של בעיה קטלנית חדשה ב-Firebase:

Node.js

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

פִּיתוֹן

@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}\`
`;

פִּיתוֹן

    # 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:

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);
}

פִּיתוֹן

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) => {

פִּיתוֹן

@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}
    `;

פִּיתוֹן

    # 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:

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);
}

פִּיתוֹן

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) => {

פִּיתוֹן

@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}
`;

פִּיתוֹן

    # 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:

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);
}

פִּיתוֹן

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 .