Python Auto Clicker
This is a script that allows you to click your mouse repeatedly with a small delay. It works on Windows, Mac and Linux and can be controlled with user-defined keys.
This project uses the cross-platform module pynput to control the mouse and monitor the keyboard at the same time to create a simple auto clicker.
If you haven’t used or setup pip before, look at my tutorial on how to setup python’s pip to setup pip.
We will be using the pynput module to listen to mouse events. To install this module execute pip install pynput in cmd. Watch the output to make sure no errors have occurred; it will tell you when the module has been successfully installed.

To double-check that it was installed successfully, open up IDLE and execute the command import pynput ; no errors should occur.

.
Writing the Code
First, we need to import time and threading. Then import Button and Controller from pynput.mouse so we can control the mouse and import Listener and KeyCode from pynput.keyboard so we can watch for keyboard events to start and stop the auto clicker.
Next create four variables as shown below. ‘delay’ will be the delay between each button click. ‘button’ will be the button to click, this can be either ‘Button.left’, ‘Button.right’ or even ‘Button.middle’. ‘start_stop_key’ is the key you want to use to start and stop the auto clicker. I have set it to the key ‘s’ to make it nice and simple, you can use any key here. Finally, the ‘exit_key’ is the key to close the program set it like before, but make sure it is a different key.
Now create a class that extends threading.Thread that will allow us to control the mouse clicks. Pass they delay and button to this and have two flags that determine whether it is running or if the whole program is stopping.
Next, add the methods shown below to control the thread externally.
Now we need to create the method that is run when the thread starts. We need to keep looping while the program_running is true and then create another loop inside that checks if the running is set to true. If we are inside both loops, click the set button and then sleep for the set delay.
Now we want to create an instance of the mouse controller, create a ClickMouse thread and start it to get into the loop in the run method.
Now create a method called on_press that takes a key as an argument and setup the keyboard listener.
Now modify the on_press method. If the key pressed is the same as the start_stop_key, stop clicking if the running flag is set to true in the thread otherwise start it. If the key pressed is the exit key, call the exit method in the thread and stop the listener. The new method will look like this:
This script can be saved as a .pyw to run in the background. It can easily be still closed using the set exit key even when no dialog is shown.
Using the Script
To use this script set the variables at the top to what you want.
- delay : They delay between each mouse click (in seconds)
- button : The mouse button to click; Button.left | Button.middle | Button.right
- start_stop_key : They key to start and stop clicking. Make sure this is either from the Key class or set using a KeyCode as shown.
- exit_key : The key to stop the program. Make sure this is either from the Key class or set using a KeyCode as shown.
Then run the script and use the start/stop key when wanted. Press the set exit key to exit.
Common Issues and Questions
ModuleNotFoundError/ImportError: No module named ‘pynput’
Did you install pynput? This error will not occur if you installed it properly. If you have multiple versions of Python, make sure you are installing pynput on the same version as what you are running the script with.
I got a SyntaxError
Syntax errors are caused by you and there is nothing I can offer to fix it apart from telling you to read the error. They always say where the error is in the output using a ^. Generally, people that get this issue have incorrect indentation, brackets in the wrong place or something spelt wrong. You can read about SyntaxError on Python’s docs here.
‘python’ is not recognized as an internal or external command
Python hasn’t been installed or it hasn’t been installed properly. Go to /blog/post/how-to-setup-pythons-pip/ and follow the tutorial. Just before you enter the scripts folder into the path variable, remove the «\scripts\» part at the end. You will also want to add another path with «\scripts\» to have pip.
Edited 11/08/18: Added Python 2 support
Owner of PyTutorials and creator of auto-py-to-exe. I enjoy making quick tutorials for people new to particular topics in Python and tools that help fix small things.
Autoclicker in Python – 2 simple and easy ways

