PDA

View Full Version : [Python] Assortment of sources



CPURules
09-14-2015, 06:56 PM
And by "assortment" I mean "I found like 4 programs I had written"

These used PyQT for a GUI and used a basic / low-level understanding of threading/signals to get the GUI to work simultaneously with the script. I'm just posting the main scripts for each thing (sans the authorization for the forum I originally wrote these for). These were written roughly 2 years ago according to the dates on the sources, so they may be out of date.

GSB is GetStringBetween. GSBA is GetStringBetweenAll.

autopricer.py - Shop Autopricer

import gui, time, [Only registered and activated users can see links] re, hashlib
from math import ceil
from Functions import *

from PyQt4.QtCore import *
from PyQt4.QtGui import *

w = [Only registered and activated users can see links]()
auth_level = "1"

try:
_fromUtf8 = QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s

try:
_encoding = QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QApplication.translate(context, text, disambig)

# Program coding goes here
class AuthThread(QThread):
# Removed

class LoginThread(QThread):
def __init__(self, parent = None):
QThread.__init__(self, parent)
self.exiting = False

def __del__(self):
self.exiting = True
self.wait()

def login(self, u, p):
self.neoUser = str(u)
self.neoPass = str(p)
self.start()

def run(self):
global w
pd = {"username": self.neoUser, "password": self.neoPass, "destination": "%2Findex.phtml"}
sHTML = w.post("[Only registered and activated users can see links]", pd, "[Only registered and activated users can see links]")
self.emit(SIGNAL("neoLogin(QString)"), sHTML)


class PriceThread(QThread):
def __init__(self, parent = None):
QThread.__init__(self, parent)
self.isRunning = False
self.exiting = False

def __del__(self, parent = None):
self.exiting = True
self.wait()

def begin(self, percent, passes, pin = False, pin_num = None):
self.isRunning = True

self.pricePercent = int(percent)
self.SWPasses = int(passes)
self.usePIN = pin
self.pin_num = pin_num

self.start()

def run(self):
global w

self.emit(SIGNAL("pricerStatus(QString)"), "Getting shop stock...")
sHTML = w.get("[Only registered and activated users can see links]")

if 'There are no items in your shop!' in sHTML:
self.emit(SIGNAL("pricerStatus(QString)"), "No items in shop!")
self.isRunning = False
self.emit(SIGNAL("stopPricer(bool)"), False)
return
elif not 'Free Space :' in sHTML:
self.emit(SIGNAL("pricerStatus(QString)"), "No shop found!")
self.isRunning = False
self.emit(SIGNAL("stopPricer(bool)"), False)
return

pages = ((int(GSB(sHTML, "Items Stocked : <b>", "</b>"))-1) / 30) + 2

for page in range(1,pages):
self.emit(SIGNAL("priceStatus(QString)"), "Pricing page " + str(page))

sHTML = w.get("[Only registered and activated users can see links]" + str(page * 30))
items = GSBA(sHTML, "/td></tr><tr><td width=60 bgcolor='#ffffcc'><b>", "</b>")
current_id = 0

price_pd = {"type": "update_prices", "order_by": "", "view": "", "lim": str(page*30)}
if self.usePIN:
price_pd.update({"pin": self.pin_num, "obj_name": ""})

inventory = sHTML

for item in items:
if not self.isRunning:
self.emit(SIGNAL("stopPricer(bool)"), True)
return

self.emit(SIGNAL("pricerStatus(QString)"), "Pricing " + item + "...")

current_id += 1
curid_string = str(current_id)

gen_item_info = GSB(inventory, item, "<option")
item_id = GSB(gen_item_info, "[", "]")
old_cost = GSB(gen_item_info, "name='oldcost_" + curid_string + "' value='", "'")

prices = []
for passthru in range(0,self.SWPasses):
search_pd = {"type": "process_wizard", "feedset": "0", "shopwizard": item, "table": "shop", "criteria": "exact", "min_price": "0", "max_price": "99999"}
sHTML = w.post("[Only registered and activated users can see links]", search_pd, "[Only registered and activated users can see links]")

if not 'I did not find anything. :(' in sHTML and not 'Whoa there, too many searches' in sHTML:
prices.append(int(GSB(sHTML, "&buy_cost_neopoints=", '"')))
else:
if 'Whoa there, too many searches' in sHTML:
self.emit(SIGNAL("pricerStatus(QString)"), "Wiz banned!")
self.isRunning = False
self.emit(SIGNAL("stopPricer(bool)"), False)
return

