this is my code:

import os,sys
import random
import webbrowser
import time
import subprocess as sp

cls=os.system("cls")
title=os.system('title Hit any key to start searhing!')

while True:
    cls
    print "" 
    title
    raw_input()
    getRandEntry()

def getRandEntry():
        theFile = open("wordlist.txt","r")
        wordList = theFile.readlines()
        theRandoms = []
        theRandoms.append(random.choice(wordList)) * 4
        startLink(theRandoms)
        return theRandoms
                
    
def startLink(theRandoms):
        child = sp.Popen(['firefox', '-p',  'myprofile', '-no-remote', 'http://swagbucks.com/?t=w&p=1&q=' + str(theRandoms)])
        time.sleep(15)
        child.terminate() #where taskkill for python goes
        for interval in range(180, 481): #180 seconds = 3 mins, 480 seconds = 8 min
        #for loop is to make the random 3min-8min interval between searches
             time.sleep(interval)
             getRandEntry()

I think I passed the variable theRandoms to the second function correctly but im not sure i need the return statement.

can someone tell me how to make this code work because its not working. also if possible how to make it a bit more effecient because i think my code is crap right now :/

This code IS crap. What is it supposed to do ? First bugs: getRandEntry is called before it is defined (in the while True). The for interval ... loop should be removed. Also did you create a profile named myprofile for firefox ? If you're on windows (which seems to be the case), 'firefox' should probably be replaced by firefox.exe. The * 4 is meaningless. Also can you attach wordlist.text to a post ?

Hint: for each function, and for the script, write a docstring describing what it does.

Edited 7 Years Ago by Gribouillis: n/a

getRandEntry() calls startLink(theRandoms) which calls getRandEntry() which will create and infinite loop.

getRandEntry() calls startLink(theRandoms) which calls getRandEntry() which will create and infinite loop.

That's intentional, this macro is intended for long periods of time's use.

Also, I made a list of things i want the program to do as a comment, and defined my functions before calling them.

import os,sys
import random
import webbrowser
import time
import subprocess as sp

cls=os.system("cls")
title=os.system('title Hit any key to start searhing!')

'''

	This program basically goes through a process (well i want it to.)
	
	1) Start a main prompt that asks you to start or not
	2) Make a variable that has 4 random words from a text file
	3) start firefox.exe to "http://swagbucks.com/?t=w&p=1&q=" and after
				the equal sign, the variable with the 4 terms.
	4) Then it should wait 15 seconds (for loading the webpage, and such)
	5) Close firefox.exe 
	6) Loop again AFTER a random 3 minute to 8 minute wait
	
'''

def getRandEntry():
        theFile = open("wordlist.txt","r")
        wordList = theFile.readlines()
        theRandoms = []
        theRandoms.append(random.choice(wordList)) #if theres no *4 on this line how do i append the variable 4 #times each time with a different random word from the wordlist?
        return theRandoms
        startLink(theRandoms)
                
    
def startLink(theRandoms):
        child = sp.Popen(['firefox.exe', '-p',  'myprofile', '-no-remote', 'http://swagbucks.com/?t=w&p=1&q=' + str(theRandoms)])
        time.sleep(15)
        child.terminate() #where taskkill for python goes
        for interval in range(180, 481): #180 seconds = 3 mins, 480 seconds = 8 min
        #for loop is to make the random 3min-8min interval between searches
             #time.sleep(interval)

#also without the for range() loop how do i get a random time between 3 mins and 8 mins?

             getRandEntry()
             
while True:
    cls
    print "" 
    title
    raw_input()
    getRandEntry()

I also attached my wordlist.exe.

Edited 7 Years Ago by ffs82defxp: n/a

