How to Use List Messages API to Get Price Summaries

To quickly run this code, check out our recipe below and replace the variables with your own! Or, keep reading for an in-depth walkthrough.

What do we need to run this code?

For the following code to work, you will need to have pandas, DateTime, and the SignalWire Python SDK installed.

Read about the different ways to install pandas here.

Read about DateTime and how to install using pip here.

Read about the SignalWire Python SDK and how to install here.

Step by Step Walkthrough

We will start by importing the necessary resources. In this example, that is datetime, pandas, and the SignalWire Client. We also need to instantiate the SignalWire client using the project ID, auth token, and space URL.

from datetime import datetime
from signalwire.rest import Client as signalwire_client
import pandas as pd

client = signalwire_client("ProjectID", "AuthToken", signalwire_space_url = 'SpaceURL')

In this example, I have included how to filter by DateSentAfter and DateSentBefore to return all messages between a specific date range. DateSent is a DateTime object where the order for the arguments is Year, Month, Date, Hour, Minute, Seconds. You can leave hour, minute, and seconds at 0, unless you have a specific time of day you would like to filter by.

📘

Octal Literals in Some Python Versions

For months Jan - September, A slight change was made because python version (3.9) does not support leading 0's in datetime anymore. You must use the 0o prefix for octal literals now. That is reflected below in the code. If your version doesn’t include that limitation, you can switch it back to 01 or whatever month you need.

Next, we will create two arrays: d and status. d will contain all of the message records within the specified date range and status will contain only the message statuses which we will use to get some summarized stats. We will loop through each message record returned by the List Messages API and add additional detail to the row as well as adding the status alone to the status array.

for record in messages:
    d.append((record.from_, record.to, record.date_sent, record.sid, record.price, record.direction, record.status))
    status.append(record.status)

Next we will categorize the message status for all our returned messages and count how many are inbound vs outbound.

# categorize message status for all returned messages
total_sent=int(status.count("sent"))
total_received=int(status.count("received"))
total_delivered=int(status.count("delivered"))
total_undelivered=int(status.count("undelivered"))

# count how many are inbound vs outbound
num_outbound_messages = total_sent + total_delivered + total_undelivered
num_inbound_messages = total_received

Now that all of the message data is stored in d, we need to convert it to a data frame to make for easier containment as well as the ability to convert to CSV. It's important to make sure that the column headers are in the same order as the message record details added to d.

# create dataframe and convert to CSV
df = pd.DataFrame(d, columns=('From', 'To', 'Date', 'MessageSID',  'Price', 'Message Direction', 'Message Status'))
print(df)
df.to_csv('Messages.csv', index=False, encoding='utf-8')
print()

As we want to get the amount spent in our date range, we will add up the cost of the Price column in the dataframe and convert the float to a currency format.

totalMess = len(df)
totalCost = df['Price'].sum()
formattedCost = "${:,.2f}".format(totalCost)

Lastly, we will use the data and values that we've calculated to display the total cost as well as some summaries about delivery status and the message type distribution.

print("You sent " + str(totalMess) + " total messages during your selected date range.")
print("The total cost of messages in your selected date range is approximately " + formattedCost + " USD.")
print("There were " + str(total_delivered) + " delivered messages and " + str(total_undelivered) +  " undelivered messages.")
print("There were " + str(num_inbound_messages) + " inbound messages and " + str(num_outbound_messages) + " outbound messages.")

Did this page help you?