Skip to content

Instantly share code, notes, and snippets.

@kawing-ho
Last active June 18, 2019 05:34
Show Gist options
  • Save kawing-ho/64468babdf5c356b4f5ae1e8f5333139 to your computer and use it in GitHub Desktop.
Save kawing-ho/64468babdf5c356b4f5ae1e8f5333139 to your computer and use it in GitHub Desktop.
Takes in a message from stdin and SMS'es it to the specified phone number via Twilio (trial)
#!/usr/bin/env python3
# some libraries that you might need to pip install
from twilio.rest import Client
from requests import get as reget
from os import environ as env
from os import path
from sys import exit as sysexit
from sys import stdin
def die_env(s):
sysexit("Could not retrieve {} from environment".format(s))
# credentials are grabbed from env
account_sid = env.get('TWILIO_SID')
if not account_sid: die_env('TWILIO_SID')
auth_token = env.get('TWILIO_AUTHTOKEN')
if not auth_token: die_env('TWILIO_AUTHTOKEN')
number_to = env.get('TWILIO_TO')
if not number_to: die_env('TWILIO_TO')
number_from = env.get('TWILIO_FROM')
if not number_from: die_env('TWILIO_FROM')
# input comes from STDIN
# use of special characters will shorten the limit to 67
if stdin.isatty(): sysexit("Only piped input accepted")
to_send = stdin.read()
# check if empty or over 160-character limit
if len(to_send) == 0: sysexit("Message is empty!")
elif len(to_send) >= 160: sysexit("Message too long!")
client = Client(account_sid, auth_token)
# send the message and store response
message = client.messages.create(from_=number_from,
to=number_to,
body=to_send)
print(message.sid)
if message.error_code: print(message.error_code, message.error_message)
# check balance and report if low
flag_location = "%s/.twilio_low_balance" % env.get('HOME')
if path.exists(flag_location): exit(0)
endpoint = 'https://api.twilio.com/2010-04-01/Accounts/%s/Balance.json' % account_sid
r = reget(endpoint, auth=(account_sid, auth_token))
r_json = r.json()
balance = r_json.get('balance')
print(r_json.get('status'), balance)
if balance and float(balance) < 1:
client.messages.create(from_=number_from,
to=number_to,
body="\nRemaining balance is less than $1.")
with open(flag_location,'w') as f: f.write("flag")
else: print("Balance is: %f" % float(balance))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment