Count click with python pyautogui - python

Hello guys i m starting learning about pyautogui and with the code below i can locate if an image is on my screen and click on it and count it and print count.
import pyautogui
import time
def main():
print('BOT PROTOTIPO 1.0')
time.sleep(5)
tentativa = 0
while True:
if pyautogui.locateOnScreen('ButtonTest.png'):
x = pyautogui.locateOnScreen('ButtonTest.png')
print('ButtonTest clicked')
pyautogui.click(x)
time.sleep(3)
tentativa += 1
print(tentativa)
main()
What i need now is if ButtonTest.png was clicked by the user mouse, count in a different variable.
Hope you help me.

Related

Pyautogui Randomize Clicks locateonscreen and moveto

Hello I want to Randomize Clicks inside Pyautogui if it found a locateonscreen image or if it found pixelmatch color
so i tryed something but i cant check it becorse of the script is only use my part of code after other actions bevore
i have no idea to try only this function
i tried
def DisclaimerCheckAndClick():
try:
# Diclaimer 1
print("locate DisclaimerBingAccept01.png")
sleep(1)
x,y = locateCenterOnScreen("DisclaimerBingAccept01.png",region=(10,400,920,630), confidence=0.7)
click(x,y)
print("clicked DisclaimerBingAccept01.png",(x,y))
sleep(5)
pyautogui.hotkey('f5')
print("hotkey('f5') pressed..")
print("sleep(10)")
sleep(10)
ClickThirdTab()
# Doesn´t work for bing
#try:
#x,y = locateCenterOnScreen("BingSearchInputfieldSymbol.png",region=(10,160,920,630), confidence=0.7)
#pyautogui.moveTo(x,y,0.5)
#sleep(1)
#click(x,y)
#sleep(0.5)
#click(x,y)
#print("clicked BingSearchInputfieldSymbol.png",(x,y))
#except:
#print("BingSearchInputfieldSymbol.png not found")
except:
try:
# Diclaimer 2
print("locate DisclaimerGoogleAccept01.png")
sleep(1)
x,y = locateCenterOnScreen("DisclaimerGoogleAccept01.png",region=(10,400,920,630), confidence=0.7)
click(x,y)
print("clicked DisclaimerGoogleAccept01.png",(x,y))
sleep(5)
pyautogui.hotkey('f5')
print("hotkey('f5') pressed..")
print("sleep(15)")
sleep(15)
try:
x,y = locateCenterOnScreen("GoogleSearchInputfieldSymbol.png",region=(10,160,920,630), confidence=0.7)
pyautogui.moveTo(x,y,0.5)
sleep(1)
click(x,y)
print("clicked GoogleSearchInputfieldSymbol.png",(x,y))
pass
except:
print("GoogleSearchInputfieldSymbol.png not found")
I Try to Randomize this Disclaime Clicker script i found this :
DisclaimerYoutubeAccept01 = locateOnScreen('DisclaimerYoutubeAccept01.png',region=(10,400,920,630), confidence=0.7)
if Bank is not None:
pyautogui.moveTo(randomClick(DisclaimerYoutubeAccept01))
click()
print("clicked DisclaimerYoutubeAccept01.png",(DisclaimerYoutubeAccept01))
this isnt working so i tryed
DisclaimerYoutubeAccept01 = locateOnScreen('DisclaimerYoutubeAccept01.png',region=(10,400,920,630), confidence=0.7)
pyautogui.moveTo(randomClick(DisclaimerYoutubeAccept01))
click()
print("clicked DisclaimerYoutubeAccept01.png",(DisclaimerYoutubeAccept01))
this is my Def for Click
#Clicks location at x,y
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(0.1) #This pauses the script for 0.1 seconds
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
and this for the RandomCLICK(box)
def randomClick(box):
x_click = int(random.uniform(box.left, box.left+box.width))
y_click = int(random.uniform(box.top, box.top+box.height))
return (x_click, y_click)
but i cant check if it works script started but i cant check if this is working becorse the check of Disclaimer will only trigger if many things before are tryed
so what you think?

Python: How to take control of the cursor if cursor is inactive for five minutes and pause the program (my python program) if user touches the mouse?

