2

I am working on a little Mouse Spamming Stopper script in Python and I don't really know how can I only block the mouse click, but still be able to move the mouse.

This is what I got so far:

from pynput.mouse import Listener
import time


mouse_allowed = True

def timeout():
    mouse_allowed = False
    time.sleep(0.1)

def on_click(x, y, button, pressed):
    if mouse_allowed:
        print("Clicked")
        timeout()

if mouse_allowed:
    with Listener(on_click=on_click) as listener:
        listener.join()
VIc Pitic
  • 21
  • 3

1 Answers1

1

One way that I found to get around the mouse being locked is to check the time. This can be done by using the time.time() function. Here is a rough example snippet of what I mean.

from pynput.mouse import Listener
import time

last_click = time.time()

def good_click_time():
    # Make sure the program knows that it's getting the global variable
    global last_click
    # Makes sure that 1 second has gone by since the last click
    if time.time() - last_click > 1:
        # Records last click
        last_click = time.time()
        return True
    else:
        return False

def on_click(x, y, button, pressed):
    if good_click_time():
        print("Clicked")
    else:
        print("You must wait 1 second to click. You have waited {} seconds".format(time.time() - last_click))

with Listener(on_click=on_click) as listener:
    listener.join()

By recording the exact time you last clicked you can use that to check if it's been at least a second (or however long you want between your clicks) since your last click.

NTSwizzle
  • 101
  • 6
  • Thanks ! This definitely helped regarding the Mouse Spamming, but is there a way to block the mouse click ? – VIc Pitic Jun 14 '21 at 19:43
  • The [documentation](https://pynput.readthedocs.io/en/latest/mouse.html#toggling-event-listening-for-the-mouse-listener) shows you how to toggle a mouse listener. However I do not think this is your problem. It is up to you to determine what will happen when the mouse is clicked. We have logic set up to determine if a click is valid or not. Now all you have to do is tell the program what to do once the click is valid or invalid. For example, you can change both print functions in the on_click() function to call functions. Now you have a function run when a click is valid and invalid. – NTSwizzle Jun 14 '21 at 21:51
  • Its good, but I think this function freezes the whole mouse, not only the clicking functions , right ? – VIc Pitic Jun 15 '21 at 13:02
  • 1
    Have you tried copying JUST my code? It should be able to block clicks and still allow mouse movement. – NTSwizzle Jun 15 '21 at 14:20
  • I did, but I feel like the mouse movement is lagging a little bit, but still thanks a lot :) – VIc Pitic Jun 15 '21 at 19:42