Guest User

freedompop telegram bot

a guest
Dec 28th, 2016
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.97 KB | None | 0 0
  1. import json
  2. import time
  3.  
  4. import requests
  5.  
  6. import config
  7. import utils
  8.  
  9.  
  10. class FreedomPop(object):
  11.     username = None
  12.     password = None
  13.  
  14.     access_token = None
  15.     refresh_token = None
  16.     token_expires = 0
  17.  
  18.     api_base = 'https://api.freedompop.com'
  19.     api_username = None
  20.     api_password = None
  21.  
  22.     def __init__(self):
  23.         self.username = config.FREEDOMPOP_USER
  24.         self.password = config.FREEDOMPOP_PASSWORD
  25.  
  26.         self.api_username = config.FREEDOMPOP_API_USER
  27.         self.api_password = config.FREEDOMPOP_API_PASSWORD
  28.  
  29.     def _update_token(self):
  30.         if time.time() < self.token_expires:
  31.             return  # no new token necessary
  32.  
  33.         url = self.api_base + '/auth/token'
  34.         auth = config.FREEDOMPOP_API_USER, config.FREEDOMPOP_API_PASSWORD
  35.  
  36.         if self.refresh_token is None:
  37.             # no refresh_token, this is the first time we log in
  38.             utils.logger.info('Obtaining a completely new access token.')
  39.             params = {'grant_type': 'password',
  40.                       'username': self.username,
  41.                       'password': self.password}
  42.             response = requests.post(url, auth=auth, params=params)
  43.             data = json.loads(response.content.decode('utf8'))
  44.         else:
  45.             # there's a refresh_token, use it to regenerate the access_token
  46.             utils.logger.info('Refreshing the current access token.')
  47.             params = {'grant_type': 'refresh_token',
  48.                       'refresh_token': self.refresh_token}
  49.             response = requests.post(url, auth=auth, params=params)
  50.             data = json.loads(response.content.decode('utf8'))
  51.  
  52.         self.access_token = data['access_token']
  53.         self.refresh_token = data['refresh_token']
  54.         self.token_expires = time.time() + int(data['expires_in'])
  55.  
  56.         utils.logger.info('New token obtained successfully.')
  57.  
  58.     def _make_request(self, endpoint, params={}, method='GET', data=None,
  59.                       files=None):
  60.         if method not in {'GET', 'POST'}:
  61.             raise ValueError('method not supported: %s' % method)
  62.         if method != 'POST' and (data is not None or files is not None):
  63.             raise ValueError('cannot post files/data with method %s' % method)
  64.  
  65.         self._update_token()
  66.  
  67.         url = self.api_base + endpoint
  68.         auth = config.FREEDOMPOP_API_USER, config.FREEDOMPOP_API_PASSWORD
  69.         params['accessToken'] = self.access_token
  70.         params['appIdVersion'] = config.FREEDOMPOP_APP_VERSION
  71.         if endpoint == '/phone/device/config':
  72.             params['deviceId'] = config.FREEDOMPOP_DEVICE_ID
  73.  
  74.         utils.logger.info('Making a %s request to %s...' %
  75.                           (method, endpoint))
  76.  
  77.         if method == 'GET':
  78.             response = requests.get(url, params=params, auth=auth)
  79.         elif method == 'POST':
  80.             response = requests.post(url, params=params, auth=auth,
  81.                                      data=data, files=files)
  82.         utils.logger.info(response.content.decode('utf8'))
  83.  
  84.         utils.logger.info('Request finished.')
  85.  
  86.         return json.loads(response.content.decode('utf8'))
  87.  
  88.     #def action_get_sip_data(self, **kwargs):
  89.         #need device_meid and/or deviceSid for acces it (or take it from the original app db)
  90.    
  91.         #endpoint = '/phone/device/config'
  92.         #
  93.         #response = self._make_request(endpoint)
  94.         #                        
  95.         #msg = 'SIP data information: \n\n'
  96.         #msg += 'Username:\n%s\n\n' % response['username']
  97.         #msg += 'Password:\n%s\n\n' % response['password']
  98.         #msg += 'Server:\n%s\n\n' % response['server']
  99.         #return msg
  100.  
  101.     def action_get_usage(self, **kwargs):
  102.         endpoint = '/user/usage'
  103.         response = self._make_request(endpoint)
  104.  
  105.         # base_bandwidth = response['baseBandwidth']
  106.         # offer_bonus_earned = response['offerBonusEarned']
  107.         total_limit = response['totalLimit']
  108.         percent_used = response['percentUsed']
  109.         balance_remaining = response['balanceRemaining']
  110.         #
  111.         used = total_limit - balance_remaining
  112.  
  113.         msg = 'Data plan usage information:\n\n'
  114.         msg += ('You have used %d MB (%.1f%%) out of your plan of %d MB.\n\n' %
  115.                 (utils.b_to_mb(used), percent_used,
  116.                  utils.b_to_mb(total_limit)))
  117.  
  118.         endTime = response['endTime'] / 1000
  119.         timeRemaining = endTime - time.time()
  120.         daysRemaining = timeRemaining / 86400
  121.         hoursRemaining = timeRemaining % 86400 / 3600
  122.         minutesRemaining = timeRemaining % 3600 / 60
  123.         msg += ('Time until quota reset:')
  124.         if daysRemaining > 0:
  125.             msg += (' %d days' %
  126.                 (daysRemaining))
  127.         if hoursRemaining > 0:
  128.             msg += (' %d hours' %
  129.                 (hoursRemaining))
  130.         if minutesRemaining > 0:
  131.             msg += (' %d minutes' %
  132.                 (minutesRemaining))
  133.  
  134.         return msg
  135.  
  136.     def action_get_balance(self, **kwargs):
  137.         endpoint = '/phone/balance'
  138.         response = self._make_request(endpoint)
  139.  
  140.         msg = 'Plan balance information:\n\n'
  141.         for plan in response:
  142.             if plan.get('voicePlanType') != 'MAIN':
  143.                 continue
  144.  
  145.             msg += 'Plan "%s":\n' % plan['name']
  146.             msg += '* Price: %.2f\n' % plan['price']
  147.             if plan.get('unlimitedVoice', False):
  148.                 msg += '* Unlimited calls\n'
  149.             else:
  150.                 msg += ('* Calls: %d min (%d min remaining)\n' %
  151.                         (utils.s_to_m(plan['baseSeconds']),
  152.                          plan['balance']['remainingMinutes']))
  153.             if plan.get('unlimitedData', False):
  154.                 msg += '* Unlimited data\n'
  155.             else:
  156.                 msg += ('* Data: %d MB remaining\n' %
  157.                         utils.b_to_mb(plan['balance']['remainingData']))
  158.             if 'baseSMS' in plan:
  159.                 msg += ('* SMS: %d (%d remaining)\n' %
  160.                         (plan['baseSMS'], plan['balance']['remainingSMS']))
  161.             msg += '\n'
  162.  
  163.         return msg
  164.  
  165.     def action_get_sms(self, **kwargs):
  166.         endpoint = '/phone/listsms'
  167.         response = self._make_request(endpoint)
  168.        
  169.         msg = 'Reading sms...\n'
  170.         for sms in response['messages']:
  171.             msg += '\n\nFrom: %s\n' % sms['from']
  172.             msg += '%s' % sms['body']
  173.         return msg
  174.  
  175.     def action_send_sms(self, **kwargs):
  176.         endpoint = '/phone/sendsms'
  177.         destination, text = kwargs['destination'], kwargs['text']
  178.         data = {'to_numbers': destination, 'message_body': text}
  179.         files = {'media_file': (None, 'none')}
  180.  
  181.         response = self._make_request(endpoint, method='POST', data=data,
  182.                                       files=files)
  183.  
  184.         if not response.get('groupId'):
  185.             return 'SMS not sent. Check the number and try again.'
  186.         else:
  187.             return 'SMS sent.'
  188.  
  189.  
  190. freedompop = FreedomPop()
Add Comment
Please, Sign In to add comment