Attachments
1
2
3
4
5
6
7
8
9
0
a
able
about
account
acid
across
act
addition
adjustment
advertisement
after
again
against
agreement
air
all
almost
among
amount
amusement
and
awake
baby
back
bad
bag
balance
ball
band
base
basin
basket
bath
be
beautiful
because
bed
bee
before
behaviour
belief
bone
book
boot
bottle
box
boy
brain
brake
branch
brass
bread
breath
brick
bridge
bright
broken
brother
brown
brush
bucket
building
bulb
burn
burst
business
but
butter
button
by
cake
camera
canvas
card
care
carriage
circle
clean
clear
clock
cloth
cloud
coal
coat
cold
collar
colour
comb
come
comfort
committee
common
company
comparison
competition
country
cover
cow
crack
credit
crime
cruel
crush
cry
cup
cup
current
curtain
curve
cushion
damage
danger
dark
daughter
day
dead
dear
death
debt
decision
deep
degree
delicate
dependent
design
dog
door
doubt
down
drain
drawer
dress
earth
east
edge
education
effect
egg
elastic
electric
end
error
even
event
ever
every
example
exchange
existence
expansion
experience
expert
eye
face
fire
first
fish
fixed
flag
flame
flat
flight
floor
flower
fly
fold
food
foolish
foot
for
force
fork
form
forward
fowl
frame
free
frequent
friend
from
front
fruit
full
future
garden
general
get
girl
give
glass
glove
go
goat
gold
good
government
grain
grass
great
green
grey
grip
group
growth
guide
gun
hair
hammer
hand
hanging
happy
harbour
hard
harmony
hat
hate
have
he
high
history
hole
hollow
hook
hope
horn
horse
hospital
hour
house
how
humour
I
ice
industry
ink
insect
jewel
join
journey
judge
jump
keep
kettle
key
kick
kind
kiss
knee
knife
knot
leg
let
letter
level
library
lift
light
like
limit
line
linen
lip
liquid
list
little
living
lock
long
look
loose
loss
loud
love
low
machine
make
male
man
manager
map
mark
medical
meeting
memory
minute
mist
mixed
money
monkey
month
moon
morning
mother
motion
mountain
new
news
night
no
noise
normal
north
nose
not
note
now
number
nut
observation
of
off
offer
office
oil
payment
peace
pen
pencil
person
physical
picture
pig
pin
pipe
place
plane
plant
position
possible
pot
potato
powder
produce
profit
property
prose
protest
public
pull
pump
punishment
purpose
push
put
quality
question
quick
quiet
quite
rail
regular
relation
religion
representative
request
respect
responsible
rest
reward
rhythm
rice
right
ring
river
road
rod
roll
roof
room
root
scissors
screw
sea
seat
second
secret
secretary
see
seed
seem
selection
self
ship
shirt
shock
shoe
short
shut
side
sign
silk
silver
simple
slope
slow
small
smash
smell
smile
smoke
smooth
stamp
star
start
statement
station
steam
steel
stem
step
stick
sticky
stiff
still
stitch
stocking
stomach
surprise
sweet
swim
system
table
tail
take
talk
tall
taste
tax
thumb
thunder
ticket
tight
till
time
tin
tired
to
toe
together
value
verse
very
vessel
view
violent
voice
waiting
walk
wall
war
warm
wash
waste
wise
with
woman
wood
wool
word
work
worm
wound
writing
wrong
year
yellow
yes
yesterday
you
young

Woooee is right. The correct structure to implement

do this
do that
loop again after a random time

is

while True:
    do_this()
    do_that()
    wait_a_random_time()

This is very different from 2 functions calling each other in an infinite recursion. So the proper design for your program is

import time
import subprocess as sp

def main():
    if prompt_do_we_start():
        while true:
            variable = make_variable()
            browser = browse_swagbucks(variable)
            time.sleep(15)
            browser.terminate()
            interval = choose_random_time(3 * 60, 8 * 60)
            time.sleep(interval)

def prompt_do_we_start():
    pass # TODO

def make_variable():
     pass # TODO

def browse_swagbucks(variable):
    pass # TODO

def choose_random_time(mini, maxi):
    pass # TODO

if __name__ == "__main__":
    main()

Edited 7 Years Ago by Gribouillis: n/a

That's intentional, this macro is intended for long periods of time's use.

You will soon reach the maximum recursion limit. Use a while loop instead as Gribouillis suggested. Also, you can read the word file once into memory, shuffle it to some random order, and then take the words in groups of 4.

word_list = open("wordlist.txt").readlines()
random.shuffle(wordlist)

start = 0
go_on = ""
while go_on != "no":
    four_random_words = [word_list[x] for x in range(start, start+4)]
    start += 4   ## ready for next 4 random words 
    
    ## then send four_random_words to function to start Firefox
    
    ##  sleep for random time, 3 to 8 minutes
    time.sleep(random.randint(3, 8) * 60)
    go_on = raw_imput("Do you want to continue (yes or no) ")
    go_on = go_on.lower()

I combined both of you guys's scripts and got this.

This is what I got:

import time
import random
import subprocess as sp

def main():
    if prompt_do_we_start():
        while true:
            variable = make_variable()
            browser = browse_swagbucks(variable)
            time.sleep(15)
            browser.terminate()
            interval()

