Python Forum
Noob Needs Help with almost finished script will pay
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Noob Needs Help with almost finished script will pay
#1
I have a Program that a friend made me and it has stopped working im just getting into python so I need help. I am willing to pay for your time. it currently uses
import httplib, urllib, json, time, sys, os, re, random, requests
from datetime import datetime
from datetime import timedelta
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning


Using python 2.7
Reply
#2
If you shared the entire code (with code tags), and explained what problem you're having, you'd probably be more likely to get relevant replies.

Just curious, why not ask your friend for help?
Reply
#3
post the code and what error you get now that you didnt before an people might post the issue for free
Recommended Tutorials:
Reply
#4
The token or 0Auth2 code I dont think is logging me in anymore I need help checking why this wont connect anymore Pm me if you think you can help please

MAIN PROGRAM

import httplib, urllib, json, time, sys, os, re, random, requests
from datetime import datetime
from datetime import timedelta
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

AREAS = {
"serviceAreaNameAndIdList": [{
"id": "09d80462-468a-4c4f-b14c-2314369ff6b6",
"name": "Berkeley - Restaurants"
}, {
"id": "290a3e5d-b9fe-4945-b2b5-9b431fe987dc",
"name": "Sunnyvale (UCA7)"
}, {
"id": "39b248a5-ecd8-4ce5-b676-0b4cabe5621d",
"name": "Berkeley (UCA8)"
}, {
"id": "7ea13a08-d82f-4652-9434-29fbe7a46163",
"name": "San Jose - Restaurants"
}, {
"id": "9949bc80-3c56-4e98-ad0a-1152c5e15d3f",
"name": "San Francisco - Restaurants"
}, {
"id": "9abe08d0-7c2c-4f24-8013-e14268d72059",
"name": "San Francisco (UCA1)"
}]
}

SOUNDS = {
'404': 'afplay /System/Library/Sounds/Sosumi.aiff',
'success': 'afplay /System/Library/Sounds/ping.aiff',

}

try:
import ssl
except ImportError:
print "error: no ssl support"

def readHeadersFromFile():
headers = {}
f = open('charles_header.txt', 'r')
if f is None:
print "File headers is not found"
return headers

for line in f:
m = re.search('([^:]+):([^\n\r]+)', line)
if m is None:
print "File headers is wrong format"
return headers
headers[m.group(1).strip()] = m.group(2).strip()
return headers

def readCookies(str):
cookies = {}
m = re.search('([^;\s]+;[^;\s]+)', str)
if m is None:
return cookies
for pair in m.groups():
m1 = re.search('([^=\s]+=[^=\s]+)', pair)
if m1 is not None:
cookies[m1.group(1).strip()] = m1.group(2).strip()
return cookies


params = urllib.urlencode({'serviceAreaIds': '39b248a5-ecd8-4ce5-b676-0b4cabe5621d'})
session = requests.Session()
session.headers = {}
session.verify = False
_count = -1
_content = ''
_icloud = ''
_previousNotification = None
_filteredOffers =

_logfile = None
def Log(s):
global _logfile
if _logfile is None :
_logfile = open('amazon_log.log', 'a')
_logfile.write("[{0}] >> {1}\n".format(str(datetime.now()), str(s) ))


def update(val):
global _count
global _content
dot = ''
_count = (_count+1)%3
if _count == 0:
dot = '.'
else:
if _count == 1:
dot = '..'
else :
dot = '...'

if val is not None:
time = str(datetime.now())
_content += "[{0}] >> {1}\n".format(time, val)

os.system('cls' if os.name == 'nt' else 'clear')

print("{0}\n{1}".format(_content, dot))



def beep():
if os.name != 'nt':
os.system('afplay /System/Library/Sounds/Sosumi.aiff')

def beep(status):
if os.name != 'nt':
os.system(SOUNDS[status])

def beep_loop(status):
for i in range(1, 1000000):
os.system(SOUNDS[status])


def setupIcloud() :
from pyicloud import PyiCloudService

api = PyiCloudService('My email', 'My password')
global _icloud

if api.requires_2fa :
import click
print "Two-factor authentication required. Your trusted devices are:"
devices = api.trusted_devices
for i, device in enumerate(devices):
print " %s: %s" % (i, device.get('deviceName', "SMS to %s" % device.get('phoneNumber')))

device = click.prompt('Which device would you like to use?', default=0)
device = devices[device]
if not api.send_verification_code(device):
print "Failed to send verification code"
sys.exit(1)

code = click.prompt('Please enter validation code')
if not api.validate_verification_code(device, code):
print "Failed to verify verification code"
sys.exit(1)

_icloud = api



def notifyIphone() :
#Temporary close
return True
global _previousNotification
global _icloud

try:
now = datetime.now()

