How use Python to simulate keybaord click to control game? - python

I'm trying to create a python script to automate a game.
I already tried these libs:
pyautogui
pywin32
ctypes (I imported this code and calling the function PressKey, https://github.com/Sentdex/pygta5/blob/master/directkeys.py)
My code is like this:
from directkeys import PressKey, ReleaseKey, W
import time
print("Script is gonna start in 5 seconds")
time.sleep(5)
PressKey(W)
time.sleep(10)
ReleaseKey(W)
print("Script finished")
I tested this script at notepad, it's working pretty well, but it's not working in the game at all.
I thought it was because of need to be direct input, but I think ctypes is already sending input as direct input.
How can I automate the game using python?

I'm going to elevate my comment to an answer since I believe it's what you're looking for.
The W is not the proper input for the PressKey and ReleaseKey functions. They're looking for hex code input. You can find the proper hex codes here: https://learn.microsoft.com/en-us/windows/desktop/inputdev/virtual-key-codes
The W hex code particularly is 0x57. So replace "W" with "0x57":
from directkeys import PressKey, ReleaseKey, W
import time
print("Script is gonna start in 5 seconds")
time.sleep(5)
PressKey(0x57)
time.sleep(10)
ReleaseKey(0x57)
print("Script finished")

What I did was to make sure it was running either the script or the IDE in Administrator mode.
For some reason, games I wrote scripts for like Black Desert Online or CSGO only detect key presses when I am running it in Administrator.

Related

killing python application after exiting it

I’m starting finishing off my new simple app and because Python isn’t my main programming language I’m struggling a lot. I would like to add a function which would kill everything - every service in the app, after clicking an exit button. (So maybe with a global variable?)
I want to do it as simple as possible. I was wondering if there is anything similar to isServerOn or so.
What I have so far is just this code below and if there would be a chance to add just one or few lines then it would be the best. Thank you all so much!!
import sys
def quit()
sys.exit()
To stop a python script use the keyboard: Ctrl + C
To stop it using code you can use these sections (Python 3) :
raise SystemExit
you can also use:
import sys
sys.exit()
or:
exit()
or:
import os
os._exit(0)

How would I create something similar to the Minecraft Server Console in python3

I'm messing around with some networking stuff and I wanted the server to be able to issue commands, namely a "stop" command. The idea was to create something similar to the minecraft server console. The issue is that when using threading, there are a few problems with just using print() and input()
Image of the Minecraft Server Console incase you dont know what I mean.
I tried to research a few things but found nothing good. I was trying to learn curses but I'm not sure how helpful it would be. I decided before I go any further I would ask on stack overflow before wasting any more time with research (I've been trying to figure this out for 2-3 days now)
Is there any simple way to do this?
I decided to go thru with learning basic curses.
I was able to make this test code and modify for my application
import curses,time
import curses.textpad
def main(screen):
h,w = screen.getmaxyx()
window = curses.newwin(h-2,w,0,0)
window.scrollok(True)
InputContainer = curses.newwin(1,w,h-1,0)
inputWindow = curses.newwin(1,w-2,h-1,2)
inputField = curses.textpad.Textbox(inputWindow,insert_mode=True)
InputContainer.addstr('> ')
window.addstr(0,0,"Console Application started\n")
screen.refresh()
InputContainer.refresh()
window.refresh()
running = True
while running:
rows, cols = screen.getmaxyx()
userIn = inputField.edit()[0:-1]
if userIn!="":
if str(userIn)=="stop":
running = False
window.addstr(f"Command Issued: {userIn}\n")
inputWindow.refresh()
inputWindow.clear()
window.refresh()
curses.wrapper(main)
Feel free to use this yourself.

I created a python bind for CS:GO with pyautogui but it doesnt work

I created a simple bind script. It works on IDLE Python but it doesn't work in CS:GO. Do you know why?
Mayby it must be on background to work?
import keyboard
import pyautogui
import time
def EventListen():
while True:
try:
if keyboard.is_pressed('n'):
pyautogui.press('`')
pyautogui.typewrite('say EZ')
pyautogui.press('enter')
pyautogui.press('`')
EventListen()
except:
EventListen()
EventListen()
I don't see the need to use pyautogui since you are already using keyboard which is sufficient to perform the tasks you need. I have made some changes to your code
import time
import keyboard
def EventListen():
while True:
try:
if keyboard.is_pressed('n'):
keyboard.press('`')
keyboard.write('say EZ')
keyboard.press('enter')
keyboard.press('`')
elif keyboard.is_pressed('/'): #add something to end the process
break
except:
EventListen()
time.sleep(0.001)
EventListen()
There is no need to call the function in the while loop, as it will anyway be executed infinitely unless you kill the process. I don't see why the script wouldn't run in the background, in fact I am typing this
n`say EZ
`
using the script. What might be possible is that your previous program ran continuously, causing high CPU usage which might have competed with the game's demand. I recomend you to add a small delay before every iteration of the while loop, in this case I have added 1 ms delay, which will cause significant reduction in CPU usage. I am not sure if that solved your problem as I am unable to reproduce your exact case, let me know if it helped.
EDIT : I forgot to mention, I have added another binding of keyboard.is_pressed('/') which will make the program break out of the loop and hence terminate it when / key is pressed. You can change this as you like. If you don't want any other binding as such (which I don't recommend) then you can rely on manually killing the task.
you should make an exe with pyinstaller and you run it background

Why msvcrt.getch() is getting always same input without pressing any key on Windows

I am using Windows. I want take user input without pressing enter key and I found many examples, but somehow they are not working on me. I do not press any key and still msvcrt.getch() function is getting input(or atleast it is printing something) all the time. My code below:
import msvcrt
from time import sleep
while True:
print(msvcrt.getch())
sleep(1)
This is printing b'\xff' all the time. And if I press something, it does not care, it still print same string. I am using python 3.6
Problem solved. If using msvcrt: Code has to run in console. I was running that with IDLE.
https://www.reddit.com/r/learnpython/comments/3ji6ew/ordgetch_returns_255_constantly/
Thanks to ingolemo.

Hide cursor when a specific program is running

I'm checking if the game is active and If it is I'm trying to hide the mouse cursor just for comfort reasons since it annoys me. But I can't find any way to do it... Any suggestions? I'm pretty new to Python.
import psutil
def isRunning(name):
for pid in psutil.pids():
prcs = psutil.Process(pid)
if name in prcs.name():
return True
while(isRunning("Brawlhalla")):
# do stuff here
You could do this using an external program. If you are under Linux, check unclutter (https://packages.ubuntu.com/bionic/x11/unclutter for example - if you are using ubuntu).
This answer lists other ways to hide the mouse cursor more or less permanently.
By the way this is not strictly speaking a Python question, and using a python script is probably not the proper way to achieve what you want... You'd better launch unclutter or one of its friends from a console and be done with it.
But assuming you really insist on using Python and your isRunning() code is correct, one naive way to implement what you want in python could look like this (leaving aside corner cases handling):
from time import sleep
import subprocess
(your isRunning code here)
proc = subprocess.Popen(["unclutter", "-root", "-idle", "0"])
while (isRunning("Brawlhalla")):
sleep(1)
proc.terminate()

Categories