1、前言
正常人每天平均耗水量為2000-2500毫升,體內物質訊訓可生水300毫升,故每日應補充水分2200毫升,包括飲食中的含水量,夏天每日補充水分在3000毫升左右,才能滿足人體需要,
如果有個機器人能按時提醒我們喝水,那該多好啊~~
2、創建一個springboot專案
(這個步驟是為小白提供,大佬們直接跳到第三步)
2.1. 新建專案

2.2. 選擇springboot專案



2.3. 創建完成的專案結構如下

3、引入simple-robot機器人依賴
3.1. 在pom.xml檔案引入simple-robot依賴
<!--java機器人框架-->
<dependency>
<groupId>love.forte.simple-robot</groupId>
<artifactId>component-mirai-spring-boot-starter</artifactId>
<version>2.0.3</version>
</dependency>

3.2. 配置application.yml檔案
simbot:
core:
# 機器人的QQ賬號與密碼(帳號:密碼)
bots: 6013505:yinfeng
component:
mirai:
# mirai心跳周期. 過長會導致被服務器斷開連接. 單位毫秒,
heartbeat-period-millis: 30000
# 每次心跳時等待結果的時間.一旦心跳超時, 整個網路服務將會重啟 (將消耗約 1s). 除正在進行的任務 (如圖片上傳) 會被中斷外, 事件和插件均不受影響.
heartbeat-timeout-millis: 5000
# 心跳失敗后的第一次重連前的等待時間.
first-reconnect-delay-millis: 5000
# 重連失敗后, 繼續嘗試的每次等待時間
reconnect-period-millis: 5000
# 最多嘗試多少次重連
reconnection-retry-times: 2147483647
# 使用協議型別,注,此值為列舉類 net.mamoe.mirai.utils.BotConfiguration.MiraiProtocol 的元素值,
# 可選值為:ANDROID_PHONE、ANDROID_PAD、ANDROID_WATCH
protocol: ANDROID_PHONE
# 是否關閉mirai的bot logger
no-bot-log: true
# 關閉mirai網路日志
no-network-log: true
# mirai bot log切換使用simbot的log
use-simbot-bot-log: true
# mirai 網路log 切換使用simbot的log
use-simbot-network-log: true
# mirai配置自定義deviceInfoSeed的時候使用的隨機種子,默認為1.
device-info-seed: 1
# mirai圖片快取策略,為列舉 love.forte.simbot.component.mirai.configuration.MiraiCacheType 的元素值,
# 可選為 FILE、 MEMORY
cache-type: MEMORY
# 如果配置項 simbot.mirai.cacheType 的值為 FILE,此處為快取檔案的保存目錄,為空時默認為系統臨時檔案夾,
cache-directory:
# 登錄驗證碼處理器,當登錄需要輸入驗證碼的時候可能會用到,
login-solver-type: DEFAULT
# 如果不為空,此處代表指定一個 deviceInfo 的 json檔案路徑,
dispatcher:
# mirai組件中,對事件進行調度的執行緒池引數:最大執行緒數,
core-pool-size: 8
# mirai組件中,對事件進行調度的執行緒池引數:最大執行緒數,
maximum-pool-size: 8
# mirai組件中,對事件進行調度的執行緒池引數:執行緒存活時間(毫秒)
keep-alive-time: 1000

3.3 在springboot啟動類加上@EnableSimbot注解
/**
* @author yinfeng
* @description 啟動類
* @since 2021/12/22 22:50
*/
@EnableSimbot
@EnableScheduling
@SpringBootApplication
@Slf4j
public class RobotApplication {
public static void main(String[] args) {
SpringApplication.run(RobotApplication.class, args);
log.info("機器人啟動成功~~~~");
}
}
3.4 simple-robot機器人官方檔案
https://www.yuque.com/simpler-robot/simpler-robot-doc/gbqsz5
4、撰寫定時任務
4.1. 創建一個DrinkNotify.java類
/**
* @author yinfeng
* @description 定時喝水提醒
* @since 2021/12/22 23:32
*/
@Component
@Slf4j
public class DrinkNotify {
@Resource
private BotManager botManager;
@Value("${bello.qq}")
private Set<String> qqSet;
/**
* 喝水語錄
*/
static List<String> content;
/**
* 喝水圖片
*/
static List<String> images;
static {
content = new ArrayList<>();
images = new ArrayList<>();
log.info("開始加載喝水語錄~~~");
// 喝水語錄
content.add("俗話說\"女人是水造的\",所以身為女生就要時刻喝水,這樣就可以保持充足的水分,皮膚、頭發就會更有光澤~");
content.add("喝多點水還可以保持身材哦,因為水促進了我們身體的回圈~");
content.add("該喝水了喲,喝多點水整體上也會容光煥發~");
content.add("該喝水了喲,要多愛護自己,多喝水、多吃新鮮水果蔬菜、盡量保證充足睡眠,加油!");
content.add("多喝水很簡單的話,多喝水對身體好!只有心中掛念著你們的人才會說你的家人也老說的話:你要多喝水呀!!~");
content.add("天氣寒冷干燥,多喝水,注意保暖,少抽煙喝酒吃辣,多想念我~");
log.info("開始加載喝水圖片~~~");
// 喝水圖片
images.add("https://gitee.com/liujian8/study-image/raw/master/image/20211224221637.jpeg");
images.add("https://gitee.com/liujian8/study-image/raw/master/image/20211224221739.jpeg");
images.add("https://gitee.com/liujian8/study-image/raw/master/image/20211224221758.jpeg");
images.add("https://gitee.com/liujian8/study-image/raw/master/image/20211224221815.jpeg");
images.add("https://gitee.com/liujian8/study-image/raw/master/image/20211224221834.jpeg");
images.add("https://gitee.com/liujian8/study-image/raw/master/image/20211224221913.jpeg");
images.add("https://gitee.com/liujian8/study-image/raw/master/image/20211224221925.jpeg");
}
/**
* 每一分鐘提醒一次: 0 0/1 * * * ?
* 每一小時提醒一次: 0 0 0/1 * * ?
*/
@Scheduled(cron = "0 0/1 * * * ?")
public void handler() {
Calendar calendar = Calendar.getInstance();
// 獲取當前小時
int hour = calendar.get(Calendar.HOUR_OF_DAY);
// 只在早上9點到晚上8點發送訊息提醒
if (hour < 9 || hour > 20) {
return;
}
qqSet.forEach(qq -> {
try {
final String msg = content.get(new Random().nextInt(content.size()));
final String img = String.format("[CAT:image,url=%s,flash=false]", images.get(new Random().nextInt(content.size())));
// 發送隨機喝水語錄
botManager.getDefaultBot().getSender().SENDER.sendPrivateMsg(qq, msg);
// 發送隨機喝水圖片
botManager.getDefaultBot().getSender().SENDER.sendPrivateMsg(qq, img);
log.info("正在發送喝水提醒,當前qq={}, 語錄={}, img={}", qq, msg, img);
} catch (Exception e) {
log.error("發送喝水提醒例外, qq={}", qq, e);
}
});
}
}
4.2. 在yml檔案中配置女神們的QQ號
#配置女神們的QQ號,多個QQ用逗號分割
bello:
qq: 1332483344,52000012

