Make a auto clicker that clicks while I'm holding left click - python

As I said, I'm pretty new to coding and python, and I need to make an auto clicker that toggles when I hold left click and stops when i release the button. The current code makes a key bind that toggles it off and on. I was searching the web for the last few days and couldn't find anything. Thanks in advance!
import time
import threading
import random
from pynput.mouse import Button, Controller
from pynput.keyboard import Listener, KeyCode
x = (0.7, 0.8, 0.9, 0.11)
delay = random.choice(x)
button = Button.left
start_stop_key = KeyCode(char='s')
exit_key = KeyCode(char='e')
class ClickMouse(threading.Thread):
def __init__(self, delay, button):
super(ClickMouse, self).__init__()
self.delay = delay
self.button = button
self.running = False
self.program_running = True
def start_clicking(self):
self.running = True
def stop_clicking(self):
self.running = False
def exit(self):
self.stop_clicking()
self.program_running = False
def run(self):
while self.program_running:
while self.running:
mouse.click(self.button)
time.sleep(self.delay)
time.sleep(0.1)
mouse = Controller()
click_thread = ClickMouse(delay, button)
click_thread.start()
def on_press(key):
if key == start_stop_key:
if click_thread.running:
click_thread.stop_clicking()
else:
click_thread.start_clicking()
elif key == exit_key:
click_thread.exit()
listener.stop()
with Listener(on_press=on_press) as listener:
listener.join()
mouse = Controller()
click_thread = ClickMouse(delay, button)
click_thread.start()
def on_press(key):
if key == start_stop_key:
if click_thread.running:
click_thread.stop_clicking()
else:
click_thread.start_clicking()
elif key == exit_key:
click_thread.exit()
listener.stop()
with Listener(on_press=on_press) as listener:
listener.join()

For what it is worth, I would look to this approach:
PyAutoGUI Chapter
With full documentation here:
PyAutoGUI Docs:

Related

How to block only one mouse button?

The middle button on my mouse sometimes clicks several times when I click it once. My mouse is expensive and I like it, so I decided to fix it with a program.
When I release the middle button, I'd like to freeze it for 0.1 seconds without freezing the other buttons.
I tried to block with the supress=True flag in pynput library, and then sending button for windows, but this doesn't work.
from pynput.mouse import Button, Controller, Listener
import time
mouse = Controller()
class BlockMiddle:
def __init__(self):
self.start = time.time()
with Listener(on_click=self.on_click, on_move=self.on_move,
suppress=True
) as listener:
listener.join()
def on_click(self, x, y, button, pressed):
if button == Button.left:
if pressed:
mouse.press(Button.left)
else:
mouse.release(Button.left)
if button == Button.right:
if pressed:
mouse.press(Button.right)
else:
mouse.release(Button.right)
if button == Button.middle:
if pressed:
if time.time() - self.start > 0.1:
mouse.press(Button.middle)
else:
mouse.release(Button.middle)
self.start = time.time()
if button == Button.x1:
if pressed:
mouse.press(Button.x1)
else:
mouse.release(Button.x1)
if button == Button.x2:
if pressed:
mouse.press(Button.x2)
else:
mouse.release(Button.x2)
def on_move(self, x, y):
mouse.position = (x, y)
block = BlockMiddle()
Finally I solved my problem.
from pynput.mouse import Button, Controller, Listener
import time
mouse = Controller()
class BlockMiddle:
def __init__(self):
self.start = time.time()
self.listener = Listener(
on_click=self.on_click,
on_move=self.on_move,
on_scroll=self.on_scroll,
suppress=False
)
with self.listener as l:
l.join()
def on_click(self, x, y, button, pressed):
self.listener._suppress = False
if not button == Button.middle:
return
if time.time() - self.start < 0.1:
self.listener._suppress = True
if not pressed:
self.start = time.time()
self.listener._suppress = False
def on_move(self, x, y):
self.listener._suppress = False
def on_scroll(self, x, y, dx, dy):
self.listener._suppress = False
block = BlockMiddle()

Simultaneous mouse press events in Python using Pynput