if _previousNotification is not None and (now - _previousNotification).seconds < 1800 :
pass
else :
_icloud.iphone.play_sound()
_previousNotification = now
except Exception, e:
update("notifyIphone: %s" %e)
Log("notifyIphone: %s" %e)





def acceptOrders(offers):
global session
result = False

for offer in offers:
data = {'offerId': offer['offerId']}
res = session.post("https://flex-capacity-na.amazon.com/AcceptOffer", json=data)
status_code = res.status_code
res.close()
if status_code == 200:
begin = datetime.fromtimestamp(offer['startTime'])
end = datetime.fromtimestamp(offer['endTime'])
update("OK ${0} {1}-{2}".format(offer['rateInfo']['priceAmount'], begin.strftime('%I%p'), end.strftime('%I%p')))
result = True
else:
update("FAILED {3} ${0} {1}-{2}".format(offer['rateInfo']['priceAmount'], begin.strftime('%I%p'), end.strftime('%I%p'), status_code))
return result


def rankingOffers(offers):
offers.sort(cmp = lambda x,y: int(y['rateInfo']['priceAmount'] - x['rateInfo']['priceAmount']) if int(y['rateInfo']['priceAmount'] - x['rateInfo']['priceAmount']) != 0 else int(x['startTime'] - y['startTime']))

def isOfferInShift(offer) :
try :
startTime = datetime.fromtimestamp(offer['startTime'])
startDate = startTime.date()
endDate = startDate + timedelta(days=1)
global session
params = {'startDate': int(startDate.strftime("%s")), 'endDate': int(endDate.strftime("%s"))}
res = session.get("https://flex-capacity-na.amazon.com/schedule", params=params)
status_code = res.status_code
if status_code == 200 :
items = res.json()['scheduleItems']
for shift in items :
pickUpTime = datetime.fromtimestamp(shift['timeBlock']['pickUpTime'])
end = pickUpTime + timedelta(hours=shift['timeBlock']['durationInHours'])
if startTime == end :
return True
return False
except Exception as e:
Log("isOfferInShift: %s" % e)
update("isOfferInShift: %s" % e)
return False

def filterOffers(offers):

try :
f = open('filter_offers.json', 'r')
if f is None:
return offers
filter = json.loads(f.read())
if filter is None or not filter:
return offers

global _filteredOffers
result =
excluded_dates = [datetime.strptime(date, "%Y/%m/%d").date() for date in filter['excluded_dates']]
excluded_hours = [datetime.strptime(hour, "%I%p").time() for hour in filter['excluded_hours']]
excluded_weekdays = [weekday.lower() for weekday in filter['excluded_weekdays']]
excepted_hours = [e.lower() for e in filter['excepted_hours']]

for offer in offers:
startTime = datetime.fromtimestamp(offer['startTime'])
endTime = datetime.fromtimestamp(offer['endTime'])

#accept excepted hours
if startTime.strftime("%a %I%p").lower() in excepted_hours :
result.append(offer)
continue

#inogre offers was taken to be filterd
if offer['offerId'] in _filteredOffers :
continue

#filter dates
if startTime.date() in excluded_dates or startTime.replace(minute=0).time() in excluded_hours or startTime.strftime("%a").lower() in excluded_weekdays:
Log("Offers filterd due to excluded_*")
update("FILTERED ${0} {1}-{2}".format(offer['rateInfo']['priceAmount'], startTime.strftime('%I:%M%p'), endTime.strftime('%I:%M%p')))
_filteredOffers.append(offer['offerId'])
elif (endTime-startTime).seconds <= 3600 :
if isOfferInShift(offer) :
Log("Offers accepted due to 1 hour continuosly")
result.append(offer)
else :
Log("Offers filterd due to gaps time too big (> 1)")
_filteredOffers.append(offer['offerId'])
update("FILTERED ${0} {1}-{2}".format(offer['rateInfo']['priceAmount'], startTime.strftime('%I:%M%p'), endTime.strftime('%I:%M%p')))
else :
result.append(offer)

return result
except Exception as e:
print("filterOffers: %s" % e)
return offers


def getIdentityFromFile():
try :
with open('amazon_id.json') as f :
data = json.loads(f.read())
return data
except:
print "Failed to get access token from file"
return False

def login():
url = 'https://api.amazon.com/auth/register'
data = getIdentityFromFile()
global session
session.headers = {}
res = session.post(url, json=data, headers={'Content-Type':'application/json'}, verify=True)

result = False
if res.status_code == 200 :
result = res.json()['response']['success']
else :
update("Login failed: %(code)s\nDetail:%(detail)s" % {'code':res.status_code,
'detail': res.json()})

res.close()
return result

def saveTokens(tokens) :
try :
with open('tokens.json', 'w') as outfile:
json.dump(tokens, outfile)
except Exception as e :
print "Save tokens: %s" % e
return False

