Skip to content

Instantly share code, notes, and snippets.

@holachek
Created September 14, 2012 01:12
Show Gist options
  • Save holachek/3719183 to your computer and use it in GitHub Desktop.
Save holachek/3719183 to your computer and use it in GitHub Desktop.
Virgin Mobile Minute Checker Python 3 Program

Virgin Mobile Minute Texter

Never go over your minutes again

Introduction

The Virgin Mobile Minute Texter is a simple Python script that scrapes your data from Virgin Mobile's website and sends you a text with your remaining minutes. Currently only works on the Virgin Mobile USA site.

Setup

First, make sure you have Python 3 installed by typing which python3 in a terminal. If you see something like /usr/local/bin/python3, you're good to go. If you see an error, install Python 3.

Go to https://sendhub.com and register for a free account. You'll use this service to send text messages to your phone. The free plan lets you send up to 1000 messages and 500 API requests a month. Copy your API Key from the Settings page.

Now download the script and modify your details:

Virgin Mobile Account Details

VIRGINMOBILEACCOUNT = {'min':1235551234, 'vkey':0000}

Replace with your Virgin Mobile account phone number and PIN.

Message Recipent

MESSAGETO = 13015551234

The number (with country code) that will receive the text message.

SendHub Number

SENDHUBNUMBER = 7035551234

The phone number you used to sign up on SendHub. This is NOT the number that SendHub gave you.

SendHub API Key

SENDHUBAPIKEY = "apikeygoeshere"

Paste in the API Key here.

Run

Now that everything is configured, run the script manually by typing:

python3 VM.py run

This will run the check and send a text message regardless of how many minutes are remaining. (Leave out the run for it to only send a text if you're low on minutes or if it's Sunday.) You should see output like this:

Logging in to Virgin Mobile.
Request finished.
You have 230 minutes remaining and 21 daysLeft on your plan.
...

Security

Both requests to Virgin Mobile and SendHub use HTTPS, so they should be secure. At the moment, I have not programmed a way to obfuscate the sensitive Virgin Mobile account information at the beginning of the script. This will be my goal in coming revisions.

Automation

Now that it works, you can set it up on a server (or just your local machine) to check periodically for low minutes. One way to do this could be using cron, by adding something like this to your crontab file: 0 8,20 * * * python3 VM.py This will trigger the script every day at 8AM and 8PM.

Troubleshooting

If something doesn't work right, please contact me.

#!/usr/local/bin python3
### Python 3 Virgin Mobile Minute Texter
### by Michael Holachek
### Version 1.1
import sys
import re
import json
import datetime
import urllib.request as req
import urllib.parse as parse
# specify your SendHub and Virgin Mobile account details here
VIRGINMOBILEACCOUNT = {'min':1235551234, 'vkey':0000} # Virgin Mobile phone # and PIN
MESSAGETO = 13015551234 # number we want to send text message to
SENDHUBNUMBER = 7035551234 # the number you used to sign up on SendHub (NOT the SendHub number)
SENDHUBAPIKEY = "apikeyhere" # API Key from https://www.sendhub.com/settings
def main():
# check first command line argument
modeArg = str(sys.argv[1])
now = datetime.datetime.now()
VirginMobileHTML = VirginMobileLogin()
Data = Calculations(VirginMobileHTML)
minutesRemaining = Data[0]
daysLeft = Data[1]
# no need to send texts everytime it checks
# only send one if it is Sunday, you have less than an hour on your plan,
# or you're running this manually
if now.weekday() == 6 or minutesRemaining <= 60 or modeArg == "run":
preMessage = LowMinuteCheck(minutesRemaining)
ContactId = FindContactId()
SendTextMessage(ContactId, preMessage, minutesRemaining, daysLeft)
def VirginMobileLogin():
# connect to Virgin Mobile's site and login
print("Logging in to Virgin Mobile.")
URLdata = req.Request("https://www1.virginmobileusa.com/login/login.do", parse.urlencode(VIRGINMOBILEACCOUNT).encode('utf-8'), {"Content-Type": "application/x-www-form-urlencoded"})
page = req.urlopen(URLdata)
print("Request finished.")
return page.read()
def Calculations(html):
# let's calculate the remaining minutes
minutesUsed = int(re.findall(b'<p id="remaining_minutes"><strong>([0-9]+)',html, re.I)[0])
minutesTotal = int(re.findall(b'<th>Anytime Minutes</th><td>([0-9]+)',html, re.I)[0])
minutesRemaining = minutesTotal - minutesUsed
# and also the remaining days in the plan
now = datetime.datetime.now()
chargeDate = int(re.findall(b'<li id="charge_date"><h3>You will be charged on</h3><p>([0-9]+)',html, re.I)[0])
daysLeft = now.day - chargeDate
print("You have {0} minutes remaining and {1} daysLeft on your plan.".format(minutesRemaining, daysLeft))
return minutesRemaining, daysLeft
def LowMinuteCheck(minutesRemaining):
# if you are low on minutes, add a special warning
if minutesRemaining < 60:
return "Uh oh!\n"
else:
return ""
def FindContactId():
# first, search SendHub contact list with number to find contact id
print("Attempting to find phone number {0} in your SendHub contacts list.".format(MESSAGETO))
contactList = req.urlopen("https://api.sendhub.com/v1/contacts/?username={0}&api_key={1}".format(SENDHUBNUMBER, SENDHUBAPIKEY))
contactListData = json.loads(contactList.read().decode('utf-8'))
for contact in range(len(contactListData['objects'])):
contactNumber = int(re.sub(r'\D+', '', contactListData['objects'][contact]['number']))
print(contactNumber)
if contactNumber == int(MESSAGETO):
print("Found it!")
return contactListData['objects'][contact]['id']
# make a new SendHub contact if number cannot be found
print("Sorry, I couldn't find that number in your SendHub contacts.\nI will attempt to make it.")
POSTdata = {"name":"MinuteCheck Contact","number":MESSAGETO[1:]}
URLdata = req.Request("https://api.sendhub.com/v1/contacts/?username={0}&api_key={1}".format(SENDHUBNUMBER, SENDHUBAPIKEY), json.dumps(POSTdata).encode('utf-8'), {"Content-Type": "application/json"})
page = req.urlopen(URLdata)
response = json.loads(page.read())
page.close()
print("Good to go! I created the new contact (Contact ID {0} successfully.".format(response['id']))
return response['id']
def SendTextMessage(ContactId, preMessage, minutesRemaining, daysLeft):
# now compose a text message and send you the details via SMS
sendToNumber = FindContactId()
print("I will now send a text message to {0} (Contact ID {1})".format(MESSAGETO, ContactId))
POSTdata = {"contacts":[ContactId],"text":"{0}{1} minutes remaining.\n{2} days left this period.".format(preMessage,minutesRemaining,daysLeft)}
request = req.Request("https://api.sendhub.com/v1/messages/?username={0}&api_key={1}".format(SENDHUBNUMBER, SENDHUBAPIKEY), json.dumps(POSTdata).encode('utf-8'), {"Content-Type": "application/json"})
page = req.urlopen(request)
response = json.loads(page.read().decode('utf-8'))
print("SMS Sent!")
page.close()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment