Skip to content

Commit

Permalink
1. Move the http actions into a new thread to avoid server lagging.
Browse files Browse the repository at this point in the history
  • Loading branch information
hezhenwei committed Aug 10, 2021
1 parent 13e0174 commit 0487041
Show file tree
Hide file tree
Showing 4 changed files with 271 additions and 152 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
apply plugin: "java"

version '0.1.1'
version '0.1.2'

sourceCompatibility = 10

Expand Down
2 changes: 1 addition & 1 deletion plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
"author": "Myke.H",
"main": "MykesTool.MTDChatBotPlugin",
"description": "Mindustry Chat Bot.",
"version": "0.1.1"
"version": "0.1.2"
}
183 changes: 33 additions & 150 deletions src/MykesTool/MTDChatBotPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,115 +32,6 @@

public class MTDChatBotPlugin extends Plugin{


private static String doGet(String httpurl) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;// 返回结果字符串
try {
// 创建远程url连接对象
URL url = new URL(httpurl);
// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
// 发送请求
connection.connect();
// 通过connection连接,获取输入流
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 封装输入流is,并指定字符集
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
// 存放数据
StringBuilder sbf = new StringBuilder();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.info("try continue");
} catch (java.net.SocketTimeoutException e){
e.printStackTrace();
Log.info("try continue");
} catch (IOException e) {
e.printStackTrace();
Log.info("try continue");
} catch (Exception e) {
e.printStackTrace();
Log.info("try continue");
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
Log.info("try continue");
} catch (Exception e) {
e.printStackTrace();
Log.info("try continue");
}
}

if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
Log.info("try continue");
}
}

if( connection!= null) {
connection.disconnect();// 关闭远程连接
}
}

return result;
}

private String AskAndGetReplyContent(String strAsk)
{
String strEncodedAsk = URLEncoder.encode(strAsk, StandardCharsets.UTF_8);
String strURL = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + strEncodedAsk;
String strJsonReply = doGet(strURL);
//Log.info(m_strLogPrefix+strAsk);
//Log.info(m_strLogPrefix+strEncodedAsk);
String strFormattedContent = "";

if( m_nDebug == 1) {
Log.info(strJsonReply);
}
//String json = "{\"2\":\"efg\",\"1\":\"abc\"}";
//JSONObject json_test = JSONObject.fromObject(strReply);
final JSONObject jsonResult = new JSONObject(strJsonReply);

//Log.info(m_strLogPrefix+jsonResult.getInt("result"));
//Log.info(m_strLogPrefix+jsonResult.getString("content"));
if (0 == jsonResult.getInt("result")) {
//Groups.player.find();
String strContent = jsonResult.getString("content");
strFormattedContent = strContent.replace("{br}", "\n");

//Time.run(1, () -> player.sendMessage(strMsgPrefix + strFormattedContent));
//text = text + "\n" + strMsgPrefix + strFormattedContent;
} else {
Log.info(m_strLogPrefix + " error getting message.");
}
return strFormattedContent;
}

private String m_strLogPrefix = "[MykesTool:ChatBot]";
private String m_strBotName = "myke";
private String m_strMsgPrefix = "[red][[[yellow]"+m_strBotName+"的小仆ff[red]]:[white] ";
Expand All @@ -149,7 +40,23 @@ private String AskAndGetReplyContent(String strAsk)
private int m_nDebug = 0;
private int m_nLessPeopleActive = 1;
private long m_nLastChatTime = 0;
private void DelayReply(Player player, String strMsg) {
private MTDChatEngineThread m_threadEngine = new MTDChatEngineThread();

private void GetAndDisplayReply()
{
MTDChatEngineThread.ChatReply chat = m_threadEngine.GetNextReply();
if( chat != null)
{
if( chat.nHideReply == 0) {
Call.sendMessage(m_strMsgPrefix + chat.strReply); // say to all
}
Log.info(m_strMsgPrefix + chat.strReply); // log this so we can trace back

m_nLastChatTime = System.currentTimeMillis();
}
}

private void AskAsync(Player player, String strMsg) {

try {
int nBotNamePos = -1;
Expand All @@ -160,36 +67,22 @@ private void DelayReply(Player player, String strMsg) {
//Log.info(nBotNamePos);
if (nBotNamePos == 0) {
String strAsk = strMsg.substring(strCallName.length());
String strFormattedReply = AskAndGetReplyContent(strAsk);
Call.sendMessage(m_strMsgPrefix + strFormattedReply); // say to all
Log.info(m_strMsgPrefix + strFormattedReply); // log this so we can trace back

m_nLastChatTime = System.currentTimeMillis();
m_threadEngine.AskAsync(player, strAsk, 0);
} // if has "@myke" prefix
else if (Groups.player.size() <= m_nLessPeopleActive) {
String strAsk = strMsg;
String strFormattedReply = AskAndGetReplyContent(strAsk);
Call.sendMessage(m_strMsgPrefix + strFormattedReply); // say to all
Log.info(m_strMsgPrefix + strFormattedReply); // log this so we can trace back
m_nLastChatTime = System.currentTimeMillis();
m_threadEngine.AskAsync(player, strAsk, 0);

} else if (0 == strMsg.indexOf("无聊") || 0 == strMsg.indexOf("有点无聊") || 0 == strMsg.indexOf("好无聊")) {

String strAsk = strMsg;
String strFormattedReply = AskAndGetReplyContent(strAsk);
Call.sendMessage(m_strMsgPrefix + strFormattedReply); // say to all
Log.info(m_strMsgPrefix + strFormattedReply); // log this so we can trace back
m_nLastChatTime = System.currentTimeMillis();
m_threadEngine.AskAsync(player, strAsk, 0);
} else {
// otherwise, only see what he will reply, but not show them.
String strAsk = strMsg;
String strFormattedReply = AskAndGetReplyContent(strAsk);
//Call.sendMessage(m_strMsgPrefix + strFormattedReply); // say to all
Log.info(m_strMsgPrefix + strFormattedReply); // log this so we can trace back

//m_nLastChatTime = System.currentTimeMillis( );

m_threadEngine.AskAsync(player, strAsk, 1);
}
Time.runTask(5*60f, () -> GetAndDisplayReply());
}catch ( Exception e)
{
e.printStackTrace();
Expand All @@ -204,18 +97,19 @@ private void StartChat(Player player)
int nStartMsg = Mathf.random(m_ArrayPossibleStart.length -1);
String strStartMsg = m_ArrayPossibleStart[nStartMsg];
Call.sendMessage(m_strMsgPrefix + "一个人的话,可以和机器人对话:"+strStartMsg); // say to all
DelayReply(player, strStartMsg);
AskAsync(player, strStartMsg);
}

//called when game initializes
@Override
public void init() {


//add a chat filter that changes the contents of all messages
//in this case, all instances of "heck" are censored
Vars.netServer.admins.addChatFilter((player, text) -> {

// if has some reply messages, show them.
GetAndDisplayReply();
/*
if(m_playerNew == null || m_nc == null) {
m_playerNew = Player.create();
Expand All @@ -233,7 +127,7 @@ public void init() {
player.sendMessage("test", m_playerNew);
*/

Time.run(0, () -> DelayReply(player,text));
AskAsync(player,text);

//player.sendMessage("try to do something for v008");
return text;
Expand All @@ -249,7 +143,7 @@ public void init() {
{
// not * 60 is 1 sec
// if has very few people, say hi hiddenly
Time.run(Mathf.random(10) * 60f, () -> DelayReply(event.player, "hi"));
AskAsync(event.player, "hi");
}

});
Expand All @@ -265,28 +159,17 @@ public void init() {
// not * 60 is 1 sec
int nPlayer = Mathf.random(Groups.player.size()-1);
Player player = Groups.player.index(nPlayer);
Time.run(Mathf.random(10) * 60f, () -> StartChat(player));
StartChat(player);
}
});

/*
Vars.netServer.admins.addActionFilter(action -> {
// when user do any action
long nNow = System.currentTimeMillis( );
long nDiff = nNow - m_nLastChatTime;
//Log.info("ndeiff." + nDiff);
if( nDiff > (120+Mathf.random(480)) * 1000)
{
if( Groups.player.size() <= m_nLessPeopleActive && Groups.player.size() > 0) {
m_nLastChatTime = System.currentTimeMillis( );

Time.run(Mathf.random(10) * 60f, () -> StartChat(action.player));
}
}
Vars.netServer.admins.addActionFilter(action -> {
// get and show it anytime.
// seems it make the server slow.
// GetAndDisplayReply();
return true;
});
*/

}

Expand Down Expand Up @@ -337,4 +220,4 @@ public void registerServerCommands(CommandHandler handler){
});
}

}
}
Loading

0 comments on commit 0487041

Please sign in to comment.