Connect with us

FACEBOOK

Building for Success: How to Visualize WhatsApp Account Metrics

Published

on

building-for-success:-how-to-visualize-whatsapp-account-metrics

WhatsApp’s Business Management API gives you access to metrics and analytics about your WhatsApp Business Account (WABA). You can get two types of data about your account:

  • Analytics for messages: The number of messages sent and delivered by phone numbers associated with a specific WABA within a given period.
  • Analytics for conversations: The conversation and cost information for messages sent within a given period.

When querying the API endpoint, you’re required to specify whether you want analytics for either messages or conversations by adding analytics or conversation_analytics as a parameter for the URL.

For example, this is a sample request if you want to get message analytics about your account:

https://graph.facebook.com/v14.0/{whatsapp-business-account-ID}       ?fields=analytics       .{filtering-parameters}       &{access-token}

In this sample, we specified that we want to retrieve message analytics for phone numbers linked to the WABA that has a unique WABA ID. You will learn more about getting your WABA ID and access token in the Requirements section that follows.

Additionally, when making a request, you can apply filtering parameters to refine the result. The Business Management API endpoint supports six filtering parameters in total. You must have the following:

  • start: If you specify a start date, the response does not include the messages sent before the given date.

  • end: If you specify an end date, the response does not include the messages sent after the given date.

  • granularity: How granular do you want the retrieved analytics to be? Possible values include HALF_HOUR, DAY, and MONTH.

As for conversation_analytics, you have nine filtering parameters, of which three — start, end, and granularity — are required.

Advertisement
free widgets for website

Requirements

For this tutorial, you will need to:

  • Install Python and pip on your local dev machine.*

  • Sign up for a developer account on Meta for Developers, create a Business Type App, and add a WhatsApp Business Account to the App.

  • Set up—on the Add Products to Your App page, click the Set Up button on the WhatsApp option.

After creating a WhatsApp Business Type App, you will get a WABA ID and a temporary access token. You need these two keys for the rest of this tutorial, so hold on to them.

You can add your personal WhatsApp number as the sender or use the test phone number provided by WhatsApp.

Create a Python App to Visualize Data

Set up a Python development environment and install the required packages.

Create a folder, give it a name and then navigate to the folder using a command-line tool. For this blog, we’ll use the requests library for making HTTP requests and the popular Matplotlib library for creating static, animated, and interactive visualizations. Run the following command to install them:

Advertisement
free widgets for website
 pip install requests matplotlib 

Now, you’ll be able to use Python requests to query the API for analytics data from WhatsApp, then use Matplotlib to visualize the metrics by plotting a graph with the data points received from the API.

Visualizing the Number of Messages Sent per Day

Start by requesting the analytics data. To do that, create a file named sent.py in your application folder and import the dependencies required for this task:

 import datetime import requests import matplotlib.pyplot as plt 

Next, create the API GET request to get the analytics using your WABA ID and access token. You can find these values on the dashboard of your developer account on Meta for Developer. The code for the GET request is as follows:

key = 'put-your-access-token-here' waba_id = 'put-your-waba-id-here'  res = requests.get(f'https://graph.facebook.com/v14.0/{waba_id}?fields=analytics.start(1662174000).end(1662548446).granularity(DAY)&access_token={key}')  dict = res.json()  print(dict)

In the request above, we represented the start date in UNIX-style, as the API requires. You can use this free converter to convert between human-readable and UNIX timestamps. The code converts the response to JSON format on the last line and prints it.

Execute the following command to run the code:

Advertisement
free widgets for website
 python app.py 

If the phone numbers linked to the WABA are used to send messages in the specified timeframe, we get a response dictionary object which looks like the following one:

 {   "analytics": {     "phone_numbers": [       "16505550111",       "16505550112",       "16505550113"     ],     "country_codes": [       "US",      ],     "granularity": "DAY",     "data_points": [       {         "start": 1662174000,         "end": 1662260400,         "sent": 199251,         "delivered": 183001       },       {         "start": 1662260400,         "end": 1662346800,         "sent": 162489,         "delivered": 141234       },       {         "start": 1662346800,         "end": 1662433200,         "sent": 67902,         "delivered": 53902       },       {         "start": 1662433200,         "end": 1662519600,         "sent": 129521,         "delivered": 117832       }     ]   },   "id": "952305634918047" } 