if len(prices) > 0:
price = str(int(ceil(max(prices) * self.pricePercent / 100.0)))
self.emit(SIGNAL("pricerStatus(QString)"), "Priced at " + price + " NP")
else:
price = "0"
self.emit(SIGNAL("pricerStatus(QString)"), "Unable to price " + item)

price_pd.update({"obj_id_" + curid_string: item_id, "oldcost_" + curid_string: old_cost, "cost_" + curid_string: price, "back_to_inv[" + item_id + "]": "0"})
time.sleep(1)

self.emit(SIGNAL("pricerStatus(QString)"), "Posting page " + str(page) + " prices")
sHTML = w.post("[Only registered and activated users can see links]", price_pd, "[Only registered and activated users can see links]")
self.emit(SIGNAL("pricerStatus(QString)"), "Prices posted!")

self.emit(SIGNAL("pricerStatus(QString)"), "All prices posted!")
self.emit(SIGNAL("stopPricer(bool)"), False)


def beginAuth():
global ui, t_auth
ui.lblAuthStatus.setText(_translate("frmMain", "Authorizing...", None))
ui.txtAuthUser.setEnabled(False)
ui.txtAuthPass.setEnabled(False)
ui.btnAuth.setEnabled(False)

t_auth.authorize(ui.txtAuthUser.text(), ui.txtAuthPass.text())

def processAuth(r):
global ui
if r:
# authorized!
ui.lblAuthStatus.setText(_translate("frmMain", "Authorized!", None))
ui.txtNeoUser.setEnabled(True)
ui.txtNeoPass.setEnabled(True)
ui.btnLogin.setEnabled(True)
else:
# auth failed
ui.lblAuthStatus.setText(_translate("frmMain", "Failed...", None))
ui.txtAuthUser.setEnabled(True)
ui.txtAuthPass.setEnabled(True)
ui.btnAuth.setEnabled(True)

def beginLogin():
global ui, t_login
ui.lblLoginStatus.setText(_translate("frmMain", "Logging in...", None))
ui.txtNeoUser.setEnabled(False)
ui.txtNeoPass.setEnabled(False)
ui.btnLogin.setEnabled(False)

t_login.login(ui.txtNeoUser.text(), ui.txtNeoPass.text())

def processLogin(r):
global ui, w

if 'Location: /index.phtml' in r:
# log-in successful!
ui.lblLoginStatus.setText(_translate("frmMain", "Logged in!", None))
ui.chkPIN.setEnabled(True)
ui.txtPasses.setEnabled(True)
ui.txtPriceEdit.setEnabled(True)
ui.btnStart.setEnabled(True)
else:
if 'errcode=1' in sHTML:
# bad password
ui.lblLoginStatus.setText(_translate("frmMain", "Bad password...", None))
elif 'errcode=2' in sHTML:
# username doesn't exist
ui.lblLoginStatus.setText(_translate("frmMain", "No such user...", None))
elif 'FROZEN' in sHTML:
# frozen
ui.lblLoginStatus.setText(_translate("frmMain", "Account frozen...", None))
else:
# other error; failed bday, too many pw guesses...
ui.lblLoginStatus.setText(_translate("frmMain", "Unknown error...", None))
ui.txtNeoUser.setEnabled(True)
ui.txtNeoPass.setEnabled(True)
ui.btnLogin.setEnabled(True)
w.jar.clear()

def togglePIN():
global ui
if ui.chkPIN.isChecked():
ui.txtPIN.setEnabled(True)
else:
ui.txtPIN.setEnabled(False)

def beginPricer():
global ui, t_pricer

ui.lblPricerStatus.setText(_translate("frmMain", "Starting...", None))
ui.chkPIN.setEnabled(False)
ui.txtPIN.setEnabled(False)
ui.txtPasses.setEnabled(False)
ui.txtPriceEdit.setEnabled(False)
ui.btnStart.setEnabled(False)
ui.btnStop.setEnabled(True)

t_pricer.begin(ui.txtPriceEdit.text(), ui.txtPasses.text(), ui.chkPIN.isChecked(), ui.txtPIN.text())

def forceStopPricer():
global ui, t_pricer

t_pricer.isRunning = False
ui.btnStop.setEnabled(False)
ui.lblPricerStatus.setText(_translate("frmMain", "Stopping...", None))

def stopPricer(wasForceStopped):
global ui

if wasForceStopped:
ui.lblPricerStatus.setText(_translate("frmMain", "Stopped!", None))