Hi there, developers!! In this tutorial, we will look at the auto clicker in Python. We will first learn what it means and how to implement it in Python. So, without further ado, let’s get right to the point.
Auto clicker is a Python software that allows the user to continually click their mouse at short intervals. It is controlled by user-defined keys and works in all environments – Windows, Mac, and Linux. In Python, we will utilize a package named PyAutoGUI to do this. This will allow us to operate the mouse and monitor the keyboard at the same time.
Method 1: Using PyAutoGui
PyAutoGUI employs the (x,y) coordinate with the origin (0,0) at the top-left corner of the screen. The x coordinates grow as we move to the right, but the y coordinates decrease.
PyAutoGUI currently only works on the primary display. It is untrustworthy for a second monitor’s screen. All keyboard pushes performed by PyAutoGUI are transmitted to the window with the current focus.
Code Implementation
Method 2: Using Pynput
Let’s try using the Pynput module to implement an autoclicker in Python.
Importing required modules
There are multiple modules imported in the program including importing the button and controller in order to control the mouse actions and also the listener and keycodes in order to keep track of the keyboard events to handle the start and stop of the auto clicker actions.
Declaring important variables
The next step is to declare some important variables including the following:
- Button variable which is set to the mouse button that needs clicking.
- Begin_Endvariable which is set to the key which starts and stops the autoclicker.
- Exit_Keyvariable to close the autoclicker.
Creating a class to extend threading
We’ll be able to manage the mouse clicks thanks to the thread we’ve constructed. There are two options: delay and button. There are additionally two indicators indicating whether or not the program is executing.
Creating methods to handle the thread externally
- start_clicking(): starts the thread
- stop_clicking(): stops the thread
- exit(): exits the program and resets
Creating a method that will run when the thread starts
When the thread starts, this method will be called. We shall iterate through the loop until the result of run_prgm equals True. The loop within the loop iterates until the value of a run is True. We press the set button once we’re within both loops.
Creating an instance for mouse controller
Creating a method to setup keyboard listener
If you hit the begin end key, it will cease clicking if the flag is set to true. Otherwise, it will begin. If the exit key is pushed, the thread’s exit method is invoked, and the listener is terminated.
Conclusion
These are two distinct approaches to developing an auto clicker in Python. It may be further customized based on the needs of the user.
Liked the tutorial? In any case, I would recommend you to have a look at the tutorials mentioned below:
Thank you for taking your time out! Hope you learned something new!! 😄
How to Make Auto Clicker in Python | Auto Clicker Script

Hello coders!! In this article, we will understand the concept of auto clicker in python. We will first understand its meaning and its implementation in python. So without wasting any time, let’s get straight into the topic.
What is an auto clicker?
Auto clicker is a script available in python that facilitates the user to repeatedly clicking their mouse within small delay intervals. It is controlled by user-defined keys and works on every environment – Windows, Mac, and Linux. To achieve this, we will use a module called PyAutoGUI in Python. This will allow us to control the mouse and monitor the keyboard at the same time.
Ways to Create an Auto Clicker in Python:
- Using PyAutoGui
- Using Pynput
PyAutoGUI Installation:
To install pyautogui, type the following command:

Key features of PyAutoGUI:
- Sends Keystrokes to applications
- Moves the mouse and clicks in the windows of other applications
- Locate an application’s window
- Display of message boxes for user interaction
Keyboard and Mouse Controls using PyAutoGUI:
PyAutoGUI uses the (x,y) coordinate with the origin (0,0) at the screen’s top-left corner. The x coordinates increase as we go to the right, whereas the ‘y’ coordinates increase as we go down. Currently, PyAutoGUI works only on the primary monitor. It isn’t reliable for the screen of a second monitor. All the presses on the keyboard done by PyAutoGUI are delivered to the window that currently has focus.
Making auto clicker in Python using PyAutoGUI:
Making Auto Clicker in Python using Pynput:
Pynput is a module available in python used to control mouse movements. It can be used to make an auto clicker in python.
Installation of Pynput:
To install pynput, type the following command:

Explanation:
Importing required modules:
- Button and controller: to control the mouse.
- Listener and KeyCode: to watch for keyboard events to start and stop the python auto clicker.
Declaring important variables:
- button: a button that will be clicked.
- begin_end: the key that we will use to start and stop the auto clicker.
- exit_key: to close and reset the program and reset everything.
Creating a class to extend threading:
The thread created will allow us to control the mouse clicks. There are two parameters – delay and button. There are also two flags about whether the program is running or not.
Creating methods to handle the thread externally:
- begin(): starts the thread
- end(): stops the thread
- exit(): exits the program and resets
Creating a method that will run when the thread starts:
This method will run once the thread starts. We will keep iterating through the loop till the value of run_prgm is True. The loop inside the first loop is iterated till the value of a run is True. Once we are inside both the loops, we click the set button.
Creating an instance for mouse controller:
The Mouse_click thread that we created will start when the user gets into the loop in the run method.
Creating a method to setup keyboard listener:
If the key pressed is the begin_end, it will stop clicking given that the flag is set to true. Otherwise, it will start it. If the key pressed is the exit_key, the exit method is called in the thread and stop the listener.
Conclusion: Python Auto Clicker
These are two different ways in which one can create an auto clicker in python. It can be further modified as per one’s requirement.
However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.
Пишем бота-кликера на Python для Lineage 2

Как можно развлечься в новогодние праздники? Поиграть в компьютерные игры? Нет! Лучше написать бота, который это будет делать за тебя, а самому пойти лепить снеговика и пить глинтвейн.
Когда-то в школьные годы был увлечен одной из популярных MMORPG — Lineage 2. В игре можно объединяться в кланы, группы, заводить друзей и сражаться с соперниками, но в общем игра наполнена однообразными действиями: выполнением квестов и фармом (сбор ресурсов, получение опыта).
В итоге решил, что бот должен решать одну задачу: фарм. Для управления будут использоваться эмулированные клики мыши и нажатия клавиш клавиатуры, а для ориентирования в пространстве — компьютерное зрение, язык программирования — Python.
Вообще, создание бота для L2 дело не новое и их готовых есть довольно много. Делятся они на 2 основные группы: те, которые внедряются в работу клиента и кликеры.
Первые — это жёсткий чит, в плане игры пользоваться ими слишком уж неспортивно. Второй вариант интереснее, учитывая, что его можно будет с некоторыми доработками применить к любой другой игре, да и реализация будет интереснее. Те кликеры, которых я находил, по разным причинам не работали, либо работали нестабильно.
Внимание: вся информация здесь изложена только в познавательных целях. Особенно для разработчиков игр, чтобы помочь им лучше бороться с ботами.
Работа с окном
Тут все просто. Будем работать со скриншотами из окна с игрой.
Для этого определим координаты окна. С окном работаем с помощью модуля win32gui. Нужное окно определим по заголовку — “Lineage 2”.
Получаем картинку нужного окна с помощью ImageGrab:
Теперь будем работать с содержимым.
Поиск монстра
Самое интересное. Те реализации, которые я находил, мне не подошли. Например, в одном из популярных и даже платном это сделано через игровой макрос. И “игрок” должен для каждого типа монстра прописывать в макросе типа “/target Monster Name Bla Bla”.
В нашем случае мы последуем такой логике: в первую очередь найдём все тексты белого цвета на экране. Белый текст может быть не только названием монстра, но и именем самого персонажа, именем NPC или других игроков. Поэтому надо навести курсор на объект и если появится подсветка с нужным нам паттерном, то можно атаковать цель.
Вот исходная картинка, с который будем работать:

Закрасим черным своё имя, чтобы не мешало и переведем картинку в ч/б. Исходная картинка в RGB — каждый пиксель это массив из трёх значений от 0 до 255, когда ч/б — это одно значение. Так мы значительно уменьшим объем данных:

Найдем все объекты белого цвета (это белый текст с названиями монстров)

- Фильтровать будем по прямоугольнику размером 50×5. Такой прямоугольник подошел лучше всех.
- Убираем шум внутри прямоугольников с текстом (по сути закрашиваем всё между букв белым)
- Еще раз убираем шум, размывая и растягивая с применением фильтра