In this case, the data_points list contains four dictionaries. Each contains the number of messages that the linked WhatsApp numbers sent and delivered during the specified date range.

Now that you have the data, you must retrieve the necessary information. Since we want to visualize the number of messages sent each day, we must get start and sent values from each dictionary.

To do that, loop through the data points using the Python for...in loop. Convert the start time from UNIX style to a human-readable version for each data object. Then, get only the numerical day of the month and add it to the list of days. Store the number of sent messages in another list named no_of_msgs_sent:

 days = [] no_of_msgs_sent = []  data_points = dict.get("analytics").get("data_points")  for point in data_points:          # Get date in human readable format     x = datetime.datetime.fromtimestamp(point.get('start'))          # Get just the day in string format     y = x.strftime("%d")          days.append(y)          # Add the number of sent messages to the list      no_of_msgs_sent.append(point.get('sent'))      print(days) print(no_of_msgs_sent)  If you run the code, you get two lists:  ['03', '04', '05', '06'] // days [196093, 147649, 61988, 132465] // number of messages  Now that you have what you need, it's time to visualize it. Add the following code to app.py:  plt.plot(days, no_of_msgs_sent)  plt.title('Our Graph') plt.xlabel('Days') plt.ylabel('Number of messages sent')  plt.show() 

Here, you’re plotting a basic graph with the days along the x-axis and the number of sent messages along the y-axis.

Advertisement
free widgets for website

Save the file and run your code. If you’re on Linux and you get an error that says the following:

 UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure. 

Make sure you have tkinter installed. If you don’t, run the following command to install it:

 sudo apt-get install python3-tk 

If you run the code, you’ll get a graph that looks like this:

Next, you’ll create a graph to visualize the number of delivered messages.

Visualizing Information for a Specific WhatsApp Number

In the previous section, we didn’t include phone numbers in the request. As a result, the API returned information for all phone numbers linked to the WABA within the specified start and end dates.

Advertisement
free widgets for website

However, if you want to retrieve analytical data for one or multiple phone numbers but not all of them, you need to put the phone numbers in an array and pass it to the .phone_numbers method when creating the request:

res = requests.get(f'https://graph.facebook.com/v14.0/{waba_id}?fields=analytics.start(1662174000).end(1662548446).phone_numbers([16505550111, // others]).granularity(DAY)&access_token={key}')

The remaining code in sent.py remains the same. You only get the analytics for the specified phone numbers when you execute it.

Visualizing the Number of Messages Delivered per Day

In the last two sections, we plotted a graph to visualize the number of messages sent each day by the linked phone numbers through WhatsApp. Now, let’s plot a graph to visualize the number of messages delivered daily.

Create a new file and name it delivered.py. Next, copy the code from sent.py into delivered.py.

Next, make a few changes to the code in delivered.py. First, rename the variable at the top from no_of_msgs_sent to no_of_msgs_del to reflect the kind of data you’re storing.

Advertisement
free widgets for website

Next, in the for...in loop, change the value in the point.get method from sent to delivered. Here’s a snippet of how your code should look like after you make the changes:

# Variables go here  for point in data_points:          # Code for getting human readable date goes here              # Now add the number of delivered messages to the list       no_of_msgs_del.append(point.get('delivered'))  print(day) print(no_of_msgs_del)  Finally, specify no_of_msgs_del in the plt.plot method and update the label shown on the y-axis:  plt.plot(days, no_of_msgs_del)  plt.title('Our Graph') plt.xlabel('Days') plt.ylabel('Number of messages delivered')  plt.show()

