Compare commits

...
22 Commits
Author SHA1 Message Date
wonder 92f9b50688 ✨Feat: 增加编码时长统计 2025-11-01 23:04:41 +08:00
wonder 2c80f1eec8 🐛Fix: SpringBoot 项目打包 2025-11-01 12:05:35 +08:00
wonder d1d411d53d 🐛Fix: SpringBoot 项目打包 2025-10-31 11:32:16 +08:00
wonder a10efc6381 🐛Fix: SpringBoot 项目打包 2025-10-31 11:23:39 +08:00
wonder 3f262aa836 🐛Fix: 找不到主类 2025-10-31 11:20:42 +08:00
wonder bc204b8575 🔧Chore: 修改pom中的build 2025-10-31 11:16:07 +08:00
wonder 5b40b591e3 🐛Fix: 修改已改为private的方法 2025-10-31 11:04:59 +08:00
wonder 430bca93b7 🔄Update: 创建部署脚本 2025-10-31 10:57:30 +08:00
wonder 5ae1c4d6b2 ✨Feat: 实现MovieDay卡片回传 2025-10-31 10:20:59 +08:00
wonder 1a7760130f 🔄Update: 实现观影记录的增加 2025-10-31 10:02:55 +08:00
wonder e5c8688659 🔄Update: 卡片回调逻辑框架 2025-10-30 22:05:58 +08:00
wonder 326d138e2c ✨Feat: 实现卡片推送的历史放映部分 2025-10-30 21:24:06 +08:00
wonder de5b7d679a 🔄Update: 获取数据库中的 Movie 2025-10-30 21:04:57 +08:00
wonder f964515038 ✨Feat: 实现消息卡片推送 2025-10-29 16:38:56 +08:00
wonder e7ce159ec4 ✅Test: 在 Lark 中使用天气服务 2025-10-29 16:24:06 +08:00
wonder 060466b7b7 ♻️Refactor: 简化微服务 2025-10-29 16:08:19 +08:00
wonder c0b89fcd95 ♻️Refactor: 微服务重构 2025-10-28 23:09:46 +08:00
wonder 44607b5e1b 🔧Chore: 暂存 2025-10-28 12:21:10 +08:00
wonder ef4a5e18c9 🔄Update: 天气板块 2025-10-28 10:31:12 +08:00
wonder 6c53f352df ✨Feat: 实现事件订阅 2025-10-27 16:33:47 +08:00
wonder 5426df2292 ✨Feat: 实现简单消息发送 2025-10-27 16:11:07 +08:00
wonder 8b2d3a409c 🔧Chore: 项目初始化 2025-10-27 15:02:08 +08:00
53 changed files with 1618 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
.idea
*/target
+38
View File
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.hezhaohui</groupId>
<artifactId>lark-panel</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>common</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,12 @@
package cn.hezhaohui.common;
public class AIConstant {
public static final String SYSTEM_PROMPT = "请根据输入的 [BackGround] 和 [Content] 生成内容";
public static final String BACKGROUND_WEATHER = "【要求】请根据传入的今日数据,采用符合的语气,emjoy和符号,带一点想象,用简洁的语句,描述一下想象中的风景,体感,并附带一点小Tips。\n" +
"【输出格式】今天的星露谷....(控制在30字)\\nTips。\n" +
"【输出示例】\n" +
"今天的星露谷天气阴沉,气温舒适,北风轻轻吹拂,风力微弱,湿度较高,仿佛连空气都带着一丝凉意。这种天气最适合在家中泡一杯热茶,或者在庭院里摆上几张藤椅,享受难得的宁静。\n" +
"Tips:可以尝试在这样的天气里种植一些耐阴植物,比如蕨类或苔藓,为你的农场增添一抹绿意哦!\uD83D\uDE09\uD83C\uDF31";
}
@@ -0,0 +1,8 @@
package cn.hezhaohui.common;
public class AppConstant {
public final static String APP_ID = "cli_a875a60984b5500c";
public final static String APP_SECRET = "toAfmMddNEG9qWsYngs7wch0HwW4vAls";
public final static String APP_USER_OPEN_ID = "ou_9eb248881be923bad599f342c22a4e7a";
}
@@ -0,0 +1,23 @@
package cn.hezhaohui.common;
public enum CardEnum {
CARD_WEATHER("AAqxas5etOJDx", "1.0.5"),
CARD_MOVIE("AAqhYDej6RK7O", "1.0.1"),
CARD_WAKATIME("AAqhg9UY0e2Ir", "1.0.1");
private final String id;
private final String versionName;
CardEnum(String id, String versionName) {
this.id = id;
this.versionName = versionName;
}
public String getId() {
return id;
}
public String getVersionName() {
return versionName;
}
}
@@ -0,0 +1,8 @@
package cn.hezhaohui.common;
public class WakaTimeConstant {
public static final String WAKATIME_API_URL_PREFIX = "https://api.wakatime.com/api/v1/";
public static final String WAKATIME_API_URL_LAST_7_DAYS = WAKATIME_API_URL_PREFIX + "users/current/summaries?range=last_7_days";
public static final String WAKATIME_API_SECRET_KEY_BASE64 = "d2FrYV80MzYyZjQzMC1kY2Y4LTQ2YzktYjdkYy0yMjMwMjUxOTkwNWQ=";
}
@@ -0,0 +1,8 @@
package cn.hezhaohui.common;
public class WeatherConstant {
public static final String API_BASE_URL = "https://restapi.amap.com/v3/weather/weatherInfo";
public static final String API_SECRET = "d0f5599ac19a5e4553ba68cd1781d2df";
public static final String CITY_CODE_WUHAN = "420100";
}
@@ -0,0 +1,16 @@
package cn.hezhaohui.pojo.dto;
import lombok.Data;
import java.util.Date;
@Data
public class MovieDTO {
private Integer id;
private String name;
private Date day;
}
@@ -0,0 +1,16 @@
package cn.hezhaohui.pojo.entity;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class Weather {
private String weather;
private String temperature;
private String windPower;
private String windDirection;
private String reportTime;
private String humidity;
private String content;
}
@@ -0,0 +1,11 @@
package cn.hezhaohui.pojo.vo;
import lombok.Data;
@Data
public class MovieVO {
private String name;
private String date;
}
+100
View File
@@ -0,0 +1,100 @@
#!/bin/bash
# 部署脚本:从远程仓库下载代码,打包并启动lark-panel的各个模块
# 使用pm2进行进程管理,确保重启后服务自动启动
# 设置变量
REPO_URL="http://47.121.181.112:3000/wonder/lark-panel.git"
WORK_DIR="/tmp/lark-panel-deploy"
DEPLOY_DIR="/opt/lark-panel"
LOG_DIR="/var/log/lark-panel"
# 创建必要的目录
mkdir -p $DEPLOY_DIR
mkdir -p $LOG_DIR
# 清理旧的工作目录
if [ -d "$WORK_DIR" ]; then
rm -rf $WORK_DIR
fi
# 克隆代码仓库
echo "正在从远程仓库下载代码..."
git clone $REPO_URL $WORK_DIR
if [ $? -ne 0 ]; then
echo "错误:无法克隆代码仓库"
exit 1
fi
# 进入工作目录
cd "$WORK_DIR" || { echo "无法进入工作目录"; exit 1; }
# 打包各个模块
echo "正在打包各个模块..."
# 清理整个项目
echo "清理项目..."
mvn clean
# 打包common模块(依赖)
echo "打包common模块..."
mvn install -pl common -am -DskipTests
# 打包movie模块
echo "打包movie模块..."
mvn package -pl movie -am -DskipTests
# 打包weather模块
echo "打包weather模块..."
mvn package -pl weather -am -DskipTests
# 打包lark模块
echo "打包lark模块..."
mvn package -pl lark -am -DskipTests
if [ $? -ne 0 ]; then
echo "错误:打包失败"
exit 1
fi
# 清理旧部署文件
echo "清理旧部署文件..."
rm -f "$DEPLOY_DIR/lark.jar" "$DEPLOY_DIR/movie.jar" "$DEPLOY_DIR/weather.jar"
# 复制jar包到部署目录
echo "复制jar包到部署目录..."
cp movie/target/movie-*.jar $DEPLOY_DIR/movie.jar
cp weather/target/weather-*.jar $DEPLOY_DIR/weather.jar
cp lark/target/lark-*.jar $DEPLOY_DIR/lark.jar
# 停止并删除现有的pm2进程(如果存在)
echo "停止现有进程..."
pm2 stop movie weather lark 2>/dev/null || true
pm2 delete movie weather lark 2>/dev/null || true
# 使用pm2启动各个模块
echo "使用pm2启动各个模块..."
# 启动movie模块
pm2 start "java -jar $DEPLOY_DIR/movie.jar" --name movie --log $LOG_DIR/movie.log --restart-delay 5000
# 启动weather模块
pm2 start "java -jar $DEPLOY_DIR/weather.jar" --name weather --log $LOG_DIR/weather.log --restart-delay 5000
# 启动lark模块
pm2 start "java -jar $DEPLOY_DIR/lark.jar" --name lark --log $LOG_DIR/lark.log --restart-delay 5000
# 保存pm2配置,确保重启后自动启动
pm2 save
pm2 startup
echo "部署完成!所有模块已启动并使用pm2管理。"
echo "使用 'pm2 list' 查看进程状态"
echo "使用 'pm2 logs [module_name]' 查看日志"
# 清理临时目录
cd /
rm -rf $WORK_DIR
exit 0
+68
View File
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.hezhaohui</groupId>
<artifactId>lark-panel</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>lark</artifactId>
<dependencies>
<dependency>
<groupId>cn.hezhaohui</groupId>
<artifactId>common</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.larksuite.oapi</groupId>
<artifactId>oapi-sdk</artifactId>
<version>2.4.24</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>cn.hezhaohui.lark.LarkApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,15 @@
package cn.hezhaohui.lark;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import static cn.hezhaohui.lark.handler.EventListener.larkClientStart;
@SpringBootApplication
public class LarkApplication {
public static void main(String[] args) {
SpringApplication.run(LarkApplication.class, args);
larkClientStart();
}
}
@@ -0,0 +1,12 @@
package cn.hezhaohui.lark.client;
import cn.hezhaohui.pojo.dto.MovieDTO;
import java.util.List;
public interface MovieClient {
List<MovieDTO> listMovies();
void addMovie(MovieDTO movieDTO);
}
@@ -0,0 +1,6 @@
package cn.hezhaohui.lark.client;
public interface WakaTimeClient {
String getLast7DaysData();
}
@@ -0,0 +1,10 @@
package cn.hezhaohui.lark.client;
import cn.hezhaohui.pojo.entity.Weather;
public interface WeatherClient {
Weather getWeather();
}
@@ -0,0 +1,23 @@
package cn.hezhaohui.lark.client.impl;
import cn.hezhaohui.pojo.dto.MovieDTO;
import cn.hezhaohui.lark.client.MovieClient;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class MovieClientImpl implements MovieClient {
@Override
public List<MovieDTO> listMovies() {
String ans = HttpUtil.get("http://localhost:8081/movie");
return JSONUtil.parseArray(ans).toList(MovieDTO.class);
}
@Override
public void addMovie(MovieDTO movieDTO) {
HttpUtil.post("http://localhost:8081/movie", JSONUtil.toJsonStr(movieDTO));
}
}
@@ -0,0 +1,18 @@
package cn.hezhaohui.lark.client.impl;
import cn.hezhaohui.common.WakaTimeConstant;
import cn.hezhaohui.lark.client.WakaTimeClient;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import org.springframework.stereotype.Component;
@Component
public class WakaTimeClientImpl implements WakaTimeClient {
@Override
public String getLast7DaysData() {
HttpRequest request = HttpUtil.createGet(WakaTimeConstant.WAKATIME_API_URL_LAST_7_DAYS);
request.auth("Basic " + WakaTimeConstant.WAKATIME_API_SECRET_KEY_BASE64);
return request.execute().body();
}
}
@@ -0,0 +1,21 @@
package cn.hezhaohui.lark.client.impl;
import cn.hezhaohui.pojo.entity.Weather;
import cn.hezhaohui.lark.client.WeatherClient;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Component;
@Component
public class WeatherClientImpl implements WeatherClient {
@Override
public Weather getWeather() {
String ans = HttpUtil.get("http://localhost:8083/get");
Weather weather = JSONUtil.toBean(ans, Weather.class);
return weather;
}
}
@@ -0,0 +1,97 @@
package cn.hezhaohui.lark.handler;
import cn.hezhaohui.common.AppConstant;
import cn.hezhaohui.common.CardEnum;
import cn.hezhaohui.lark.service.MovieService;
import cn.hezhaohui.lark.service.WakaTimeService;
import cn.hezhaohui.pojo.entity.Weather;
import cn.hezhaohui.lark.client.WeatherClient;
import cn.hezhaohui.lark.util.BeanUtil;
import cn.hezhaohui.lark.util.LarkUtil;
import cn.hezhaohui.pojo.vo.MovieVO;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.event.EventDispatcher;
import com.lark.oapi.event.cardcallback.P2CardActionTriggerHandler;
import com.lark.oapi.event.cardcallback.model.CallBackCard;
import com.lark.oapi.event.cardcallback.model.CallBackToast;
import com.lark.oapi.event.cardcallback.model.P2CardActionTrigger;
import com.lark.oapi.event.cardcallback.model.P2CardActionTriggerResponse;
import com.lark.oapi.service.application.ApplicationService;
import com.lark.oapi.service.application.v6.model.P2BotMenuV6;
import com.lark.oapi.service.im.ImService;
import com.lark.oapi.service.im.v1.model.P2MessageReceiveV1;
import com.lark.oapi.ws.Client;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EventListener {
// onP2MessageReceiveV1 为接收消息 v2.0;onCustomizedEvent 内的 message 为接收消息 v1.0。
private static final EventDispatcher EVENT_HANDLER = EventDispatcher.newBuilder("", "")
.onP2MessageReceiveV1(new ImService.P2MessageReceiveV1Handler() {
@Override
public void handle(P2MessageReceiveV1 event) throws Exception {
System.out.printf("[ onP2MessageReceiveV1 access ], data: %s\n", Jsons.DEFAULT.toJson(event.getEvent()));
}
})
.onP2BotMenuV6(new ApplicationService.P2BotMenuV6Handler() {
@Override
public void handle(P2BotMenuV6 event) throws Exception {
String eventKey = event.getEvent().getEventKey();
if (eventKey.equals("weather")) {
WeatherClient weatherClient = BeanUtil.getBean(WeatherClient.class);
Weather weather = weatherClient.getWeather();
LarkUtil.sendCard(CardEnum.CARD_WEATHER, weather);
} else if (eventKey.equals("movie")) {
MovieService movieService = BeanUtil.getBean(MovieService.class);
Map<String, Object> data = movieService.getMovies();
LarkUtil.sendCard(CardEnum.CARD_MOVIE, data);
} else if (eventKey.equals("code")) {
WakaTimeService wakaTimeService = BeanUtil.getBean(WakaTimeService.class);
HashMap<String, Object> last7DaysCardData = wakaTimeService.getLast7DaysCardData();
LarkUtil.sendCard(CardEnum.CARD_WAKATIME, last7DaysCardData);
}
}
})
.onP2CardActionTrigger(new P2CardActionTriggerHandler() {
@Override
public P2CardActionTriggerResponse handle(P2CardActionTrigger event) throws Exception {
System.out.printf("[ onP2CardActionTrigger access ], data: %s\n", Jsons.DEFAULT.toJson(event.getEvent()));
String input = event.getEvent().getAction().getFormValue().get("movie_name").toString();
System.out.println(input);
MovieService movieService = BeanUtil.getBean(MovieService.class);
movieService.addMovie(input);
P2CardActionTriggerResponse response = new P2CardActionTriggerResponse();
CallBackToast toast = new CallBackToast();
toast.setType("success");
toast.setContent("Successful Operation!!!");
response.setToast(toast);
CallBackCard card = new CallBackCard();
card.setType("template");
Map<String, Object> movies = movieService.getMovies();
Map<String, Object> data = new HashMap<>();
data.put("template_id", CardEnum.CARD_MOVIE.getId());
data.put("template_version_name", CardEnum.CARD_MOVIE.getVersionName());
data.put("template_variable", movies);
card.setData(data);
response.setCard(card);
return response;
}
})
.build();
public static void larkClientStart() {
Client cli = new Client.Builder(AppConstant.APP_ID, AppConstant.APP_SECRET)
.eventHandler(EVENT_HANDLER)
.build();
cli.start();
}
}
@@ -0,0 +1,51 @@
package cn.hezhaohui.lark.service;
import cn.hezhaohui.lark.client.MovieClient;
import cn.hezhaohui.pojo.dto.MovieDTO;
import cn.hezhaohui.pojo.vo.MovieVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class MovieService {
@Resource
private MovieClient movieClient;
public Map<String, Object> getMovies() {
List<MovieVO> input = this.listMovies();
List<Object> output = new ArrayList<>();
for (MovieVO movieVO : input) {
Map<String, String> movieInfo = new HashMap<>();
movieInfo.put("movie_title", movieVO.getName());
movieInfo.put("submit_time", movieVO.getDate());
output.add(movieInfo);
}
Map<String, Object> data = new HashMap<>();
data.put("recent_movie", output);
return data;
}
private List<MovieVO> listMovies() {
List<MovieDTO> movieDTOS = movieClient.listMovies();
List<MovieVO> movieVOS = new ArrayList<>();
for (MovieDTO movieDTO : movieDTOS) {
MovieVO movieVO = new MovieVO();
movieVO.setName(movieDTO.getName());
movieVO.setDate(new SimpleDateFormat("yyyy-MM-dd").format(movieDTO.getDay()));
movieVOS.add(movieVO);
}
return movieVOS;
}
public void addMovie(String movie_name) {
MovieDTO movieDTO = new MovieDTO();
movieDTO.setName(movie_name);
movieDTO.setDay(new Date());
System.out.println("movieDTO: " + movieDTO);
movieClient.addMovie(movieDTO);
}
}
@@ -0,0 +1,126 @@
package cn.hezhaohui.lark.service;
import cn.hezhaohui.lark.client.WakaTimeClient;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class WakaTimeService {
@Resource
private WakaTimeClient wakaTimeClient;
public List<Map<String, Object>> getLast7DaysData() {
String last7DaysData = wakaTimeClient.getLast7DaysData();
JSONObject jsonObject = JSONUtil.parseObj(last7DaysData);
JSONArray dataArray = jsonObject.getJSONArray("data");
// Init
List<Map<String, Object>> dailyActivities = new ArrayList<>();
// Traverse
for (int i = 0; i < dataArray.size(); i++) {
JSONObject day = dataArray.getJSONObject(i);
// 获取日期
String date = day.getJSONObject("range").getStr("date");
// 获取当天编码时间
JSONObject grandTotal = day.getJSONObject("grand_total");
double total_seconds = grandTotal.getDouble("total_seconds");
int total_minutes = (int) (total_seconds / 60);
// Map 存储
Map<String, Object> activity = new HashMap<>();
activity.put("date", date);
activity.put("total_minutes", total_minutes);
dailyActivities.add(activity);
}
return dailyActivities;
}
public HashMap<String, Object> getLast7DaysCardData() {
List<Map<String, Object>> daysData = this.getLast7DaysData();
int totalMinutes = 0;
for (Map<String, Object> dayData : daysData) {
totalMinutes += (int) dayData.get("total_minutes");
}
HashMap<String, Object> cardData = new HashMap<>();
cardData.put("total_time", totalMinutes);
cardData.put("average_time", totalMinutes / 7);
// 图表
// 日期格式化器
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d");
// 构造 values 数组
List<Map<String, Object>> valuesList = new ArrayList<>();
for (int i = 0; i < daysData.size(); i++) {
Map<String, Object> entry = daysData.get(i);
String originalDate = (String) entry.get("date");
Integer singleMinutes = (Integer) entry.get("total_minutes");
// 将 "2025-10-26" 转换为 "10/26"
LocalDate date = LocalDate.parse(originalDate);
String formattedDate = date.format(formatter);
// 构造数据项
Map<String, Object> item = new HashMap<>();
item.put("date", formattedDate);
item.put("day", "Day" + (i + 1)); // Day1, Day2, ...
item.put("minutes", singleMinutes);
valuesList.add(item);
}
// 构造 axes 数组
List<Map<String, Object>> axesList = new ArrayList<>();
// 构造第一个轴(y轴)
Map<String, Object> axisY = new HashMap<>();
axisY.put("orient", "left");
Map<String, Object> titleY = new HashMap<>();
titleY.put("text", "编码时长(分钟)");
axisY.put("title", titleY);
axesList.add(axisY);
// 构造第二个轴(x轴)
Map<String, Object> axisX = new HashMap<>();
axisX.put("orient", "bottom");
Map<String, Object> titleX = new HashMap<>();
titleX.put("text", "日期");
axisX.put("title", titleX);
axesList.add(axisX);
// 构造 data 对象
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("values", valuesList);
// 构造 label
Map<String, Object> labelMap = new HashMap<>();
labelMap.put("visible", true);
// 构造 legends
Map<String, Object> legendsMap = new HashMap<>();
legendsMap.put("orient", "top");
legendsMap.put("visible", true);
// 构造 chartConfig 对象
Map<String, Object> chartConfig = new HashMap<>();
chartConfig.put("axes", axesList);
chartConfig.put("data", dataMap);
chartConfig.put("label", labelMap);
chartConfig.put("legends", legendsMap);
chartConfig.put("seriesField", "day");
chartConfig.put("title", new HashMap<>(Map.of("text", "每日编码时长(分钟)")));
chartConfig.put("type", "bar");
chartConfig.put("xField", "date");
chartConfig.put("yField", "minutes");
cardData.put("chart", chartConfig);
return cardData;
}
}
@@ -0,0 +1,25 @@
package cn.hezhaohui.lark.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class BeanUtil implements ApplicationContextAware {
private static ApplicationContext context;
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
public static <T> T getBean(String name, Class<T> beanClass) {
return context.getBean(name, beanClass);
}
public static Object getBean(String name) {
return context.getBean(name);
}
@Override
public void setApplicationContext(ApplicationContext appContext) {
context = appContext;
}
}
@@ -0,0 +1,97 @@
package cn.hezhaohui.lark.util;
import cn.hezhaohui.common.AppConstant;
import cn.hezhaohui.common.CardEnum;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.google.gson.JsonParser;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.im.v1.model.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class LarkUtil {
// SDK 使用文档:https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/server-side-sdk/java-sdk-guide/preparations
// 复制该 Demo 后, 需要将 "YOUR_APP_ID", "YOUR_APP_SECRET" 替换为自己应用的 APP_ID, APP_SECRET.
// 以下示例代码默认根据文档示例值填充,如果存在代码问题,请在 API 调试台填上相关必要参数后再复制代码使用
public static void sendText(String content) throws Exception {
// 构建client
Client client = Client.newBuilder(AppConstant.APP_ID, AppConstant.APP_SECRET).build();
// Json 包装
Map<String, String> text = new HashMap<>();
text.put("text", content);
String textJson = JSONUtil.toJsonStr(text);
// 创建请求对象
CreateMessageReq req = CreateMessageReq.newBuilder()
.receiveIdType("open_id")
.createMessageReqBody(CreateMessageReqBody.newBuilder()
.receiveId(AppConstant.APP_USER_OPEN_ID)
.msgType("text")
.content(textJson)
.uuid(IdUtil.randomUUID())
.build())
.build();
// 发起请求
CreateMessageResp resp = client.im().v1().message().create(req);
// 处理服务端错误
if(!resp.success()) {
System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
return;
}
// 业务数据处理
System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
}
public static void sendCard(CardEnum cardEnum, Object object) throws Exception {
// 构建client
Client client = Client.newBuilder(AppConstant.APP_ID, AppConstant.APP_SECRET).build();
// Json 包装
Map<String, Object> data = new HashMap<>();
data.put("template_id", cardEnum.getId());
data.put("template_version_name", cardEnum.getVersionName());
if (object != null) {
data.put("template_variable", object);
}
Map<String, Object> content = new HashMap<>();
content.put("type", "template");
content.put("data", data);
// 创建请求对象
CreateMessageReq req = CreateMessageReq.newBuilder()
.receiveIdType("open_id")
.createMessageReqBody(CreateMessageReqBody.newBuilder()
.receiveId(AppConstant.APP_USER_OPEN_ID)
.msgType("interactive")
.content(JSONUtil.toJsonStr(content))
.uuid(IdUtil.randomUUID())
.build())
.build();
// 发起请求
CreateMessageResp resp = client.im().v1().message().create(req);
// 处理服务端错误
if(!resp.success()) {
System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
return;
}
// 业务数据处理
System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
}
}
+8
View File
@@ -0,0 +1,8 @@
spring:
application:
name: lark
server:
port: 8082
service-weather:
url: http://localhost:8081/api/weather
@@ -0,0 +1,24 @@
package cn.hezhaohui.lark.client.impl;
import cn.hezhaohui.pojo.dto.MovieDTO;
import cn.hezhaohui.lark.client.MovieClient;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class MovieClientImplTest {
@Resource
private MovieClient movieClient;
@Test
void listMovies() {
List<MovieDTO> movieDTOS = movieClient.listMovies();
for(MovieDTO movieDTO : movieDTOS) {
System.out.println(movieDTO);
}
}
}
@@ -0,0 +1,20 @@
package cn.hezhaohui.lark.client.impl;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class WakaTimeClientImplTest {
@Resource
private WakaTimeClientImpl wakaTimeClient;
@Test
void getLast7DaysData() {
String last7DaysData = wakaTimeClient.getLast7DaysData();
System.out.println(last7DaysData);
}
}
@@ -0,0 +1,22 @@
package cn.hezhaohui.lark.client.impl;
import cn.hezhaohui.pojo.entity.Weather;
import cn.hezhaohui.lark.client.WeatherClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@Slf4j
class WeatherClientImplTest {
@Resource
private WeatherClient weatherClient;
@Test
void getWeather() {
Weather weather = weatherClient.getWeather();
log.info(weather.toString());
}
}
@@ -0,0 +1,24 @@
package cn.hezhaohui.lark.service;
import cn.hezhaohui.pojo.vo.MovieVO;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class MovieServiceTest {
@Resource
private MovieService movieService;
@Test
void listMovies() {
Map<String, Object> movies = movieService.getMovies();
System.out.println(movies);
}
}
@@ -0,0 +1,32 @@
package cn.hezhaohui.lark.service;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class WakaTimeServiceTest {
@Resource
private WakaTimeService wakaTimeService;
@Test
void getLast7DaysData() {
List<Map<String, Object>> last7DaysData = wakaTimeService.getLast7DaysData();
// System.out.println(last7DaysData);
for (Map<String, Object> data : last7DaysData) {
System.out.println(data);
}
}
@Test
void getLast7DaysCardData() {
Map<String, Object> last7DaysCardData = wakaTimeService.getLast7DaysCardData();
System.out.println(last7DaysCardData);
}
}
@@ -0,0 +1,26 @@
package cn.hezhaohui.lark.util;
import cn.hezhaohui.lark.client.WeatherClient;
import cn.hezhaohui.common.CardEnum;
import cn.hezhaohui.pojo.entity.Weather;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class LarkUtilTest {
@Resource
private WeatherClient weatherClient;
@Test
void sendText() throws Exception {
LarkUtil.sendText("你好");
}
@Test
void sendCard() throws Exception {
Weather weather = weatherClient.getWeather();
LarkUtil.sendCard(CardEnum.CARD_WEATHER, weather);
}
}
+9
View File
@@ -0,0 +1,9 @@
CREATE DATABASE IF NOT EXISTS panel;
USE panel;
CREATE TABLE IF NOT EXISTS movie (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
day DATE NOT NULL
);
+62
View File
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.hezhaohui</groupId>
<artifactId>lark-panel</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>movie</artifactId>
<dependencies>
<dependency>
<groupId>cn.hezhaohui</groupId>
<artifactId>common</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>cn.hezhaohui.movie.MovieApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,14 @@
package cn.hezhaohui.movie;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("cn.hezhaohui.movie.mapper")
public class MovieApplication {
public static void main(String[] args) {
SpringApplication.run(MovieApplication.class, args);
}
}
@@ -0,0 +1,32 @@
package cn.hezhaohui.movie.controller;
import cn.hezhaohui.movie.entity.Movie;
import cn.hezhaohui.movie.service.MovieService;
import cn.hezhaohui.pojo.dto.MovieDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("movie")
public class MovieController {
@Resource
private MovieService movieService;
@GetMapping
public List<Movie> getMovieList(){
return movieService.list(new QueryWrapper<Movie>().orderByDesc("id"));
}
@PostMapping
public void addMovie(@RequestBody MovieDTO movieDTO){
Movie movie = new Movie();
movie.setName(movieDTO.getName());
movie.setDay(movieDTO.getDay());
movieService.save(movie);
}
}
@@ -0,0 +1,71 @@
package cn.hezhaohui.movie.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.Date;
import lombok.Data;
/**
*
* @TableName movie
*/
@TableName(value ="movie")
@Data
public class Movie {
/**
*
*/
@TableId(type = IdType.AUTO)
private Integer id;
/**
*
*/
private String name;
/**
*
*/
private Date day;
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
Movie other = (Movie) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
&& (this.getDay() == null ? other.getDay() == null : this.getDay().equals(other.getDay()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
result = prime * result + ((getDay() == null) ? 0 : getDay().hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", day=").append(day);
sb.append("]");
return sb.toString();
}
}
@@ -0,0 +1,18 @@
package cn.hezhaohui.movie.mapper;
import cn.hezhaohui.movie.entity.Movie;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* @author 23117
* @description 针对表【movie】的数据库操作Mapper
* @createDate 2025-10-30 19:52:48
* @Entity cn.hezhaohui.movie.entity.Movie
*/
public interface MovieMapper extends BaseMapper<Movie> {
}
@@ -0,0 +1,13 @@
package cn.hezhaohui.movie.service;
import cn.hezhaohui.movie.entity.Movie;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author 23117
* @description 针对表【movie】的数据库操作Service
* @createDate 2025-10-30 19:52:48
*/
public interface MovieService extends IService<Movie> {
}
@@ -0,0 +1,22 @@
package cn.hezhaohui.movie.service.impl;
import cn.hezhaohui.movie.entity.Movie;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hezhaohui.movie.service.MovieService;
import cn.hezhaohui.movie.mapper.MovieMapper;
import org.springframework.stereotype.Service;
/**
* @author 23117
* @description 针对表【movie】的数据库操作Service实现
* @createDate 2025-10-30 19:52:48
*/
@Service
public class MovieServiceImpl extends ServiceImpl<MovieMapper, Movie>
implements MovieService{
}
+8
View File
@@ -0,0 +1,8 @@
spring:
datasource:
username: root
password: dn293830
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://47.121.181.112:3306/panel
server:
port: 8081
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.hezhaohui.movie.mapper.MovieMapper">
<resultMap id="BaseResultMap" type="cn.hezhaohui.movie.entity.Movie">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="day" column="day" />
</resultMap>
<sql id="Base_Column_List">
id,name,day
</sql>
</mapper>
@@ -0,0 +1,25 @@
package cn.hezhaohui.movie.service.impl;
import cn.hezhaohui.movie.entity.Movie;
import cn.hezhaohui.movie.service.MovieService;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class MovieServiceImplTest {
@Resource
private MovieService movieService;
@Test
void getMovies() {
List<Movie> list = movieService.list();
System.out.println(list);
}
}
+91
View File
@@ -0,0 +1,91 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 项目基本信息 -->
<groupId>cn.hezhaohui</groupId>
<artifactId>lark-panel</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<name>all-in-one panel</name>
<!-- 子模块 -->
<modules>
<module>lark</module>
<module>weather</module>
<module>common</module>
<module>movie</module>
</modules>
<!-- 依赖管理 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>3.3.13</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.9</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.14</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
</dependencies>
</dependencyManagement>
<!-- 构建配置 -->
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<source>21</source>
<target>21</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<!-- 编译插件 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.2.2</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<!-- Maven 属性 -->
<properties>
<java.version>21</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
</project>
+67
View File
@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.hezhaohui</groupId>
<artifactId>lark-panel</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>weather</artifactId>
<dependencies>
<dependency>
<groupId>cn.hezhaohui</groupId>
<artifactId>common</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.27</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>cn.hezhaohui.weather.WeatherApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,11 @@
package cn.hezhaohui.weather;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WeatherApplication {
public static void main(String[] args) {
SpringApplication.run(WeatherApplication.class, args);
}
}
@@ -0,0 +1,15 @@
package cn.hezhaohui.weather.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping
public class HealthController {
@GetMapping("/health")
public String health() {
return "Hello wonder!";
}
}
@@ -0,0 +1,17 @@
package cn.hezhaohui.weather.controller;
import cn.hezhaohui.pojo.entity.Weather;
import cn.hezhaohui.weather.util.WeatherUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping
public class WeatherController {
@GetMapping("/get")
public Weather getWeather() {
return WeatherUtil.getWeather();
}
}
@@ -0,0 +1,30 @@
package cn.hezhaohui.weather.service;
import cn.hezhaohui.common.AIConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class ChatService {
private final ChatClient chatClient;
public ChatService(ChatClient.Builder chatClientBuilder) {
this.chatClient = chatClientBuilder.build();
}
public String doChat(String background, String content) {
String ans = chatClient
.prompt()
.system(AIConstant.SYSTEM_PROMPT)
.user("[BackGround]: " + background + "\n" + "[Content]: " + content)
.call()
.content();
log.info(ans);
return ans;
}
}
@@ -0,0 +1,21 @@
package cn.hezhaohui.weather.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
@Service
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
}
@@ -0,0 +1,62 @@
package cn.hezhaohui.weather.util;
import cn.hezhaohui.common.AIConstant;
import cn.hezhaohui.pojo.entity.Weather;
import cn.hezhaohui.weather.service.ChatService;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import static cn.hezhaohui.common.WeatherConstant.*;
@Slf4j
public class WeatherUtil {
/**
* 参考文档: https://lbs.amap.com/api/webservice/guide/api/weatherinfo
* URL 格式: https://restapi.amap.com/v3/weather/weatherInfo?parameters
*
*/
private static String createUrl() {
String url = API_BASE_URL +
"?key=" +
API_SECRET +
"&city=" +
CITY_CODE_WUHAN +
"&extensions=base";
log.info("[Weather] URL: {}", url);
return url;
}
public static Weather getWeather() {
String url = createUrl();
String ans = HttpUtil.get(url);
log.info("[Weather] Response: {}", ans);
JSONObject obj = JSONUtil.parseObj(ans);
log.info("[Weather] Obj: {}", obj);
// 检查返回状态码
String status = obj.getStr("status");
if (!"1".equals(status)) {
String info = obj.getStr("info", "Unknown Error");
String errorCode = obj.getStr("infocode", "N/A");
log.error("[Weather] Request failed with code: {}, error: {}", errorCode, info);
return null;
}
// 获取天气信息数组
JSONObject weatherData = obj.getJSONArray("lives").getJSONObject(0);
Weather weather = Weather.builder()
.weather(weatherData.getStr("weather"))
.temperature(weatherData.getStr("temperature"))
.windDirection(weatherData.getStr("winddirection"))
.windPower(weatherData.getStr("windpower"))
.reportTime(weatherData.getStr("reporttime"))
.humidity(weatherData.getStr("humidity"))
.build();
String content = SpringContextUtil.getBean(ChatService.class).doChat(AIConstant.BACKGROUND_WEATHER, weather.toString());
weather.setContent(content);
log.info("[Weather] Prepared: {}", weather);
return weather;
}
}
@@ -0,0 +1,14 @@
spring:
application:
name: service-weather
ai:
openai:
api-key: sk-ihsqnxhnzmgsaojdkxomcmgdypdfpzojymfndfklgzfchlgz
base-url: https://api.siliconflow.cn
chat:
options:
model: Pro/Qwen/Qwen2.5-7B-Instruct
temperature: 0.7
server:
port: 8083
@@ -0,0 +1,18 @@
package cn.hezhaohui.weather.service;
import cn.hezhaohui.common.AIConstant;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ChatServiceTest {
@Resource
private ChatService chatService;
@Test
void chat() {
chatService.doChat(AIConstant.BACKGROUND_WEATHER, "今天下雨");
}
}
@@ -0,0 +1,15 @@
package cn.hezhaohui.weather.util;
import cn.hezhaohui.pojo.entity.Weather;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class WeatherUtilTest {
@Test
void getWeather() {
Weather weather = WeatherUtil.getWeather();
System.out.println(weather);
}
}