def prompt_do_we_start():
##im lost here too..if its 'y' then how do i break out of this function and continue on the main() function?
    print ''
    print 'Would you like to run the SwagBot now? [Y/N] ONLY'
    dec = raw_input("--> ")
    if dec == Y:
        pass
    elif dec == N:
        pass
        ##in this spot i'd normally put something to redo prompt_do_we_start() till the user says 'y'
    else:
        ##if else i want it to keep refreshing prompt_do_we_start() so the user can wait on it until 'y' is inputted.

def make_variable():
    word_list = open("wordlist.txt").readlines()
    random.shuffle(wordlist)

    start = 0
    four_random_words = [word_list[x] for x in range(start, start+4)]
    start += 4   ## ready for next 4 random words 

    
    ## then send four_random_words to function to start Firefox
    return (four_random_words)
    ##i don't think return here is right. how do i escape a function and
    ##continue on the main() function up there from the last point i was at?
    ##, the part that called this function


def browse_swagbucks():
    browser = sp.Popen(['firefox.exe', '-p',  'myprofile', '-no-remote', 'http://swagbucks.com/?t=w&p=1&q=' + str(variable)])
    

def interval():
    
    ##  sleep for random time, 3 to 8 minutes
    time.sleep(random.randint(3, 8) * 60)


if __name__ == "__main__":
    main()

Oh yeah! i forgot, i need the 4 word variable up there to be seperated by + signs between each word..i forgot to mention that.
how would i do that?

Edited 7 Years Ago by ffs82defxp: n/a

Here is a working version. See how function parameters and return values are used to answer your questions.

import time
import random
import subprocess as sp

FIREFOX = 'firefox.exe'
PROFILE = 'myprofile'
TIME_MINI = 3 * 60
TIME_MAXI = 8 * 60

def main():
    if prompt_do_we_start():
        word_list = open("wordlist.txt").readlines() # read the file only once
        make_variable.start = len(word_list)
        while True:
            variable = make_variable(word_list)
            browser = browse_swagbucks(variable)
            time.sleep(15)
            browser.terminate()
            interval()

def prompt_do_we_start():
    """prompt_do_we_start() -> True or False
    Prompt the user if he/she wants to run SwagBot."""
    while True:
        print ''
        print 'Would you like to run the SwagBot now? [Y/N] ONLY'
        dec = raw_input("--> ")
        if dec == 'Y':
            return True
        elif dec == 'N':
            print("Bye...")
            return False
        else:
            print("Please enter Y or N")

def make_variable(word_list):
    """make_variable -> a string of 4 random words separated by +"""
    start = make_variable.start
    if start >= len(word_list):
        random.shuffle(word_list)
        start = 0
    four_random_words = [word_list[x] for x in range(start, start + 4)]
    make_variable.start = start + 4   ## ready for next 4 random words 
    return "+".join(four_random_words)

def browse_swagbucks(variable):
    """browse_swagbucks(variable) -> a subprocess.Popen object
    Start firefox with a query to swagbucks.com in a separate process."""
    browser = sp.Popen([FIREFOX, '-p',  PROFILE, '-no-remote',
       'http://swagbucks.com/?t=w&p=1&q=' + str(variable)])
    return browser    

def interval():
    """interval() -> None. Pause the program during a random period of time"""
    sec = random.randint(TIME_MINI, TIME_MAXI)
    print("wait %d seconds ..." % sec)
    time.sleep(sec)

if __name__ == "__main__":
    main()

Edited 7 Years Ago by Gribouillis: Added docstrings.

The %d in print("wait %d seconds ..." % sec) will be replaced with the numeric value of sec.

I didn't see the %s, but it is used for string values.

@Gribouillis
Shouldn't line 39 test start + 3 against the length of the list?
We're going to be referencing array elements that high.

@Gribouillis
Shouldn't line 39 test start + 3 against the length of the list?
We're going to be referencing array elements that high.

Yes, you are right, I missed that. It was woooee's idea to shuffle the list once
and take subsequent groups of 4 words. I don't think it's a very good method, because a word can't be repeated until all the words have been chosen once. We should probably choose 4 random positions in the list instead.

I would also have leaned toward re-shuffling for each set of random words. Just as long as you don't re-read the words from the file, you've saved most of the work.

You could also use choice() instead of shuffling, but you'd have to protect against selecting the same word more than once in a set.

Yes, you are right, I missed that. It was woooee's idea to shuffle the list once
and take subsequent groups of 4 words. I don't think it's a very good method, because a word can't be repeated until all the words have been chosen once. We should probably choose 4 random positions in the list instead.