Once you run the code on your terminal (with python delivered.py), you’ll get a graph like the one below.

Now that you’ve represented two sets of analytics data for messages, you will next represent the cost of messages using conversation_analytics.

Visualizing the Cost of Messages Sent per Day

Once again, create a new file for this section, and name the file cost.py. Copy the code from sent.py into cost.py. Now let’s make a few modifications.

First, modify the request code. Since you’re getting the conversation information, set the fields parameter to conversation_analytics and set granularity to daily.

Advertisement
free widgets for website
res = requests.get(f'https://graph.facebook.com/v14.0/{waba_id}?fields=conversation_analytics.start(1662174000).end(1662548446).granularity(DAILY).phone_numbers([])&access_token={key}')

Note that the conversation_anaytics field supports several other filtering parameters for getting other kinds of information. To learn more, read the full documentation.

After making the above request, you should get a response object very similar to the following:

{   "conversation_analytics": {     'data': {         "data_points": [           {             "start": 1662174000,             "end": 1662260400,             "conversation": 5250,             "cost": 45.0532           },           {             "start": 1662260400,             "end": 1662346800,             "conversation": 2250,             "cost": 25.0290           },           {             "start": 1662346800,             "end": 1662433200,             "conversation": 800,             "cost": 0.0000           },           {             "start": 1662433200,             "end": 1662519600,             "conversation": 3150,             "cost": 33.2015           }         ]     }   }, }

As seen above, the data_points are inside the data dictionary. Each data point in the dictionary has a conversation amount and cost.

Next, in cost.py, change the variable at the top from no_of_msgs_del to cost_of_convo. In the for...in loop, change the value in the point.get method from delivered to cost. Here’s a snippet of how your code should look like after you make the changes:

days = [] cost_of_convo = []  data_points = dict.get('conversation_analytics').get("data").get("data_points")  for point in data_points:         x = datetime.datetime.fromtimestamp(point.get('start'))        y = x.strftime("%d")          days.append(y)          # Add the cost of messages in each data point     cost_of_convo.append(point.get('cost'))  Now, to plot a graph visualizing it:  plt.plot(days, cost_of_convo)  plt.title('Our Graph') plt.xlabel('Days') plt.ylabel('Cost of messages sent')  plt.show()

If you run your code using the terminal (with python cost.py), you’ll get a graph like this:

Advertisement
free widgets for website

And that’s it!

To take things further, you can follow the same method to visualize other metrics that the WhatsApp Business Management API provides.

Conclusion

In this tutorial, we used the matplotlib data visualization library to visualize data showing the number of messages sent per day, the number of messages delivered per day, and the cost of each message conversation.

The WhatsApp Business Management API gives you these filtering parameters and many more, which you can use to specify the metrics you want in each request. To learn more, check out the full API documentation.

As a developer, the WhatsApp Business Management API gives you relevant information and metrics from the WhatsApp account of your users. For example, you can show your users the number of WhatsApp messages they have sent on a given day on their dashboard.

Advertisement
free widgets for website

The possibilities are endless!

*Meta cannot be held responsible for any third party apps.

First seen at developers.facebook.com

See also  Google and Facebook are brilliant and dangerous and entirely out of control | The Spinoff
Continue Reading
Advertisement free widgets for website
Click to comment

Leave a Reply

Your email address will not be published.

FACEBOOK

Introducing Facebook Graph API v18.0 and Marketing API v18.0

Published

on

By

introducing-facebook-graph-api-v180-and-marketing-api-v18.0

Today, we are releasing Facebook Graph API v18.0 and Marketing API v18.0. As part of this release, we are highlighting changes below that we believe are relevant to parts of our developer community. These changes include announcements, product updates, and notifications on deprecations that we believe are relevant to your application(s)’ integration with our platform.

For a complete list of all changes and their details, please visit our changelog.

General Updates

Consolidation of Audience Location Status Options for Location Targeting