I want to write a bot that will simulate mouse movements when user is away for more than 5 minutes and stay put when user takes control i.e. moves the mouse.
I have written following code as a part of the program.
Here is the link to my old program which clicks at given points periodically. The problem with this program is I have to start the program when I want to go somewhere and after returning close the program in order to resume working.
Here is the one of the module I wrote for the new program which detects whether mouse is moving or not.
import win32api
from time import sleep
print("starting engine.")
count = 0
while(True):
savedpos = win32api.GetCursorPos()
if count>20*5:
break
sleep(1)
curpos = win32api.GetCursorPos()
if savedpos == curpos:
savedpos = curpos
print("Mouse is steady.")
else:
print("Mouse is moving.")
count += 1
I wont be writing the code but I have the Idea to solve the problem
you use pyautogui.position() to keep checking the position and if it doesnt change position for 300 seconds you move it
I wrote following code referring other Stackoverflow posts.
This code waits 4 minutes for mouse being steady. Whenever mouse is moved, timer is reset to zero.
import win32api
from time import sleep
import pyautogui as gui
print("starting engine.")
count = 0
savedpos = win32api.GetCursorPos()
def actions():
print(gui.size())
while True:
#toast.show_toast("ROBOT V2 !", "Robot is active.", threaded=False, icon_path=None, duration=2)
gui.click()
gui.press('home')
gui.moveTo(541, 142, 0.25) # Money Transfer dropdown
gui.click()
sleep(0.5)
gui.moveTo(541, 172, 0.25) # Money Transfer link
gui.click()
sleep(5)
cond()
def cond():
count = 0
while True:
savedpos = win32api.GetCursorPos()
sleep(0.5)
curpos = win32api.GetCursorPos()
if savedpos == curpos:
savedpos = curpos
print("Mouse is steady. Elapsed time: ", (count+1)/2, " seconds.")
count += 1
if count >= 480: # if count is greater than 60 it means timeout will occur after mouse is steady for more than
# 240 seconds i.e. 4 minutes. (approx.)
print("User away for more than 4 minutes, taking control of the system.")
actions()
break
else:
pass
else:
print("Mouse is moving.")
count = 0
cond()

python - can't get audio player working

everything works except the next song doesn't play after the first is finished.
import os, random
from pygame import mixer
from pynput import keyboard
startup = 0
pause = 0
volume = 0.5
def Picker():
global startup
global volume
startup += 1
if startup > 1:
ThisSong = random.choice(os.listdir("C:\\Users\\...\\Music"))
NextSong = random.choice(os.listdir("C:\\Users\\...\\Music"))
ThisSong = NextSong
if ThisSong != NextSong:
mixer.init()
mixer.music.load("C:\\Users\\...\\Music" + ThisSong)
mixer.music.play(0)
mixer.music.set_volume(volume)
while mixer.music.get_busy():
def on_press(key):
global pause
global volume
if key == keyboard.KeyCode(char='-'):
volume -= 0.1
if volume < 0.1:
volume = 0.1
mixer.music.set_volume(volume)
if key == keyboard.KeyCode(char='='):
volume += 0.1
if volume > 1:
volume = 1
mixer.music.set_volume(volume)
if key == keyboard.KeyCode(char='['):
pause += 1
if pause == 1:
mixer.music.pause()
pause = 2
if pause == 3:
mixer.music.unpause()
pause = 0
with keyboard.Listener(on_press=on_press) as listener: listener.join()
else:
Picker()
else:
pass
Picker()
Picker()
screenshot of code
I can't get it to work, i'm very new to python so i'm probably missing something
obvious
Before starting: Thx #JGreenwell for copying the code.
Ok, so first, I’ll help you clean your code.
Things that are wrong
Having all that ThisSong and NextSong things: It won’t get saved when you restart Picker(). Either just have ThisSong, or place the ThisSong and NextSong assignment with the volume and pause variables:
.
pause = 0 # this is a problem! Next point
volume = 0.5
ThisSong = random.choice(...)
NextSong = random.choice(...)
The pause variable should be a boolean (True/False) and the pausing code should be like this:
.
pause = not pause
if pause:
# pause
else:
# unpause
Also, it would ideally be called paused
on_press and the Listener declaration should be outside the while loop, because otherwise they just keep being declared every time it loops. Then you should import time and put time.sleep(500) or something like that in the while loop, so that it doesn’t check every fraction of second.
As for the next song not playing, I don’t really know, but I’d suggest entering Picker() in the shell after the program has run (python -i script.py from CMD, IDLE leaves you in a shell by default). I would also suggest really following recommendation #3 as having them in the loop may break the loop and stop it from finishing. Most importantly, I would ask you to debug your code by adding print in every step of your code:
print(1)
if something:
print(2)
etc...
And seeing where it blocks
P.S.: The random dots are because you can’t have code in lists, so I had to exit the list.
Working solution, incase anyone else has the same problem as me in the future :)
from pygame import mixer
from pynput import keyboard
import threading
import random
import os
paused = 0
def player():
song = random.choice(os.listdir("C:\\users\\...\\desktop\\music"))
mixer.init()
mixer.music.load("C:\\users\\...\\desktop\\music\\" + song)
mixer.music.play(0)
while mixer.music.get_busy():
pass
else:
player()
def main():
t = threading.Thread(target = player, name = 'thread1', args = ())
t.start()
main()
def on_press(key):
global paused
if key == keyboard.KeyCode(char='['):
paused = not paused
if paused:
mixer.music.pause()
else:
mixer.music.unpause()
with keyboard.Listener(on_press=on_press) as listener: listener.join()

