Search code examples
pythonmacrosminecraftpynput

How to control keyboard in Minecraft with Pynput


I am trying to make a macro in Minecraft using pynput, but it seems that pynput does not press the correct buttons on the keyboard. I know this because when I ran (code snippet 1) while setting the controls of Hotbar slot 3 it showed as a weird character instead of a number. (see picture) Is there a way to make pynput press the correct buttons?

# Code snippet 1
import time
from pynput.keyboard import Controller

time.sleep(7) # this is just so I have time to switch to minecraft before it activates

board = Controller()
board.press('2')
time.sleep(.1)
board.release('2')

minecraft reads board.press('2') as soh\soh"]"soh

In place of '2' I have also tried KeyCode(49) and gotten the same result. It is properly recognised by the computer, as shown by keycode.info and notepad.
When I replaced '2' with 'e' Minecraft recognised it as the same as '2', and it even pressed the button, so I am extra confused now.

Extra notes:

  • For now I will just set the controls to what pynput gives minecraft to make my macro work, but I would prefer to be able to use the button(s) outside of the macro as well.
  • Pynput's click and scroll seem to work fine.
  • I am not using the mouse for my macro, but if you have knowledge about the mouse there is a stackOverflow question about it here: How to control the mouse in Minecraft using Python?
  • For anyone wondering, I am making this macro to empty water buckets quickly after I have used them to remove an area of water in the ocean

Solution

  • The easiest way i think is using pydirectinput.

    pydirectinput is exactly like pyautogui. Its just that its name changed and that it can work with games using DirectX (minecraft, roblox)

    To use it you can just do

    import pydirectinput
    import pyautogui
    import time
    
    time.sleep(2)#so u can switch to your game
    
    pydirectinput.keyDown('v')
    time.sleep(0.5)
    pydirectinput.keyUp('v)