Hello my first time posting, I have a problem with python. So I have this code and it's a keybind like when I press the number 1 i need to execute1() but after this run I don't want the program to exit but just wait and run in the background and wait for another key to be pressed. With this program it keeps looping the execute(). How I can solve this?
import threading
import pyautogui
import time
import pyscreeze
from pynput import keyboard
cmb = [{keyboard.Key.alt_l, keyboard.Key.page_up}] #keybind
current = set()
def execute1():
pyautogui.moveTo(2459,122)
pyautogui.leftClick()
pyautogui.moveTo(2368,392)
pyautogui.leftClick()
pyautogui.moveTo(1542,447)
pyautogui.leftClick()
pyautogui.moveTo(1546,518)
pyautogui.leftClick()
pyautogui.moveTo(1649,635)
pyautogui.leftClick()
pyautogui.moveTo(2018,320)
time.sleep(1.35)
pyautogui.leftClick()
pyautogui.typewrite("111")
pyautogui.moveTo(2006,379)
pyautogui.leftClick()
def execute2():
pyautogui.moveTo(2459,122)
pyautogui.leftClick()
pyautogui.moveTo(2271,505)
pyautogui.leftClick()
pyautogui.moveTo(1542,447)
pyautogui.leftClick()
pyautogui.moveTo(1546,518)
pyautogui.leftClick()
pyautogui.moveTo(1649,635)
pyautogui.leftClick()
pyautogui.moveTo(2018,320)
time.sleep(1.35)
pyautogui.leftClick()
pyautogui.typewrite("111")
pyautogui.moveTo(2006,379)
pyautogui.leftClick()
def execute3():
pyautogui.moveTo(2459,122)
pyautogui.leftClick()
pyautogui.moveTo(2292,603)
pyautogui.leftClick()
pyautogui.moveTo(1542,447)
pyautogui.leftClick()
pyautogui.moveTo(1546,518)
pyautogui.leftClick()
pyautogui.moveTo(1649,635)
pyautogui.leftClick()
pyautogui.moveTo(2018,320)
time.sleep(1.35)
pyautogui.leftClick()
pyautogui.typewrite("111")
pyautogui.moveTo(2006,379)
pyautogui.leftClick()
def on_press(key): #check when key presses
if key == keyboard.KeyCode(char='1'): # check if '1' key is pressed
execute1()
current.add(key)
elif key == keyboard.KeyCode(char='2'): # check if '2' key is pressed
execute2()
current.add(key)
elif key == keyboard.KeyCode(char='3'): # check if '3' key is pressed
execute3()
current.add(key)
def on_release(key): #check when key releases
if any([key in z for z in cmb]):
current.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
I tried to do this:
def on_press(key): #check when key presses
if key == keyboard.KeyCode(char='1'): # check if '1' key is pressed
t = threading.Thread(target=execute1)
t.start()
t.join()
current.add(key)
for all the executes but there was another problem, when it reached the pyautogui.typewrite("111") it just typed one of the characters but I wanted to be fast.
This program worked when I had only 1 execution but I want 6 of them now and I can't find a solution
You need to create a listener, but you are missing the correct way.
Here are a couple of examples...
Center the mouse in the middle of the screen when you press F7:
import pyautogui
import pynput.mouse
import pynput.keyboard
def center_mouse_on_press(key):
if key == pynput.keyboard.Key.f7:
screen_width, screen_height = pyautogui.size()
center_x, center_y = screen_width / 2, screen_height / 2
pyautogui.moveTo(center_x, center_y)
keyboard_listener = pynput.keyboard.Listener(on_press=center_mouse_on_press)
keyboard_listener.start()
keyboard_listener.join()
Move the mouse to different points in the screen depending on whether you press F7, F8 or F9:
import pyautogui
import pynput.mouse
import pynput.keyboard
def move_mouse_on_press(key):
screen_width, screen_height = pyautogui.size()
center_x, center_y = screen_width / 2, screen_height / 2
if key == pynput.keyboard.Key.f7:
pyautogui.moveTo(center_x, center_y/2)
if key == pynput.keyboard.Key.f8:
pyautogui.moveTo(center_x, center_y)
if key == pynput.keyboard.Key.f9:
pyautogui.moveTo(center_x, center_y*2)
keyboard_listener = pynput.keyboard.Listener(on_press=move_mouse_on_press)
keyboard_listener.start()
keyboard_listener.join()
Related
I am using pynput and so far i haven't figured it out i have tried arrow keys and teleporting the mouse relative to its position and to specified coordinates
from pynput.keyboard import Key, Controller as KeyboardController
from pynput.mouse import Button, Controller as MouseController
import time
keyboard = KeyboardController()
mouse = MouseController()
mouse.position = (-1756, 1079)
time.sleep(0.5)
mouse.click(Button.left, 1)
time.sleep(1.5)
mouse.position = (904, 181)
mouse.press(Button.left)
for number in range (80):
keyboard.press(Key.left)
keyboard.release(Key.left)
mouse.release(Button.left)
print("done")
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.
I am trying to make a windows analog of the Chat-wheel from Dota 2 or Battlefield with some fast commands like this.
How it should be:
While the G-key is pressed - the wheel with some sections appears at the centre of the screen, with the mouse centered on it and if I move the mouse to side_1 and then release the G-key -> func_1 executes.
If it was on side_2 -> func_2.
If I release the G-key at the centre -> wheel disappears and nothing happens.
So to monitor the X Y coordinates of the mouse I use following code:
from pynput import mouse
def on_move(x, y):
print(x, y)
# Collect events until released
with mouse.Listener(on_move=on_move) as listener:
listener.join()
It is spamming coordinates when I move the mouse.
But I am stuck in the part where i need:
to start the listener from another .py file and take these coordinates for the visual part of the program (like highlight the side of the wheel with command descriptions),
to close the listener from another .py file and take the last coordinates of the mouse when the G-key is released to compare with tge range of coordinates prescribed for functions.
You want something like this:
from pynput import mouse, keyboard
import time
def on_press(key):
print("pressed {}".format(key))
def on_release(key):
print("released {}".format(key))
def on_move(x,y):
print((x,y))
mouse_listener = mouse.Listener(
on_move=on_move)
mouse_listener.start()
key_listener = keyboard.Listener(
on_press=on_press,
on_release=on_release)
key_listener.start()
# prevent the script from exiting immediately
time.sleep(10)
import time
import keyboard
from pynput.mouse import Controller
def get_xy():
mouse = Controller()
mouse_coord = str(mouse.position)
mouse_coord = mouse_coord.replace("(", "")
mouse_coord = mouse_coord.replace(")", "")
mouse_coord = mouse_coord.replace(",", "")
mouse_coord = mouse_coord.split(" ")
mouse_x = int(mouse_coord[0])
mouse_y = int(mouse_coord[1])
print(mouse_x, mouse_y)
while True:
if keyboard.is_pressed('b'):
get_xy()
time.sleep(0.01)
Output example: 654 326
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:
I made this little autofarm bot for GT since I was bored, but problem is, that I don't have any way of stopping it other than Task Manager. So I was thinking, is there a way for my program to detect if any key is pressed down no matter what window is on foreground?
Here is the code I am using right now:
import pyautogui
import sys
from pynput.mouse import Controller
from sys import exit
from time import sleep
from msvcrt import getch
mouse = Controller()
move = int()
move = 0
collections = int()
collections = 0
input("Hover your mouse over FIRST BLOCK and press ENTER.")
b1 = mouse.position
input("Hover your mouse over SECOND BLOCK and press ENTER.")
b2 = mouse.position
input("Hover your mouse over PUNCH and press ENTER.")
p = mouse.position
input("Hover your mouse over COLLECT moving direction and press ENTER.")
c1 = mouse.position
input("Hover your mouse over RETURN moving direction and press ENTER.")
c2 = mouse.position
pt = float(input("Insert punch TIME (ftank 1.0; pepper 1.2; pball 2.6)"))
try:
while True:
pyautogui.click(b1)#Block 1
pyautogui.dragTo(b2, duration = 0.25)#Block 2
pyautogui.mouseDown(p)#Punch
print("Punch Start.")
sleep(pt)
pyautogui.mouseUp()#Stop Punch
move = move + 1 #Count loops
print("Loop ", move, " Complete.")
if move >= 150: #Gem Collection
print("Collecting...")
pyautogui.mouseDown(c1) #Collect Gems
sleep(0.137)
print("Finished.")
pyautogui.mouseDown(c2) #Return to original position
sleep(0.8)
pyautogui.mouseUp()#Stop Moving
move = 0 #Reset Counter
collections = collections + 1
print("Finished ", collections,". Collecting Loop.")
except KeyboardInterrupt:
sys.exit()