Okay so whats the altered code, because i hve no idea how to do that.

Okay so whats the altered code, because i hve no idea how to do that.

You can write

def make_variable(word_list):
    return "+".join(random.sample(word_list, 4))

I just learned about random.sample in the python documentation.

Okay i replaced the old variable function with that new one.

import time
import time
import random
import subprocess as sp

FIREFOX = 'firefox.exe'
PROFILE = 'myprofile'
TIME_MINI = 3 * 60
TIME_MAXI = 8 * 60

def main():
    if prompt_do_we_start():
        word_list = open("wordlist.txt").readlines() # read the file only once
        make_variable.start = len(word_list)
        while True:
            variable = make_variable(word_list)
            browser = browse_swagbucks(variable)
            time.sleep(15)
            browser.terminate()
            interval()

def prompt_do_we_start():
    """prompt_do_we_start() -> True or False
    Prompt the user if he/she wants to run SwagBot."""
    while True:
        print ''
        print 'Would you like to run the SwagBot now? [Y/N] ONLY'
        dec = raw_input("--> ")
        if dec == 'Y':
            return True
        elif dec == 'N':
            print("Bye...")
            return False
        else:
            print("Please enter Y or N")

def make_variable(word_list):
    return "+".join(random.sample(word_list, 4))

def browse_swagbucks(variable):
    """browse_swagbucks(variable) -> a subprocess.Popen object
    Start firefox with a query to swagbucks.com in a separate process."""
    browser = sp.Popen([FIREFOX, '-p',  PROFILE, '-no-remote',
       'http://swagbucks.com/?t=w&p=1&q=' + str(variable)])
    return browser    

def interval():
    """interval() -> None. Pause the program during a random period of time"""
    sec = random.randint(TIME_MINI, TIME_MAXI)
    print("wait %d seconds ..." % sec)
    time.sleep(sec)

if __name__ == "__main__":
    main()

But I got these errors for that code:

Traceback (most recent call last):
File "C:\Documents and Settings\Sameer\Desktop\Python Creations\Swagbucks Macro v2.5\new swagbot.py", line 54, in <module>
main()
File "C:\Documents and Settings\Sameer\Desktop\Python Creations\Swagbucks Macro v2.5\new swagbot.py", line 17, in main
browser = browse_swagbucks(variable)
File "C:\Documents and Settings\Sameer\Desktop\Python Creations\Swagbucks Macro v2.5\new swagbot.py", line 44, in browse_swagbucks
'http://swagbucks.com/?t=w&p=1&q=' + str(variable)])
File "C:\Python\lib\subprocess.py", line 621, in __init__
errread, errwrite)
File "C:\Python\lib\subprocess.py", line 830, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

Edited 7 Years Ago by ffs82defxp: n/a

It seems that your program cannot find firefox.exe. Try to locate this file manually in your file system (probably in C:\Program Files .... Then put the whole path

FIREFOX = r"C:\Program Files ..."

at the top of the program.

Edited 7 Years Ago by Gribouillis: n/a

I still get errors,

Traceback (most recent call last):
File "C:\Documents and Settings\Sameer\Desktop\Python Creations\Swagbucks Macro v2.5\new swagbot.py", line 54, in <module>
main()
File "C:\Documents and Settings\Sameer\Desktop\Python Creations\Swagbucks Macro v2.5\new swagbot.py", line 17, in main
browser = browse_swagbucks(variable)
File "C:\Documents and Settings\Sameer\Desktop\Python Creations\Swagbucks Macro v2.5\new swagbot.py", line 44, in browse_swagbucks
'http://swagbucks.com/?t=w&p=1&q=' + str(variable)])
File "C:\Python\lib\subprocess.py", line 621, in __init__
errread, errwrite)
File "C:\Python\lib\subprocess.py", line 830, in _execute_child
startupinfo)
WindowsError: [Error 3] The system cannot find the path specified

Ok, replace the browse function by this one

def browse_swagbucks(variable):
    """browse_swagbucks(variable) -> a subprocess.Popen object
    Start firefox with a query to swagbucks.com in a separate process."""
    command = [FIREFOX, '-p',  PROFILE, '-no-remote',
       'http://swagbucks.com/?t=w&p=1&q=' + str(variable)]
    print( " ".join(command))
    browser = sp.Popen(command)
    return browser

It will print the command on the output before it tries to run it. Then see if you can run this command in a windows command shell yourself. Also post the command here.

This question has already been answered. Start a new discussion instead.