[Python] Subeta Class (UNDER DEVELOPMENT)
Python Version = 3.1.2
NOTE: You need the latest versions of general.py and session.py to use this.
If you wish to collaborate, please be kind enough to follow some guidelines:
- Document every function. Please follow the examples provided in the source code below.
- Keep lines equal to, or under, 100 cols.
- It would be VERY helpful if you comment every step, it helps other people see the why you did certain things, and helps in the understanding of the script (especially if it needs updating and you haven't touched the script in a long time).
When developing in real world commercial applications, you will be asked to follow a strict set of guidelines so there is a standard flow of the source code. Otherwise the source code (especially open source) would have too many different styles of scripting, and it would be hard to follow and understand.
Needed modules can be found here: http://forum.logicalgamers.com/progr...ral-class.html and http://forum.logicalgamers.com/progr...ion-class.html
Main Subeta Class:
Code:
#!/usr/bin/env python
#####################
#Author: Riddle
#Website: www.logicalgamers.com
#E-mail: NONE
#Version: 0.3.0
#####################
# Subeta Class: Subeta Package #
# Imports #
import general
import session
import slots
class Subeta:
"""
Static Objects:
URL_NORM = 'http://subeta.net/'
URL_INDEX = self.URL_NORM + 'index.php'
URL_LOGIN = self.URL_NORM + 'login.php?act=login'
URL_GAME_INDEX = URL_NORM + 'games/' + URL_INDEX
URL_GAME_SLOTS = URL_NORM + 'games/slots.php'
EVENT_ACHIEVEMENT = '<div id="achievement">'
EVENT_OPPONENT = ''
SLOTS_COST = 50
"""
# Set basic URL constants #
URL_NORM = 'http://subeta.net/'
URL_INDEX = URL_NORM + 'index.php'
URL_LOGIN = URL_NORM + 'login.php?act=login'
# URL constants for games #
URL_GAME_INDEX = URL_NORM + 'games/' + URL_INDEX
URL_GAME_SLOTS = URL_NORM + 'games/slots.php'
# URL constants for forums #
# Event string Constants #
EVENT_ACHIEVEMENT = '<div id="achievement">' # An achievement event has been
# triggered, use this to identify it.
EVENT_OPPONENT = '' # An opponent has been discovered, use
# this to identify the event. Incomplete
# Constant Misc Data #
SLOTS_COST = 50
def __init__(self, username = None, password = None):
"""
Subeta(username = None, password = None):
If username and password are provided, it will Login and return a Bool.
-> Subeta Functions
Login(data,delimiter)
Login(username, password)
CheckForAchievement(self, htmlStr)
ParseAchievement(self, htmlStr)
PlaySlots(self, maxGamesInt = 100, maxToSpendInt = None, loggingFunction = None)
-> Class Properties
HTTP = session.HTTP()
Gen = general.General()
USER = None
PASS = None
LOGGED = False
"""
# Set class properties #
self.HTTP = session.HTTP()
self.Gen = general.General()
# self.Ex = exception.Exception() # Exception Class, not created yet.
# Username and Password for Class, is the acc logged? #
self.USER = None
self.PASS = None
# Logged in Flag #
self.LOGGED = False
# Login if applicable #
if username != None and password != None:
return Login(username, password)
return
def Login(self, data, delimiter = ':'):
"""
Login(data, delimiter = ':')
Logs into www.subeta.net with provided user information.
-> data: valid Subeta "username:password", where ':' can be replaced with any delimiter.
-> delimiter: Default = ':'. Can be changed to anything, preferably a single char.
Returns:
-> Bool: True when successfully logins
-> Bool: False when fails. Raises Exception.
"""
# Split the data string to obtain username and password #
tmpArr = data.split(':')
# Attempt to Login to Subeta #
return Login(tmpArr[0],tmpArr[1])
# MUST FINISH EXCEPTION HANDLING #
def Login(self, username, password):
"""
Login(username, password)
Logs into www.subeta.net with provided user information.
-> username: valid Subeta username
-> password: valid Subeta password
Returns:
-> Bool: True when successfully logins
-> Bool: False when fails. Raises Exception.
"""
# Set referer #
self.HTTP.Set_Referer(self.URL_INDEX)
# User Data Dict #
pData = { 'Name' : username,
'Password' : password }
# Send POST data to login to Subeta #
html = self.HTTP.POST(self.URL_LOGIN, pData)
# Check for success #
if html.find(username) > -1:
self.LOGGED = True
self.USER = username
self.PASS = password
return self.LOGGED
else:
# Raise errors #
# if html.find(error1) > -1:
# do something...
self.LOGGED = False
return self.LOGGED
# MUST FINISH EXCEPTION HANDLING #
def CheckForAchievement(self, htmlStr):
"""
CheckForAchievement(htmlStr)
Checks a page to see if an achievement has been acquired.
-> htmlStr: www.subeta.net webpage HTML string
Returns:
-> Bool: True when the event is found.
-> Bool: False when the event is not found.
-> None: If acc. is not logged in.
"""
# Check if we're logged in #
if (not self.LOGGED):
# Raise Exception #
return None
# See if the unique event string is contained in htmlStr #
if htmlStr.find(Subeta.EVENT_ACHIEVEMENT) > -1:
return True
# Achievement event not found in htmlStr #
return False
# MUST FINISH EXCEPTION HANDLING #
def ParseAchievement(self, htmlStr):
"""
ParseAchievement(htmlStr)
Parses an Achievement Event data from www.subeta.net
-> htmlStr: www.subeta.net webpage HTML string
Returns:
-> Dict: { title, img, text } on success
-> None: On fail. Raises exception with the exception class.
-> None: If acc. is not logged in.
"""
# Check if we're logged in #
if (not self.LOGGED):
# Raise Exception #
return None
try:
# Parse the Achievement div box from htmlStr #
rawStr = self.Gen.GetBetween(htmlStr, Subeta.EVENT_ACHIEVEMENT, '</div></div>')
# Get the link to the image used in the event #
imgStr = self.Gen.GetBetween(rawStr, '<img src="', '">')
# Get the text of the event #
achStr = self.Gen.GetBetween(rawStr, '<div id="achievement_text">', '<a href=')
# Replace bold tags for quotes #
achStr.replace("<b>", "\"")
achStr.replace("</b>","\"")
# Remove any other tags #
achStr = self.Gen.strip_ml_tags(achStr)
# Add everything to a dictionary #
achDict = { 'title' : 'Achievement Event!',
'img' : imgStr,
'text' : achStr }
return achDict
except:
# Raise Exception with our own Exception Class
return None
def PlaySlots(self, maxGamesInt = 100, maxToSpendInt = None, loggingFunction = None):
# Check if we're logged in #
if (not self.LOGGED):
# Raise Exception #
return None
# If the max money to spend is passed as an argument, and not max games to play #
if maxGamesInt == None and maxToSpendInt.__class__ == int:
# We calculate the maximum games we will play... #
maxGamesInt = round(maxToSpendInt / Subeta.SLOTS_COST)
# We must verify that the user has => than the amount of max games to play requires #
# verify...
if loggingFunction == None:
slots.Slots(maxGamesInt, self.HTTP)
else:
slots.Slots(maxGamesInt, self.HTTP, loggingFunction)
return
Slots Class:
Code:
#!/usr/bin/env python
#####################
#Author: Riddle
#Website: www.logicalgamers.com
#E-mail: NONE
#Version: 0.9.0
#####################
# Slots Class: Subeta Package #
# Imports #
import general
import subeta
class Slots:
# Static Objects #
SLOT_PICTURE_PATH = 'Slots' + general.General().sep()
def __init__(self, maxGamesInt, session):
"""
Slots(maxGamesInt, session)
Plays subeta.net Slots game with a given session.
-> Slots Functions
Spin()
RealSpin(hash_sub, act)
ParseJackpot(htmlStr)
ParseResults(htmlStr)
DisplayImgs(htmlStr)
CheckForWin(htmlStr)
LogFunction(status)
GetHashInput(htmlStr)
GetActInput(htmlStr)
UpdateJackpot(htmlStr)
UpdateObjects(htmlStr)
ShowJackpot(jackpot)
SetJackpotFunc(jackFunc = None)
SetLogFunc(logFunc = None)
SetDispImgFunc(dispFunc = None)
GetSpinImgs(htmlStr)
Stop()
Sleep()
SetSleepTime(secsLow, secsHigh)
NoSleep()
CheckAchievements(choiceBool)
SetAchievementFunc(achieveFunc = None)
RealAchievementCheck()
CheckInv(htmlStr)
SetMoveItemsFunc(moveFunc = None)
RealCheckInv(htmlStr)
SetAfterStopFunc(afterFunc = None)
-> Slots Properties
HTTP = session
Gen = general.General()
FUNC_LOG = lambda x: print(x)
FUNC_JACKPOT = lambda x: print("Current Jackpot: "+x)
FUNC_DISP_IMGS = None
FUNC_ACHIEVEMENTS = None
STOP_FLAG = False
CURR_JACKPOT = None
CURR_WIN = None
CURR_STATUS = None
GAMES_TO_PLAY = maxGamesInt
WAIT_BEFORE_SPIN = False
WAIT_TIME1 = 0
WAIT_TIME2 = 0
CHECK_ACHIEVEMENTS = False
PLAYED_GAMES = 1
CHECK_ACHIEVEMENTS = False
SLOT_IMG = 'http://images.subeta.net/items/'
"""
#Set class properties #
self.HTTP = session
self.Gen = general.General()
# self.Ex = exception.Exception() # Exception Class, not created yet.
# Function used to Log Data #
self.FUNC_LOG = lambda x: print(x)
self.FUNC_JACKPOT = lambda x: print("Current Jackpot: "+x)
self.FUNC_DISP_IMGS = None
self.FUNC_ACHIEVEMENTS = None
self.FUNC_MOVE_ITEMS = None
self.FUNC_AFTER_STOP = lambda: print("Finished!")
# Stop Playing #
self.STOP_FLAG = False # BOOL #
# Variables for logging and record keeping #
self.CURR_JACKPOT = None # STRING #
self.CURR_WIN = None # BOOL #
self.CURR_STATUS = None # STRING #
self.PLAYED_GAMES = 1 # INT #
# SETTINGS #
self.GAMES_TO_PLAY = maxGamesInt
self.WAIT_BEFORE_SPIN = False # BOOL #
self.WAIT_TIME1 = 0 # SECS #
self.WAIT_TIME2 = 0 # SECS #
self.CHECK_ACHIEVEMENTS = False # BOOL #
# IMG URL Constant #
self.SLOT_IMG = 'http://images.subeta.net/'
return
def Spin(self):
"""
Spin()
Plays www.subeta.net Slots game.
"""
# Set Referer #
self.HTTP.Set_Referer(subeta.Subeta.URL_GAME_INDEX)
# Go to the Slots page #
htmlStr = self.HTTP.GET(subeta.Subeta.URL_GAME_SLOTS)
# Update inputs and Jackpot #
hash_sub, act = self.UpdateObjects(htmlStr)
# Start Spinning the Slots #
while (not self.STOP_FLAG) and (self.PLAYED_GAMES < self.GAMES_TO_PLAY+1):
# Make sure we don't play with empty variables. Keep trying until stopped #
if hash_sub == None or act == None:
# Log failure, and annouce we're retrying until stopped #
self.Spin()
return
# Set Referer #
self.HTTP.Set_Referer(subeta.Subeta.URL_GAME_SLOTS)
# Get the current html content #
htmlStr = self.RealSpin(hash_sub, act)
# Check if inventory is full... #
self.RealCheckInv(htmlStr)
# Update inputs and Jackpot #
hash_sub, act = self.UpdateObjects(htmlStr)
# Parse results of the spin #
self.ParseResults(htmlStr)
# Check for Achievements #
self.RealAchievementCheck(htmlStr)
# Log Status #
self.LogFunction(self.CURR_STATUS)
# Add to game count #
self.PLAYED_GAMES += 1
# Wait x seconds if applies #
self.Sleep()
# Call the FUNC_AFTER_STOP function (probaby to enable/disable GUI commands?)#
self.AfterStop()
return
def RealSpin(self, hash_sub, act):
"""
RealSpin()
The actual post method to ACTUALLY play the slots game.
-> hash_sub: hidden input in slots webpage needed to play.
-> act : hidden input in slots webpage needed to play.
"""
pData = { 'hash_sub' : hash_sub,
'act' : act }
return self.HTTP.POST(subeta.Subeta.URL_GAME_SLOTS, pData)
def ParseJackpot(self, htmlStr):
"""
ParseJackpot(htmlStr)
Parses the Jackpot from the Slots game @ www.subeta.net
-> htmlStr: String containing Jackpot for Slots (Subeta.net)
Returns:
-> String: Jackpot value for the Slots game (Subeta.net)
-> Bool: False, when the Jackpot text is not found on htmlStr
-> None: When an error occurs parsing Jackpot. Raises exception.
"""
# Check if the Jackpot is in the string given #
if htmlStr.find("The current jackpot") > -1:
try:
# Get the value of the Jackpot #
return self.Gen.GetBetween(htmlStr, "The current jackpot is <b>", "</b>")
except:
# HANDLE EXCEPTION HERE! #
return None
return False
def ParseResults(self, htmlStr):
"""
ParseResults(htmlStr)
Parses the results page for the Slots game @ www.subeta.net. Updates CURR_STATUS.
-> htmlStr: Slots game output page (after spin).
"""
# Check if we won #
self.WIN = self.CheckForWin(htmlStr)
# Display Slots images #
self.DisplayImgs(htmlStr)
if not self.WIN:
# Loosing Spin #
self.CURR_STATUS = "Spin #"+str(self.PLAYED_GAMES)+": Nothing won."
elif self.WIN:
# Winning Spin #
winnings = self.Gen.GetBetween(htmlStr, "<b>You won ","</b>")
self.CURR_STATUS = "Spin #"+str(self.PLAYED_GAMES)+": You won "+winnings
#######
#DEBUG#
try:
if winnings == "":
self.Gen.Str_To_File(htmlStr,str(self.PLAYED_GAMES)+".html",'w') # Jackpot win page is not the same as other prizes! #
except:
pass
#######
else:
# Something Went Wrong! #
pass
return
def DisplayImgs(self, htmlStr):
"""
DisplayImgs(htmlStr)
Displays imgs of the slots results with a given function
self.FUNC_DIS_IMGS()
"""
if self.FUNC_DISP_IMGS != None:
# Get result images #
imgList = self.GetSpinImgs(htmlStr)
# Display Images #
try:
self.FUNC_DISP_IMGS(imgList)
except:
# Display an error img #
# Couldn't load img correctly #
pass
def CheckForWin(self, htmlStr):
"""
CheckForWin(htmlStr)
Checks if we won something from the Slots game.
-> htmlStr: Results page from the Slots game.
Returns:
-> Bool: True on Win.
-> Bool: False on Loose.
"""
if htmlStr.find("You win!") > -1:
return True
return False
def LogFunction(self, status):
"""
LogFunction(status)
Tries to pass the current status through a set Logging Function.
-> status: String to pass to the logging function.
"""
try:
if self.FUNC_LOG != None:
self.FUNC_LOG(str(status))
except:
# HANDLE EXCEPTION #
pass
return
def GetHashInput(self, htmlStr):
"""
GetHashInput(htmlStr)
Returns the hash_sub value from Slots page.
"""
return self.Gen.GetInputValue(htmlStr, "hash_sub")
def GetActInput(self, htmlStr):
"""
GetActInput(htmlStr)
Returns the act value from Slots page.
-> htmlStr: Slots page.
"""
return self.Gen.GetInputValue(htmlStr, "act")
def UpdateJackpot(self, htmlStr):
"""
UpdateJackpot(htmlStr)
Updates the current Jackpot and calls ShowJackpot()
-> htmlStr: Slots page.
"""
self.CURR_JACKPOT = self.ParseJackpot(htmlStr)
self.ShowJackpot(self.CURR_JACKPOT)
return
def UpdateObjects(self, htmlStr):
"""
UpdateObjects(htmlStr)
Updates the hash_sub, act, and current Jackpot
-> htmlStr: Slot page.
Returns:
-> String, String: hash_sub, act on success.
-> None, None: On exception, failure.
"""
try:
# Get the hidden input hash_sub #
hash_sub = self.GetHashInput(htmlStr)
# Get the hidden input act #
act = self.GetActInput(htmlStr)
# Update Jackpot #
self.UpdateJackpot(htmlStr)
return hash_sub, act
except:
# WHAT HAPPENED? HANDLE EXCEPTION! #
return None, None
def ShowJackpot(self, jackpot):
"""
ShowJackpot(jackpot)
Calls the set function to show the Jackpot.
-> jackpot: Jackpot to be displayed.
"""
try:
if self.FUNC_JACKPOT != None:
self.FUNC_JACKPOT(str(jackpot))
except:
# HANDLE #
pass
return
def SetJackpotFunc(self, jackFunc = None):
"""
SetJackpotFunc(jackFunc = None)
Sets the function to be used when the Jackpot is displayed.
If set to None, Jackpot won't be displayed.
"""
self.FUNC_JACKPOT = jackFunc
return
def SetLogFunc(self, logFunc = None):
"""
SetLogFunc(logFunc = None)
Sets the function to be used to display the results of each spin.
If set to None, the results won't be displayed.
"""
self.FUNC_LOG = logFunc
return
def SetDispImgFunc(self, dispFunc = None):
"""
SetDispImgFunc(dispFunc = None)
Sets the function to be used to display the img results of each spin.
If set to None, the results won't be displayed.
The function must take a List for a parameter
"""
self.FUNC_DISP_IMGS = dispFunc
return
def GetSpinImgs(self, htmlStr):
"""
GetSpinImgs(htmlStr)
Returns a list of nine image names that were displayed in the slot's page output
-> htmlStr: Slot's output in subeta.net
"""
# Sub-Strings that we want to remove from image names #
cleanList = ['items','/']
# Constant beggining of URLs for Slot Images #
URL = self.SLOT_IMG
strToSearch = self.Gen.GetBetween(htmlStr, 'The current jackpot is', '<form method=post')
# Find all the image names #
imgs = self.Gen.Find_All("<img src='http://images.subeta.net/([a-zA-Z0-9-_\./]+)'>", strToSearch)
# Clean the imgs list #
for x in cleanList:
for y in range(0,len(imgs)):
imgs[y] = imgs[y].replace(x,'')
# Loop through all 9 images and save them if they don't exist already #
for img in imgs:
path = Slots.SLOT_PICTURE_PATH + img
if not self.Gen.File_Exists(path):
if img != 'slots_jackpot.gif': #this image is in a different path than the rest
self.HTTP.Save_Image(URL+'items/'+img,path)
else:
self.HTTP.Save_Image(URL+img,path)
return imgs
def Stop(self):
"""
Stop()
When called, the program will put a flag so the spinning loop stops ASAP.
"""
self.STOP_FLAG = True
return
def Sleep(self):
"""
Sleep()
Halts the program for self.WAIT_TIME seconds
"""
if self.WAIT_BEFORE_SPIN:
realWait = self.Gen.RandFloat(self.WAIT_TIME1,self.WAIT_TIME2)
self.LogFunction("Waiting " + str(realWait) + " seconds...")
self.Gen.Sleep(realWait)
return
def SetSleepTime(self, secsLow, secsHigh):
"""
SetSleepTime(secs)
Sets the amount of time, in seconds, to wait between each spin.
Waits between secsLow and secsHigh.
"""
if secsLow.__class__ == int and secsHigh.__class__ == int and secsHigh > 0 and secsLow < secsHigh:
self.WAIT_BEFORE_SPIN = True
self.WAIT_TIME1 = secsLow
self.WAIT_TIME2 = secsHigh
else:
self.WAIT_BEFORE_SPIN = False
return
def NoSleep(self):
"""
NoSleep()
Toggles the Sleep flag to False. Meaning that the program won't wait between spins.
"""
self.WAIT_BEFORE_SPIN = False
return
def CheckAchievements(self, choiceBool = True):
"""
CheckAchievements(choiceBool)
If choiceBool == True, then achievements will be logged with FUNC_ACHIEVEMENT.
Must set FUNC_ACHIEVEMENT with SetAchievementFunc()
"""
self.CHECK_ACHIEVEMENTS = choiceBool
return
def SetAchievementFunc(self, achieveFunc = None):
"""
SetAchievementFunc(achieveFunc = None)
Function used to check achievements in each page refresh.
If set to None, then the program won't check for any achievements.
Must take htmlStr as a argument (subeta.net page)
"""
self.FUNC_ACHIEVEMENT = achieveFunc
return
def RealAchievementCheck(self, htmlStr):
"""
RealAchievementCheck()
Checks if there was any achievement awarded on htmlStr.
Send the htmlStr to function that handles achievements.
"""
if self.CHECK_ACHIEVEMENTS and self.FUNC_ACHIEVEMENT != None:
self.FUNC_ACHIEVEMENT(htmlStr)
return
def CheckInv(self, htmlStr):
"""
CheckInv(htmlStr)
Checks to see if the inventory is full and items need to be removed from it.
Sets the FULL_INVENTORY Flag.
"""
# WHEN YOU HAVE TOO MANY ITEMS IN INVENTORY: Oops, you have too many items in your Inventory! #
if htmlStr.find('too many items in your Inventory!') > -1:
return True
else:
return False
def SetMoveItemsFunc(self, moveFunc = None):
"""
SetMoveItemsFunc(moveFunc = None)
Function to move items to vault, shop, or just announce the inve. is full.
If set to None, program will simply stop when inventory is full.
Takes no arguments.
"""
self.FUNC_MOVE_ITEMS = moveFunc
return
def RealCheckInv(self, htmlStr):
"""
RealCheckInv(htmlStr)
If the inventory is full, use FUNC_MOVE_ITEMS to handle the situation.
"""
flag = self.CheckInv(htmlStr)
if flag and self.FUNC_MOVE_ITEMS != None:
self.FUNC_MOVE_ITEMS()
elif flag:
self.Stop()
return
def SetAfterStopFunc(self, afterFunc = None):
"""
SetAfterStopFunc(afterFunc = None)
Set a function that will be called after the the function Stop() is called.
Takes no arguments.
"""
self.FUNC_AFTER_STOP = afterFunc
return
def AfterStop(self):
"""
AfterStop()
Calls a function FUNC_AFTER_STOP when the program stops spinning the slots.
"""
if self.FUNC_AFTER_STOP != None:
self.FUNC_AFTER_STOP()
return
OUTPUT:
Code:
>>> ================================ RESTART ================================
>>>
True
Current Jackpot: 3150 sP
Current Jackpot: 3150 sP
Spin #1: Nothing won.
Current Jackpot: 3180 sP
Spin #2: Nothing won.
Current Jackpot: 3210 sP
Spin #3: Nothing won.
Current Jackpot: 3240 sP
Spin #4: Nothing won.
Current Jackpot: 3270 sP
Spin #5: Nothing won.
Current Jackpot: 3300 sP
Spin #6: You won the book "The Slots!"
Current Jackpot: 3330 sP
Spin #7: Nothing won.
Current Jackpot: 3360 sP
Spin #8: Nothing won.
Current Jackpot: 3390 sP
Spin #9: Nothing won.
Current Jackpot: 3420 sP
Spin #10: Nothing won.
>>>
Changelog:
- 6/30/2010: Added more functions to Subeta Class. Added Slots class to post. Added version doc. in classes.
- 7/1/2010: Updated Slots class to version 0.8.5. Fully documented source up to current development. Fixed and added new functions.
- 7/4/2010:
Version 0.8.7; Added SetDispImgFunc(self, dispFunc = None), DisplayImgs(htmlStr), GetSpinImgs(self, htmlStr).
Version 0.8.8; Added Stop(), Sleep(). Added support for different Settings. Changed WAIT_TIME to WAIT_TIME1 and WAIT_TIME2, to add support for in between sleep.
Version 0.9.0; Added CheckAchievements(choiceBool), SetAchievementFunc(achieveFunc = None), RealAchievementCheck(), CheckInv(htmlStr), SetMoveItemsFunc(moveFunc = None), RealCheckInv(htmlStr), SetAfterStopFunc(afterFunc = None), AfterStop().