From 1bb64ce55b686904f3bb0243759c0d2797a450e4 Mon Sep 17 00:00:00 2001 From: jenzur Date: Wed, 22 Apr 2020 00:17:28 +0200 Subject: [PATCH] minor updates to improve the bot tracking players ingame, still a lot left to do probably --- AutismBotIngame/python/ingamefollowct.py | 350 +++++++----------- AutismBotIngame/python/ingamerunning_2.py | 191 ---------- .../python/ingamerunning_xdotool.py | 177 --------- AutismBotIngame/python/start.sh | 2 +- AutismBotIngame/python/start2.sh | 3 - AutismBotIngame/python/start3.sh | 3 - AutismBotIngame/python/start4.sh | 2 +- AutismBotIngame/scripting/autism_bot_info.sp | 170 ++++++++- 8 files changed, 290 insertions(+), 608 deletions(-) delete mode 100644 AutismBotIngame/python/ingamerunning_2.py delete mode 100644 AutismBotIngame/python/ingamerunning_xdotool.py delete mode 100644 AutismBotIngame/python/start2.sh delete mode 100644 AutismBotIngame/python/start3.sh diff --git a/AutismBotIngame/python/ingamefollowct.py b/AutismBotIngame/python/ingamefollowct.py index 34f4cb09..d683e871 100644 --- a/AutismBotIngame/python/ingamefollowct.py +++ b/AutismBotIngame/python/ingamefollowct.py @@ -1,100 +1,34 @@ import os +import sys import subprocess import atexit from threading import Timer import string import random import time - +import mysql.connector +from mysql.connector import Error +from settings import mysql_connection_ip, mysql_connection_user, mysql_connection_pw, mysql_connection_database looptestPath = '/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/looptest.cfg' -consolelogPath = '/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/console.log' -clearbool = True -def id_generator(size=6, chars=string.ascii_uppercase + string.digits): - return ''.join(random.choice(chars) for _ in range(size)) - -def switchbool(): - global clearbool - clearbool = True - -def clearconsolelog(): - global clearbool - if clearbool: - clearbool = False - open(consolelogPath, 'w').close() - #print('cleaned console') - connectionTimer = Timer(3.0, switchbool) - #daemon true kills thread instead of deadlock waiting in case program exits - connectionTimer.daemon = True - connectionTimer.start() +def get_connection(): + return mysql.connector.connect( + host=mysql_connection_ip, + user=mysql_connection_user, + passwd=mysql_connection_pw, + database=mysql_connection_database) def writeCfgInput(Input): with open(looptestPath, 'w') as f: f.write(Input) - -def getconsoleOutputForStatus(): - i = 0 - while i < 8: - time.sleep(0.25) - randomlygeneratedString = id_generator(11) - str = "status; wait 5; {0}; wait 5;".format(randomlygeneratedString) - writeCfgInput(str) - checkConsoleOutput(randomlygeneratedString) - server_str = "" - player_count = 0 - with open(consolelogPath, 'r') as f: - for line in f: - try: - if "udp/ip" in line: server_str = line[9:].strip() - if "players " in line: player_count = int(line[9:].split()[0].strip()) - except Exception: - pass - if server_str: - print('server_str: ', server_str, '\nplayer_count: ', player_count) - return (server_str, player_count) - i += 1 - return ("None", "None") - -def get_output_if_spec(): - randomlygeneratedString = id_generator(11) - str = "zspawn; wait 500; {0}; wait 5;".format(randomlygeneratedString) - writeCfgInput(str) - #is sm_team a command to show team? - #maybe instead say !teaminfo, add sourcemod command to autism_bot_info.sp to print team to chat instead - targetstr = "This feature requires that you are on a team." - failurestr = "Unknown command \"zspawn\"" - alivestr = "This feature requires that you are dead." - checkConsoleOutput(randomlygeneratedString) - with open(consolelogPath, 'r') as f: - for line in f: - if alivestr in line: return 2 - if targetstr in line: return 1 - if failurestr in line: return 0 - return 0 - -def checkConsoleOutput(input): - iterations_count = 0 - #print('entered checkconsole output') - while iterations_count < 6: - time.sleep(0.5) - with open(consolelogPath, 'r') as f: - for line in f: - if input in line: - iterations_count += 6 - break - iterations_count += 1 def resetCfgInputShortWait(): - #getpos - randomlygeneratedString = id_generator(11) - #print('randomlygeneratedString: ', randomlygeneratedString) - str = "{0}; wait 5;".format(randomlygeneratedString) + str = "{0}; wait 5;" with open(looptestPath, 'w') as f: f.write(str) - checkConsoleOutput(randomlygeneratedString) - + time.sleep(0.5) def exit_handler(): print('reached exithandler') @@ -103,151 +37,132 @@ def exit_handler(): f.write(str) def joinTeam(): - randomlygeneratedString = id_generator(11) - str = "jointeam 2; wait 2; zspawn; wait 1; {0}; wait 5;".format(randomlygeneratedString) + str = "jointeam 2; wait 2; zspawn; wait 1; {0}; wait 5;" writeCfgInput(str) - checkConsoleOutput(randomlygeneratedString) + time.sleep(4.5) + print('jointeam func: ') def checkbotteam(): - while True: - clearconsolelog() - state = get_output_if_spec() - if state == 1: - joinTeam() - break - if state == 2: - break + mysql_check_spectator() resetCfgInputShortWait() connectionTimer = Timer(20.0, checkbotteam) connectionTimer.daemon = True connectionTimer.start() -def checkIfConnected(): - randomlygeneratedString = id_generator(11) - server_str, player_count = getconsoleOutputForStatus() - connectionTimer = None - if "27015" not in server_str: - str1 = "connect 151.80.230.149:27015; {0}; wait 500;".format(randomlygeneratedString) - writeCfgInput(str1) - checkConsoleOutput(randomlygeneratedString) - elif player_count > 63: - #TODO check team differently because zspawn unknown command on zr server - writeCfgInput("connect 151.80.230.149:27016; {0}; wait 5;".format(randomlygeneratedString)) - checkConsoleOutput(randomlygeneratedString) - connectionTimer = Timer(60.0 * 15, checkIfConnected) - resetCfgInputShortWait() - if not connectionTimer: - connectionTimer = Timer(60.0 * 2, checkIfConnected) - #daemon true kills thread instead of deadlock waiting in case program exits - connectionTimer.daemon = True - connectionTimer.start() - #print('finished checkIfConnected') +def mysql_check_spectator(): + cnx = get_connection() + cur = cnx.cursor() + sql_statement = f"""SELECT spectate from unloze_css_autism_bot.`bot status`""" + cur.execute(sql_statement) + result = cur.fetchall()[0] + spectate = result[0] + print('spectate: ', spectate) + if spectate != 0: + joinTeam() + cur.close() + cnx.close() -def get_player_info(): - movement_input = [] - ct_angles = [] - ct_origin_diff = [] - ct_origin_position = [] - ct_distance = 0 - while True: - with open(consolelogPath, 'r') as f: - try: - for line in f: - print('line: ', line) - if "movement_input_specific:" in line and len(line) > 26: - movement_input = line.split("movement_input_specific:", 1)[1].split("+") - movement_input = [element.replace("\n", "") for element in movement_input] - #print('movement: ', movement) - if "ct_eye_angles_:" in line: - ct_angles = line.split("ct_eye_angles_:", 1)[1].split("+") - ct_angles = [element.strip() for element in ct_angles] - if "player_origin_diff:" in line: - ct_origin_diff = line.split("player_origin_diff:", 1)[1].split("+") - ct_origin_diff = [element.strip() for element in ct_origin_diff] - ct_origin_diff = [float(element) for element in ct_origin_diff] - if "player_origin_position:" in line: - ct_origin_position = line.split("player_origin_position:", 1)[1].split("+") - ct_origin_position = [element.strip() for element in ct_origin_position] - if "player_lowest_distance:" in line: - ct_distance = line.split("player_lowest_distance:", 1)[1].strip() - ct_distance = float(ct_distance) - if movement_input and ct_angles and ct_origin_diff and ct_origin_position and ct_distance: - return (movement_input, ct_angles, ct_origin_diff, ct_origin_position, ct_distance) - except (UnicodeDecodeError, IndexError): - pass - -def getBotOrgin(botOrigin): - #x -> z -> y coordAxis order - botOrigin = [x.strip() for x in botOrigin] - botOrigin = [x.replace(";", "") for x in botOrigin] - #botOrigin = [x.replace(";", "") for x in botOrigin] - botIntorigin0 = float(botOrigin[0]) - botIntorigin1 = float(botOrigin[1]) - botIntorigin2 = float(botOrigin[2]) - #bot coordinates might be usefull? - return [botIntorigin0, botIntorigin1, botIntorigin2] - -def getBotOrigin(): - while True: - str = "getpos; wait 1; wait 5;" - writeCfgInput(str) - previousStr = "" - with open(consolelogPath, 'r') as f: - for line in f: - if "setpos" in line: - try: - print('found setpos line: ', line) - coords = line.split("setpos")[1].split(";setang")[0].split() - #print('coords: ', coords) - return getBotOrgin(coords) - except IndexError as err: - pass - previousStr = line - -def followPlayer(remaining_instructions = [], indexCounter = 0, previousmoment = []): - #setang 0 180 0; - #default_input = "+attack; wait 50; cl_minmodels; wait 50; +right; wait 50; +jump; wait 50; -jump; wait 50; +forward; wait 50; {0}; wait 5;".format(randomlygeneratedString) - #writeCfgInput(default_input) - botOrigin = getBotOrigin() - movement_input, ct_angles, ct_origin_diff, ct_origin_position, ct_distance = get_player_info() - print('movement_input: ', movement_input, '\nct_angles: ', ct_angles, "\nct_origin_diff: ", ct_origin_diff, "\nct_origin_position: ", ct_origin_position, "\nct_distance: ", ct_distance, "\nbotOrigin: ", botOrigin) - randomlygeneratedString = id_generator(11) - remaining_instructions.append([movement_input, ct_angles]) - strInput = "-jump; wait 5; +attack; wait 5; cl_minmodels 1; wait 5; setang 0 180 0; wait 5;".format(ct_angles[0], ct_angles[1], ct_angles[2]) - #strInput += "-forward; wait 5; -back; wait 5; -moveleft; wait 5; -moveright; wait 5; " - if ct_distance > 250: - remaining_instructions = [] - indexCounter = 0 - #0 180 0: W = X axis greater minus, S = X axis greater plus, A = Y axis greater minus, D = Y axis greater plus - if botOrigin[0] + 50 > ct_origin_diff[0]: - strInput += "wait 5; +forward;" - elif botOrigin[0] - 50 < ct_origin_diff[0]: - strInput += "wait 5; +back;" - if botOrigin[1] + 50 > ct_origin_diff[1]: - strInput += "wait 5; +moveleft;" - elif botOrigin[1] - 50 < ct_origin_diff[1]: - strInput += "wait 5; +moveright;" - print('ct_distance > 250:') +def mysql_get_player_info(movement_list): + #1 = forward, 2 = back, 3 = left, 4 = right + #use previous movement instead for evaluation + strInput = "-attack; -jump; -duck; +attack; cl_minmodels 1; " + print('movement_list[0]: ', movement_list[0], '#1 = forward, 2 = back, 3 = left, 4 = right') + print('movement_list[1]: ', movement_list[1], '#1 = forward, 2 = back, 3 = left, 4 = right') + if movement_list[0] == 1: + strInput += " -back; wait 5;" else: - (movement, angles) = remaining_instructions[indexCounter] - if previousmoment != movement: - strInput += "-forward; wait 5; -back; wait 5; -moveleft; wait 5; -moveright; wait 5; " - previousmoment = movement - strInput = strInput.replace("setang 0 180 0;", "setang {0} {1} {2};".format(angles[0], angles[1], angles[2])) - for move in movement: - strInput += "+" - strInput += move - strInput += "; " - indexCounter += 1 - strInput += " wait 5; {0}; ".format(randomlygeneratedString) - print('strInput: ', strInput) - writeCfgInput(strInput) - checkConsoleOutput(randomlygeneratedString) - clearconsolelog() - connectionTimer = Timer(0.2, followPlayer, args=(remaining_instructions, indexCounter)) + strInput += " -forward; wait 5;" + if movement_list[1] == 4: + strInput += " -moveleft; wait 5;" + else: + strInput += " -moveright; wait 5;" + #print('strInput movement_list:', strInput) + cnx = get_connection() + cur = cnx.cursor() + sql_statement = f"""SELECT * from unloze_css_autism_bot.`bot movement input` ORDER BY entry_time LIMIT 1""" + sql_row_count = "SELECT COUNT(*) FROM unloze_css_autism_bot.`bot movement input`" + cur.execute(sql_statement) + result = cur.fetchall() + cur.execute(sql_row_count) + result_count = cur.fetchone()[0] + if result: + movement_list = [] + result = result[0] + movement_input = result[0] + client_angles = [result[1], result[2], result[3]] + xyz_difference = [result[4], result[5], result[6]] + client_coordinates = [result[7], result[8], result[9]] + lowest_distance = result[10] + print('result_count: ', result_count) + if "+jump;" in movement_input: + strInput += " +jump;" + if "+duck;" in movement_input: + strInput += " +duck;" + #print('xyz_difference: ', xyz_difference) + if xyz_difference[0] > 0: + movement_list.append(1) + strInput += " +forward; wait 5;" + else: + movement_list.append(2) + strInput += " +back; wait 5;" + if xyz_difference[1] < 0: + movement_list.append(4) + strInput += " +moveright; wait 5;" + else: + movement_list.append(3) + strInput += " +moveleft; wait 5;" + strInput += f""" setang 0 180 0; wait 5; """ + #print('strInput final:', strInput) + writeCfgInput(strInput) + time.sleep(0.20) + writeCfgInput("wait 5;") + limit = 0 + if result_count > 7: + limit = result_count - 2 + else: + limit = 1 + sql_statement = f"""DELETE FROM unloze_css_autism_bot.`bot movement input` ORDER BY entry_time LIMIT {limit}""" + cur.execute(sql_statement) + cnx.commit() + cur.close() + cnx.close() + connectionTimer = Timer(0.10, mysql_get_player_info, args=[movement_list]) connectionTimer.daemon = True connectionTimer.start() +def mysql_check_if_connected(): + cnx = get_connection() + cur = cnx.cursor() + sql_statement = """SELECT connected, playercount from unloze_css_autism_bot.`bot status`""" + cur.execute(sql_statement) + result = cur.fetchall()[0] + #print('result: ', result, ' result[0]: ', result[0]) + connected = result[0] + playercount = result[1] + #playercount might not be updated ingame and auto leave? + print('connected: ', connected) + if connected == 0: + str1 = "connect 151.80.230.149:27015;" + writeCfgInput(str1) + time.sleep(0.5) + writeCfgInput("wait 500;") + time.sleep(15.50) + print('not yet connected') + mysql_check_if_connected() + obsolete = """ + elif playercount > 60: + str1 = "connect 151.80.230.149:27016;" + writeCfgInput(str1) + time.sleep(0.5) + writeCfgInput("wait 500;") + time.sleep(15.50) + print('not yet connected') + mysql_check_if_connected() """ + connectionTimer = Timer(60.0 * 2, mysql_check_if_connected) + connectionTimer.daemon = True + connectionTimer.start() + cur.close() + cnx.close() def deadlock(): try: @@ -257,14 +172,17 @@ def deadlock(): if __name__ == '__main__': atexit.register(exit_handler) - clearconsolelog() resetCfgInputShortWait() - checkIfConnected() + mysql_check_if_connected() checkbotteam() - print('reached followPlayer') - followPlayer() + print('reached mysql _get_player_info') + mysql_get_player_info([" +forward;", " +moveright;"]) print('reached deadlock') deadlock() -#autoexec.cfg: -#alias loop "exec looptest.cfg; wait 5; loop;"; wait 5; loop; \ No newline at end of file +#/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/autoexec.cfg: +#alias loop "exec looptest.cfg; wait 300; loop;"; wait 5; loop; + +#-condebug +#cd /home/nonroot/.steam/ +#./steam.sh -applaunch 240 -textmode -textmessagedebug -novid -nosound -noipx -nojoy -noshaderapi +exec looptest.cfg \ No newline at end of file diff --git a/AutismBotIngame/python/ingamerunning_2.py b/AutismBotIngame/python/ingamerunning_2.py deleted file mode 100644 index 7d87fc56..00000000 --- a/AutismBotIngame/python/ingamerunning_2.py +++ /dev/null @@ -1,191 +0,0 @@ -import os -import subprocess -import time, threading -import atexit -from random import randrange, choice - -currentmap = "" - -#condebug instead of condump, remove all condump entries, instead read from console.log, remove deleteConDump Calls -#perharps instead of opening constantly opening once and somehow updating might be more efficient - -def clearconsolelog(): - open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/console.log', 'w').close() - -def readMapFromConsoleLog(): - with open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/console.log', 'r') as f: - for line in f: - #print('line: ', line) - if '[SM] The current map is ' in line: - currentmap = line[line.find('map is ') + len('map is '):line.rfind('.')] - return currentmap - return "" - -def writeCfgInput(Input): - with open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/looptest.cfg', 'w') as f: - f.write(Input) - -def checkConsoleOutput(input): - bool = False - while not bool: - with open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/console.log', 'r') as f: - for line in f: - if input in line: - #print('line: ', line, ' \ninput: ', input) - bool = True - break - -def resetCfgInputShortWait(): - str = "wait 1; getpos; wait 1; exec looptest.cfg;" - with open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/looptest.cfg', 'w') as f: - f.write(str) - checkConsoleOutput("setpos") - -def findcurrentmap(): - currentmap = "" - clearconsolelog() - while not currentmap: - try: - #print("post resetcfg") - writeCfgInput("say currentmap; wait 1; exec looptest.cfg;") - time.sleep(0.02) - currentmap = readMapFromConsoleLog() - except OSError: - #print('failed opening file') - pass - resetCfgInputShortWait() - clearconsolelog() - print("currentmap is: {}".format(currentmap)) - return currentmap - - -def deleteCondump(): - [os.remove(os.path.join("/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/",f)) for f in os.listdir("/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/") if f.startswith("condump")] - - -def joinTeam(): - print("reached joinTeam") - str = "jointeam 2; wait 2; zspawn; wait 1; exec looptest.cfg;" - writeCfgInput(str) - checkConsoleOutput("zspawn") - -def floatconverter(Array, index): - return float(Array[index].replace('\U00002013', '-').replace(';', '')) - -def findClosestCt(originPosition): - PositionArray = originPosition.split() - #print('PositionArray: ', PositionArray) - xAxis = floatconverter(PositionArray, 0) - yAxis = floatconverter(PositionArray, 1) - zAxis = floatconverter(PositionArray, 2) - x = 0.0 - y = 0.0 - z = 0.0 - defaultDistance = 1000000.0 - #use CTOrigin to find, input comes from plugin spammed all 3 seconds - checkConsoleOutput("CTOrigin:") - try: - with open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/console.log', 'r') as f: - playerOrigin = [0, 0, 0] - for line in f: - #print('line: ', line) - if 'CTOrigin:' in line: - #print('found origin line: ', line) - playerArray = line[10:].split() - playerArray[2].replace(";", "") - print('playerArray: ', playerArray) - playerOrigin[0] = floatconverter(PositionArray, 0) - playerOrigin[1] = floatconverter(PositionArray, 1) - playerOrigin[2] = floatconverter(PositionArray, 2) - xValue = xAxis - playerOrigin[0] - yValue = yAxis - playerOrigin[1] - zValue = zAxis - playerOrigin[2] - if xValue < 0: xValue * -1 - if yValue < 0: yValue * -1 - if zValue < 0: zValue * -1 - totalDistance = xValue + yValue + zValue - if totalDistance < defaultDistance: - defaultDistance = totalDistance - x = playerOrigin[0] - y = playerOrigin[1] - z = playerOrigin[2] - except OSError: - print('failed opening file readorigin') - return (x, y ,z) - - -def readOrigin(): - originPosition = "" - writeCfgInput("getpos; wait 1; exec looptest.cfg;") - while not originPosition: - try: - with open('/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/console.log', 'r') as f: - for line in f: - if 'setpos' in line: - originPosition = line[line.find('setpos') + len('setpos'):line.rfind(';setang')] - break - except OSError: - #print('failed opening file readorigin') - pass - return originPosition - - -def findDirection(x, y, z, originPosition): - directions = ["forward", "back", "moveleft", "moveright"] - PositionArray = originPosition.split() - xAxis = floatconverter(PositionArray, 0) - yAxis = floatconverter(PositionArray, 1) - zAxis = floatconverter(PositionArray, 2) - print('xAxis, yAxis , zAxis', xAxis, yAxis, zAxis) - print('x, y , z', x, y, z) - if x > xAxis + 200 : return directions[1] - elif x < xAxis - 200 : return directions[0] - elif y > yAxis + 200 : return directions[3] - elif y < yAxis - 200 : return directions[2] - return choice(directions) - -def followPlayer(): - direction = "" - prev_direction = "forward" - default_input = "+attack; wait 1; cl_minmodels 1; wait 5; setang 0 180 0; wait 1;" - while True: - try: - print("start of try") - originPosition = readOrigin() - #print('originPosition: ', originPosition) - CrouchOrJump = "wait 1; -duck; wait 1; +jump; wait 1; -jump;" - if randrange(0, 10) > 8: - CrouchOrJump = "wait 1; +duck;" - x, y, z = findClosestCt(originPosition) - if x != 0.0: - clearconsolelog() - resetCfgInputShortWait() - direction = findDirection(x, y ,z, originPosition) - print('movedirection: ', direction) - str = "" - if direction != prev_direction: - str = "{} -{}; wait 1; +{}; {} wait 1; exec looptest.cfg;".format(default_input, prev_direction, direction, CrouchOrJump) - prev_direction = direction - else: - str = "{} +{}; {} wait 1; exec looptest.cfg;".format(default_input, direction, CrouchOrJump) - writeCfgInput(str) - checkConsoleOutput(str) - except ValueError as err: - print('ValueError occured: ', err) - pass - -def exit_handler(): - #deleteCondump() - resetCfgInputShortWait() - -if __name__ == '__main__': - atexit.register(exit_handler) - resetCfgInputShortWait() - currentmap = findcurrentmap() - joinTeam() - #circlespin() - resetCfgInputShortWait() - followPlayer() - #exploreMap(currentmap) - #loadMapPattern(currentmap) - #final idea: send printchat to bot for movement input from plugin \ No newline at end of file diff --git a/AutismBotIngame/python/ingamerunning_xdotool.py b/AutismBotIngame/python/ingamerunning_xdotool.py deleted file mode 100644 index 14422a8c..00000000 --- a/AutismBotIngame/python/ingamerunning_xdotool.py +++ /dev/null @@ -1,177 +0,0 @@ -import os -import subprocess -import time, threading -import os -# COMMENTS -#sm_track_movement jenz -#direct input -#xdotool search --name "Counter-Strike Source - OpenGL" key m - -#setxkbmap -layout dk -#xdotool search --name "Counter-Strike Source - OpenGL" -#xdotool windowfocus 10488872 / 31457297 // 67108881 -# keydown -# COMMENTS OVER - -def processType(type): - subprocess.call(["xdotool", "type", type]) - -def processKeys(key): - subprocess.call(["xdotool", "key", key]) - -def findPosOrigin(line): - originPost = line[line.find('setpos ') + len('setpos'):line.rfind(';setang')] - print('originPost: ', originPost) - return originPost - -def deleteCondump(): - [os.remove(os.path.join("/home/john/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/",f)) for f in os.listdir("/home/john/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/") if f.startswith("condump")] - -def processLine(line): - if '[SM] The current map is ' in line: - processType("say") - processKeys("space") - processType("currentmap") - processKeys("space") - processType("is") - processKeys("space") - currentmap = line[line.find('map is ') + len('map is '):line.rfind('.')] - processType(currentmap) - processKeys("Return") - global currentFilename - currentFilename = str(currentmap) - -def reachgetDifference(reachpos, getpos): - #print('reachpos: ', reachpos) - #print('getpos: ', getpos) - if getpos[1] == '-': - getpos = getpos[2:] - if reachpos[1] == '-': - reachpos = reachpos[2:] - reachposAxis = float(reachpos[0].strip('"')) - getposAxis = float(getpos[0].strip('"')) - if reachposAxis - 50.0 < getposAxis: - processType("setang") - processKeys("space") - processType("0") - processKeys("space") - processType("180") - processKeys("space") - processType("0") - processKeys("Return") - return True - elif reachposAxis + 50.0 > getposAxis: - processType("setang") - processKeys("space") - processType("0") - processKeys("space") - processType("0") - processKeys("space") - processType("0") - processKeys("Return") - return True - return False - -def readmovement(line): - doubleString = "setang " - processphase = 0; - characterString = "" - for index, character in enumerate(line): - #print('character: ', character) - if processphase == 0: - if character.isspace(): - continue - if character.isalpha(): - if character != characterString: - processKeys("minus") - if character == "w": - characterString = "forward" - elif character == "s": - characterString = "back" - print('characterString: ', characterString) - print('character: ', character) - processType(characterString) - processKeys("Return") - time.sleep(0.5) - processKeys("plus") - if character == "w": - characterString = "forward" - elif character == "s": - characterString = "back" - processType(characterString) - print('characterString2: ', characterString) - processKeys("Return") - characterString = character - processphase += 1 - if processphase == 1: - if character.isdigit() or character == '.': - doubleString += character - elif character.isspace() and len(doubleString) > 10: - doubleString += " " - if line[index + 1] == "o": - processType(doubleString) - processKeys("Return") - doubleString = "" - processphase += 1 - if processphase == 2: - if not character.isdigit() and not doubleString: - continue - elif character.isdigit() or character == '.': - doubleString += character - elif character.isspace() and doubleString and not line[index + 1].isalpha(): - doubleString += " " - else: - reachpos = doubleString.split() - getpos = ["0.0", "0.0", "0.0"] - while reachgetDifference(reachpos, getpos): - processType("clear") - processKeys("Return") - processType("getpos") - processKeys("Return") - time.sleep(2) - processType("condump") - processKeys("Return") - time.sleep(2) - with open('/home/john/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/condump000.txt') as f: - for line in f: - if 'setpos' in line: - getpos = findPosOrigin(line) - break - time.sleep(2) - deleteCondump() - processphase = 0 - doubleString = "setang " - -def findcurrentmap(): - subprocess.call(["xdotool", "search", "--name", "Counter-Strike Source - OpenGL", "windowactivate"]) - #clear console field before retrieving info - processKeys("Return") - #clean console prompt - processType("clear") - processKeys("Return") - processType("say") - processKeys("space") - processType("currentmap") - processKeys("Return") - time.sleep(2) - processType("condump") - processKeys("Return") - time.sleep(2) - with open('/home/john/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/condump000.txt') as f: - for line in f: - processLine(line) - time.sleep(2) - deleteCondump() - #subprocess.call(["xdotool", "key", "Escape"]) - #subprocess.call(["xdotool", "key", "o"]) - -def mapmovementpattern(): - stringfile = "/home/nonroot/zeeman/maps/%s.txt" % (currentFilename) - with open(stringfile) as f: - for line in f: - readmovement(line) - -if __name__ == '__main__': - deleteCondump() - findcurrentmap() - mapmovementpattern() \ No newline at end of file diff --git a/AutismBotIngame/python/start.sh b/AutismBotIngame/python/start.sh index cf54d8af..6329f32a 100644 --- a/AutismBotIngame/python/start.sh +++ b/AutismBotIngame/python/start.sh @@ -3,7 +3,7 @@ #glxinfo #source venv/bin/activate export SDL_VIDEO_X11_VISUALID="0x0e5" #0x0e5 -python connectServer.py +python3.8 connectServer.py ###Nomachine related diff --git a/AutismBotIngame/python/start2.sh b/AutismBotIngame/python/start2.sh deleted file mode 100644 index 91527d86..00000000 --- a/AutismBotIngame/python/start2.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash -#source venv/bin/activate -python ingamerunning_2.py \ No newline at end of file diff --git a/AutismBotIngame/python/start3.sh b/AutismBotIngame/python/start3.sh deleted file mode 100644 index 07f83931..00000000 --- a/AutismBotIngame/python/start3.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash -#source venv/bin/activate -python rejoinze.py \ No newline at end of file diff --git a/AutismBotIngame/python/start4.sh b/AutismBotIngame/python/start4.sh index 9e7f81dc..bda03189 100644 --- a/AutismBotIngame/python/start4.sh +++ b/AutismBotIngame/python/start4.sh @@ -1,5 +1,5 @@ #!/bin/bash #source venv/bin/activate -python ingamefollowct.py +python3.8 ingamefollowct.py #dont need x2go connection for hl2 process or ./steam.sh -textmode, both work with regular ssh if logged in already \ No newline at end of file diff --git a/AutismBotIngame/scripting/autism_bot_info.sp b/AutismBotIngame/scripting/autism_bot_info.sp index dc82da0e..8927dae5 100644 --- a/AutismBotIngame/scripting/autism_bot_info.sp +++ b/AutismBotIngame/scripting/autism_bot_info.sp @@ -4,6 +4,7 @@ #define PLUGIN_AUTHOR "jenz" #define PLUGIN_VERSION "1.00" +#define generic_length 256 #include #include @@ -25,23 +26,51 @@ public Plugin myinfo = public void OnClientDisconnect(int client) { if (present == client) + { present = 0; + mysql_enable_disable_connected(0); + } + } public void OnPluginStart() { //hooks HookEvent("round_start", Event_RoundStart, EventHookMode_PostNoCopy); + HookEvent("player_team", event_playerteam, EventHookMode_PostNoCopy); + + //mysql + sql_create_table(); } +public Action event_playerteam(Event event, const char[] name, bool dontBroadcast) +{ + int client = GetClientOfUserId(event.GetInt("userid")); + if (client == present) + { + //PrintToChatAll("called event_playerteam"); + int team = event.GetInt("team"); + //PrintToChatAll("team: %i", team); + if (team == 2 || team == 3) + mysql_bot_not_spec(); + } +} public void Event_RoundStart(Handle event, const char[] name, bool dontBroadcast) { targethuman = 0; + int server_port = GetConVarInt(FindConVar("hostport")); + if (server_port == 27015) + { + mysql_update_playercount(); + } + if (present) + mysql_clean_movement_input(); } public void OnMapStart() { - CreateTimer(0.3, recursive_pressing, INVALID_HANDLE, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE); + sql_create_table(); + CreateTimer(1.0, recursive_pressing, INVALID_HANDLE, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE); } public bool TraceEntityFilterPlayer(int entity, int contentsMask) @@ -52,7 +81,7 @@ public bool TraceEntityFilterPlayer(int entity, int contentsMask) public Action recursive_pressing(Handle timer, any data) { //PrintToChatAll("present: %N", present); - if (present) + if (present && IsPlayerAlive(present)) { float client_coord[3]; float xyz[3]; @@ -85,35 +114,32 @@ public Action recursive_pressing(Handle timer, any data) float clientangles[3]; GetClientAbsAngles(targethuman, clientangles); int keys = GetClientButtons(targethuman); - char keyinput[256]; + char keyinput[generic_length]; if (keys & IN_FORWARD) { - StrCat(keyinput, sizeof(keyinput), "forward+"); + StrCat(keyinput, sizeof(keyinput), "+forward; "); } if (keys & IN_BACK) { - StrCat(keyinput, sizeof(keyinput), "back+"); + StrCat(keyinput, sizeof(keyinput), "+back; "); } if (keys & IN_MOVELEFT) { - StrCat(keyinput, sizeof(keyinput), "moveleft+"); + StrCat(keyinput, sizeof(keyinput), "+moveleft; "); } if (keys & IN_MOVERIGHT) { - StrCat(keyinput, sizeof(keyinput), "moveright+"); + StrCat(keyinput, sizeof(keyinput), "+moveright; "); } if (keys & IN_JUMP) { - StrCat(keyinput, sizeof(keyinput), "jump+"); + StrCat(keyinput, sizeof(keyinput), "+jump; "); } - //PrintToChatAll("keyinput: %s", keyinput); - //PrintToChatAll("xyz[0], xyz[1], xyz[2]: %f %f %f", xyz[0], xyz[1], xyz[2]); - //PrintToChatAll("lowest_distance: %f", lowest_distance); - ServerCommand("sm_psay #[U:1:120378081] movement_input_specific:%s", keyinput); - ServerCommand("sm_psay #[U:1:120378081] ct_eye_angles_:%f+%f+%f", clientangles[0], clientangles[1], clientangles[2]); - ServerCommand("sm_psay #[U:1:120378081] player_origin_diff:%f+%f+%f", xyz[0], xyz[1], xyz[2]); - ServerCommand("sm_psay #[U:1:120378081] player_origin_position:%f+%f+%f", client_coord[0], client_coord[1], client_coord[2]); - ServerCommand("sm_psay #[U:1:120378081] player_lowest_distance:%f", lowest_distance); + if (keys & IN_DUCK) + { + StrCat(keyinput, sizeof(keyinput), "+duck; "); + } + mysql_send_input(keyinput, clientangles, xyz, client_coord, lowest_distance); } } return Plugin_Handled; @@ -137,7 +163,119 @@ public void OnClientPostAdminCheck(int client) char auth[50]; GetClientAuthId(client, AuthId_Engine, auth, sizeof(auth)); if (StrEqual("[U:1:120378081]", auth, false)) + { + mysql_enable_disable_connected(1); present = client; + } else if (StrEqual("STEAM_0:1:60189040", auth, false)) + { + mysql_enable_disable_connected(1); present = client; + } +} + +public void sql_create_table() +{ + char error_connect[generic_length]; + Database database_connection; + if (SQL_CheckConfig("css_autism_bot_info")) + database_connection = SQL_Connect("css_autism_bot_info", true, error_connect, sizeof(error_connect)); + if (database_connection == null) + PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!"); + //256 not enough + char query_start[generic_length * 2]; + Format(query_start, sizeof(query_start), "CREATE TABLE IF NOT EXISTS unloze_css_autism_bot.`bot status` (`connected` BOOL DEFAULT false, `spectate` BOOL DEFAULT true, `ID` INT NOT NULL DEFAULT 1, `playercount` INT DEFAULT 0, PRIMARY KEY (`ID`))"); + mysql_exec_prepared_statement(database_connection, query_start); + Format(query_start, sizeof(query_start), "CREATE TABLE IF NOT EXISTS unloze_css_autism_bot.`bot movement input` (`keyinput` text NOT NULL, `clientangles_0` FLOAT DEFAULT 0.0, `clientangles_1` FLOAT DEFAULT 0.0, `clientangles_2` FLOAT DEFAULT 0.0, `xyz_0` FLOAT DEFAULT 0.0, `xyz_1` FLOAT DEFAULT 0.0, `xyz_2` FLOAT DEFAULT 0.0, `client_coord_0` FLOAT DEFAULT 0.0, `client_coord_1` FLOAT DEFAULT 0.0, `client_coord_2` FLOAT DEFAULT 0.0, `lowest_distance` FLOAT DEFAULT 0.0, `entry_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)"); + mysql_exec_prepared_statement(database_connection, query_start); + Format(query_start, sizeof(query_start), "INSERT INTO unloze_css_autism_bot.`bot status` (connected, spectate, ID) VALUES (0, 1, 1) ON DUPLICATE KEY UPDATE connected = VALUES(connected), spectate = VALUES(spectate)"); + mysql_exec_prepared_statement(database_connection, query_start); + delete database_connection; +} + +public void mysql_clean_movement_input() +{ + char error_connect[generic_length]; + Database database_connection; + if (SQL_CheckConfig("css_autism_bot_info")) + database_connection = SQL_Connect("css_autism_bot_info", true, error_connect, sizeof(error_connect)); + if (database_connection == null) + PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!"); + char query_start[generic_length]; + Format(query_start, sizeof(query_start), "delete from unloze_css_autism_bot.`bot movement input`"); + mysql_exec_prepared_statement(database_connection, query_start); +} + +public void mysql_update_playercount() +{ + char error_connect[generic_length]; + Database database_connection; + if (SQL_CheckConfig("css_autism_bot_info")) + database_connection = SQL_Connect("css_autism_bot_info", true, error_connect, sizeof(error_connect)); + if (database_connection == null) + PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!"); + char query_start[generic_length]; + Format(query_start, sizeof(query_start), "INSERT INTO unloze_css_autism_bot.`bot status` (playercount, ID) VALUES (%i, 1) ON DUPLICATE KEY UPDATE playercount = %i", MaxClients, MaxClients); + mysql_exec_prepared_statement(database_connection, query_start); + delete database_connection; +} + +public void mysql_bot_not_spec() +{ + char error_connect[generic_length]; + Database database_connection; + if (SQL_CheckConfig("css_autism_bot_info")) + database_connection = SQL_Connect("css_autism_bot_info", true, error_connect, sizeof(error_connect)); + if (database_connection == null) + PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!"); + char query_start[generic_length]; + Format(query_start, sizeof(query_start), "INSERT INTO unloze_css_autism_bot.`bot status` (connected, spectate, ID) VALUES (1, 0, 1) ON DUPLICATE KEY UPDATE connected = VALUES(connected), spectate = VALUES(spectate)"); + mysql_exec_prepared_statement(database_connection, query_start); +} + +public void mysql_enable_disable_connected(int state) +{ + char error_connect[generic_length]; + Database database_connection; + if (SQL_CheckConfig("css_autism_bot_info")) + database_connection = SQL_Connect("css_autism_bot_info", true, error_connect, sizeof(error_connect)); + if (database_connection == null) + PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!"); + char query_start[generic_length]; + if (!state) + Format(query_start, sizeof(query_start), "INSERT INTO unloze_css_autism_bot.`bot status` (connected, spectate, ID) VALUES (0, 1, 1) ON DUPLICATE KEY UPDATE connected = VALUES(connected), spectate = VALUES(spectate)"); + else + Format(query_start, sizeof(query_start), "INSERT INTO unloze_css_autism_bot.`bot status` (connected, spectate, ID) VALUES (1, 1, 1) ON DUPLICATE KEY UPDATE connected = VALUES(connected), spectate = VALUES(spectate)"); + //PrintToChatAll("query_start: %s", query_start); + mysql_exec_prepared_statement(database_connection, query_start); + delete database_connection; +} + +public void mysql_send_input(char []keyinput, float clientangles[3], float xyz[3], float client_coord[3], float lowest_distance) +{ + //TODO maybe add autism bot coords too as information + char error_connect[generic_length]; + Database database_connection; + if (SQL_CheckConfig("css_autism_bot_info")) + database_connection = SQL_Connect("css_autism_bot_info", true, error_connect, sizeof(error_connect)); + if (database_connection == null) + PrintToChatAll("{green}[UNLOZE] {white}Error! Could not connect to maria-DB!"); + char query_start[generic_length]; + Format(query_start, sizeof(query_start), "INSERT INTO unloze_css_autism_bot.`bot movement input` VALUES ('%s', %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, NOW())", keyinput, clientangles[0], clientangles[1], clientangles[2], xyz[0], xyz[1], xyz[2], client_coord[0], client_coord[1], client_coord[2], lowest_distance); + mysql_exec_prepared_statement(database_connection, query_start); + //PrintToChatAll("query_start: %s", query_start); + delete database_connection; +} + +public void mysql_exec_prepared_statement(Database database_connection, char []query_statement) +{ + char error[generic_length]; + DBStatement create_statement = SQL_PrepareQuery(database_connection, query_statement, error, sizeof(error)); + if (create_statement == INVALID_HANDLE) + { + CloseHandle(create_statement); + return; + } + SQL_Execute(create_statement); + CloseHandle(create_statement); } \ No newline at end of file