return True


def loadTokens():
result = False
try :
with open('tokens.json', 'r') as inputfile:
result = json.loads(inputfile.read())
except Exception as e:
print "Load Tokens: %s" % e

return result


def refreshToken(refesh_token) :
url = 'https://api.amazon.com/auth/token'
data = {
"source_token": refesh_token,
"source_token_type":"refresh_token",
"requested_token_type":"access_token",
"app_name":"com.amazon.rabbit"
}
global session
res = session.post(url, json=data)

result = False
if res.status_code == 200 :
result = res.json()
result = result["access_token"]
else :
print "Refresh Token: %s" % res.json()

return result

def lookForOffers(endpointOrdinal):
global session
endpoints = [{'serviceAreaId':'09d80462-468a-4c4f-b14c-2314369ff6b6', 'name':'Berkeley Restaurants'},
{'serviceAreaId':'39b248a5-ecd8-4ce5-b676-0b4cabe5621d', 'name':'Berkeley UC8'}]

url = 'https://flex-capacity-na.amazon.com/GetOffersForProvider'
result = False
try:
params = urllib.urlencode({'serviceAreaIds': endpoints[endpointOrdinal]['serviceAreaId']})
res = session.get(url, params=params)
resData = res.json()
status_code = res.status_code
result = {'status_code': status_code, 'data': resData}
res.close()
except Exception as e :
update("lookForOffers: %s" % e)

return result

indexer = {'current':0, 'next':1}
tokens = loadTokens()
if tokens :
session.headers['x-amz-access-token'] = tokens['access_token']

#check identity file
if type(getIdentityFromFile()) is not dict:
sys.exit()



endpoints = [{'serviceAreaId':'09d80462-468a-4c4f-b14c-2314369ff6b6', 'name':'Berkeley Restaurants'},
{'serviceAreaId':'39b248a5-ecd8-4ce5-b676-0b4cabe5621d', 'name':'Berkeley UC8'}]

while 1:
if indexer['next'] == 0 :
time.sleep(random.random()+0.5)

update(None)

try:
offerRes = lookForOffers(indexer['current'])

if not offerRes :
continue

#swap index
next = indexer['next']
indexer['next'] = indexer['current']
indexer['current'] = next

if offerRes['status_code'] == 403 : #No access token OR expired
update('Access Token expired OR not found. Try refesh...')
tokens = loadTokens()
if tokens : #Have a refresh token
tokensResult = refreshToken(tokens['refresh_token'])
if tokensResult : #refresh token success
tokens['access_token'] = tokensResult
session.headers['x-amz-access-token'] = tokens['access_token']
saveTokens(tokens)
continue
else : #try to login
loginResult = login()
if loginResult : #login success
tokens = loginResult['tokens']['bearer']
saveTokens(tokens)
session.headers['x-amz-access-token'] = tokens['access_token']
continue
else : #login failed
print 'Login failed'
beep('404')
break
else : #Try to login
loginResult = login()
if loginResult : #login success
tokens = loginResult['tokens']['bearer']
saveTokens(tokens)
session.headers['x-amz-access-token'] = tokens['access_token']
continue
else : #login failed
print 'Login failed'
Log('Login failed')
beep('404')
break

else :
if offerRes['status_code'] != 200 :
print status_code
beep('404')
break

d = offerRes['data']
if len(d['offerList']) > 0:
filteredOffers = filterOffers(d['offerList'])
rankingOffers(filteredOffers)
if acceptOrders(filteredOffers) :
Log("Access offers: %s" % filteredOffers)
notifyIphone()
beep('success')
except requests.exceptions.ConnectionError:
update("Connection Error. It's OK. Still running")
Log("Connection Error. It's OK. Still running")
except Exception as e:
update("Something wrong")
Log("Something wrong: %s" %e)
print "%s" % e
break

os.system("shutdown -h now")