Находим середины получившихся пятен
Работает, но можно сделать прикольнее (например, для монстров, имена которых не видны, т.к. находятся далеко) — с помощью TensorFlow Object Detection, как тут, но когда-нибудь в следующей жизни.
Теперь наводим курсор на найденного монстра и смотрим, появилась ли подсветка с помощью метода cv2.matchTemplate. Осталось нажать ЛКМ и кнопку атаки.
С поиском монстра разобрались, бот уже может найти цели на экране и навести на них мышь. Чтобы атаковать цель, нужно кликнуть левой кнопкой мыши и нажать «атаковать» (на кнопку «1» можно забиндить атаку). Клик правой кнопкой мыши нужен для того, чтобы вращать камеру.
На сервере, где я тестировал бота, я вызвал клик через AutoIt, но он почему-то не сработал.
Как оказалось, игры защищаются от автокликеров разными способами:
- поиск процессов, которые эмулируют клики
- запись кликов и определение, какого цвета объект, на который кликает бот
- определение паттернов кликов
- определение бота по периодичности кликов
А некоторые приложения, как клиент этого сервера, могут определять источник клика на уровне ОС. (будет здорово, если кто-нибудь подскажет как именно).
Были перепробованы некоторые фреймворки, которые могут кликать (в т.ч. pyautogui, robot framework и что-то еще), но ни один из вариантов не сработал. Проскользнула мысль соорудить устройство, которое будет нажимать кнопку (кто-то даже так делал). Похоже, что нужен клик максимально хардварный. В итоге стал смотреть в сторону написания своего драйвера.
На просторах интернета был найден способ решения проблемы: usb-устройство, которое можно запрограммировать на подачу нужного сигнала — Digispark. 
Ждать несколько недель с Алиэкспресса не хочется, поэтому поиски продолжились.
Библиотека у меня не завелась на питоне 3.6 — вываливалась ошибка Access violation что-то там. Поэтому пришлось соскочить на питон 2.7, там всё заработало like a charm.
Движение курсора
Библиотека может посылать любые команды, в том числе, куда переместить мышь. Но выглядит это как телепортация курсора. Нужно сделать движение курсора плавным, чтобы нас не забанили.
По сути задача сводится к тому, чтобы перемещать курсор из точки A в точку B с помощью обертки AutoHotPy. Неужели придется вспоминать математику?
Немного поразмыслив, всё-таки решил погуглить. Оказалось, что ничего придумывать не надо — задачу решает алгоритм Брезенхэма, один из старейших алгоритмов в компьютерной графике:
Прямо с Википедии можно взять и реализацию
Логика работы
Все инструменты есть, осталось самое простое — написать сценарий.
- Если монстр жив, продолжаем атаковать
- Если нет цели, найти цель и начать атаковать
- Если не удалось найти цель, немного повернемся
- Если 5 раз никого не удалось найти — идём в сторону и начинаем заново
Из более-менее интересного опишу, как я получал статус здоровья жертвы. В общих чертах: находим по паттерну с помощью OpenCV элемент управления, показывающий статус здоровья цели, берём полоску высотой в один пиксель и считаем в процентах, сколько закрашено красным.
Теперь бот понимает, сколько HP у жертвы и жива ли она еще.
Основная логика готова, вот как теперь он выглядит в действии:
Для занятых я ускорил на 1.30
Остановка работы
Вся работа с курсором и клавиатурой ведется через объект autohotpy, работу которого в любой момент можно остановить нажатием кнопки ESC.
Проблема в том, что всё время бот занят выполнением цикла, отвечающим за логику действий персонажа и обработчики событий объекта и autohotpy не начинают слушать события, пока цикл не закончится. Работу программы не остановить и с помощью мыши, т.к. бот управляет ей и уводит курсор куда ему нужно.
Нам это не подходит, поэтому пришлось разделить бота на 2 потока: слушание событий и выполнение логики действий персонажа.
Создадим 2 потока
и теперь вешаем обработчик на ESC:
при нажатии ESC устанавливаем событие
и в цикле логики персонажа проверяем, установлено ли событие:
Теперь спокойно останавливаем бота по кнопке ESC.
Заключение
Казалось бы, зачем тратить время на продукт, который не приносит никакой практической пользы?
На самом деле компьютерная игра с точки зрения компьютерного зрения — почти то же самое, что и снятая на камеру реальность, а там возможности для применения огромны. Отличный пример описан в статье про подводных роботов, которые лазером стреляют по лососям. Также статья может помочь разработчикам игр в борьбе с ботоводами.
Ну а я ознакомился с Python, прикоснулся к компьютерному зрению, написал свой первый слабоумный искусственный интеллект и получил массу удовольствия.
Надеюсь, было интересно и вам.