ui.btnStart.setEnabled(True)
ui.chkPIN.setEnabled(True)
ui.txtPIN.setEnabled(True)
ui.txtPasses.setEnabled(True)
ui.txtPriceEdit.setEnabled(True)

def updateStatus(s):
global ui
ui.lblPricerStatus.setText(_translate("frmMain", s, None))

if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
frmMain = QWidget()
ui = gui.Ui_frmMain()
ui.setupUi(frmMain)

# Create threads and connect them to GUI
t_auth = AuthThread()
QObject.connect(ui.btnAuth,SIGNAL("clicked()"),beginAuth)
QObject.connect(t_auth,SIGNAL("**Auth(bool)"),processAuth)

t_login = LoginThread()
QObject.connect(ui.btnLogin,SIGNAL("clicked()"),beginLogin)
QObject.connect(t_login,SIGNAL("neoLogin(QString)"),processLogin)

t_pricer = PriceThread()
QObject.connect(ui.chkPIN,SIGNAL("stateChanged(int)"),togglePIN)
QObject.connect(ui.btnStart,SIGNAL("clicked()"),beginPricer)
QObject.connect(ui.btnStop,SIGNAL("clicked()"),forceStopPricer)
QObject.connect(t_pricer,SIGNAL("stopPricer(bool)"),stopPricer)
QObject.connect(t_pricer,SIGNAL("pricerStatus(QString)"),updateStatus)
# End thread connections

frmMain.show()
sys.exit(app.exec_())


tyranu.py - Smart Tyranu Evavu auto player.

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'C:\Users\Charlie\Desktop\Python\Tyranu AP\tyranu.ui'
#
# Created: Mon Jul 08 22:09:28 2013
# by: PyQt4 UI code generator 4.10.2
#
# WARNING! All changes made in this file will be lost!

import time

from PyQt4 import QtCore, QtGui
from http import [Only registered and activated users can see links]
from random import randint
from Functions import GSB

prog_running = False
w = [Only registered and activated users can see links]()
action_on_ai_fail = "lower" # if the AI has a 50/50 chance of getting it right or wrong, then it will guess this value. valid values: lower, higher

try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s

try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)

