您好,登录后才能下订单哦!
这篇文章主要介绍“SpringBoot如何搭建go-cqhttp机器人”,在日常操作中,相信很多人在SpringBoot如何搭建go-cqhttp机器人问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”SpringBoot如何搭建go-cqhttp机器人”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
测试
给自己好友发送一条私聊消息(user_id:好友的QQ号)
# cmd crul '127.0.0.1:5700/send_private_msg?user_id=xxxxxx&message=你好~' #postMan GET http://127.0.0.1:5700/send_private_msg?user_id=xxxxx&message=你好~
响应:
基本环境
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.46</version> </dependency> <!--httpUtils--> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4.1</version> </dependency> <!--websocket作为客户端--> <dependency> <groupId>org.java-websocket</groupId> <artifactId>Java-WebSocket</artifactId> <version>1.3.5</version> </dependency> </dependencies>
修改go-cqhhtp 配置文件 config.yml
post: # 这里一定要填成这样的http://{host}:{ip} - url: 'http://127.0.0.1:8400' secret: ''
Java 代码
测试案例:https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E7%A7%81%E8%81%8A%E6%B6%88%E6%81%AF 发送私聊消息
QqRobotController.java
@RestController @Slf4j public 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 @Slf4j public class QqRobotServiceImpl implements QqRobotService { @Override public void QqRobotEvenHandle(HttpServletRequest request) { //JSONObject JSONObject jsonParam = this.getJSONParam(request); log.info("接收参数为:{}",jsonParam.toString() !=null ? "SUCCESS" : "FALSE"); if("message".equals(jsonParam.getString("post_type"))){ String message = jsonParam.getString("message"); if("你好".equals(message)){ // user_id 为QQ好友QQ号 String url = "http://127.0.0.1:5700/send_private_msg?user_id=xxxxx&message=你好~"; String result = HttpRequestUtil.doGet(url); log.info("发送成功:==>{}",result); } } } public JSONObject getJSONParam(HttpServletRequest request){ JSONObject jsonParam = null; try { // 获取输入流 BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8")); // 数据写入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 工具类
public class HttpRequestUtil { /** * @Description: 发送get请求 */ 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: 发送http post请求 */ 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; } }
响应:
发送成功:==>{"data":{"message_id":2113266863},"retcode":0,"status":"ok"}
一般WebScoket的客户端都是H5, 但是为了测试本篇博客使用Java作为客户端
修改go-cqhhtp 配置文件 config.yml
- ws: # 正向WS服务器监听地址 host: 127.0.0.1 # 正向WS服务器监听端口 port: 5701
Java 代码
需要导入pom包
WebsocketClient.java
@Slf4j @Component public 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] 连接成功"); } @Override public void onMessage(String message) { log.info("[websocket] 收到消息={}",message); } @Override public void onClose(int code, String reason, boolean remote) { log.info("[websocket] 退出连接"); } @Override public void onError(Exception ex) { log.info("[websocket] 连接错误={}",ex.getMessage()); } }; webSocketClient.connect(); return webSocketClient; } catch (Exception e) { e.printStackTrace(); } return null; } }
测试
[websocket] 收到消息={"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}
到此,关于“SpringBoot如何搭建go-cqhttp机器人”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。