Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- runme.py:
- ===============================================================================================================
- ===============================================================================================================
- ===============================================================================================================
- import stocks
- import socket
- import select
- import traceback
- from time import sleep
- from datetime import datetime
- server = "irc.freenode.net"
- channel = "###stocks"
- botnick = "stockbot614"
- def connect():
- global irc
- irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- irc.connect((server,6667))
- irc.setblocking(0)
- irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :TPTAPI stock helper bot\n")
- irc.send("NICK "+ botnick +"\n")
- irc.send("JOIN "+ channel +"\n")
- stocks.setirc(irc)
- def main():
- while True:
- try:
- line = ""
- ready = select.select([irc], [], [], 1.0)
- if ready[0]:
- line = irc.recv(2040)
- except socket.timeout, e:
- if e.args[0] == "timed out":
- continue
- else:
- print e
- except socket.error, e:
- print e
- quit()
- except KeyboardInterrupt:
- irc.send("QUIT :Keyboard Interrupt\r\n")
- irc.close()
- quit()
- else:
- if len(line):
- print line
- text = line.split()
- try:
- if len(text) >= 4 and stocks.checkowner(text[0]) and text[1] == "PRIVMSG" and text[2][0] == "#":
- command = text[3].lower().lstrip(":")
- if command == "!!reload":
- cookies = stocks.cookies
- portfolio = stocks.portfolio
- reload(stocks)
- stocks.cookies = cookies
- stocks.portfolio = portfolio
- irc.send("PRIVMSG " + text[2] + " :Reloaded stocks.py\r\n")
- elif command == "!!join":
- irc.send("JOIN "+ text[4] +"\n")
- elif command == "!!part":
- irc.send("PART "+ text[4] +"\n")
- if len(text):
- stocks.parse(text)
- except KeyboardInterrupt:
- irc.send("QUIT :Keyboard Interrupt\r\n")
- irc.close()
- quit()
- except Exception, error:
- print "=======ERROR=======\n" + traceback.format_exc() + "========END========\n"
- irc.send("PRIVMSG " + channel + " :Error printed to console\r\n")
- try:
- now = datetime.now()
- if now.minute % 10 == 0 and now.second == 3:
- stocks.getStockInfo(True)
- stocks.printStocks("###stocks")
- sleep(1)
- except:
- print "=======ERROR=======\n" + traceback.format_exc() + "========END========\n"
- irc.send("PRIVMSG " + channel + " :Error printed to console\r\n")
- connect()
- main()
- ===============================================================================================================
- ===============================================================================================================
- ===============================================================================================================
- stocks.py:
- import socket
- import re
- import time
- def setirc(irc_):
- global irc
- irc = irc_
- def checkowner(hostmask):
- host = hostmask.split("!")
- if len(host) < 2:
- return False
- return host[1] == "jacob1@Powder/Developer/jacob1"
- cookies = {}
- def login(username = "jacob2", password = "imapotato"): #seriously, I am
- cj = CookieJar()
- opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
- opener.addheaders = [('User-agent', 'Mozzarella/5.0 (Windows NT 6.3; WOW64; rv:14.0) Gecko/20100101 Firefox/24.0.0')]
- urllib2.install_opener(opener)
- urllib2.urlopen(urllib2.Request(
- "http://tptapi.com/login_proc.php?login",
- urllib.urlencode({"Username":username, "Password":password})))
- for i in list(cj):
- cookies[i.name] = i.value
- def getPage(url):
- return urllib2.urlopen(urllib2.Request(url, urllib.urlencode(cookies))).read()
- results = {}
- def getStockInfo(new = False):
- page = getPage("http://tptapi.com/getstock.php")
- stocks = []
- for i in page.splitlines():
- stocks.extend(re.findall("<td width='\d+%'>([^<>]*)</td>", i))
- for i in range(0, len(stocks), 4):
- try:
- results[stocks[i]] = {'value':re.sub(",", "", stocks[i+1]), 'shares':re.sub(",", "", stocks[i+2]), 'ceo':stocks[i+4]}
- except:
- i -= 1
- portfolio = {}
- def getPortfolioInfo():
- page = getPage("http://tptapi.com/portfolio.php")
- stocks = []
- for i in page.splitlines():
- stocks.extend(re.findall("<td width='\d+%'>([^<>]*)</td>", i)) #"<font color=[^<>]*>([^<>]*)</font>"
- #for i in range(0, len(stocks), 3):
- #portfolio[stocks[i]] = {'shares':stocks[i+1], 'value':stocks[i+2]}
- #return money
- output = ""
- for i in range(0, len(stocks), 3):
- try:
- output = output + "08%s: %s " % (stocks[i], stocks[i+1])
- except:
- pass
- return output
- money = 0
- def getMoney():
- global money
- page = getPage("http://tptapi.com/money.php")
- start = page.find("Current Balance:")+21
- money = int(re.sub(",", "", page[start:start+page[start:].find("<")]))
- def buysellStocks(channel, action, element, amount):
- tempcookies = cookies
- tempcookies.update({"shares":amount})
- page = getPage("http://tptapi.com/stockProc.php?%s=%s" % (action, element))
- irc.send("PRIVMSG " + channel + " :" + re.sub("<.*?>", "", page) + "\r\n")
- def printStocks(channel):
- output = "08"
- for i in sorted(results):
- output = output + i + " - $" + results[i]["value"] + " 08"
- if len(output) > 410:
- irc.send("PRIVMSG " + channel + " :" + output + "\r\n")
- output = "08"
- #print i + " - $" + results[i]["value"] + " " + results[i]["shares"] + " shares. CEO: " + results[i]["ceo"]
- irc.send("PRIVMSG " + channel + " :" + output + "\r\n")
- def printstockValue(stock, channel):
- if stock in results:
- irc.send("PRIVMSG " + channel + " :" + results[stock]["value"] + "\r\n")
- """
- http://tptapi.com/getjson.php?type=balance&key=PUBLIC_KEY
- irc things:
- :jacob1!jacob1@Powder/Developer/jacob1 NICK :jacob2
- :jacob2!jacob1@Powder/Developer/jacob1 NICK :jacob1
- :jacob1!jacob1@Powder/Developer/jacob1 PRIVMSG ###stocks :asdf
- :logbot614!~logbot614@99-161-188-221.lightspeed.livnmi.sbcglobal.net JOIN ###sto
- cks
- :wolfe.freenode.net 332 logbot614 ###stocks :Illegal insider trading takes place
- here, also drug smuggling
- :wolfe.freenode.net 333 logbot614 ###stocks jacob1!jacob1@Powder/Developer/jacob
- 1 1379977409
- :wolfe.freenode.net 353 logbot614 @ ###stocks :logbot614 @jacob1
- :wolfe.freenode.net 366 logbot614 ###stocks :End of /NAMES list.
- """
- def parse(text):
- if text[0] == "PING":
- irc.send("PONG " + text[1] + "\r\n")
- if len(text) < 4:
- return
- if text[1] == "PRIVMSG":
- channel = text[2]
- command = text[3].lower().lstrip(":")
- if command == "!!ping":
- irc.send("PRIVMSG " + channel + " :Pong\r\n")
- elif command == "!!print" or command == "!!log":
- getStockInfo()
- printStocks(channel)
- elif checkowner(text[0]) and (command == "!!print2" or command == "!!log2"):
- getStockInfo(True)
- elif command == "!!stock" and len(text) > 4:
- getStockInfo()
- printstockValue(text[4].upper(), channel)
- elif checkowner(text[0]) and command == "!!quit":
- irc.send ("QUIT :i'm a potato\r\n")
- irc.close()
- quit()
- elif checkowner(text[0]) and command == "!!login":
- login()
- elif checkowner(text[0]) and command == "!!buy" and len(text) > 5:
- element = text[4].upper()
- total = text[5]
- if total[-1] == "%":
- getStockInfo()
- getMoney()
- total = int(money/int(results[element]["value"])*float(text[5].rstrip("%"))/100)
- irc.send("PRIVMSG " + channel + " :" + str(total) + "\r\n")
- buysellStocks(channel, "buy", element, total)
- portfolio[element] = {'shares':total}
- elif checkowner(text[0]) and command == "!!sell" and len(text) > 5:
- buysellStocks(channel, "sell", text[4].upper(), text[5])
- elif checkowner(text[0]) and command == "!!sellall" and len(text) > 4:
- #print portfolio[text[4].upper()]["shares"]
- buysellStocks(channel, "sell", text[4].upper(), portfolio[text[4].upper()]["shares"])
- elif checkowner(text[0]) and command == "!!money":
- getMoney()
- irc.send("PRIVMSG " + channel + " :" + str(money) + "\r\n")
- elif checkowner(text[0]) and command == "!!portfolio":
- irc.send("PRIVMSG " + channel + " :" + getPortfolioInfo() + "\r\n")
Advertisement
Add Comment
Please, Sign In to add comment