5、加入智能聊天功能
5.1. 這里主要使用青云客的api進行聊天,官網
http://api.qingyunke.com/
5.2. 封裝http工具類
/**
* @author yinfeng
* @description http工具類
* @since 2021/12/23 23:21
*/
public class HttpUtil {
/**
* 向指定URL發送GET方法的請求
*
* @param url 發送請求的URL
* @param param 請求引數,請求引數應該是 name1=value1&name2=value2 的形式,
* @return URL 所代表遠程資源的回應結果
*/
public static String sendGet(String url, String param) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String urlNameString = url;
if (!StringUtils.isEmpty(param)) {
urlNameString += "?" + param;
}
URL realUrl = new URL(urlNameString);
// 打開和URL之間的連接
URLConnection connection = realUrl.openConnection();
// 設定通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1");
// 建立實際的連接
connection.connect();
// 定義 BufferedReader輸入流來讀取URL的回應
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
System.out.println("發送GET請求出現例外!" + e);
e.printStackTrace();
}
// 使用finally塊來關閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result.toString();
}
}
5.3. 創建訊息監聽類,支持私聊訊息和群訊息的智能聊天
/**
* @author yinfeng
* @description 機器人監聽
* @since 2021/11/6 20:51
*/
@Component
@Slf4j
public class MessageListener {
static final String URL = "http://api.qingyunke.com/api.php";
/**
* 監聽私聊訊息
*/
@OnPrivate
public void privateMsg(PrivateMsg privateMsg, MsgSender sender) {
sendMsg(privateMsg, sender);
}
/**
* 監聽群訊息
*/
@OnGroup
public void groupMsg(GroupMsg groupMsg, MsgSender sender) {
sendMsg(groupMsg, sender);
}
/**
* 通過青云客封裝智能聊天
*
* @param commonMsg commonMsg
* @param sender sender
*/
private void sendMsg(MessageGet commonMsg, MsgSender sender) {
log.info("智能聊天中~~~,接收訊息:qq={}, msg={}", commonMsg.getAccountInfo().getAccountCode(),
commonMsg.getMsgContent().getMsg());
// MsgSender中存在三大送信器,以及非常多的多載方法,
// 通過get請求呼叫聊天介面
final String result = HttpUtil.sendGet(URL,
"key=free&appid=0&msg=".concat(commonMsg.getMsgContent().getMsg()));
if (!StringUtils.isEmpty(result)) {
final JSONObject json = JSONObject.parseObject(result);
if (json.getInteger("result") == 0 && !StringUtils.isEmpty(json.getString("content"))) {
final String msg = json.getString("content").replace("{br}", "\n");
sender.SENDER.sendPrivateMsg(commonMsg, msg);
log.info("智能聊天中~~~,發送訊息:qq={}, msg={}", commonMsg.getAccountInfo().getAccountCode(), msg);
}
}
}
}
6、測驗一下
6.1. 啟動專案

6.2. 喝水提醒測驗

可以看到兩個qq都收到了提醒訊息 ,后臺日志也有了

6.3. 智能聊天測驗

可以看到聊天功能也是正常的 ,后臺日志也有了

7、原始碼地址
// 原始碼地址,下載運行即可
// 也可打成jar包放在服務器一直運行
// 老鐵們可以加6013505進行智能聊天測驗哈
https://gitee.com/liujian8/java-robot
碼字不易,老鐵們三連一波支持下吧,謝謝大家了~~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/393138.html
標籤:java
