Last active
August 5, 2021 22:51
-
-
Save edilAraujo/fcdbcd04f563c9e01ac4ad28fe5ebfd5 to your computer and use it in GitHub Desktop.
This Python script pulls the last 90 days of messages and saves it to a CSV file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import csv | |
import datetime | |
# create CSV file from array or arrays. array structure = [["Sender Type", "Sender Name", "Sent Time", "Message Text", "Read"]] | |
def write_CSV(row_array, filename): | |
with open(filename + '.csv', 'w') as csvfile: | |
filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) | |
filewriter.writerow(["Sender Type", "Sender Name", "Sent Time", "Message Text", "Read"]) | |
for row in row_array: | |
filewriter.writerow(row) | |
# You can pull messages from any timeframe by specifying the endMs and durationMs | |
# For example, for messages from between 01/01/2019 and 04/01/2019, the query URL would be | |
# https://api.samsara.com/v1/fleet/messages?endMs=1554102000000&durationMs=7776000000 | |
url = "https://api.samsara.com/v1/fleet/messages?durationMs=7776000000" | |
APIKEY = 'add key here' | |
# Need valid API key | |
payload={} | |
headers = { | |
'Authorization': 'Bearer ' + APIKEY | |
} | |
response = requests.request("GET", url, headers=headers, data=payload) | |
data = response.json()['data'] | |
output = [] | |
for messages in data: | |
output.append((messages['sender']['type'], messages['sender']['name'], datetime.datetime.fromtimestamp(int(messages['sentAtMs']) / 1000).strftime('%Y-%m-%d %H:%M:%S.%f'), messages['text'], messages['isRead'])) | |
write_CSV(output, "messages - " + datetime.datetime.now().strftime('%Y-%m-%d')) | |
# JSON individual message structure | |
# { | |
# "driverId": 128319, | |
# "text": "This is a message from dispatch", | |
# "sentAtMs": 1626710454992, | |
# "sender": { | |
# "type": "dispatch", | |
# "name": "Eddy Araujo" | |
# }, | |
# "isRead": true | |
# } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment