skip to Main Content

I’m trying to make an app that send keyboard commands to my computer. I have a server running on my computer that receives messages from the app and simulate keystrokes.
The problem is that the keystrokes are not working when the terminal I used to run the server is not on focus.

I’m using pynput to simulates the keyboard.
The part of the server receiving and sending messages is working fine.
I’m doing this on Ubuntu 24.04.

My code:

import asyncio
import websockets
from pynput.keyboard import Key, Controller

controller = Controller()


def play_pause():
    
    #this print shows up on my terminal
    print("Sending Play...")
    
    controller.press(Key.ctrl)
    controller.press(Key.alt)
    controller.press(Key.shift)
    controller.press(Key.space)
    
    controller.release(Key.space)
    controller.release(Key.shift)
    controller.release(Key.alt)
    controller.release(Key.ctrl)

async def handle_connection(websocket, path):
    async for message in websocket:
        command = message

        if command == "play/pause":
            play_pause()
            print("play/pause")

        else:
            print(f"Unknown command: {command}")

        await websocket.send(f"Command '{command}' received")

async def main():
    async with websockets.serve(handle_connection, "localhost", 9999):
        print("WebSocket server started at ws://localhost:9999")
        await asyncio.Future()  # Run forever

if __name__ == "__main__":
    asyncio.run(main())

I tried to use the libraries pyautogui and keyboard.

2

Answers


  1. Chosen as BEST ANSWER

    I don't know what was the problem but when I used playerctl it works fine.


  2. Have you tried using xdotools?

    Install xdotool

    sudo apt-get install xdotool
    

    Update your Python function:

    import subprocess
    
    def play_pause():
        print("Sending Play...")
        subprocess.run(["xdotool", "key", "ctrl+alt+shift+space"])
    

    This simulates pressing Ctrl + Alt + Shift + Space globally, even when the terminal is not focused. It’s a simple way to send keystrokes globally.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search