I have an error in python with tkinter and need help(school project)

I have to create a little text adventure for school in python.
To detect keyboard inputs I decided to use tkinter and disable the window.
All is working fine but if I try to calculate with a variable after a key was pressed, I get the following error...This is the error message
This is the script I am using(I don't have much experience with python...)
import os
import sys
import tkinter
menueeintraege = ["Start", "Steuerung", "Credits", "Beenden"]
index = 0
def menueaufbauen():
os.system("cls")
print("Menue")
print("")
print("")
for i in range(4):
if i == index:
print(menueeintraege[i] + "<")
else:
print(menueeintraege[i])
menueaufbauen()
def startgame():
os.system("game.py");
def steuerung():
os.system("cls")
print("Steuerung")
print("")
print("Norden = Pfeiltaste Hoch")
print("Sueden = Pfeiltaste Runter")
print("Osten = Pfeiltaste Rechts")
print("Westen = Pfeiltaste Links")
print("Bestaetigen = Enter")
def credits():
os.system("cls")
print("Credits")
print("")
print("Jannik Nickel")
print("Thomas Kraus")
print("")
def exitgame():
sys.exit()
def menueauswahl(taste):
print(taste)
if taste == "Up":
if index > 0:
index -= 1
print(index)
elif taste == "Down":
if index < 3:
index += 1
menueaufbau()
def tasteneingabe(event):
tastenname = event.keysym
menueauswahl(tastenname)
fenster = tkinter.Tk()
fenster.bind_all('<Key>', tasteneingabe)
fenster.withdraw()
fenster.mainloop()
I think the mistake have to be in the last part of the script, I hope someone here knows a solution because it's really important for school.
Thanks for any help
(I'm using Visual Studio 2015)
Okay so I caught a couple of errors. The first is that you are referencing a global variable (index) inside of a function. To do that, you need to tell python that you are using a global variable.
def menueauswahl(taste):
global index
print(taste)
And also you need to change the function name in line 61 to menuaufbauen().

Python Cookie Clicker: Auto Click Function?

My Background:
I have done quite a bit of programming with python, I would say I am not bad at it. I am familiar with most of the modules, OOP programming and stuff. You can check my pastebin profile to see what level I am actually in: www.pastebin.com/u/GameNationRDF/
The Code:
from tkinter import *
import time
master = Tk()
def uiPrint():
info()
print ("")
print (click)
blankLine()
def info():
print ("Double click purchases need 750 clicks!")
info()
click = 0
mult = 1
dcp1 = 0
def blankLine():
for i in range(20):
print ("")
def purchaseDoubleClicksCommand():
global click
global mult
if click < 750:
print ("Not enough clicks!")
blankLine()
elif click >= 750:
mult = mult*2
click = click - 750
print ("Double Clicks Purchased!")
blankLine()
def buttonCommand():
global click
global mult
click += 1*(mult)
uiPrint()
if click == 100:
print ('''Achievement Unlocked: Junior Clicker!
BONUS 100!''')
click += 100
elif click == 400:
print ('''Achievement Unlocked: Little Ninja Clicks!
BONUS 200!''')
click += 300
elif click == 900:
print ('''Achievement Unlocked: Legit Ninja!
DOUBLE CLICKS!''')
mult = mult * 2
elif click == 1500:
print ('''Achievement Unlocked: Click Ninja Master!
QUAD CLICKS!''')
mult = mult * 4
elif click == 3000:
print ('''Achievement Unlocked: Jackie Chan Style!
8 TIMES THE CLICKS!''')
mainClickButton = Button(master, text="Click!", command=buttonCommand)
mainClickButton.pack()
purchaseDoubleClickButton = Button(master, text="Purchase Double Clicks", command = purchaseDoubleClicksCommand)
purchaseDoubleClickButton.pack()
master.title("Clicker! v0.0.6")
master.geometry("%sx%s+%s+%s" % (200,70,512,512))
mainloop()
I need a way to be able to add a auto-clicker that would add certain amount of cookies in a given time. I want it to be purchased by a button. I couldnt get it to work though :(
Any help? Thanks :)
The PyUserInput project looks promising and straightforward:
from pymouse import PyMouse
m = PyMouse()
x_dim, y_dim = m.screen_size()
m.click(x_dim/2, y_dim/2, 1)
Why do you import * by the way? It's bad practice to import more dependencies than needed.
Also if I were you I would move the following section of code:
master = ()
info()
click = 0
mult = 1
dcp1 = 0
to reside above this line:
mainlickButton = Button(master, text="Click!", command=buttoncommand)
It's just cleaner to add declarations and functions. It doesn't make a GINORMOUS difference now, but when your file gets bigger and you have a lot of code it will be easier to read.

Categories

Resources