jacob614

tptapi stock bot

Sep 27th, 2013
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.38 KB | None | 0 0
  1. runme.py:
  2. ===============================================================================================================
  3. ===============================================================================================================
  4. ===============================================================================================================
  5.  
  6. import stocks
  7. import socket
  8. import select
  9. import traceback
  10. from time import sleep
  11. from datetime import datetime
  12.  
  13. server = "irc.freenode.net"
  14. channel = "###stocks"
  15. botnick = "stockbot614"
  16.  
  17. def connect():
  18.     global irc
  19.     irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  20.     irc.connect((server,6667))
  21.     irc.setblocking(0)
  22.     irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :TPTAPI stock helper bot\n")
  23.     irc.send("NICK "+ botnick +"\n")
  24.     irc.send("JOIN "+ channel +"\n")
  25.     stocks.setirc(irc)
  26.  
  27. def main():
  28.     while True:
  29.         try:
  30.             line = ""
  31.             ready = select.select([irc], [], [], 1.0)
  32.             if ready[0]:
  33.                 line = irc.recv(2040)
  34.         except socket.timeout, e:
  35.             if e.args[0] == "timed out":
  36.                 continue
  37.             else:
  38.                 print e
  39.         except socket.error, e:
  40.             print e
  41.             quit()
  42.         except KeyboardInterrupt:
  43.                 irc.send("QUIT :Keyboard Interrupt\r\n")
  44.                 irc.close()
  45.                 quit()
  46.         else:
  47.             if len(line):
  48.                 print line
  49.                 text = line.split()
  50.                 try:
  51.                     if len(text) >= 4 and stocks.checkowner(text[0]) and text[1] == "PRIVMSG" and text[2][0] == "#":
  52.                         command = text[3].lower().lstrip(":")
  53.                         if command == "!!reload":
  54.                             cookies = stocks.cookies
  55.                             portfolio = stocks.portfolio
  56.                             reload(stocks)
  57.                             stocks.cookies = cookies
  58.                             stocks.portfolio = portfolio
  59.                             irc.send("PRIVMSG " + text[2] + " :Reloaded stocks.py\r\n")
  60.                         elif command == "!!join":
  61.                             irc.send("JOIN "+ text[4] +"\n")
  62.                         elif command == "!!part":
  63.                             irc.send("PART "+ text[4] +"\n")
  64.                     if len(text):
  65.                         stocks.parse(text)
  66.                 except KeyboardInterrupt:
  67.                     irc.send("QUIT :Keyboard Interrupt\r\n")
  68.                     irc.close()
  69.                     quit()
  70.                 except Exception, error:
  71.                     print "=======ERROR=======\n" + traceback.format_exc() + "========END========\n"
  72.                     irc.send("PRIVMSG " + channel + " :Error printed to console\r\n")
  73.         try:  
  74.             now = datetime.now()
  75.             if now.minute % 10 == 0 and now.second == 3:
  76.                 stocks.getStockInfo(True)
  77.                 stocks.printStocks("###stocks")
  78.                 sleep(1)
  79.         except:
  80.             print "=======ERROR=======\n" + traceback.format_exc() + "========END========\n"
  81.             irc.send("PRIVMSG " + channel + " :Error printed to console\r\n")
  82.  
  83. connect()
  84. main()
  85.  
  86.  
  87. ===============================================================================================================
  88. ===============================================================================================================
  89. ===============================================================================================================
  90.  
  91. stocks.py:
  92.  
  93. import socket
  94. import re
  95. import time
  96.  
  97. def setirc(irc_):
  98.     global irc
  99.     irc = irc_
  100.  
  101. def checkowner(hostmask):
  102.     host = hostmask.split("!")
  103.     if len(host) < 2:
  104.         return False
  105.     return host[1] == "jacob1@Powder/Developer/jacob1"
  106.  
  107. cookies = {}
  108. def login(username = "jacob2", password = "imapotato"): #seriously, I am
  109.     cj = CookieJar()
  110.     opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  111.     opener.addheaders = [('User-agent', 'Mozzarella/5.0 (Windows NT 6.3; WOW64; rv:14.0) Gecko/20100101 Firefox/24.0.0')]
  112.     urllib2.install_opener(opener)
  113.  
  114.     urllib2.urlopen(urllib2.Request(
  115.             "http://tptapi.com/login_proc.php?login",
  116.             urllib.urlencode({"Username":username, "Password":password})))
  117.  
  118.     for i in list(cj):
  119.         cookies[i.name] = i.value
  120.  
  121. def getPage(url):
  122.     return urllib2.urlopen(urllib2.Request(url, urllib.urlencode(cookies))).read()
  123.  
  124. results = {}
  125. def getStockInfo(new = False):
  126.     page = getPage("http://tptapi.com/getstock.php")
  127.     stocks = []
  128.     for i in page.splitlines():
  129.         stocks.extend(re.findall("<td width='\d+%'>([^<>]*)</td>", i))
  130.    
  131.     for i in range(0, len(stocks), 4):
  132.         try:
  133.             results[stocks[i]] = {'value':re.sub(",", "", stocks[i+1]), 'shares':re.sub(",", "", stocks[i+2]), 'ceo':stocks[i+4]}
  134.         except:
  135.             i -= 1
  136.  
  137. portfolio = {}
  138. def getPortfolioInfo():
  139.     page = getPage("http://tptapi.com/portfolio.php")
  140.     stocks = []
  141.     for i in page.splitlines():
  142.         stocks.extend(re.findall("<td width='\d+%'>([^<>]*)</td>", i)) #"<font color=[^<>]*>([^<>]*)</font>"
  143.    
  144.     #for i in range(0, len(stocks), 3):
  145.         #portfolio[stocks[i]] = {'shares':stocks[i+1], 'value':stocks[i+2]}
  146.     #return money
  147.     output = ""
  148.     for i in range(0, len(stocks), 3):
  149.         try:
  150.             output = output + "08%s: %s  " % (stocks[i], stocks[i+1])
  151.         except:
  152.             pass
  153.     return output
  154.  
  155. money = 0
  156. def getMoney():
  157.     global money
  158.     page = getPage("http://tptapi.com/money.php")
  159.     start = page.find("Current Balance:")+21
  160.     money = int(re.sub(",", "", page[start:start+page[start:].find("<")]))
  161.  
  162. def buysellStocks(channel, action, element, amount):
  163.     tempcookies = cookies
  164.     tempcookies.update({"shares":amount})
  165.     page = getPage("http://tptapi.com/stockProc.php?%s=%s" % (action, element))
  166.     irc.send("PRIVMSG " + channel + " :" + re.sub("<.*?>", "", page) + "\r\n")
  167.    
  168. def printStocks(channel):
  169.     output = "08"
  170.     for i in sorted(results):
  171.         output = output + i + " - $" + results[i]["value"] + "  08"
  172.         if len(output) > 410:
  173.             irc.send("PRIVMSG " + channel + " :" + output + "\r\n")
  174.             output = "08"
  175.         #print i + " - $" + results[i]["value"] + " " + results[i]["shares"] + " shares. CEO: " + results[i]["ceo"]
  176.     irc.send("PRIVMSG " + channel + " :" + output + "\r\n")
  177.  
  178. def printstockValue(stock, channel):
  179.     if stock in results:
  180.         irc.send("PRIVMSG " + channel + " :" + results[stock]["value"] + "\r\n")
  181.  
  182.  
  183. """
  184.  
  185. http://tptapi.com/getjson.php?type=balance&key=PUBLIC_KEY
  186.  
  187. irc things:
  188. :jacob1!jacob1@Powder/Developer/jacob1 NICK :jacob2
  189.  
  190. :jacob2!jacob1@Powder/Developer/jacob1 NICK :jacob1
  191.  
  192. :jacob1!jacob1@Powder/Developer/jacob1 PRIVMSG ###stocks :asdf
  193.  
  194.  
  195. :logbot614!~logbot614@99-161-188-221.lightspeed.livnmi.sbcglobal.net JOIN ###sto
  196. cks
  197.  
  198. :wolfe.freenode.net 332 logbot614 ###stocks :Illegal insider trading takes place
  199. here, also drug smuggling
  200. :wolfe.freenode.net 333 logbot614 ###stocks jacob1!jacob1@Powder/Developer/jacob
  201. 1 1379977409
  202. :wolfe.freenode.net 353 logbot614 @ ###stocks :logbot614 @jacob1
  203. :wolfe.freenode.net 366 logbot614 ###stocks :End of /NAMES list.
  204.  
  205. """
  206.  
  207. def parse(text):
  208.     if text[0] == "PING":
  209.         irc.send("PONG " + text[1] + "\r\n")
  210.  
  211.     if len(text) < 4:
  212.         return
  213.     if text[1] == "PRIVMSG":
  214.         channel = text[2]
  215.         command = text[3].lower().lstrip(":")
  216.         if command == "!!ping":
  217.             irc.send("PRIVMSG " + channel + " :Pong\r\n")
  218.         elif command == "!!print" or command == "!!log":
  219.             getStockInfo()
  220.             printStocks(channel)
  221.         elif checkowner(text[0]) and (command == "!!print2" or command == "!!log2"):
  222.             getStockInfo(True)
  223.         elif command == "!!stock" and len(text) > 4:
  224.             getStockInfo()
  225.             printstockValue(text[4].upper(), channel)
  226.         elif checkowner(text[0]) and command == "!!quit":
  227.             irc.send ("QUIT :i'm a potato\r\n")
  228.             irc.close()
  229.             quit()
  230.         elif checkowner(text[0]) and command == "!!login":
  231.             login()
  232.         elif checkowner(text[0]) and command == "!!buy" and len(text) > 5:
  233.             element = text[4].upper()
  234.             total = text[5]
  235.             if total[-1] == "%":
  236.                 getStockInfo()
  237.                 getMoney()
  238.                 total = int(money/int(results[element]["value"])*float(text[5].rstrip("%"))/100)
  239.                 irc.send("PRIVMSG " + channel + " :" + str(total) + "\r\n")
  240.             buysellStocks(channel, "buy", element, total)
  241.             portfolio[element] = {'shares':total}
  242.         elif checkowner(text[0]) and command == "!!sell" and len(text) > 5:
  243.             buysellStocks(channel, "sell", text[4].upper(), text[5])
  244.         elif checkowner(text[0]) and command == "!!sellall" and len(text) > 4:
  245.             #print portfolio[text[4].upper()]["shares"]
  246.             buysellStocks(channel, "sell", text[4].upper(), portfolio[text[4].upper()]["shares"])
  247.         elif checkowner(text[0]) and command == "!!money":
  248.             getMoney()
  249.             irc.send("PRIVMSG " + channel + " :" + str(money) + "\r\n")
  250.         elif checkowner(text[0]) and command == "!!portfolio":
  251.             irc.send("PRIVMSG " + channel + " :" + getPortfolioInfo() + "\r\n")
Advertisement
Add Comment
Please, Sign In to add comment