completed switch to UDP featuring ingame chat support again

This commit is contained in:
jenzur 2020-07-03 22:50:21 +02:00
parent 870651e0ef
commit 6d58c75d12
5 changed files with 141 additions and 259 deletions

View File

@ -105,34 +105,6 @@ public class DataMapper {
return hlStatsMessages; return hlStatsMessages;
} }
public static String check_autismo_mysql() {
String target = "";
try (Connection l_cCon = DBCPDataSourceAutismo.getConnection()) {
String l_sSQL = "SELECT chatmessage FROM unloze_css_autism_bot.chatting c WHERE c.responsemessage = '' LIMIT 1";
try (PreparedStatement l_pStatement = l_cCon.prepareStatement(l_sSQL)) {
try (ResultSet l_rsSearch = l_pStatement.executeQuery()) {
while (l_rsSearch.next()) {
target = l_rsSearch.getString(1);
}
}
}
} catch (SQLException ex) {
Logger.getLogger(DataMapper.class.getName()).log(Level.SEVERE, null, ex);
}
return target;
}
public static void update_autismo_mysql(String responseMsg, String update_string) {
try (Connection l_cCon = DBCPDataSourceAutismo.getConnection()) {
String l_sSQL = "UPDATE unloze_css_autism_bot.`chatting` SET `responsemessage` = '" + responseMsg + "' WHERE `chatmessage` = '" + update_string + "'";
try (PreparedStatement l_pStatement = l_cCon.prepareStatement(l_sSQL)) {
l_pStatement.execute();
}
} catch (SQLException ex) {
Logger.getLogger(DataMapper.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void CloseConnections(PreparedStatement ps, ResultSet rs, Connection con) { public static void CloseConnections(PreparedStatement ps, ResultSet rs, Connection con) {
if (rs != null) { if (rs != null) {
try { try {

View File

@ -21,7 +21,12 @@ import edu.stanford.nlp.tagger.maxent.MaxentTagger;
import edu.stanford.nlp.trees.GrammaticalStructureFactory; import edu.stanford.nlp.trees.GrammaticalStructureFactory;
import edu.stanford.nlp.trees.TreebankLanguagePack; import edu.stanford.nlp.trees.TreebankLanguagePack;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import static java.lang.Math.random; import static java.lang.Math.random;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.AbstractMap; import java.util.AbstractMap;
import java.util.ArrayList; import java.util.ArrayList;
@ -790,15 +795,30 @@ public class Datahandler {
return stringCache.values().size() - (stringCache.values().size() / 10); return stringCache.values().size() - (stringCache.values().size() / 10);
} }
public void update_autismo_mysql() { public void update_autismo_socket_msg() {
String update_string = DataMapper.check_autismo_mysql(); try {
if (!update_string.isEmpty()) { try (DatagramSocket serverSocket = new DatagramSocket(48477)) {
try { byte[] receiveData = new byte[4096];
String getResponseMsg = getResponseMsg(update_string); InetAddress IPAddress = InetAddress.getByName("151.80.230.149");
DataMapper.update_autismo_mysql(getResponseMsg, update_string); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
while (true) {
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
sentence = sentence.replace("clientmessage:", "");
String getResponseMsg = getResponseMsg(sentence);
byte[] sendData = getResponseMsg.getBytes("UTF-8");
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 48477);
serverSocket.send(sendPacket);
}
} catch (CustomError ex) { } catch (CustomError ex) {
Logger.getLogger(Datahandler.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(Datahandler.class.getName()).log(Level.SEVERE, null, ex);
} }
} catch (SocketException ex) {
Logger.getLogger(Datahandler.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Datahandler.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Datahandler.class.getName()).log(Level.SEVERE, null, ex);
} }
} }

View File

@ -31,17 +31,11 @@ import org.javacord.api.DiscordApiBuilder;
* @author install1 * @author install1
*/ */
public class DiscordHandler { public class DiscordHandler {
public static class update_autismo_ingame_msgs extends TimerTask {
@Override
public void run() {
Datahandler.instance.update_autismo_mysql();
}
}
public static void main(String[] args) { public static void main(String[] args) {
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "15"); System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "15");
try { try {
Datahandler.instance.initiateMYSQL(); Datahandler.instance.initiateMYSQL();
//nohup screen -d -m -S nonroot java -Xmx6900M -jar /home/javatests/ArtificialAutism-1.0.jar
//uncomment db fetch when ready, just keep the comment for future reference //uncomment db fetch when ready, just keep the comment for future reference
System.out.println("finished initiating MYSQL"); System.out.println("finished initiating MYSQL");
} catch (SQLException | IOException ex) { } catch (SQLException | IOException ex) {
@ -56,13 +50,13 @@ public class DiscordHandler {
Datahandler.instance.updateStringCache(); Datahandler.instance.updateStringCache();
String token = "NTI5NzAxNTk5NjAyMjc4NDAx.Dw0vDg.7-aMjVWdQMYPl8qVNyvTCPS5F_A"; String token = "NTI5NzAxNTk5NjAyMjc4NDAx.Dw0vDg.7-aMjVWdQMYPl8qVNyvTCPS5F_A";
DiscordApi api = new DiscordApiBuilder().setToken(token).login().join(); DiscordApi api = new DiscordApiBuilder().setToken(token).login().join();
Timer timer = new Timer(); new Thread(() -> {
timer.scheduleAtFixedRate(new update_autismo_ingame_msgs(), 700, 700); Datahandler.instance.update_autismo_socket_msg();
}).start();
api.addMessageCreateListener(event -> { api.addMessageCreateListener(event -> {
if (!FunctionLayer.DoStuff.isOccupied()) { if (!FunctionLayer.DoStuff.isOccupied()) {
FunctionLayer.DoStuff.doStuff(event, api); FunctionLayer.DoStuff.doStuff(event, api);
} }
}); });
} }
} }

View File

@ -6,10 +6,8 @@ from threading import Timer
import string import string
import random import random
import time import time
import mysql.connector import socket
from mysql.connector import Error import codecs
from contextlib import closing
from settings import mysql_connection_ip, mysql_connection_user, mysql_connection_pw, mysql_connection_database
looptestPath = '/home/gameservers/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/looptest.cfg' looptestPath = '/home/gameservers/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/looptest.cfg'
chatmsg = "" chatmsg = ""
@ -34,224 +32,122 @@ def joinTeam():
time.sleep(4.5) time.sleep(4.5)
print('jointeam func: ') print('jointeam func: ')
def checkbotteam():
with closing(mysql.connector.connect(host=mysql_connection_ip, database=mysql_connection_database, user=mysql_connection_user, password=mysql_connection_pw, def bot_process_movement(input_lines):
auth_plugin='mysql_native_password')) as cnx: movement_list = [1, 0]
with closing(cnx.cursor()) as cur: strInput = "-attack; wait 5; -jump; wait 5; -duck; wait 5; +attack; wait 5; cl_minmodels 1; "
mysql_check_spectator(cur) for input_line in input_lines.splitlines():
resetCfgInputShortWait() movement_input = input_line[input_line.index("keyinput:") + len("keyinput:"):input_line.index("clientangles:")]
connectionTimer = Timer(20.0, checkbotteam) client_angles = input_line[input_line.index("clientangles:") + len("clientangles:"):input_line.index("xyz:")]
connectionTimer.daemon = True xyz = input_line[input_line.index("xyz:") + len("xyz:"):input_line.index("hunt_or_mimic:")]
connectionTimer.start() hunt_or_mimic = input_line[input_line.index("hunt_or_mimic:") + len("hunt_or_mimic:"):input_line.index("stuckX:")]
stuckx = input_line[input_line.index("stuckX:") + len("stuckX:"):input_line.index("stuckY:")]
stucky = input_line[input_line.index("stuckY:") + len("stuckY:"):]
if not hunt_or_mimic:
axis_distance = 50
if stuckX:
print('stuckX enabled')
if movement_list[0] == 0:
movement_list[0] = 1
elif movement_list[0] == 1:
movement_list[0] = 0
strInput += " +jump; wait 3; +duck; wait 5;"
if stuckY:
print('stuckY enabled')
if movement_list[1] == 0:
movement_list[1] = 1
elif movement_list[1] == 1:
movement_list[1] = 0
strInput += " +jump; wait 3; +duck; wait 5;"
print('hunt mode enabled')
if not stuckX and not stuckY:
if xyz_difference[0] > axis_distance:
movement_list[0] = 1
elif xyz_difference[0] < -axis_distance:
movement_list[0] = 0
if xyz_difference[1] < -axis_distance:
movement_list[1] = 1
elif xyz_difference[1] > axis_distance:
movement_list[1] = 0
def mysql_check_spectator(cur): if movement_list[0] == 1:
sql_statement = f"""SELECT spectate from unloze_css_autism_bot.`bot status`""" strInput += " -back; wait 5; +forward; wait 5;"
cur.execute(sql_statement) elif movement_list[0] == 0:
result = cur.fetchall()[0] strInput += " -forward; wait 5; +back; wait 5;"
spectate = result[0] if movement_list[1] == 1:
print('spectate: ', spectate) strInput += " -moveleft; wait 5; +moveright; wait 5;"
if spectate != 0: elif movement_list[1] == 0:
joinTeam() strInput += " -moveright; wait 5; +moveleft; wait 5;"
print('xyz_difference[0]: ', xyz_difference[0])
print('xyz_difference[1]: ', xyz_difference[1])
print('movement_list[0]: ', movement_list[0], '0 = back. 1 = forward.')
print('movement_list[1]: ', movement_list[1], '0 = moveleft. 1 = moveright')
strInput += f""" setang 0 180 0; wait 5; """
else:
strInput += f"""setang {client_angles[0]} {client_angles[1]} {client_angles[2]}; wait 5; {movement_input}; wait 5; """
#print('strInput final:', strInput)
def organize_player_info(movement_list):
strInput = "-attack; wait 5; -jump; wait 5; -duck; wait 5; +attack; wait 5; cl_minmodels 1; "
writeCfgInput(strInput) writeCfgInput(strInput)
time.sleep(0.4)
writeCfgInput("wait 5;")
def bot_connect_ze():
#use whatever ip you want here to connect with
strdev = "connect 151.80.230.149:27019/test132;"
str1 = "connect 151.80.230.149:27015;"
writeCfgInput(strdev)
time.sleep(0.2) time.sleep(0.2)
writeCfgInput("wait 5;") writeCfgInput("wait 5;")
mysql_get_player_info(movement_list) time.sleep(15.50)
mysql_delete_rows() print('not yet connected')
post_chatmsg()
run_delay = 0.2 #0.05
connectionTimer = Timer(run_delay, organize_player_info, args=[movement_list])
connectionTimer.daemon = True
connectionTimer.start()
def post_chatmsg():
global chatmsg
strInput = f"""{chatmsg}"""
chatmsg = ""
writeCfgInput(strInput)
time.sleep(0.5)
writeCfgInput("wait 5;")
def mysql_delete_rows():
with closing(mysql.connector.connect(host=mysql_connection_ip, database=mysql_connection_database, user=mysql_connection_user, password=mysql_connection_pw,
auth_plugin='mysql_native_password')) as cnx:
with closing(cnx.cursor()) as cur:
sql_statement = f"""SELECT hunt_or_mimic from unloze_css_autism_bot.`bot movement input` ORDER BY entry_time desc LIMIT 1"""
results = cur.execute(sql_statement, multi=True)
if results:
for result in results:
if result.with_rows:
resultfetch = result.fetchone()
break
if resultfetch:
hunt_or_mimic = resultfetch[0]
print('hunt_or_mimic delete: ', hunt_or_mimic)
if hunt_or_mimic:
sql_statement = f"""DELETE FROM unloze_css_autism_bot.`bot movement input` ORDER BY entry_time asc LIMIT 10"""
cur.execute(sql_statement)
print('Deleted ', cur.rowcount, ' rows')
cnx.commit()
def mysql_get_player_info(movement_list):
with closing(mysql.connector.connect(host=mysql_connection_ip, database=mysql_connection_database, user=mysql_connection_user, password=mysql_connection_pw,
auth_plugin='mysql_native_password')) as cnx:
with closing(cnx.cursor()) as cur:
sql_statement = f"""SELECT StuckX, StuckY, xyz_0, xyz_1, xyz_2, hunt_or_mimic from unloze_css_autism_bot.`bot movement input` bmi ORDER BY entry_time desc LIMIT 1"""
cur.execute(sql_statement)
huntfetch = cur.fetchone()
if huntfetch:
hunt_or_mimic = huntfetch[5]
if not hunt_or_mimic:
stuckX = huntfetch[0]
stuckY = huntfetch[1]
xyz_difference = [huntfetch[2], huntfetch[3], huntfetch[4]]
strInput = ""
axis_distance = 50
if stuckX:
print('stuckX enabled')
if movement_list[0] == 0:
movement_list[0] = 1
elif movement_list[0] == 1:
movement_list[0] = 0
strInput += " +jump; wait 3; +duck; wait 5;"
if stuckY:
print('stuckY enabled')
if movement_list[1] == 0:
movement_list[1] = 1
elif movement_list[1] == 1:
movement_list[1] = 0
strInput += " +jump; wait 3; +duck; wait 5;"
print('hunt mode enabled')
if not stuckX and not stuckY:
if xyz_difference[0] > axis_distance:
movement_list[0] = 1
elif xyz_difference[0] < -axis_distance:
movement_list[0] = 0
if xyz_difference[1] < -axis_distance:
movement_list[1] = 1
elif xyz_difference[1] > axis_distance:
movement_list[1] = 0
if movement_list[0] == 1:
strInput += " -back; wait 5; +forward; wait 5;"
elif movement_list[0] == 0:
strInput += " -forward; wait 5; +back; wait 5;"
if movement_list[1] == 1:
strInput += " -moveleft; wait 5; +moveright; wait 5;"
elif movement_list[1] == 0:
strInput += " -moveright; wait 5; +moveleft; wait 5;"
print('xyz_difference[0]: ', xyz_difference[0])
print('xyz_difference[1]: ', xyz_difference[1])
print('movement_list[0]: ', movement_list[0], '0 = back. 1 = forward.')
print('movement_list[1]: ', movement_list[1], '0 = moveleft. 1 = moveright')
strInput += f""" setang 0 180 0; wait 5; """
writeCfgInput(strInput)
time.sleep(0.4)
writeCfgInput("wait 5;")
else:
sql_statement = f"""SELECT * from unloze_css_autism_bot.`bot movement input` ORDER BY entry_time asc LIMIT 10"""
cur.execute(sql_statement)
resultfetch = cur.fetchall()
#print('resultfetch: ', resultfetch)
for result in resultfetch:
#print('result: ', result)
movement_input = result[0]
client_angles = [result[1], result[2], result[3]]
strInput = ""
#print('client_angles: ', client_angles)
print('movement_input: ', movement_input)
strInput += f"""setang {client_angles[0]} {client_angles[1]} {client_angles[2]}; wait 5; {movement_input}; wait 5; """
#print('strInput final:', strInput)
writeCfgInput(strInput)
time.sleep(0.04)
writeCfgInput("wait 5;")
def mysql_check_messages():
with closing(mysql.connector.connect(host=mysql_connection_ip, database=mysql_connection_database, user=mysql_connection_user, password=mysql_connection_pw,
auth_plugin='mysql_native_password')) as cnx:
with closing(cnx.cursor()) as cur:
sql_statement = """SELECT responsemessage FROM unloze_css_autism_bot.chatting WHERE responsemessage != '' LIMIT 1"""
cur.execute(sql_statement)
result = cur.fetchall()
if result:
result = result[0][0]
str = f"""say {result}"""
print('str: ', str)
global chatmsg
chatmsg = str
sql_statement = f"""DELETE FROM unloze_css_autism_bot.`chatting` WHERE `responsemessage` = '{result}'"""
#print('sql_statement: ', sql_statement)
cur.execute(sql_statement)
cnx.commit()
connectionTimer = Timer(0.9, mysql_check_messages)
connectionTimer.daemon = True
connectionTimer.start()
def mysql_check_if_connected():
with closing(mysql.connector.connect(host=mysql_connection_ip, database=mysql_connection_database, user=mysql_connection_user, password=mysql_connection_pw,
auth_plugin='mysql_native_password')) as cnx:
with closing(cnx.cursor()) as cur:
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.2)
writeCfgInput("wait 5;")
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()
def deadlock():
try:
while True: 42 == 42
except KeyboardInterrupt:
pass
def mysql_reset_input():
with closing(mysql.connector.connect(host=mysql_connection_ip, database=mysql_connection_database, user=mysql_connection_user, password=mysql_connection_pw,
auth_plugin='mysql_native_password')) as cnx:
with closing(cnx.cursor()) as cur:
sql_statement = f"""DELETE FROM unloze_css_autism_bot.`bot movement input`"""
cur.execute(sql_statement)
cnx.commit()
if __name__ == '__main__': if __name__ == '__main__':
atexit.register(exit_handler) atexit.register(exit_handler)
resetCfgInputShortWait() resetCfgInputShortWait()
mysql_check_if_connected() local_ip = "127.0.0.1"
checkbotteam() local_port = 48477
print('reached mysql _get_player_info') udp_external_ip = "62.210.110.245"
mysql_reset_input() buffer_size = 4096 #potentially not large enough?
organize_player_info([False, True]) with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
mysql_check_messages() with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock_external:
print('reached deadlock') sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
deadlock() sock.bind(("", local_port))
print('reached deadlock')
try:
while True:
data, addr = sock.recvfrom(buffer_size)
databyte = data
data = codecs.decode(data, "utf-8", "ignore")
ip = addr[0]
port = addr[1]
print('port: ', port, " ip: ", ip)
if not data:
continue
if ip not in [local_ip, udp_external_ip]:
continue
if ip == udp_external_ip:
print("enabled remote UDP packet")
response_msg = f"""say {data}"""
writeCfgInput(response_msg)
time.sleep(0.5)
resetCfgInputShortWait()
time.sleep(0.2)
print('data: ', data)
if data == "autismo connected":
print('Bot connected!')
time.sleep(2)
joinTeam()
elif data == "connect to ze":
bot_connect_ze()
elif "clientmessage:" in data:
sock_external.sendto(databyte, (udp_external_ip, local_port))
print('sent databyte: ', databyte)
elif data.startswith("keyinput:"):
bot_process_movement(data)
except KeyboardInterrupt:
pass
#/home/gameservers/.steam/debian-installation/steamapps/common/Counter-Strike Source/cstrike/cfg/autoexec.cfg: #/home/gameservers/.steam/debian-installation/steamapps/common/Counter-Strike Source/cstrike/cfg/autoexec.cfg:
#/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/autoexec.cfg: #/home/nonroot/.steam/steam/steamapps/common/Counter-Strike Source/cstrike/cfg/autoexec.cfg:

View File

@ -49,7 +49,7 @@ public void OnPluginStart()
//socket otherwise declare in public OnConfigsExecuted(){} //socket otherwise declare in public OnConfigsExecuted(){}
Handle socket = SocketCreate(SOCKET_UDP, OnSocketError); Handle socket = SocketCreate(SOCKET_UDP, OnSocketError);
SocketSetOption(socket, SocketReuseAddr, 1); SocketSetOption(socket, SocketReuseAddr, 1);
SocketBind(socket, "127.0.0.1", 48476); SocketBind(socket, "127.0.0.1", 48475);
connect(socket); connect(socket);
global_socket = socket; global_socket = socket;
} }
@ -275,7 +275,7 @@ public OnSocketError(Handle socket, const int errorType, const int errorNum, any
stock void connect(Handle socket) stock void connect(Handle socket)
{ {
if (!SocketIsConnected(socket)) if (!SocketIsConnected(socket))
SocketConnect(socket, OnSocketConnected, OnSocketReceive, OnSocketDisconnected, "127.0.0.1", 48476); SocketConnect(socket, OnSocketConnected, OnSocketReceive, OnSocketDisconnected, "127.0.0.1", 48475);
} }
public void OnClientDisconnect(int client) public void OnClientDisconnect(int client)