Making an autoclicker in python? - python

I have designed this simple autoclicker in python using the pynput library
import time
import threading
from pynput.mouse import Button, Controller
from pynput.keyboard import Listener, KeyCode
TOGGLE_KEY = KeyCode(char="t")
activated = False
mouse = Controller()
def on_press(key):
global activated
if key == TOGGLE_KEY:
activated = not activated
while activated:
mouse.click(Button.left, 1)
time.sleep(0.01)
listner = Listener(on_press=on_press)
listner.start()
input()
This code activates a listner and when the user presses any key it calls the on_press function which checks if the button is equal to 't' then it inverts the property of activated and starts the while loop
I tried the above code and it worked but when I pressed 't' again the autoclicker did not switch off

I believe you are stuck in your while activated: loop. Pushing T again does not make the function run again unless the first function has stopped. A simple solution would be to put the click event in its own thread.
import time
import threading
from pynput.mouse import Button, Controller
from pynput.keyboard import Listener, KeyCode
TOGGLE_KEY = KeyCode(char="t")
activated = False
mouse = Controller()
def on_press(key):
global activated
if key == TOGGLE_KEY:
activated = not activated
def doClick():
global activated
while True:
if activated:
mouse.click(Button.left, 1)
time.sleep(0.01)
threading.Thread(target = doClick).start()
listner = Listener(on_press=on_press)
listner.start()
input()

I think the problem is that the program is stuck in the loop. A solution I found is to use a thread
import threading
import time
from pynput.keyboard import Listener, KeyCode
from pynput.mouse import Controller
mouse = Controller()
class Clicker(threading.Thread):
__TOGGLE_KEY = KeyCode(char="t")
__activated = False
def run(self) -> None:
super().run()
while True:
if self.__activated:
# mouse.click(Button.left, 1)
time.sleep(1)
print("activated")
def keyboard_listener(self, key) -> None:
if key == self.__TOGGLE_KEY:
self.__activated = not self.__activated
clicker = Clicker()
listner = Listener(on_press=clicker.keyboard_listener)
listner.start()
clicker.start()
print("Listener started")
input()

Related

Roblox won't detect mouse movement from autopygui

I am trying to create a script that automatically rejoins a roblox game on disconnect. I have beeen using ctypes to obtain a pixel on the screen, and if the pixel matches a color, it should automatically press the rejoin button. the problem is that it wont press the button. After some troubleshooting, I have figured out that the mouse movement wont register with the game, as if I move my mouse manually, it clicks the button.
In short, the game won't detect mouse movement from autopygui. If I move my mouse manually, it registers.
Video example:
https://youtu.be/VvAfHHXul8Q
Code:
import pyautogui as py
import keyboard
import tkinter
import requests
from ctypes import windll
from time import sleep
key = "m"
toggled = False
rjcolor = 16777215
root = tkinter.Tk()
root.withdraw()
width, height = root.winfo_screenwidth(), root.winfo_screenheight()
dc= windll.user32.GetDC(0)
def getpixel(x,y):
return windll.gdi32.GetPixel(dc,x,y)
while True:
if keyboard.is_pressed(key):
toggled = not toggled
print("toggled to " + str(toggled))
sleep(0.5)
if toggled == True:
py.moveTo(width / 2, 800)
py.click(button='left')
if getpixel(1050, 600) == rjcolor:
print("disconnected, waiting until internet back online!")
while True:
try:
requests.head("http://www.google.com/", timeout=3)
print('The internet connection is active, rejoining.')
py.moveTo(1050, 590)
py.mouseDown(button='left')
sleep(0.1)
py.mouseUp(button='left')
break
except requests.ConnectionError:
print("The internet connection is down")
sleep(3)
sleep(0.1)
Pyautogui has issues with clicking on roblox, but i've found a workaround:
Replace py.click(button="left") with autoit.mouse_click("left")
import autoit
autoit.mouse_click("left")

Why do I always have the error message Controller has no attribute is_pressed?

I've been coding a very simple autoclicker. My autoclicker works just fine, but the only way to kill it is forcefully shut down my computer because it clicks so fast I can't access my taskbar. I could make it slower, but I'd prefer a way for the user to close the autoclicker with the press of a button. I've tried if keyboard.is_presssed('q'): break but I always get the error message AttributeError: 'Controller' object has no attribute 'is_pressed'. Did you mean: 'alt_pressed'? I expected my code to break the loop when I press q, but instead I get an error message. The error message will also pop up without the pressing of q. My code as of now is:
from pynput.mouse import Button, Controller
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
mouse = Controller()
while True:
time.sleep(10)
mouse.click(Button.left)
if keyboard.is_pressed('q'):
break
pynput doesn't have is_pressed() - I don't know where you find it.
You should rather use pynput.keyboard.Listener to run code when q is pressed and set some variable - q_is_pressed = True - or run code which ends program.
You can't have two objects with the same name Controller.
One Controller replaces other Controller and later you use the same Controller to create mouse and keyboard - and this makes problem.
You have to use pynput.mouse.Controller and pynput.keyboard.pynput.Controller
import pynput
from pynput.mouse import Button
from pynput.keyboard import Key
import time
keyboard = pynput.keyboard.Controller()
mouse = pynput.mouse.Controller()
while True:
time.sleep(10)
mouse.click(Button.left)
#if keyboard.is_pressed('q'): # <-- this will need Listener()
# break
EDIT:
To end code when q was pressed you have to use Listener
For example:
import pynput
from pynput.mouse import Button
import time
mouse_controller = pynput.mouse.Controller()
def on_press(key):
print('pressed:', key)
if str(key) == "'q'": # it has to be with `' '` inside `" "`
# Stop listener
print("exit listener")
return False # `False` ends listener
with pynput.keyboard.Listener(on_press=on_press) as keyboard_listener:
while keyboard_listener.is_alive():
time.sleep(10)
mouse_controller.click(Button.left)
print('clicked')

