本QQ機器人實現的功能
1.調用青云客的API進行自動聊天
2.輸入關鍵詞自動添加為好友
技術棧
非特殊情況保持一致即可!
1.SpringBoot-3.0.5
2.JDK-17
3.go-cqhttp1.0
Github:GitHub - Mrs4s/go-cqhttp: cqhttp的golang實現,輕量、原生跨平臺.
gocq api文檔地址:https://docs.go-cqhttp.org/api/
源碼
https://gitee.com/mumangguo/go-cqhttp
實現步驟:
1. 新建一個springBoot項目,不選任何依賴直接創(chuàng)建即可
?
?2. 引入相關依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.21</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- httpclient用來請求自動回復API -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
3.編寫相關實體類,處理json
Friend類
import lombok.Data;
@Data
public class Friend {
private String user_id;
private String comment;
private String flag;
}
Message類
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import java.io.Serializable;
@Data
public class Message implements Serializable {
@JSONField(name = "post_type")
private String postType;
@JSONField(name = "meta_event_type")
private String metaEventType;
@JSONField(name = "message_type")
private String messageType;
@JSONField(name = "notice_type")
private String noticeType;
// 操作人id 比如群管理員a踢了一個人,那么該值為a的qq號
@JSONField(name = "operator_id")
private String operatorId;
private Long time;
@JSONField(name = "self_id")
private String selfId;
@JSONField(name = "sub_type")
private String subType;
@JSONField(name = "user_id")
private String userId;
@JSONField(name = "sender_id")
private String senderId;
@JSONField(name = "group_id")
private String groupId;
@JSONField(name = "target_id")
private String targetId;
private String message;
@JSONField(name = "raw_message")
private String rawMessage;
private Integer font;
//private Sender sender;
@JSONField(name = "message_id")
private String messageId;
@JSONField(name = "message_seq")
private Integer messageSeq;
private String anonymous;
}
Request類
import lombok.Data;
@Data
public class Request<T> {
private String action;
private T params;
private String echo;
}
4.編寫消息監(jiān)聽類(Websocket實現)
/**
* 消息監(jiān)聽
*/
@ClientEndpoint
public class Client {
private static final Logger logger = LoggerFactory.getLogger(Client.class);
private Session session;
public static Client instance;
public static boolean isOpen = false;
private Client(String url) {
try {
session = ContainerProvider.getWebSocketContainer().connectToServer(this, URI.create(url));
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized static boolean connect(String url) {
instance = new Client(url);
return true;
}
@OnOpen
public void onOpen(Session session) {
isOpen = true;
logger.info("連接成功!");
}
@OnClose
public void onClose(Session session) {
isOpen = false;
logger.info("連接關閉!");
}
@OnError
public void onError(Session session, Throwable throwable) {
logger.info("連接錯誤!");
}
@OnMessage
public void onMessage(String message) {
if (message.contains("\"request_type\":\"friend\"")) {
sendFriend(message);
}
if (message.contains("\"post_type\":\"message\"") && message.contains("\"message_type\":\"private\"")) {
sendMsg(message);
}
}
/**
* 好友請求
*/
private synchronized void sendFriend(String msg) {
Friend parseObject = JSONObject.parseObject(msg, Friend.class);
logger.info("收到好友請求:" + parseObject.getUser_id() + ",驗證消息:" + parseObject.getComment());
Request<Object> paramsRequest = new Request<>();
paramsRequest.setAction("set_friend_add_request");
Map<String, Object> params = new HashMap<>();
params.put("flag", parseObject.getFlag());
if (parseObject.getComment().equals("木芒果")) {
params.put("approve", true);
logger.info("已同意好友請求:" + parseObject.getUser_id());
} else {
params.put("approve", false);
logger.info("已拒絕好友請求:" + parseObject.getUser_id());
}
paramsRequest.setParams(params);
instance.session.getAsyncRemote().sendText(JSONObject.toJSONString(paramsRequest));
}
/**
* 好友消息
*/
public synchronized static void sendMsg(String msg) {
Message parseObject = JSONObject.parseObject(msg, Message.class);
String message = parseObject.getMessage();
//message = message.replaceAll(" ", ",");
logger.info("收到好友" + parseObject.getUserId() + "的消息:" + message);
Request<Object> paramsRequest = new Request<>();
paramsRequest.setAction("send_private_msg");
Map<String, Object> params = new HashMap<>();
params.put("user_id", parseObject.getUserId());
String ai = AiOne(message);
if (ai == null) {
ai = "寶,回復失敗!重新試試把!";
}
params.put("message",ai);
paramsRequest.setParams(params);
msg = JSONObject.toJSONString(paramsRequest);
System.out.println("msg="+msg);
instance.session.getAsyncRemote().sendText(msg);
}
public static String AiOne(String sendMsg) {
try {
HttpGet httpGet = new HttpGet("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + sendMsg);
String user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.42";
httpGet.addHeader("user-agent", user_agent);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpGet);
String body = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
body = body.substring(body.indexOf("content") + 10, body.length() - 2);
logger.info("AiOne={}", body);
return body;
} catch (Exception e) {
logger.error(e.toString());
return null;
}
}
}
5.代碼部分完成,下載go-cqhttp
下載鏈接:Releases · Mrs4s/go-cqhttp · GitHub,根據自身實際情況下載對應的操作系統(tǒng)版本,當然我的源碼中包含了Linux版本和Windows版本
?6.這邊只演示windows操作系統(tǒng)如何啟動,Linux啟動可以看api文檔
官方推薦使用cmd的方式啟動,我們就在文件目錄上輸入cmd啟動即可
?
可以看到他在當前文件夾下生成了一個config.yml文件,我們打開看看,只要修改我箭頭標注位置即可
?修改完后,重新啟動該程序,完成qq的登錄驗證,正常完成驗證的情況下,就會出現登錄成功!
登錄出現45/235錯誤代表著當前QQ號處于騰訊的風控,就需要修改協(xié)議(不用配置密碼,把密碼保持為空即可)采用掃碼的方式進行登錄!
一、修改config.yml,把密碼置為空表示掃碼登錄?
二、修改剛剛生成的device.json
三、把這個protocol修改為2或者0,保存后再繼續(xù)啟動,出現掃碼登錄即可文章來源:http://www.zghlxwxcb.cn/news/detail-620451.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-620451.html
7.編寫啟動類,啟動項目即可,就可以實現自動所有功能了,需要特別注意的是要先啟動go-cqhttp才能啟動項目!
import com.mmg.gocqhttp.websocket.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Timer;
import java.util.TimerTask;
/**
* https://docs.go-cqhttp.org/guide/quick_start.html
*/
@SpringBootApplication
public class GoCqhttpApplication implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(GoCqhttpApplication.class);
public static void main(String[] args) {
SpringApplication.run(GoCqhttpApplication.class, args);
}
@Override
public void run(String... args) {
Client.connect("ws://127.0.0.1:9090");
// 斷線重連
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!Client.isOpen || Client.instance == null) {
Client.connect("ws://127.0.0.1:9090");
logger.error("正在斷線重連!");
}
}
}, 1000, 5000);
}
}
到了這里,關于go-cqhttp+SpringBoot3實現QQ機器人的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!