##############################################################################
# save this script to peerbetsatoshibot.py                                   #
#                                                                            #
# TO RUN IT USE THIS CODE                                                    #
# python -u peerbetsatoshibot.py USERNAME PASSWORD                           #
# PLEASE DONATE SOME TO: 1FpHgWtpQ5bynPpvNXsWbDQNqv6zWJgBv7                  #
##############################################################################
import cookielib, urllib2,urllib,random,time,sys,traceback,StringIO,gzip

def call(opener,url,params=None):
	time.sleep(1)
	url=url+'&compress=1'
	if params is not None:
		uri=url+"&"+params
	else: uri=url
	try:
		opener.addheaders=[("Accept-Encoding", "gzip")]
#		print uri
		f=opener.open(uri)
		response=f.read()
	except urllib2.URLError:
		time.sleep(random.uniform(1,5))
		return call(opener,url,params)
	read=f.info().getheader("Content-Encoding")
	if read=='gzip':
		sio =  StringIO.StringIO(response)
		sio.seek(0)
		gz=gzip.GzipFile(None,mode='rb',fileobj=sio)
		
		response= gz.read()
		gz.close()
		sio.close()
#	print response
	if response is None:
		return call(opener,url,params)			
	else:	
		try:
			read=eval(response)
		except:
			print '>>> traceback <<<'
			traceback.print_exc()
			print '>>> end of traceback <<<'
			time.sleep(random.uniform(1,5))
			return call(opener,url,params)							

		error=None
		try:
			error= read['error']
			print "|",error,"|"
		except:
			return read
		if 'limit' in str(error):
			time.sleep(random.uniform(1,5))
			return call(opener,url,params)
		else: raise NameError(error)	

def login(opener):
	global password
	global username
	params = urllib.urlencode({'username': username, 'password': password})
	print "login",call(opener,'https://peerbet.org/api.php?method=login',params)


if sys.argv[1] is not None: username=sys.argv[1]
if sys.argv[2] is not None: password=sys.argv[2]



while True:
	try:
		cj = cookielib.CookieJar()
		opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
		params = urllib.urlencode({'username': username, 'password': password})
		print call(opener,"https://peerbet.org/api.php?method=login",params)


		params = urllib.urlencode({'message': 'satoshi'})
		
		message=call(opener,"https://peerbet.org/api.php?method=postchatmessage",params)
		print message['message_id'];

	except:
		print '>>> traceback <<<'
		traceback.print_exc()
		print '>>> end of traceback <<<'
	time.sleep(random.uniform(60*60,2*60*60))