I am using scrcpy to mirror an Android phone to my computer in order to play a game. The issue is that scrcpy does not support keyboard mapping natively, so I'm writing a Python script to map the keyboard to execute the key presses I need to play the game (using WASD to move around, space to jump, etc.).
I'm fairly new to programing in general and to Python in particular, but so far it's been going pretty well using Pynput. Basically, I am mapping different keys on my keyboard to correspond to mouse clicks on different areas of the screen. My issue is that, as written, my script can only push one left mouse press event at a time.
For example, pressing "w" (to move forward) and space (jump) at the same time will move the cursor to different areas on the screen, and will therefore not result in the desired outcome. The game itself supports simultaneous touch input when played on an Android screen (I can press different areas on the screen at the same time to execute certain actions), so ideally I would need my script to be able to recreate this behavior.
I was wondering if there was a way to do this in Python?
from pynput.mouse import Button, Controller
from pynput.keyboard import Key, KeyCode, Listener
global MOUSE
MOUSE = Controller()
global CENTER
global HEIGHT
CENTER = 315
HEIGHT = 800
global LISTEN
def cust_click(x,y):
MOUSE.position = (x,y)
MOUSE.press(Button.left)
def cust_mvmt_click(x, y):
MOUSE.position = (CENTER, HEIGHT)
MOUSE.press(Button.left)
MOUSE.move(x, y)
#WASD movement
def w():
cust_mvmt_click(0, -100)
def s():
cust_mvmt_click(0, 100)
def a():
cust_mvmt_click(-100, 0)
def d():
cust_mvmt_click(100, 0)
#Miscellaneous
def space():
cust_click(CENTER*5.75,HEIGHT*0.95)
def c():
cust_click(CENTER*5.15, HEIGHT*1.2)
#Weapon controls
def r():
cust_click(CENTER*4.75, HEIGHT*1.15)
def f():
cust_click(CENTER*0.5, HEIGHT*0.7)
def ctrl():
cust_click(CENTER*5.15, HEIGHT)
def q():
cust_click(CENTER*5.3, HEIGHT*0.77)
def switch1():
cust_click(CENTER*2.75, HEIGHT*1.15)
def switch2():
cust_click(CENTER*3.3, HEIGHT*1.15)
def switch3():
cust_click(CENTER*3, HEIGHT*1.05)
def on_press(key):
if key == KeyCode(char='w'):
w()
elif key == KeyCode(char='f'):
f()
elif key == Key.shift_l:
ctrl()
elif key == KeyCode(char='q'):
q()
elif key == KeyCode(char='s'):
s()
elif key == KeyCode(char='a'):
a()
elif key == KeyCode(char='d'):
d()
elif key == KeyCode(char='c'):
c()
elif key == KeyCode(char='r'):
r()
elif key == Key.space:
space()
elif key == KeyCode(char='1'):
switch1()
elif key == KeyCode(char='2'):
switch2()
elif key == KeyCode(char='3'):
switch3()
elif key == Key.tab:
LISTEN.stop()
def on_release(key):
if key == Key.shift_l or key == KeyCode(char='1') or key == KeyCode(char='f') or key == KeyCode(char='2') or key == KeyCode(char='3') or key == KeyCode(char='r') or key == KeyCode(char='c') or key == KeyCode(char='s') or key == KeyCode(char='a') or key == KeyCode(char='d') or key == Key.space or key == KeyCode(char='q') or key == KeyCode(char='w'):
MOUSE.release(Button.left)
MOUSE.position = (CENTER*390/100,HEIGHT*70/100) #1235, 565
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as LISTEN:
LISTEN.join()
You can use pydirectinput or pydirectinput-rgx for clicking. Check
https://www.google.com/url?sa=t&source=web&rct=j&url=https://pypi.org/project/PyDirectInput/&ved=2ahUKEwi9sbb7w6b6AhXE23MBHV85ChgQFnoECBEQAQ&usg=AOvVaw2EChi0UGXZlMafbw1aHhod
for its documentation.

How to detect what button was clicked? (Pynput)