Why does my code not work in windows terminal but does in others? (Python)

Ok so I am making an autoclicker, and all works great so far - kinda. It works perfectly in PyCharm terminal, and IDLE, but when double-clicking on the .py file, it opens windows terminal as expected, but only clicks once. Upon clicking any key on my keyboard, it then continues and stops in the same place, then I must click a key on my keyboard before it starts again, and it continues doing this. I used pyinstaller to convert to an exe, and converts fine but when I run it, it doesn't work at all. Someone please help with this.
import time
mouse = Controller()
clicker_on_query = True
clicker_time_interval = 1
while clicker_on_query == True:
print('loop activated')
mouse.press(Button.left)
mouse.release(Button.left)
print('1')
time.sleep(clicker_time_interval)
print('loop end')
After some testing I realized that this happens only when you run the script in command prompt, while using PowerShell there seems to be no issues at all.
You can try using this piece of code which is kind of more advanced using a class and featuring start/stop keys and maybe experiment a bit more.
By the way, this seems to work on prompt as well.
import time
import threading
from pynput.mouse import Button, Controller
from pynput.keyboard import Listener, KeyCode
delay = 1.00
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()
credits for the code: https://nitratine.net/blog/post/python-auto-clicker/

Question about mouse and keyboard events in python

from pynput.keyboard import Key, Controller as KeyboardController
from pynput.mouse import Button, Controller as MouseController
from pynput.keyboard import Key, Listener
keyboard = KeyboardController()
mouse = MouseController()
def on_press(key):
if key.char == 'q':
print(mouse.position)
return True
# Collect events until released
with Listener(
on_press=on_press) as listener:
listener.join()
I made this simple script to return the mouse's position if I press the letter q. It works fine until I press something that is not a char, for example, the Enter key. I've been searching around but couldn't find good ways of implementing an if "certain button clicked" to do that. How can I fix this?
Evidently, the key object returned to on_press does not have a char attribute unless you have actually hit a character key. So you have to check for the existence of that attribute. You can do that using hasattr:
from pynput.keyboard import Key, Controller as KeyboardController
from pynput.mouse import Button, Controller as MouseController
from pynput.keyboard import Key, Listener
keyboard = KeyboardController()
mouse = MouseController()
def on_press(key):
if hasattr(key, 'char'):
if key.char == 'q':
print(mouse.position)
return True
# Collect events until released
with Listener(
on_press=on_press) as listener:
listener.join()

Instance of 'Controller' has no 'type' member pynput module

I am fairly new to Python, I recently made this program to automatically click a text box in a program and type text (hello). But everytime I run the program, it says:
Instance of 'Controller' has no 'type' member.
I am using pynput and Python 3.8.1 32bit. I installed pynput manually through the console with
pip install pynput
Here is my code:
import time
from pynput.keyboard import Key, Controller
from pynput.mouse import Button, Controller
def controlMouse(x, y):
mouse = Controller()
mouse.position = (x, y)
def controlKeyboard(txt):
keyboard = Controller()
keyboard.type(txt)
def clickMouse():
mouse = Controller()
mouse.click(Button.left, 1)
def pressKeyboard(key):
keyboard.press(Key.key)
keyboard.release(Key.key)
mouse = Controller()
controlMouse(268, 1030)
time.sleep(1)
clickMouse()
time.sleep(1)
controlMouse(400, 955)
time.sleep(1)
clickMouse()
controlKeyboard('Hello')
pressKeyboard(enter)
You have this:
from pynput.keyboard import Key, Controller
from pynput.mouse import Button, Controller
After that, Controller refers to pynput.mouse.Controller (because it was the last time Controller was defined). If you want to be able to refer to both Controller types, you should do something like this:
from pynput.keyboard import Key, Controller as KeyboardController
from pynput.mouse import Button, Controller as MouseController
You can then use KeyboardController and MouseController to refer to the right kind of Controller.
Alternatively, you can:
import pynput.keyboard
import pynput.mouse
You can then just refer to pynput.keyboard.Controller and pynput.mouse.Controller.

Categories