class Ui_frmMain(object):
def setupUi(self, frmMain):
frmMain.setObjectName(_fromUtf8("frmMain"))
frmMain.resize(250, 250)
frmMain.setMinimumSize(QtCore.QSize(250, 250))
frmMain.setMaximumSize(QtCore.QSize(250, 250))
self.tabs = QtGui.QTabWidget(frmMain)
self.tabs.setGeometry(QtCore.QRect(0, 0, 250, 250))
self.tabs.setObjectName(_fromUtf8("tabs"))
self.tLogin = QtGui.QWidget()
self.tLogin.setObjectName(_fromUtf8("tLogin"))
self.txtUser = QtGui.QLineEdit(self.tLogin)
self.txtUser.setGeometry(QtCore.QRect(10, 10, 221, 21))
#self.txtUser.setVerticalScrollBarPolicy(QtCore.Qt .ScrollBarAlwaysOff)
#self.txtUser.setHorizontalScrollBarPolicy(QtCore. Qt.ScrollBarAlwaysOff)
self.txtUser.setObjectName(_fromUtf8("txtUser"))
self.txtPass = QtGui.QLineEdit(self.tLogin)
self.txtPass.setGeometry(QtCore.QRect(10, 40, 221, 21))
#self.txtPass.setVerticalScrollBarPolicy(QtCore.Qt .ScrollBarAlwaysOff)
#self.txtPass.setHorizontalScrollBarPolicy(QtCore. Qt.ScrollBarAlwaysOff)
self.txtPass.setObjectName(_fromUtf8("txtPass"))
self.btnLogin = QtGui.QPushButton(self.tLogin)
self.btnLogin.setGeometry(QtCore.QRect(10, 70, 221, 23))
self.btnLogin.setObjectName(_fromUtf8("btnLogin"))
self.label = QtGui.QLabel(self.tLogin)
self.label.setGeometry(QtCore.QRect(10, 100, 46, 13))
self.label.setAlignment(QtCore.Qt.AlignRight|QtCor e.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label.setObjectName(_fromUtf8("label"))
self.lblStatus = QtGui.QLabel(self.tLogin)
self.lblStatus.setGeometry(QtCore.QRect(70, 100, 161, 16))
self.lblStatus.setObjectName(_fromUtf8("lblStatus"))
self.tabs.addTab(self.tLogin, _fromUtf8(""))
self.tAP = QtGui.QWidget()
self.tAP.setObjectName(_fromUtf8("tAP"))
self.btnStart = QtGui.QPushButton(self.tAP)
self.btnStart.setGeometry(QtCore.QRect(10, 10, 221, 23))
self.btnStart.setObjectName(_fromUtf8("btnStart"))
self.btnStop = QtGui.QPushButton(self.tAP)
self.btnStop.setEnabled(False)
self.btnStop.setGeometry(QtCore.QRect(10, 40, 221, 23))
self.btnStop.setObjectName(_fromUtf8("btnStop"))
self.lstLog = QtGui.QListWidget(self.tAP)
self.lstLog.setGeometry(QtCore.QRect(10, 70, 221, 141))
self.lstLog.setObjectName(_fromUtf8("lstLog"))
self.tabs.addTab(self.tAP, _fromUtf8(""))

self.retranslateUi(frmMain)
self.tabs.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(frmMain)

def retranslateUi(self, frmMain):
frmMain.setWindowTitle(_translate("frmMain", "Tyranu Evavu APer", None))
self.txtUser.setText(_translate("frmMain", "Username...", None))
self.txtPass.setText(_translate("frmMain", "Password...", None))
self.btnLogin.setText(_translate("frmMain", "Login!", None))
self.label.setText(_translate("frmMain", "Status:", None))
self.lblStatus.setText(_translate("frmMain", "Idle...", None))
self.tabs.setTabText(self.tabs.indexOf(self.tLogin ), _translate("frmMain", "Neopets Login", None))
self.btnStart.setText(_translate("frmMain", "Start...", None))
self.btnStop.setText(_translate("frmMain", "Stop...", None))
self.tabs.setTabText(self.tabs.indexOf(self.tAP), _translate("frmMain", "Autoplayer", None))

# added by Charlie
self.tabs.setTabEnabled(self.tabs.indexOf(self.tAP ), False)
#self.txtUser.setTabChangesFocus(True)
#self.txtPass.setTabChangesFocus(True)
#self.txtUser.setLineWrapMode(self.txtUser.NoWrap)
#self.txtPass.setLineWrapMode(self.txtPass.NoWrap)

QtCore.QObject.connect(self.btnLogin,QtCore.SIGNAL ("clicked()"),self.callLogin)
QtCore.QObject.connect(self.btnStart,QtCore.SIGNAL ("clicked()"),self.callStart)
QtCore.QObject.connect(self.btnStop,QtCore.SIGNAL("clicked()"),self.callStop)

self.login_thread = LoginWorker()
self.worker_thread = APWorker(self)

QtCore.QObject.connect(self.login_thread, QtCore.SIGNAL("login(int)"),self.processLogin)
QtCore.QObject.connect(self.worker_thread, QtCore.SIGNAL("log(QString)"),self.addLog)
QtCore.QObject.connect(self.worker_thread, QtCore.SIGNAL("stopped()"),self.processStop)

def addLog(self, log):
self.lstLog.insertItem(0, log)

def callLogin(self):
self.lblStatus.setText(_translate("frmMain", "Logging in...", None))
self.txtUser.setReadOnly(True)
self.txtPass.setReadOnly(True)
self.btnLogin.setEnabled(False)

self.login_thread.login(self.txtUser.text(), self.txtPass.text())

def processLogin(self, result):
global w

if result == 1:
# login successful
self.lblStatus.setText(_translate("frmMain", "Logged in!", None))
#self.tabs.setTabEnabled(self.tabs.indexOf(self.tL ogin), False)
self.tabs.setTabEnabled(self.tabs.indexOf(self.tAP ), True)
else:
# not logged in
if result == 2:
r = "Bad password..."
elif result == 3:
r = "No such user..."
elif result == 4:
r = "Account frozen..."
elif result == 5:
r = "Unknown error..."
w.jar.clear()
self.lblStatus.setText(_translate("frmMain", r, None))
self.txtUser.setReadOnly(False)
self.txtPass.setReadOnly(False)
self.btnLogin.setEnabled(True)

def callStart(self):
self.btnStart.setEnabled(False)
self.btnStop.setEnabled(True)
self.addLog("Starting autoplayer...")
self.worker_thread.startAP()

def callStop(self):
self.addLog("Stopping autoplayer...")
self.btnStop.setEnabled(False)
self.worker_thread.prog_running = False

def processStop(self):
self.btnStop.setEnabled(False) # just in case!
self.btnStart.setEnabled(True)
self.addLog("Autoplayer stopped")



class LoginWorker(QtCore.QThread):
def __init__(self, parent = None):
QtCore.QThread.__init__(self, parent)
self.exiting = False

def __del__(self):
self.exiting = True
self.wait()

def login(self, un, pw):
self.un = un
self.pw = pw
self.start()

def run(self):
global w
pd = {"username": self.un, "password": self.pw, "destination": "%2Findex.phtml"}
sHTML = w.request("[Only registered and activated users can see links]", "[Only registered and activated users can see links]", pd, False, True)

if 'Location: /index.phtml' in sHTML:
# log-in successful!
r = 1
else:
if 'errcode=1' in sHTML:
# bad password
r = 2
elif 'errcode=2' in sHTML:
# username doesn't exist
r = 3
elif 'FROZEN' in sHTML:
# frozen
r = 4
else:
# other error; failed bday, too many pw guesses...
r = 5

self.emit(QtCore.SIGNAL("login(int)"), r)

class APWorker(QtCore.QThread):
prog_running = False

def __init__(self, ui, parent = None):
QtCore.QThread.__init__(self, parent)
self.exiting = False

def __del__(self):
self.exiting = True
self.wait()

def startAP(self):
self.prog_running = True
self.start()

def run(self):
global w
global action_on_ai_fail

sHTML = w.request("[Only registered and activated users can see links]")
ref_ck = GSB(sHTML, "name='_ref_ck' value='", "'>")
d = {"_ref_ck": ref_ck, "type": "play", "action": "shuffle", "dealer": randint(0,2)}
sHTML = w.request("[Only registered and activated users can see links]", w.lastURL, d, False, True)

while not 'UGGGGA! Neopoints-a-uggh! :(' in sHTML and not 'played enough for today' in sHTML and self.prog_running:
self.emit(QtCore.SIGNAL("log(QString)"), "Starting a game...")

rnd = 0
deck = {"clubs": range(2,15), "hearts": range(2,15), "spades": range(2,15), "diamonds": range(2,15)}
while not 'The correct answer was' in sHTML:
time.sleep(1)
rnd+=1
remove_card = True

card = GSB(sHTML, "<tr><td><img src='[Only registered and activated users can see links]", ".gif")
try:
card_val, card_suit = card.split("_")
except ValueError:
card_val = 7
remove_card = False

card_val = int(card_val)

if remove_card:
deck[card_suit].remove(card_val)

if card_val == 2:
action = "higher"
elif card_val == 14:
action = "lower"
else:
h = 0
l = 0
for suit in deck:
for v in deck[suit]:
if v <= card_val:
l+=1
else:
h+=1
if h > l:
action = "higher"
elif l > h:
action = "lower"
else:
action = action_on_ai_fail

self.emit(QtCore.SIGNAL("log(QString)"), "Current card: %d; guessing %s..." % (card_val, action))
sHTML = w.request("[Only registered and activated users can see links]" + action, w.lastURL)

# game over
self.emit(QtCore.SIGNAL("log(QString)"), "Game over after %d rounds" % (rnd-1))
self.emit(QtCore.SIGNAL("log(QString)"), "You won %s NP!" % GSB(sHTML, "<br>That's worth <b>", " np"))
time.sleep(1)

if self.prog_running:
sHTML = w.request("[Only registered and activated users can see links]", "[Only registered and activated users can see links]", d, False, True)

# out of NP or plays exhausted or user stopped program from running
if 'UGGGGA! Neopoints-a-uggh! :(' in sHTML:
# need 30NP to play this game
self.emit(QtCore.SIGNAL("log(QString)"), "Out of NP!")
elif 'played enough for today' in sHTML:
# plays for today exhausted
self.emit(QtCore.SIGNAL("log(QString)"), "Out of plays for today!")

self.emit(QtCore.SIGNAL("stopped()"))


if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
frmMain = QtGui.QWidget()
ui = Ui_frmMain()
ui.setupUi(frmMain)
frmMain.show()
sys.exit(app.exec_())


I'm also attaching a score sender source, if anybody is curious. Also very old, uses the flare method of downloading the SWF and decompiling it (also fun fact, I'm pretty sure I was one of the first people who started implementing this method, way way back on **.. I know I at least implemented it / figured it out before Andreas did. Now it seems to be pretty common knowledge.)

I'm mostly posting these because I just wiped my computer and they were in my backup, and I'm planning on deleting them. But I wanted to at least share it with y'all first in case it's helpful to anybody at all.

17671

j03
09-14-2015, 07:00 PM
Great sources! These will definitely be useful to anyone wanting to learn some Neopets automating with Python. :)