I'm trying to detect what mouse button was clicked
so here is my code:
from pynput.mouse import Listener
def on_click(button, pressed):
if button.Left and pressed:
print("You pressed the left mouse button")
if button.Right and pressed:
print("You pressed the right mouse button")
so there was no errors but It's not working any Ideas?
From the Documentation Here
CODE
from pynput import mouse
def on_move(x, y):
print('Pointer moved to {0}'.format(
(x, y)))
def on_click(x, y, button, pressed):
print(button) # Print button to see which button of mouse was pressed
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
# Collect events until released
with mouse.Listener(
on_click=on_click
) as listener:
listener.join()
# ...or, in a non-blocking fashion:
listener = mouse.Listener(on_click=on_click)
listener.start()
As you can see, the button parameter in the function on_click tells you which button was pressed.
EDIT:
Here is how you may handle action based on which button of the mouse was pressed
def on_click(x, y, button, pressed):
btn = button.name
if btn == 'left':
print('Left if Pressed')
# ====== < Handle Pressed or released Event ====== > #
if pressed:
print('Do somethin when Pressed with LEft')
else:
print('LEFT is Released')
elif btn == 'right':
print('Right BTN was pressed ')
# ====== < Handle Pressed or released Event ====== > #
if not pressed:
print('right Button is released')
else:
pass
I post a second answer because of a different nature of the issue found on code here
The issue is how you call the imports.
CORRET CODE
from pynput import mouse
mouse_ = mouse.Controller()
button = mouse.Button
def on_click(x, y, button, pressed):
btn = button.name
if btn == 'left':
if pressed:
mouse_.click(button_.left)
print('works')
with mouse.Listener(
on_click=on_click
) as listener:
listener.join()
Copy and Paste the code without changes.
WARNING
when I use button.left my pc becomes extremely lagy so i suggest you to don't use is unless you know what you are doing

How to manage events in pyglet as Pygame?

I do not understand completely how to use pyglet's event system. What I need to do is to get each event for each frame. In Pygame I can do it in the following way:
import sys, pygame
pygame.init()
size = width, height = 320, 240
screen = pygame.display.set_mode(size)
while 1:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT: sys.exit()
screen.fill((0,0,0))
pygame.display.flip()
I accomplish something similar with pyglet, using 'pyglet.window.event.WindowEventLogger()' but I do not how to acces to the information that the WindowEventLogger prints, and it prints the same event more than once.
How could I obtain a pyglet version of the pygame code above?
Here's a basic example of a working class that dispatches events.
#!/usr/bin/python
import pyglet
from time import time, sleep
class Window(pyglet.window.Window):
def __init__(self, refreshrate):
super(Window, self).__init__(vsync = False)
self.frames = 0
self.framerate = pyglet.text.Label(text='Unknown', font_name='Verdana', font_size=8, x=10, y=10, color=(255,255,255,255))
self.last = time()
self.alive = 1
self.refreshrate = refreshrate
def on_draw(self):
self.render()
def render(self):
self.clear()
if time() - self.last >= 1:
self.framerate.text = str(self.frames)
self.frames = 0
self.last = time()
else:
self.frames += 1
self.framerate.draw()
self.flip()
def on_close(self):
self.alive = 0
def run(self):
while self.alive:
self.render()
event = self.dispatch_events() # <-- This is the event queue
sleep(1.0/self.refreshrate)
win = Window(23) # set the fps
win.run()
However note that normally I never encounter any events at all in this event queue. Most likely because Pyglet works with function decorators/hooks.
So for instance, if you want to catch keyboard events, you would simply add the following code to this awesome class:
def on_key_release(self, symbol, modkey):
print(symbol, modkey)
There's also on_mouse_motion etc :)

Pygame music pause/unpause toggle

Okay here's my code:
def toggleMusic():
if pygame.mixer.music.get_busy():
pygame.mixer.music.pause()
else:
pygame.mixer.music.unpause()
---event handling---
if pressed 'm' it should toggle whether the music is paused and not paused
toggleMusic()
It can pause the music but not unpause, any explanation?
Had the same problem. For others' reference, my solution was to use a simple class.
class Pause(object):
def __init__(self):
self.paused = pygame.mixer.music.get_busy()
def toggle(self):
if self.paused:
pygame.mixer.music.unpause()
if not self.paused:
pygame.mixer.music.pause()
self.paused = not self.paused
# Instantiate.
PAUSE = Pause()
# Detect a key. Call toggle method.
PAUSE.toggle()
It doesn't unpause the music because pygame.mixer.music.pause() doesn't affect the state of pygame.mixer.music.get_busy().
To get the behavior you are looking for you will need to your maintain your own variable which keeps track of the paused/unpaused state. You can do this in a class:
class mixerWrapper():
def __init__(self):
self.IsPaused = False
def toggleMusic(self):
if self.IsPaused:
pygame.mixer.music.unpause()
self.IsPaused = False
else:
pygame.mixer.music.pause()
self.IsPaused = True
this one is good, i use it for games
source https://youtu.be/kzTloDq1FiQ
is_paused = False
def toggle_pause():
global is_paused
if is_paused == True:
is_paused = False
else:
is_paused = True
wn.listen()
wn.onkeypress(toggle_pause, " ")
while True:
if not is_paused:
bob.fd(1)
bob.lt(1)
else:
wn.update()

Categories

Resources