Write a simple python program that simulates user activity

We write a simple python program that will help you simulate an actual user working on the system. This application has several uses where you do not want to let your laptop go to sleep and continue to simulate that you are still there on the laptop …. for some reason. Another application is to simulate testing for certain applications that will help you run a software on auto-pilot mode. The sample application I’ve written can be the base for your auto application bot. Go ahead and feel free to use this code.

This is written in python 3 and is easily extensible. You would need to install couple of packages to make this code working

pip install ctypes

pip install pyautogui — This is the package that is the heart of the application and it is very flexible and useful in all automatic gui things.

import ctypes
from ctypes import wintypes
import time
import pyautogui
import random


user32 = ctypes.WinDLL('user32', use_last_error=True)

INPUT_MOUSE    = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2

KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP       = 0x0002
KEYEVENTF_UNICODE     = 0x0004
KEYEVENTF_SCANCODE    = 0x0008

MAPVK_VK_TO_VSC = 0

# msdn.microsoft.com/en-us/library/dd375731
VK_TAB  = 0x09
VK_MENU = 0x12
VK_RETURN = 0x0D

# C struct definitions

wintypes.ULONG_PTR = wintypes.WPARAM

class MOUSEINPUT(ctypes.Structure):#
    _fields_ = (("dx",          wintypes.LONG),
                ("dy",          wintypes.LONG),
                ("mouseData",   wintypes.DWORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (("wVk",         wintypes.WORD),
                ("wScan",       wintypes.WORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

    def __init__(self, *args, **kwds):
        super(KEYBDINPUT, self).__init__(*args, **kwds)
        # some programs use the scan code even if KEYEVENTF_SCANCODE
        # isn't set in dwFflags, so attempt to map the correct code.
        if not self.dwFlags & KEYEVENTF_UNICODE:
            self.wScan = user32.MapVirtualKeyExW(self.wVk,
                                                 MAPVK_VK_TO_VSC, 0)

class HARDWAREINPUT(ctypes.Structure):
    _fields_ = (("uMsg",    wintypes.DWORD),
                ("wParamL", wintypes.WORD),
                ("wParamH", wintypes.WORD))

class INPUT(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = (("ki", KEYBDINPUT),
                    ("mi", MOUSEINPUT),
                    ("hi", HARDWAREINPUT))
    _anonymous_ = ("_input",)
    _fields_ = (("type",   wintypes.DWORD),
                ("_input", _INPUT))

LPINPUT = ctypes.POINTER(INPUT)

def _check_count(result, func, args):
    if result == 0:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

user32.SendInput.errcheck = _check_count
user32.SendInput.argtypes = (wintypes.UINT, # nInputs
                             LPINPUT,       # pInputs
                             ctypes.c_int)  # cbSize

## Set this to False so that the program does not terminate --
'''PyAutoGUI fail-safe triggered from mouse moving to a corner of the screen.
To disable this fail-safe, set pyautogui.FAILSAFE to False.
DISABLING FAIL-SAFE IS NOT RECOMMENDED.
'''
pyautogui.FAILSAFE = False

# Functions

def PressKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def ReleaseKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode,
                            dwFlags=KEYEVENTF_KEYUP))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def SimulatesUserWorking():

    #Loop it over increment. with 200 iterations it will run the program for 1 hour and 40 minutes. 
    for i in range (1, 300):
        time.sleep(2)
        # Random number generators
        ranPixels = random.randint(5, 200)  ## Move between 5 to 200 Pixels
        ranSecs = random.randint(1,7)  ## Duration between 1 to 7 seconds
        ranTabs = random.randint(1,6)  ## Randomly press tabs between 1 to 6
        ## DEBUG MESSAGES
        ##print (" Mouse move pixels: ", ranPixels, " Seconds to move: ", ranSecs," Tabs shifted: ", ranTabs)        

        pyautogui.moveRel(0, ranPixels, duration = ranSecs)  ## Simulate mouse movement 
        pyautogui.keyDown('alt')
        pyautogui.press('tab', presses=ranTabs) ##Press tabs between a random number we specified above
        time.sleep(2)
        pyautogui.keyUp('tab') 
        pyautogui.keyUp('alt')
        time.sleep(30)
        
    print("\n DECREMENTED FOR LOOP") 
    for j in range(40, -1, -1):
        time.sleep(10)
        print(i)
    

if __name__ == "__main__":
    SimulatesUserWorking()

copy paste this code in the file of your choice and run it. See what it does. The hours and time can be manipulated to your hearts content. Let me know if this standalone program helped you in any way. I am looking forward for your comments. These inspire me to put more programs and stuff for you. Thank you! & Stay focused.

Dhakate Rahul

Dhakate Rahul

Leave a Reply

Your email address will not be published. Required fields are marked *