Guest User

p2pooltip.py

a guest
Jul 26th, 2014
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.96 KB | None | 0 0
  1. import time
  2. import praw
  3. import urllib.request
  4. import json
  5. import pymysql
  6.  
  7. # ---------------------------------------- CONFIGURATIONS ----------------------------------------
  8. ownerusername 'aaaaaaaaaaa' # Reddit username of bot owner
  9. walletIdentifier = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'   # blockchain.info wallet identifer
  10. walletPassword = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'     # blockchain.info wallet password
  11. dbuser = 'root'             # database username
  12. dbpass = 'aaaaaaaaaaaaaaaa' # database password
  13. dbdb = 'p2pooltip'          # database name
  14. # ------------------------------------------------------------------------------------------------
  15.  
  16. r = praw.Reddit(user_agent="bot by /u/{0}".format(ownerusername))
  17. r.login()
  18. already_done = []   # array containing messages already processed
  19.  
  20. # Return the first substring in a string between two search strings
  21. def find_between(s, first, last):
  22.     try:
  23.         start = s.index(first) + len(first)
  24.         end = s.index(last, start)
  25.         return s[start:end]
  26.     except ValueError:
  27.         return ""
  28.  
  29. # Return the last substring in a string between two search strings
  30. def rfind_between(s, first, last):
  31.     try:
  32.         start = s.rindex(first) + len(first)
  33.         end = s.rindex(last, start)
  34.         return s[start:end]
  35.     except ValueError:
  36.         return ""
  37.  
  38. # Return a p2pool sendmany for a given tip amount
  39. def getTipSendMany(amount):
  40.     response = urllib.request.urlopen('http://p2pool.org:9332/patron_sendmany/'+str(float(amount)/100000000))
  41.     sendmanybtc = json.loads(response.read().decode('ascii', 'ignore'))
  42.     sendmany = '%7B'
  43.     for key, value in sendmanybtc.items():
  44.         sendmany += '%22'+key+'%22%3A%20'+str(round(value*100000000))+'%2C%20'
  45.     sendmany = sendmany[:-6]+'%7D'
  46.     return sendmany
  47.  
  48. # Return a child comment from a post, containing the tip
  49. def getChildTipCommentFromPost(parent, tipper):
  50.     submission = r.get_info(thing_id=parent.parent_id)
  51.     for reply in submission.comments:
  52.         if reply.author.name == tipper:
  53.             return reply
  54.     return 0
  55.  
  56. # Return a child comment containing the tip
  57. def getChildTipComment(parent, tipper):
  58.     for reply in parent.replies:
  59.         if reply.author.name == tipper:
  60.             return reply
  61.     return 0
  62.  
  63. # Return previously processed commentid's from the database
  64. def loadFromDatabase():
  65.     conn = pymysql.connect(host='127.0.0.1', port=3306, user=dbuser, passwd=dbpass, db=dbdb)
  66.     cur = conn.cursor()
  67.     cur.execute('SELECT messageid FROM tips')
  68.     commentids = []
  69.     for r in cur.fetchall():
  70.         commentids.append(r[0])
  71.     cur.close()
  72.     conn.close()
  73.     return commentids
  74.  
  75. # Store information for a tip in the database
  76. def storeInDatabase(commentid, messageid, amount, sendamount, username, txid):
  77.     conn = pymysql.connect(host='127.0.0.1', port=3306, user=dbuser, passwd=dbpass, db=dbdb)
  78.     cur = conn.cursor()
  79.     cur.execute('INSERT INTO tips (commentid, messageid, amount, sent, username, txid) VALUES ("'+commentid+'", "'+messageid+'", '+str(amount)+', '+str(sendamount)+', "'+username+'", "'+txid+'")')
  80.     cur.close()
  81.     conn.commit()
  82.     conn.close()
  83.     return True
  84.  
  85. already_done.extend(loadFromDatabase()) # append previously processed commentid's to avoid processing them again
  86.  
  87. while True:
  88.     inbox = r.get_inbox()
  89.     for message in inbox:
  90.         if message.author.name == 'changetip':
  91.             if message.subject == 'You\'ve received a tip via ChangeTip':
  92.                 if message.id not in already_done:
  93.                     already_done.append(message.id)
  94.                     start = "The tip has been delivered, and "
  95.                     end = " is available in your"
  96.                     tip = rfind_between(message.body.encode('utf-8'), start.encode('utf-8'), end.encode('utf-8'))
  97.                     number = float(tip.split(' '.encode('utf-8'))[0].decode('ascii', 'ignore'))
  98.                     denomination = tip.split(' '.encode('utf-8'))[1]
  99.                     amount = 0
  100.                     if denomination == 'BTC'.encode('utf-8'):
  101.                         amount = round(number * 100000000)
  102.                     elif denomination == 'mBTC'.encode('utf-8'):
  103.                         amount = round(number * 100000)
  104.                     else: # denomination == microBTC
  105.                         amount = round(number * 100)
  106.                     parentIsPost = find_between(message.body.encode('utf-8').decode('ascii', 'ignore'), '[your post]', ')')[-1:] == '/'
  107.                     parentID = find_between(message.body.encode('utf-8').decode('ascii', 'ignore'), '/comments/', '/') if parentIsPost else rfind_between(find_between(message.body.encode('utf-8').decode('ascii', 'ignore'), '[your post]', ')')+').', '/', ')')
  108.                     thethingid = 't'+('3' if parentIsPost else '1')+'_'+parentID
  109.                     parent = r.get_submission(r.get_info(thing_id=thethingid).permalink).comments[0]
  110.                     username = find_between(message.body, 'Fellow Redditor /u/', ' sent you')
  111.                     tipComment = getChildTipCommentFromPost(parent, username) if parentIsPost else getChildTipComment(parent, username)
  112.                     if tipComment != 0:
  113.                         if amount < 100000:
  114.                             tipComment.reply('I\'m sorry, but the minimum P2Pool tip is currently 1 mBTC because of transaction fees.\n\n/u/changetip '+str(amount)+' satoshis')
  115.                             commentid = tipComment.id
  116.                             amount = 0
  117.                             sendamount = 0
  118.                             txid = 'none'
  119.                             storeInDatabase(commentid, message.id, amount, sendamount, username, txid)
  120.                         else:
  121.                             sendamount = amount - 10000
  122.                             sendamount *= 1.00 #0.99 for 1% fee
  123.                             sendamount = round(sendamount)
  124.                             sendMany = getTipSendMany(sendamount)
  125.                             sendManyUrl = 'https://blockchain.info/merchant/'+walletIdentifier+'/sendmany?password='+walletPassword+'&recipients='+sendMany
  126.                             response = urllib.request.urlopen(sendManyUrl).read().decode('ascii', 'ignore')
  127.                             sendmanyresponse = json.loads(response)
  128.                             txid = sendmanyresponse["tx_hash"]
  129.                             commentid = tipComment.id
  130.                             print('\n'+username+' tipped '+str(round(float(amount)/100000, 2))+' mBTC.')
  131.                             storeInDatabase(commentid, message.id, amount, sendamount, username, txid)
  132.                             tipComment.reply('The Bitcoin tip for '+str(round(float(amount)/100000, 2))+' mBTC (minus fees) [has been forwarded](https://blockchain.info/tx/'+txid+') to P2Pool miners.\n\n^(Brought to you by /u/'+ownerusername+'.)')
  133.     time.sleep(5)
Advertisement
Add Comment
Please, Sign In to add comment