Reputation: 3663
How do I loop through messages received by a Twilio phone number, and delete each one?
I see this section: https://www.twilio.com/docs/api/rest/message#instance-delete
Is this possible in Bash?
I've written this code so far:
#!/bin/bash
curl -G https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXX/Messages.json \
-d "Body=" \
-u 'ACYYYYYYY'
This only lists all messages my Twilio account received. I do not know what the output should look like if I run a successful delete program.
Upvotes: 1
Views: 616
Reputation: 536
Doing this in bash without external tools ( like jq which is a JSON processing tool similar to awk ) is probably a bit... unreliable but here we go.
If you curl your messages we can see with their tool that the output is some JSON and that each message has a URI which we will need. We also see that to redact a message we use curl XPOST <message_uri> -d "Body=" -u "<auth_string>"
... So if we select the URI for each message and use curl to post an empty body at each message URI we will delete the messages!
curl -G https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXX/Messages.json -u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token' \
| grep '"uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/' \
| cut -d'"' -f 4 \
| xargs -I {} curl -XPOST "https://api.twilio.com/"{} -d "Body=`-u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token'
Obviously you need to replace all the ACXX strings with your account info!
So first we curl Messages.json to get our messages. We use grep to rip out the URI for each message. We use cut to get just the raw URI. Then we use xargs
and curl
to make the empty body post to each messages URI.
This is pretty brittle in that it doesn't handle pagination, it absolutely doesn't handle anything but expected output from the messages.json endpoint, it doesn't do any checking of the response from the empty body posts when redacting messages, the output will probably be ugly too. However if everything is as the API docs say it should work and at the very least give you a starting place to see why maybe doing this in a language that has more robust JSON parsing is a good idea.
Upvotes: 2