As previously announced in May 2023, we have consolidated Audience Location Status to our current default option of “People living in or recently in this location” when choosing the type of audience to reach within their Location Targeting selections. This update reflects a consolidation of other previously available options and removal of our “People traveling in this location” option.

We are making this change as part of our ongoing efforts to deliver more value to businesses, simplify our ads system, and streamline our targeting options in order to increase performance efficiency and remove options that have low usage.

This update will apply to new or duplicated campaigns. Existing campaigns created prior to launch will not be entered in this new experience unless they are in draft mode or duplicated.

Advertisement
free widgets for website

Add “add_security_recommendation” and “code_expiration_minutes” to WA Message Templates API

Earlier this year, we released WhatsApp’s authentication solution which enabled creating and sending authentication templates with native buttons and preset authentication messages. With the release of Graph API v18, we’re making improvements to the retrieval of authentication templates, making the end-to-end authentication template process easier for BSPs and businesses.

With Graph API v18, BSPs and businesses can have better visibility into preset authentication message template content after creation. Specifically, payloads will return preset content configuration options, in addition to the text used by WhatsApp. This improvement can enable BSPs and businesses to build “edit” UIs for authentication templates that can be constructed on top of the API.

See also  Facebook Shares New Overview of its Evolving Approach to Marketing Mix Modeling

Note that errors may occur when upgrading to Graph API v18 if BSPs or businesses are taking the entire response from the GET request and providing it back to the POST request to update templates. To resolve, the body/header/footer text fields should be dropped before passing back into the API.

Re-launching dev docs and changelogs for creating Call Ads

  • Facebook Reels Placement for Call Ads

    Meta is releasing the ability to deliver Call Ads through the Facebook Reels platform. Call ads allow users to call businesses in the moment of consideration when they view an ad, and help businesses drive more complex discussions with interested users. This is an opportunity for businesses to advertise with call ads based on peoples’ real-time behavior on Facebook. Under the Ad set Level within Ads Manager, businesses can choose to add “Facebook Reels” Under the Placements section.
  • Re-Launching Call Ads via API

    On September 12, 2023, we’re providing updated guidance on how to create Call Ads via the API. We are introducing documentation solely for Call Ads, so that 3P developers can more easily create Call Ads’ campaigns and know how to view insights about their ongoing call ad campaigns, including call-related metrics. In the future, we also plan to support Call Add-ons via our API platform. Developers should have access to the general permissions necessary to create general ads in order to create Call Ads via the API platform.

    Please refer to developer documentation for additional information.

Deprecations & Breaking Changes

Graph API changes for user granular permission feature

We are updating two graph API endpoints for WhatsAppBusinessAccount. These endpoints are as follows:

  • Retrieve message templates associated with WhatsAppBusiness Account
  • Retrieve phone numbers associated with WhatsAppBusiness Account

With v18, we are rolling out a new feature “user granular permission”. All existing users who are already added to WhatsAppBusinessAccount will be backfilled and will continue to have access (no impact).

The admin has the flexibility to change these permissions. If the admin changes the permission and removes access to view message templates or phone numbers for one of their users, that specific user will start getting an error message saying you do not have permission to view message templates or phone numbers on all versions v18 and older.

Advertisement
free widgets for website

Deprecate legacy metrics naming for IG Media and User Insights

Starting on September 12, Instagram will remove duplicative and legacy, insights metrics from the Instagram Graph API in order to share a single source of metrics to our developers.

This new upgrade reduces any confusion as well as increases the reliability and quality of our reporting.

After 90 days of this launch (i.e. December 11, 2023), we will remove all these duplicative and legacy insights metrics from the Instagram Graph API on all versions in order to be more consistent with the Instagram app.

We appreciate all the feedback that we’ve received from our developer community, and look forward to continuing to work together.

Please review the media insights and user insights developer documentation to learn more.

Advertisement
free widgets for website

Deprecate all Facebook Wi-Fi v1 and Facebook Wi-Fi v2 endpoints

Facebook Wi-Fi was designed to improve the experience of connecting to Wi-Fi hotspots at businesses. It allowed a merchant’s customers to get free Wi-Fi simply by checking in on Facebook. It also allowed merchants to control who could use their Wi-Fi and for how long, and integrated with ads to enable targeting to customers who had used the merchant’s Wi-Fi. This product was deprecated on June 12, 2023. As the partner notice period has ended, all endpoints used by Facebook Wi-Fi v1 and Facebook Wi-Fi v2 have been deprecated and removed.

API Version Deprecations:

As part of Facebook’s versioning schedule for Graph API and Marketing API, please note the upcoming deprecations:

Graph API

  • September 14, 2023: Graph API v11.0 will be deprecated and removed from the platform
  • February 8, 2024: Graph API v12.0 will be deprecated and removed from the platform
  • May 28, 2024: Graph API v13.0 will be deprecated and removed from the platform

Marketing API

  • September 20, 2023: Marketing API v14.0 will be deprecated and removed from the platform
  • September 20, 2023: Marketing API v15.0 will be deprecated and removed from the platform
  • February 06, 2024: Marketing API v16.0 will be deprecated and removed from the platform

To avoid disruption to your business, we recommend migrating all calls to the latest API version that launched today.

Facebook Platform SDK

As part of our 2-year deprecation schedule for Platform SDKs, please note the upcoming deprecations and sunsets:

  • October 2023: Facebook Platform SDK v11.0 or below will be sunset
  • February 2024: Facebook Platform SDK v12.0 or below will be sunset

First seen at developers.facebook.com

See also  Facebook Reels: How to Add Audio to a Reel - Adweek
Continue Reading

FACEBOOK

Allowing Users to Promote Stories as Ads (via Marketing API)

Published

on

By

allowing-users-to-promote-stories-as-ads-(via-marketing-api)

Before today (August 28, 2023), advertisers could not promote images and/or videos used in Instagram Stories as ads via the Instagram Marketing API. This process created unwanted friction for our partners and their customers.

After consistently hearing about this pain point from our developer community, we have removed this unwanted friction for advertisers and now allow users to seamlessly promote their image and/or video media used in Instagram Stories as ads via the Instagram Marketing API as of August 28, 2023.

We appreciate all the feedback received from our developer community, and hope to continue improving your experience.

Please review the developer documentation to learn more.

First seen at developers.facebook.com

Advertisement
free widgets for website
See also  Facebook may have vastly overpaid in data privacy settlement: court filing
Continue Reading

FACEBOOK

Launching second release of Facebook Reels API: An enterprise solution for desktop and web publishers

Published

on

By

launching-second-release-of-facebook-reels-api:-an-enterprise-solution-for-desktop-and-web-publishers

We’re excited to announce that the second release of FB Reels API is now publicly available for third-party developers. FB Reels API enables users of third-party platforms to share Reels directly to public Facebook Pages and the New Pages Experience.

FB Reels API has grown significantly since the first release in September 2022. The new version of the APIs now support custom thumbnails, automatic music tagging, tagging collaborators, longer format of reels and better error handling.

FB Reels API will also support scheduling and draft capability to allow creators to take advantage of tools provided either by Meta or by our partners. Based on the feedback we received from our partners, we’ll now provide additional audio insights via the Audio Recommendations API and reels performance metrics via the Insights API.

Our goal in the next couple of releases is to continue to make it easier for creators to develop quality content by adding features like early copyright detection and A/B testing. We’re also excited to start working on enhanced creation features like Video clipping- so stay tuned to hear more about those features in the future.

Call-to-Action

If you are a developer interested in integrating with the Facebook Reels API, please refer to the Developer Documents for more info.

Advertisement
free widgets for website

Not sure if this product is for you? Check out our entire suite of sharing offerings.

Tune in to Product @scale event to learn more about FB Video APIs and hear from some of our customers.

First seen at developers.facebook.com

See also  The Facebook and Instagram memes bringing Indian history (and independence struggle) back to life
Continue Reading

Trending