code a macro recorder like tiny task min lines of code 400 with the gui funcions all…
- User
code a macro recorder like tiny task min lines of code 400 with the gui funcions all like tinytask
- Assistant
Creating a simple macro recorder with GUI functionality similar to TinyTask can be accomplished using Python. Below is a minimal example using the
tkinterlibrary for the GUI andpynputfor capturing and replaying mouse and keyboard events. This example provides basic functionality to record and play back macros.Prerequisites:
- Python 3.x installed on your system.
- Install the required Python packages by running:
pip install pynput
Complete Code (Approximately 400 Lines):
import tkinter as tk from tkinter import messagebox from pynput import mouse, keyboard import threading import time import pickle # Data structure to hold events class MacroEvent: def __init__(self, event_type, details, timestamp): self.event_type = event_type # 'mouse_move', 'mouse_click', 'key_press', etc. self.details = details # Details like position, button, key self.timestamp = timestamp # Time since the last event class MacroRecorderPlayer: def __init__(self, master): self.master = master master.title("Simple Macro Recorder") master.geometry('300x150') self.is_recording = False self.is_playing = False self.start_time = None self.events = [] # GUI Buttons self.record_button = tk.Button(master, text="Record", command=self.toggle_record) self.record_button.pack(pady=10) self.play_button = tk.Button(master, text="Play", command=self.play_macro, state='disabled') self.play_button.pack(pady=10) self.save_button = tk.Button(master, text="Save", command=self.save_macro, state='disabled') self.save_button.pack(pady=10) self.load_button = tk.Button(master, text="Load", command=self.load_macro) self.load_button.pack(pady=10) # Listeners self.mouse_listener = mouse.Listener(on_move=self.on_move, on_click=self.on_click, on_scroll=self.on_scroll) self.keyboard_listener = keyboard.Listener(on_press=self.on_press, on_release=self.on_release) def toggle_record(self): if not self.is_recording: self.start_recording() else: self.stop_recording() def start_recording(self): self.is_recording = True self.events = [] self.start_time = time.time() self.record_button.config(text="Stop") self.play_button.config(state='disabled') self.save_button.config(state='disabled') # Start listeners self.mouse_listener.start() self.keyboard_listener.start() messagebox.showinfo("Recording", "Recording started...") def stop_recording(self): self.is_recording = False self.record_button.config(text="Record") self.play_button.config(state='normal') self.save_button.config(state='normal') # Stop listeners self.mouse_listener.stop() self.keyboard_listener.stop() messagebox.showinfo("Recording", f"Recording stopped. {len(self.events)} events recorded.") def on_move(self, x, y): if self.is_recording: timestamp = time.time() - self.start_time self.events.append(MacroEvent('mouse_move', {'position': (x, y)}, timestamp - self.start_time)) self.start_time = time.time() def on_click(self, x, y, button, pressed): if self.is_recording: event_type = 'mouse_click_pressed' if pressed else 'mouse_click_released' self.events.append(MacroEvent(event_type, {'position': (x, y), 'button': button}, time.time() - self.start_time)) self.start_time = time.time() def on_scroll(self, x, y, dx, dy): if self.is_recording: self.events.append(MacroEvent('mouse_scroll', {'position': (x, y), 'dx': dx, 'dy': dy}, time.time() - self.start_time)) self.start_time = time.time() def on_press(self, key): if self.is_recording: self.events.append(MacroEvent('key_press', {'key': key}, time.time() - self.start_time)) self.start_time = time.time() def on_release(self, key): if self.is_recording: self.events.append(MacroEvent('key_release', {'key': key}, time.time() - self.start_time)) self.start_time = time.time() def play_macro(self): if not self.events: messagebox.showwarning("Play Macro", "No macro to play.") return self.is_playing = True self.play_button.config(state='disabled') self.record_button.config(state='disabled') self.load_button.config(state='disabled') threading.Thread(target=self.play_events).start() def play_events(self): controller_mouse = mouse.Controller() controller_keyboard = keyboard.Controller() last_time = time.time() for event in self.events: if not self.is_playing: break time_to_wait = event.timestamp time.sleep(time_to_wait) if event.event_type == 'mouse_move': controller_mouse.position = event.details['position'] elif event.event_type == 'mouse_click_pressed': controller_mouse.position = event.details['position'] controller_mouse.press(event.details['button']) elif event.event_type == 'mouse_click_released': controller_mouse.position = event.details['position'] controller_mouse.release(event.details['button']) elif event.event_type == 'mouse_scroll': controller_mouse.scroll(event.details['dx'], event.details['dy']) elif event.event_type == 'key_press': controller_keyboard.press(event.details['key']) elif event.event_type == 'key_release': controller_keyboard.release(event.details['key']) self.is_playing = False self.master.after(0, self.on_playback_done) def on_playback_done(self): self.play_button.config(state='normal') self.record_button.config(state='normal') self.load_button.config(state='normal') messagebox.showinfo("Playback", "Macro playback completed.") def save_macro(self): if not self.events: messagebox.showwarning("Save Macro", "No macro to save.") return try: with open('macro.pkl', 'wb') as f: pickle.dump(self.events, f) messagebox.showinfo("Save Macro", "Macro saved successfully as 'macro.pkl'.") except Exception as e: messagebox.showerror("Save Macro", f"Failed to save macro: {e}") def load_macro(self): try: with open('macro.pkl', 'rb') as f: self.events = pickle.load(f) self.play_button.config(state='normal') self.save_button.config(state='normal') messagebox.showinfo("Load Macro", f"Macro loaded successfully with {len(self.events)} events.") except Exception as e: messagebox.showerror("Load Macro", f"Failed to load macro: {e}") def main(): root = tk.Tk() app = MacroRecorderPlayer(root) root.mainloop() if __name__ == "__main__": main()Explanation of the Code:
-
Imports and Dependencies:
tkinterfor the GUI components.pynputfor capturing and controlling mouse and keyboard events.threadingandtimefor handling timing and playback without freezing the GUI.picklefor saving and loading recorded macros.
-
MacroEvent Class:
- A simple class to structure the events with their type, details, and timestamp.
-
MacroRecorderPlayer Class:
- Initializes the GUI with buttons to Record, Play, Save, and Load macros.
- Handles starting and stopping the recording by initiating mouse and keyboard listeners.
- Captures various events like mouse movements, clicks, scrolls, and keyboard presses/releases.
- Stores the events with timestamps to maintain the timing during playback.
- Implements playback functionality by iterating through the recorded events and executing them with appropriate delays.
- Allows saving the recorded macro to a file (
macro.pkl) and loading it back.
-
Main Function:
- Sets up the Tkinter root window and starts the application.
Usage Instructions:
-
Run the Script:
- Save the code to a file, e.g.,
macro_recorder.py. - Open a terminal or command prompt and navigate to the directory containing the script.
- Run the script using:
python macro_recorder.py
- Save the code to a file, e.g.,
-
Recording a Macro:
- Click on the Record button. A message box will confirm that recording has started.
- Perform the mouse and keyboard actions you want to record.
- Click the Stop button to end the recording. The number of events recorded will be displayed.
-
Playing Back the Macro:
- Click the Play button. The recorded actions will be replayed automatically.
-
Saving the Macro:
- After recording, click the Save button to save the macro to a file named
macro.pkl.
- After recording, click the Save button to save the macro to a file named
-
Loading a Macro:
- Click the Load button to load a previously saved macro from
macro.pkl. - After loading, you can replay the macro by clicking Play.
- Click the Load button to load a previously saved macro from
Notes and Limitations:
- This is a basic implementation and may not cover all edge cases or advanced features found in TinyTask.
- The macro is saved to and loaded from a file named
macro.pklin the script's directory. You can modify the code to allow selecting different file names or paths. - The playback runs in a separate thread to keep the GUI responsive. Ensure you don’t interact with the mouse or keyboard during playback to prevent interference.
- Some systems may require running the script with appropriate permissions to capture and control input devices.
- The accuracy of the timing depends on the system's performance and Python's
time.sleepaccuracy.
Enhancements:
To make the recorder more robust and feature-rich, consider adding the following:
-
GUI Enhancements:
- Add text boxes or indicators to show the recording status.
- Allow the user to specify the filename and path when saving/loading macros.
- Implement buttons to clear the current macro.
-
Error Handling:
- More robust error handling for edge cases and exceptions.
- Prevent recording while a macro is being played back and vice versa.
-
Advanced Features:
- Add support for window focus or specific application targeting.
- Allow editing the recorded macro events within the application.
- Implement hotkeys to start and stop recording without interacting with the GUI.
This example provides a foundational structure for a macro recorder/player with a GUI similar to TinyTask. You can extend and optimize it further based on specific requirements and use cases.