TOKEN
{"access_token": "Atna|EwICINg5W-n16LueSZZmVOtelQb6dbaiTRblpn5Fnk8XgqOpGscvBwORlwwY0EulQAnCZ-fL92whKU8AZ2syjj5obEnzs5kGaa2KrU6HdGWmcZw-jbQLYhdbez2nJkcDrz7ws6me-RoPPOCZzVVFCIx7Y_SK2HhCJtyMr5n7Se9FhcEif8p53FpO5zufNoFQb70rqe1P_5CrYv3LdYtTfEjQMU9pJ6I_Z8ulHu4ctGuII6jz4LmSINN9XtB2QJp3OWaXC4faQG2XEM7aAAYgRe-ZEFbmWvwhy_rSJAwRmxdrm--mOoBmghWf8IjRvTKLxPUOPKss17Z3wqC_AWOMVHYehWA2YHd2HmcP6lekrH3_cJkmDA", "expires_in": "3600", "refresh_token": "Atnr|EwICII4XltNEklY8KLZjvQ7jEU6bTYAdtDTpp8QC4e63NTPC3snxo5Dm39Hg31A5DRNmX1Nv9-U9xU3TkoNIL7SZW49C7yNG0UQEwkB8WcxVN-4np-f91Z_bkVL5uDSaA82az-mQgQ4Vr1vUq08mbPNwGyQhlS42l7P4dkqiXgPswVXSjGXjCY5jPsc5oGHKSYngDFsXkxY9klgDH3WRQ60SuSYUZt92uR3b_eR48x9iZIpeHXJSEo59sRLQBSSft25tcmrMwt64bTFPIrTveB8fmhIFC96xUBlPJjTgFLV-90SnttYC8BBCg2EnuRh_3yPzTD95KFXUvNY6Y22KnaiZvTEO"}


Amazon_id File
{"auth_data":{"use_global_authentication":"true","user_id_password":{"user_id":"MY_EMAIL","password":"MYPASSWORD"}},"registration_data":{"domain":"Device","device_type":"A1MPSLFC7L5AFK","device_serial":"ecada8a3ee8d4b36904024f8d9dde9af","app_name":"com.amazon.rabbit","app_version":"303338310","device_model":"Le X522","os_version":"LeEco\/Le2_NA\/le_s2_na:6.0.1\/IFXNAOP5801910272S\/61:user\/release-keys","software_version":"130050002"},"requested_token_type":["bearer","mac_dms","store_authentication_cookie","website_cookies"],"cookies":{"domain":".amazon.com","website_cookies":},"user_context_map":{"frc":"AGZV+D3BgIDqKBml5vNK+y\/j\/LleoaKQqZLxr6s72zpsbqBXEefMvBCJcwxTrp6FbY\/oG8iQtGPp9A4NGUuhKbb2zV2W7yhPh\/RCt1f0g7fw8wt4MShPJM+aXEqQdlUmMF5uoLMws4CxKbuswKFciSxVy7YMUnHbOi1OcI5v8iheMhGx9V\/pyw5d\/mDoz0l1y1Y9ZN4HwfKPLRrGGm7HbzQehx6pMxdNoGjKUcw30esMNHkL+nXpyZ0RaIgBZNHlRJoxZlRt2KEkOL413OWFbCjzz8QhNDNG3UpM1KkvLpOMd6iWbuKsf8cuHZfUo27hWY51uPgTjhFxE3YZebf+vPgv7mEQU3LVhDYuNu83TWUFyu6GAbaZ19XbyD\/UKc\/iVKHxjxs9Q8XvPr2EsZKCRTk5WR3xwqOBgT0YO8\/9oyE2i\/iX+jTcwuo="},"device_metadata":{"device_os_family":"android","device_type":"A1MPSLFC7L5AFK","device_serial":"ecada8a3ee8d4b36904024f8d9dde9af","mac_address":"C248C629AF1FE0A8C46B95668064C1D2952A9E91D207BC0CC3C5D584C2F7553A","imei":"8DD91594C487CB2F6C47DAF4EF22760484FC2C80A34138E128625B7D60F30BA6","manufacturer":"LeMobile","model":"Le X522","os_version":"23","android_id":"52aee8aecab31ee3","build_serial":"1706dc04","product":"Le2_NA"},"requested_extensions":["device_info","customer_info"]}
Reply
#5
os.system("shutdown -h now")
hmmm...looks mighty suspicious
When my code doesn't work I don't know why **think** and when my code works I don't know why **think**
Reply
#6
How does it not work? Don't produce an output or unexpected one, prints an error? See the moderator's comment at the bottom of your topic
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#7
What is supposed to do, 1 use 0auth2 token to connect to amazons server log in with username and password then it searches for shifts (amazon flex is a job app for amazon) once it sees a shift it accepts it. What it currently does is just turn on but not pick up any shifts and the 401 error code thats says it did not connect does not come up so I don't know what is wrong. I have the files with my email and password in the code if anyone is willing to take a crack at it. will pay 200$ if you can get it working again, I also have the job app it takes the web addresses from.
Reply
#8
(Dec-17-2017, 07:11 AM)dirty794 Wrote: buran wrote 10 hours ago: Please, use proper tags when post code, traceback, output, etc. See BBcode help for more info.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#9
Did anyone get to fix this I'm willing to pay for this to be fixed too.
Reply
#10
(Feb-13-2020, 06:15 PM)Dulcitab2018 Wrote: Did anyone get to fix this I'm willing to pay for this to be fixed too.

Hello,
Greetings

I'd Glad to assist you.
Email Sent, Please Check.

Very Best Regards
Carter W
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020