Advertisement
ChrisProsser

product_available.py

Oct 10th, 2013
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.13 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. # send_sms and send_email are also available from http://pastebin.com/u/ChrisProsser
  4. import os, sys, urllib, datetime as dt, time, send_sms, send_mail, traceback
  5.  
  6. # globals
  7. # example here checking for availability of Google Nexus 4, change globals in <>
  8. products = ['Nexus 4 - 16GB', 'Nexus 4 - 8GB']
  9. # if an entry in the check strings is found in the html then it is found to be out of stock
  10. check_strings = ['We are out of stock',
  11.                  'This device is not for sale at this time',
  12.                  'main_page_js_compiled_main_page_js__en_gb.js']
  13. urls = ['https://play.google.com/store/devices/details/Nexus_4_16_GB?id=nexus_4_16gb&hl=en_GB',
  14.         'https://play.google.com/store/devices/details/Nexus_4_8_GB?id=nexus_4_8gb&hl=en_GB']
  15. program = os.path.split(sys.argv[0])[1]
  16. # email account to send from (gmail for this email module) with base 64 encoded pwd
  17. email_sender, enc_pwd = '<[email protected]>', '<base64encpwd>'
  18. email_recipient = '<email_recipient@whoever>'
  19. # use details from send_sms account
  20. sms_account, sms_sender = '<account_name>', '<sender>'
  21. mobile_nos = '447504750054' #string with no spaces, comma separated
  22. log_file_path = 'prod_available_log.csv'
  23.  
  24. def log(param, progress, exit=False):
  25.     log_file = open(log_file_path, 'a')
  26.     info = ', '.join((program, dt.datetime.now().strftime("%Y-%m-%d"),
  27.                       dt.datetime.now().strftime("%H:%M:%S"), param, progress, '\n'))
  28.     log_file.write(info)
  29.     if exit:
  30.         sys.exit(progress)
  31.     log_file.close()
  32.  
  33. def check(product_name, url):
  34.     try:
  35.         html = urllib.urlopen(url).read()
  36.     except:
  37.         if logging_on:
  38.             err = 'Error opening URL'
  39.             log(product_name, err, True)
  40.  
  41.     in_stock = True
  42.     for entry in check_strings:
  43.         if entry in html or not html:
  44.             in_stock = False
  45.  
  46.     if not in_stock:
  47.         log(product_name, 'Out of stock')
  48.     else:
  49.         try:
  50.             msg = product_name + ' may be available now, check on ' + url
  51.             send_sms.main(msg, mobile_nos, sms_account, sms_sender)
  52.         except:
  53.             exc_type, exc_value, exc_traceback = sys.exc_info()
  54.             lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
  55.             err = 'Error sending email: ' + ''.join('!! ' + line for line in lines)
  56.             log(product_name, err, True)
  57.         else:
  58.             log(product_name, 'In stock! SMS sent.')
  59.             try:
  60.                 f = open('prod_available.html', 'wb')
  61.                 f.write(html)
  62.             except:
  63.                 pass
  64.        
  65.         # break loop once product is available
  66.         return True
  67.    
  68.     return False
  69.  
  70. def send_update():
  71.     subject = 'Daily ' + program + ' update'
  72.     try:
  73.         f = open(log_file_path, 'rb')
  74.         data = [line for line in f]
  75.         lines = len(data)
  76.         body = str(lines) + ' lines of data in log file so far, here are the last 10 lines:<br/>'
  77.         body += '<br/>'.join([line for line in data[-10:]])
  78.         f.close()
  79.     except:
  80.         exc_type, exc_value, exc_traceback = sys.exc_info()
  81.         lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
  82.         body = 'Error getting email body... ' + ''.join('!! ' + line for line in lines)
  83.     try:
  84.         send_mail.mail(email_sender, enc_pwd, email_recipient, subject, body, None)
  85.     except:
  86.         exc_type, exc_value, exc_traceback = sys.exc_info()
  87.         lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
  88.         err = 'Error sending update email!: '  + ''.join('!! ' + line for line in lines)
  89.         log(product_name, err, True)
  90.                                                          
  91. def main():
  92.     # set to pause for 2 mins after each run...
  93.     finished, delay, loops = False, 120, 0
  94.     update_interval = 86400 / delay
  95.     while not finished:
  96.         loops += 1
  97.         for i in range(len(urls)):
  98.             finished = check(products[i], urls[i])
  99.         if loops == 1:
  100.             send_update()
  101.         elif loops >= update_interval:
  102.             loops = 0
  103.         time.sleep(delay)
  104.  
  105. if __name__ == '__main__':
  106.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement