Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build go-cqhttp Robot by SpringBoot

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to build a go-cqhttp robot in SpringBoot". In daily operation, I believe many people have doubts about how to build a go-cqhttp robot in SpringBoot. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to build a go-cqhttp robot in SpringBoot"! Next, please follow the editor to study!

First, build a go-cqhttp robot

test

Send a private chat message to your friend (user_id: friend's QQ number)

# cmdcrul '127.0.0.1 postManGET Vlux 5700 Compact Sendcoat privateExpenditure msgmessages = Hello ~ # postManGET message = Hello

Response:

Second, build the SpringBoot environment

Basic environment

Org.springframework.boot spring-boot-starter-web org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test com.alibaba fastjson 1.2.46 commons-httpclient commons-httpclient 3.1 org.apache. Httpcomponents httpclient 4.4.1 org.java-websocket Java-WebSocket 1.3.5 1 、 HTTP communication

Modify go-cqhhtp configuration file config.yml

Post: # http://{host}:{ip}-url: 'http://127.0.0.1:8400' secret:' must be filled in here.

Java code

Test case: https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E7%A7%81%E8%81%8A%E6%B6%88%E6%81%AF sends a private chat message

QqRobotController.java

@ RestController@Slf4jpublic class QqRobotController {@ Resource private QqRobotService robotService; @ PostMapping public void QqRobotEven (HttpServletRequest request) {robotService.QqRobotEvenHandle (request);}}

QqRobotService.java

Public interface QqRobotService {void QqRobotEvenHandle (HttpServletRequest request);}

QqRobotServiceImpl.java

@ Service@Slf4jpublic class QqRobotServiceImpl implements QqRobotService {@ Override public void QqRobotEvenHandle (HttpServletRequest request) {/ / JSONObject JSONObject jsonParam = this.getJSONParam (request); log.info ("receive parameter is: {}", jsonParam.toString ()! = null? "SUCCESS": "FALSE"); if ("message" .equals (jsonParam.getString ("post_type")) {String message = jsonParam.getString ("message") If ("Hello" .equals (message)) {/ / user_id is QQ friend QQ number String url = "http://127.0.0.1:5700/send_private_msg?user_id=xxxxx&message= Hello ~"; String result = HttpRequestUtil.doGet (url); log.info ("sent successfully: = > {}", result) } public JSONObject getJSONParam (HttpServletRequest request) {JSONObject jsonParam = null; try {/ / get input stream BufferedReader streamReader = new BufferedReader (new InputStreamReader (request.getInputStream (), "UTF-8")); / / data is written to Stringbuilder StringBuilder sb = new StringBuilder (); String line = null While ((line = streamReader.readLine ())! = null) {sb.append (line);} jsonParam = JSONObject.parseObject (sb.toString ());} catch (Exception e) {e.printStackTrace ();} return jsonParam;}}

HttpUtils utility class

Public class HttpRequestUtil {/ * @ Description: send get request * / public static String doGet (String url) {CloseableHttpClient httpClient = HttpClients.createDefault (); HttpGet httpGet = new HttpGet (url); httpGet.setHeader ("Content-type", "application/json"); httpGet.setHeader ("DataEncoding", "UTF-8") RequestConfig requestConfig = RequestConfig.custom (). SetConnectTimeout (35000) .setConnectionRequestTimeout (35000) .setSocketTimeout (60000). Build (); httpGet.setConfig (requestConfig); CloseableHttpResponse httpResponse = null; try {httpResponse = httpClient.execute (httpGet); HttpEntity entity = httpResponse.getEntity (); if (httpResponse.getStatusLine (). GetStatusCode ()! = 200) {return null } return EntityUtils.toString (entity);} catch (ClientProtocolException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace () } finally {if (httpResponse! = null) {try {httpResponse.close ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace () }} if (null! = httpClient) {try {httpClient.close ();} catch (IOException e) {e.printStackTrace ();} return null } / * * @ Description: send http post request * / public static String doPost (String url, String jsonStr) {CloseableHttpClient httpClient = HttpClients.createDefault (); HttpPost httpPost = new HttpPost (url); RequestConfig requestConfig = RequestConfig.custom (). SetConnectTimeout (35000) .setConnectionRequestTimeout (35000) .setSocketTimeout (60000). Build (); httpPost.setConfig (requestConfig) HttpPost.setHeader ("Content-type", "application/json"); httpPost.setHeader ("DataEncoding", "UTF-8"); CloseableHttpResponse httpResponse = null; try {httpPost.setEntity (new StringEntity (jsonStr)); httpResponse = httpClient.execute (httpPost); if (httpResponse.getStatusLine (). GetStatusCode ()! = 200) {return null } HttpEntity entity = httpResponse.getEntity (); String result = EntityUtils.toString (entity); return result;} catch (ClientProtocolException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace () } finally {if (httpResponse! = null) {try {httpResponse.close ();} catch (IOException e) {e.printStackTrace () } if (null! = httpClient) {try {httpClient.close ();} catch (IOException e) {e.printStackTrace ();} return null;}}

Response:

Sent successfully: = > {"data": {"message_id": 2113266863}, "retcode": 0, "status": "ok"}

2. WebScoket communication

Generally speaking, the client of WebScoket is H5, but Java is used as the client in order to test this blog.

Modify go-cqhhtp configuration file config.yml

-ws: # forward WS server listening address host: 127.0.0.1 # forward WS server listening port port: 5701

Java code

Need to import pom package

WebsocketClient.java

@ Slf4j@Componentpublic class WebSocketConfig {@ Bean public WebSocketClient webSocketClient () {try {WebSocketClient webSocketClient = new WebSocketClient (new URI ("ws://127.0.0.1:5701"), new Draft_6455 ()) {@ Override public void onOpen (ServerHandshake handshakedata) {log.info ("[websocket] connection successful") } @ Override public void onMessage (String message) {log.info ("[websocket] received message = {}", message) } @ Override public void onClose (int code, String reason, boolean remote) {log.info ("[websocket] exit connection") } @ Override public void onError (Exception ex) {log.info ("[websocket] connection error = {}", ex.getMessage ());}}; webSocketClient.connect (); return webSocketClient } catch (Exception e) {e.printStackTrace ();} return null;}}

test

[websocket] received message = {"interval": 5000, "meta_event_type": "heartbeat", "post_type": "meta_event", "self_id": 2878522414, "status": {"app_enabled": true, "app_good": true, "app_initialized": true, "good": true, "online": true, "plugins_good": null, "stat": {"packet_received": 29, "packet_sent": 21, "packet_lost": 0 "message_received": 0, "message_sent": 0, "disconnect_times": 0, "lost_times": 0, "last_message_time": 0}}, "time": 1639797397}

At this point, the study on "how to build a go-cqhttp robot by SpringBoot" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report