├── src └── main │ ├── resources │ ├── META-INF │ │ └── spring.factories │ ├── static │ │ ├── favicon.ico │ │ ├── js │ │ │ ├── SideButtonPosition.js │ │ │ └── UpdateInformation.js │ │ ├── webui.html │ │ └── css │ │ │ └── index.css │ ├── application.properties │ └── logback-spring.xml │ ├── java │ └── cn │ │ └── travellerr │ │ └── onebottelegram │ │ ├── config │ │ ├── ProxyType.java │ │ ├── ConfigEntity.java │ │ ├── Config.java │ │ └── ConfigGenerator.java │ │ ├── webui │ │ ├── WebuiController.java │ │ ├── entity │ │ │ └── BotInfo.java │ │ ├── api │ │ │ ├── LogWebSocketHandler.java │ │ │ └── ApiController.java │ │ └── WebSecurityConfig.java │ │ ├── converter │ │ ├── LanguageCode.java │ │ ├── Translator.java │ │ ├── AudioConverter.java │ │ └── TelegramToOnebot.java │ │ ├── model │ │ ├── ApiRequest.java │ │ └── Messages.java │ │ ├── hibernate │ │ ├── entity │ │ │ ├── Message.java │ │ │ └── Group.java │ │ └── HibernateUtil.java │ │ ├── onebotWebsocket │ │ ├── WebSocketConfig.java │ │ ├── OneBotWebSocketHandler.java │ │ └── onebotSerialize │ │ │ └── OnebotAction.java │ │ ├── telegramApi │ │ ├── SSLSocketClient.java │ │ └── TelegramApi.java │ │ ├── TelegramOnebotAdapter.java │ │ └── command │ │ └── CommandHandler.java │ └── kotlin │ └── cn │ └── travellerr │ └── onebotApi │ ├── MicrosoftTranslateApi.kt │ ├── PublicApi.kt │ ├── MessageApi.kt │ ├── SubClassApi.kt │ └── ResponseApi.kt ├── settings.gradle ├── .gitattributes ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── gradlew.bat ├── .github └── workflows │ └── gradle.yml ├── README.md ├── gradlew └── LICENSE /src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'Tele-KiraLink' 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | /gradlew text eol=lf 2 | *.bat text eol=crlf 3 | *.jar binary 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Echomirix/Tele-KiraLink/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/resources/static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Echomirix/Tele-KiraLink/HEAD/src/main/resources/static/favicon.ico -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/config/ProxyType.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.config; 2 | 3 | public enum ProxyType { 4 | HTTP, HTTPS, SOCKS4, SOCKS5, VMESS 5 | } 6 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=Tele-KiraLink 2 | 3 | logging.config= classpath:logback-spring.xml 4 | 5 | spring.web.resources.add-mappings=true 6 | spring.web.resources.static-locations=classpath:/static/ -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/config/ConfigEntity.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.config; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.RetentionPolicy; 5 | 6 | @Retention(RetentionPolicy.RUNTIME) 7 | public @interface ConfigEntity { 8 | String name(); 9 | String filePath(); 10 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/webui/WebuiController.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.webui; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | 7 | @Controller 8 | @RequestMapping("/") 9 | public class WebuiController { 10 | 11 | @GetMapping 12 | public String index() { 13 | return "webui"; 14 | } 15 | 16 | @GetMapping("/webui") 17 | public String webui() { 18 | return "webui.html"; 19 | } 20 | 21 | 22 | 23 | 24 | 25 | 26 | } -------------------------------------------------------------------------------- /src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | %highlight(%d{yyyy-MM-dd HH:mm:ss} %.-1level %msg%n) 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/converter/LanguageCode.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.converter; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | 6 | import javax.annotation.Nullable; 7 | import java.util.Locale; 8 | 9 | @Getter 10 | @AllArgsConstructor 11 | public enum LanguageCode { 12 | AUTO("auto-detect"), 13 | ZH("zh"), 14 | ZH_HANS("zh-hans"), 15 | EN("en"), 16 | JA("ja"), 17 | FR("fr"), 18 | DE("de"), 19 | RU("ru"); 20 | 21 | private final String code; 22 | 23 | public static LanguageCode parseLanguageCode(@Nullable String code) { 24 | if (code == null) { 25 | return EN; 26 | } 27 | for (LanguageCode languageCode : LanguageCode.values()) { 28 | if (languageCode.getCode().equals(code.toLowerCase(Locale.ROOT))) { 29 | return languageCode; 30 | } 31 | } 32 | return EN; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/kotlin/cn/travellerr/onebotApi/MicrosoftTranslateApi.kt: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebotApi 2 | 3 | import kotlinx.serialization.Serializable 4 | import kotlinx.serialization.json.Json 5 | 6 | @Serializable 7 | class TranslateResponse : ArrayList() { 8 | companion object { 9 | private val json = Json { ignoreUnknownKeys = true } 10 | 11 | fun parse(jsonStr: String): TranslateResponse { 12 | return json 13 | .decodeFromString(serializer(), jsonStr) 14 | } 15 | } 16 | } 17 | @Serializable 18 | data class TranslateResponseItem( 19 | val detectedLanguage: DetectedLanguage, 20 | val translations: List, 21 | ) { 22 | companion object { 23 | private val json = Json { ignoreUnknownKeys = true } 24 | 25 | fun parse(jsonStr: String): TranslateResponseItem { 26 | return json 27 | .decodeFromString(serializer(), jsonStr) 28 | } 29 | } 30 | } 31 | @Serializable 32 | data class DetectedLanguage( 33 | val language: String 34 | ) 35 | @Serializable 36 | data class Translation( 37 | val text: String, 38 | val to: String 39 | ) -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/model/ApiRequest.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.model; 2 | 3 | import com.google.gson.JsonArray; 4 | import com.google.gson.annotations.SerializedName; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Getter; 7 | import lombok.NoArgsConstructor; 8 | import lombok.Setter; 9 | 10 | public class ApiRequest { 11 | @AllArgsConstructor 12 | @NoArgsConstructor 13 | @Getter 14 | @Setter 15 | public static class BaseApiRequest { 16 | private String action = ""; 17 | private Params params = new Params(); 18 | private String echo = "0"; 19 | } 20 | 21 | @AllArgsConstructor 22 | @NoArgsConstructor 23 | @Getter 24 | @Setter 25 | public static class Params { 26 | @SerializedName("user_id") 27 | Long userId = -1L; 28 | 29 | @SerializedName("group_id") 30 | Long groupId = -1L; 31 | 32 | @SerializedName("message_id") 33 | Integer messageId = -1; 34 | 35 | @SerializedName("duration") 36 | Integer duration; 37 | 38 | @SerializedName("message") 39 | JsonArray message; 40 | 41 | @SerializedName("group_name") 42 | String groupName = ""; 43 | 44 | @SerializedName("special_title") 45 | String specialTitle; 46 | } 47 | 48 | 49 | } 50 | 51 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/webui/entity/BotInfo.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.webui.entity; 2 | 3 | import cn.hutool.core.codec.Base64Encoder; 4 | import cn.hutool.core.date.BetweenFormatter; 5 | import cn.hutool.core.date.DateUtil; 6 | import cn.travellerr.onebottelegram.TelegramOnebotAdapter; 7 | import com.pengrad.telegrambot.response.GetMeResponse; 8 | import lombok.Data; 9 | 10 | import java.io.File; 11 | import java.nio.file.Files; 12 | import java.util.Date; 13 | 14 | @Data 15 | public class BotInfo { 16 | private String firstName; 17 | private String name; 18 | private String uptime; 19 | private String version; 20 | private String avatarUrl; 21 | private int latency; 22 | 23 | public BotInfo(GetMeResponse getMe, String avatarUrl, boolean withAvatar) { 24 | String avatar; 25 | try { 26 | File file = new File(avatarUrl); 27 | if (file.exists()) { 28 | avatar = "data:image/png;base64," + Base64Encoder.encode(Files.readAllBytes(file.toPath())); 29 | } else { 30 | throw new Exception("File not found"); 31 | } 32 | } catch (Exception e) { 33 | avatar = avatarUrl; 34 | } 35 | 36 | this.firstName = getMe.user().firstName(); 37 | this.name = "@"+getMe.user().username(); 38 | this.avatarUrl = withAvatar ? avatar : ""; 39 | this.uptime = DateUtil.formatBetween(new Date(TelegramOnebotAdapter.startTime), new Date(), BetweenFormatter.Level.SECOND); 40 | this.version = "OneBot v11"; 41 | this.latency = 0; // Placeholder for latency, implement actual logic if needed 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/hibernate/entity/Message.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.hibernate.entity; 2 | 3 | import cn.hutool.json.JSONObject; 4 | import com.google.gson.JsonObject; 5 | import com.google.gson.JsonParser; 6 | import com.pengrad.telegrambot.model.Chat; 7 | import jakarta.persistence.*; 8 | import lombok.AllArgsConstructor; 9 | import lombok.Builder; 10 | import lombok.Data; 11 | import lombok.NoArgsConstructor; 12 | 13 | import java.util.Date; 14 | 15 | @Data 16 | @AllArgsConstructor 17 | @NoArgsConstructor 18 | @Builder 19 | @Table(name = "Message") 20 | @Entity 21 | public class Message { 22 | @Id 23 | private int messageId; 24 | 25 | private long contactId; 26 | 27 | @Builder.Default 28 | private Date createTime = new Date(); 29 | 30 | @Enumerated(EnumType.STRING) 31 | private Chat.Type contactType; 32 | 33 | /** 34 | * 规定此message为array格式的onebotV11 json字符串 35 | */ 36 | private String message; 37 | 38 | public Message(com.pengrad.telegrambot.model.Message message, String array) { 39 | this.messageId = message.messageId(); 40 | this.contactId = message.chat().id(); 41 | this.contactType = message.chat().type(); 42 | this.createTime = new Date(); 43 | this.message = array; 44 | } 45 | 46 | public JsonObject getMessage() { 47 | return JsonParser.parseString(this.message).getAsJsonObject(); 48 | } 49 | 50 | public void setMessage(String message) { 51 | this.message = message; 52 | } 53 | 54 | public void setMessage(JSONObject message) { 55 | this.message = message.toString(); 56 | } 57 | 58 | public String getMessageString() { 59 | return this.message; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/webui/api/LogWebSocketHandler.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.webui.api; 2 | 3 | 4 | import cn.travellerr.onebottelegram.onebotWebsocket.OneBotWebSocketHandler; 5 | import org.jetbrains.annotations.NotNull; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.web.socket.TextMessage; 10 | import org.springframework.web.socket.WebSocketSession; 11 | import org.springframework.web.socket.handler.TextWebSocketHandler; 12 | 13 | import java.io.IOException; 14 | import java.util.Set; 15 | import java.util.concurrent.ConcurrentHashMap; 16 | 17 | @Component 18 | public class LogWebSocketHandler extends TextWebSocketHandler { 19 | 20 | public static final Set sessions = ConcurrentHashMap.newKeySet(); 21 | private static final Logger log = LoggerFactory.getLogger(OneBotWebSocketHandler.class); 22 | 23 | // 广播消息给所有客户端 24 | public static void broadcast(String message) { 25 | sessions.forEach(session -> { 26 | try { 27 | if (session.isOpen()) { 28 | session.sendMessage(new TextMessage(message)); 29 | } 30 | } catch (IOException e) { 31 | log.error("广播消息失败", e); 32 | } 33 | }); 34 | } 35 | 36 | @Override 37 | public void afterConnectionEstablished(@NotNull org.springframework.web.socket.WebSocketSession session) { 38 | sessions.add(session); 39 | } 40 | 41 | @Override 42 | public void afterConnectionClosed(@NotNull org.springframework.web.socket.WebSocketSession session, @NotNull org.springframework.web.socket.CloseStatus status) { 43 | sessions.remove(session); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/onebotWebsocket/WebSocketConfig.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.onebotWebsocket; 2 | 3 | import cn.travellerr.onebottelegram.webui.api.LogWebSocketHandler; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.web.socket.config.annotation.EnableWebSocket; 8 | import org.springframework.web.socket.config.annotation.WebSocketConfigurer; 9 | import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; 10 | import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; 11 | 12 | import static cn.travellerr.onebottelegram.TelegramOnebotAdapter.config; 13 | 14 | @Configuration 15 | @EnableWebSocket 16 | public class WebSocketConfig implements WebSocketConfigurer { 17 | 18 | @Autowired 19 | private OneBotWebSocketHandler handler; 20 | 21 | @Autowired 22 | private LogWebSocketHandler logHandler; 23 | 24 | @Override 25 | public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { 26 | registry.addHandler(handler, config.getOnebot().getPath()) 27 | .addHandler(logHandler, "/ws/logs") 28 | .setAllowedOrigins("*"); 29 | } 30 | 31 | 32 | @Bean 33 | public ServletServerContainerFactoryBean createWebSocketContainer() { 34 | ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean(); 35 | // 在此处设置bufferSize 36 | container.setMaxTextMessageBufferSize(102400000); 37 | container.setMaxBinaryMessageBufferSize(102400000); 38 | container.setMaxSessionIdleTimeout(15 * 60000L); 39 | return container; 40 | } 41 | } -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/hibernate/HibernateUtil.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.hibernate; 2 | 3 | import cn.chahuyun.hibernateplus.Configuration; 4 | import cn.chahuyun.hibernateplus.DriveType; 5 | import cn.chahuyun.hibernateplus.HibernatePlusService; 6 | import cn.travellerr.onebottelegram.TelegramOnebotAdapter; 7 | import cn.travellerr.onebottelegram.config.Config; 8 | 9 | import java.nio.file.Path; 10 | 11 | public class HibernateUtil { 12 | /** 13 | * Hibernate初始化 14 | * 15 | * @param app 插件 16 | * @author Moyuyanli 17 | * @date 2022/7/30 23:04 18 | */ 19 | public static void init(TelegramOnebotAdapter app) { 20 | Config config = TelegramOnebotAdapter.config; 21 | 22 | Configuration configuration = HibernatePlusService.createConfiguration(app.getClass()); 23 | configuration.setPackageName("cn.travellerr.onebottelegram.hibernate.entity"); 24 | 25 | DriveType dataType = config.getSpring().getDatabase().getDataType(); 26 | configuration.setDriveType(dataType); 27 | Path dataFolderPath = Path.of("./"); 28 | switch (dataType) { 29 | case MYSQL: 30 | configuration.setAddress(config.getSpring().getDatabase().getMysqlUrl()); 31 | configuration.setUser(config.getSpring().getDatabase().getMysqlUser()); 32 | configuration.setPassword(config.getSpring().getDatabase().getMysqlPassword()); 33 | break; 34 | case H2: 35 | configuration.setAddress(dataFolderPath.resolve("TelegramData.h2").toString()); 36 | break; 37 | case SQLITE: 38 | configuration.setAddress(dataFolderPath.resolve("TelegramData").toString()); 39 | break; 40 | } 41 | 42 | HibernatePlusService.loadingService(configuration); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/resources/static/js/SideButtonPosition.js: -------------------------------------------------------------------------------- 1 | 2 | const toggleBtn = document.getElementById('toggle-btn'); 3 | let isDragging = false, startY = 0, currentTop = 20; 4 | 5 | toggleBtn.style.top = `${currentTop}px`; 6 | 7 | toggleBtn.addEventListener('mousedown', startDrag); 8 | document.addEventListener('mousemove', drag); 9 | document.addEventListener('mouseup', endDrag); 10 | 11 | toggleBtn.addEventListener('touchstart', e => startDrag(e.touches[0])); 12 | document.addEventListener('touchmove', e => drag(e.touches[0])); 13 | document.addEventListener('touchend', endDrag); 14 | 15 | function startDrag(e) { 16 | isDragging = true; 17 | startY = e.clientY; 18 | toggleBtn.classList.add('dragging'); 19 | toggleBtn.style.transition = 'none'; 20 | } 21 | 22 | function drag(e) { 23 | if (!isDragging) return; 24 | const deltaY = e.clientY - startY; 25 | startY = e.clientY; 26 | 27 | const maxTop = sidebar.getBoundingClientRect().height - toggleBtn.offsetHeight - 20; 28 | currentTop = Math.max(20, Math.min(maxTop, currentTop + deltaY)); 29 | 30 | updateButtonPosition(); 31 | } 32 | 33 | function endDrag() { 34 | isDragging = false; 35 | toggleBtn.classList.remove('dragging'); 36 | toggleBtn.style.transition = 'top 0.2s ease'; 37 | updateButtonPosition(); 38 | } 39 | 40 | function updateButtonPosition() { 41 | toggleBtn.style.top = `${currentTop}px`; 42 | sidebar.scrollTop = currentTop - 20; 43 | savePosition(); 44 | } 45 | 46 | sidebar.addEventListener('scroll', () => { 47 | if (!isDragging) { 48 | currentTop = sidebar.scrollTop + 20; 49 | updateButtonPosition(); 50 | } 51 | }); 52 | 53 | toggleBtn.addEventListener('dblclick', () => { 54 | currentTop = 20; 55 | updateButtonPosition(); 56 | }); 57 | 58 | function savePosition() { 59 | localStorage.setItem('toggleBtnPosition', currentTop); 60 | } 61 | 62 | function loadPosition() { 63 | const saved = localStorage.getItem('toggleBtnPosition'); 64 | if (saved) currentTop = parseInt(saved); 65 | updateButtonPosition(); 66 | } 67 | 68 | document.addEventListener('DOMContentLoaded', loadPosition); -------------------------------------------------------------------------------- /src/main/resources/static/webui.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Telegram Bot 控制台 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 27 | 28 | 29 |
30 |
31 |
[系统] 服务已启动
32 |
[连接] 已接入OneBot客户端
33 |
34 | 35 |
36 |
37 | 38 | 43 |
44 | 45 | 46 | 47 | 48 | 49 |
50 |
51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/converter/Translator.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.converter; 2 | 3 | import cn.travellerr.onebotApi.TranslateResponseItem; 4 | import cn.travellerr.onebotApi.Translation; 5 | import okhttp3.OkHttpClient; 6 | import okhttp3.Request; 7 | import okhttp3.RequestBody; 8 | import okhttp3.Response; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | 12 | public class Translator { 13 | 14 | private static final Logger logger = LoggerFactory.getLogger(Translator.class); 15 | 16 | public static String Trans(LanguageCode to, String text) { 17 | LanguageCode from = LanguageCode.AUTO; 18 | OkHttpClient okHttpClient = new OkHttpClient(); 19 | RequestBody body = RequestBody.create( 20 | ("fromLang="+from.getCode()+"&to="+to.getCode()+"&text="+text+"&tryFetchingGenderDebiasedTranslations=true&token=4hGHCk1A8zGjT-iDmwfYR8qgW8JyDcGL&key=1744467356960").getBytes() 21 | ); 22 | Request request = new Request.Builder() 23 | .url("https://cn.bing.com/ttranslatev3?isVertical=1&IG=339F15526F524081823C28726EFC8796&IID=translator.5026") 24 | .addHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8") 25 | .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36") 26 | .post(body).build(); 27 | 28 | 29 | try (Response response = okHttpClient.newCall(request).execute()) { 30 | if (response.body() == null) { 31 | throw new RuntimeException("Response body is null"); 32 | } 33 | try { 34 | String responseBody = response.body().string(); 35 | System.out.println(responseBody); 36 | TranslateResponseItem responseItems = TranslateResponseItem.Companion.parse(responseBody.substring(1, responseBody.length() - 1)); 37 | Translation translation = responseItems.getTranslations().get(0); 38 | 39 | return translation.getText(); 40 | } catch (Exception e) { 41 | logger.error("解析翻译结果失败!", e); 42 | return text; 43 | } 44 | } catch (Exception e) { 45 | logger.error("出错了!", e); 46 | } 47 | return text; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/kotlin/cn/travellerr/onebotApi/PublicApi.kt: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebotApi 2 | 3 | import kotlinx.serialization.SerialName 4 | import kotlinx.serialization.Serializable 5 | import kotlinx.serialization.serializer 6 | 7 | val Json = kotlinx.serialization.json.Json { 8 | ignoreUnknownKeys = true 9 | prettyPrint = true 10 | } 11 | 12 | interface OnebotPublicApi { 13 | companion object { 14 | const val API = "" 15 | 16 | fun parse(json: String): OnebotPublicApi { 17 | return Json.decodeFromString(serializer(), json) 18 | } 19 | } 20 | } 21 | 22 | 23 | @Serializable 24 | data class GetGroupInfo( 25 | @SerialName("group_id") 26 | val groupId: Long, 27 | 28 | @SerialName("no_cache") 29 | val noCache: Boolean 30 | ) : OnebotPublicApi{ 31 | companion object { 32 | const val API = "/get_group_info" 33 | 34 | fun parse(json: String): GetGroupInfo { 35 | return Json.decodeFromString(serializer(), json) 36 | } 37 | } 38 | } 39 | 40 | @Serializable 41 | data class SendMessage( 42 | @SerialName("message_type") 43 | val messageType: String, 44 | 45 | @SerialName("user_id") 46 | val userId: Long? = null, 47 | 48 | @SerialName("group_id") 49 | val groupId: Long? = null, 50 | 51 | @SerialName("message") 52 | val message: String 53 | 54 | ) : OnebotPublicApi{ 55 | companion object { 56 | const val API = "/send_msg" 57 | 58 | fun parse(json: String): SendMessage { 59 | return Json.decodeFromString(serializer(), json) 60 | } 61 | } 62 | } 63 | 64 | 65 | @Serializable 66 | data class GetGroupMemberInfo( 67 | @SerialName("group_id") 68 | val groupId: Long, 69 | 70 | @SerialName("user_id") 71 | val userId: Long, 72 | 73 | @SerialName("no_cache") 74 | val noCache: Boolean 75 | ) : OnebotPublicApi{ 76 | companion object { 77 | const val API = "/get_group_member_info" 78 | 79 | fun parse(json: String): GetGroupMemberInfo { 80 | return Json.decodeFromString(serializer(), json) 81 | } 82 | } 83 | } 84 | 85 | @Serializable 86 | data class GetGroupMemberList( 87 | @SerialName("group_id") 88 | val groupId: Long 89 | ) : OnebotPublicApi{ 90 | companion object { 91 | const val API = "/get_group_member_list" 92 | 93 | fun parse(json: String): GetGroupMemberList { 94 | return Json.decodeFromString(serializer(), json) 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/telegramApi/SSLSocketClient.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.telegramApi; 2 | 3 | import javax.net.ssl.*; 4 | import java.security.KeyStore; 5 | import java.security.SecureRandom; 6 | import java.security.cert.X509Certificate; 7 | import java.util.Arrays; 8 | 9 | 10 | public class SSLSocketClient { 11 | 12 | //获取这个SSLSocketFactory 13 | public static SSLSocketFactory getSSLSocketFactory() { 14 | try { 15 | SSLContext sslContext = SSLContext.getInstance("SSL"); 16 | sslContext.init(null, getTrustManager(), new SecureRandom()); 17 | return sslContext.getSocketFactory(); 18 | } catch (Exception e) { 19 | throw new RuntimeException(e); 20 | } 21 | } 22 | 23 | //获取TrustManager 24 | private static TrustManager[] getTrustManager() { 25 | return new TrustManager[]{ 26 | new X509TrustManager() { 27 | @Override 28 | public void checkClientTrusted(X509Certificate[] chain, String authType) { 29 | } 30 | 31 | @Override 32 | public void checkServerTrusted(X509Certificate[] chain, String authType) { 33 | } 34 | 35 | @Override 36 | public X509Certificate[] getAcceptedIssuers() { 37 | return new X509Certificate[]{}; 38 | } 39 | } 40 | }; 41 | } 42 | 43 | //获取HostnameVerifier 44 | public static HostnameVerifier getHostnameVerifier() { 45 | return (s, sslSession) -> true; 46 | } 47 | 48 | public static X509TrustManager getX509TrustManager() { 49 | X509TrustManager trustManager = null; 50 | try { 51 | TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); 52 | trustManagerFactory.init((KeyStore) null); 53 | TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); 54 | if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { 55 | throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); 56 | } 57 | trustManager = (X509TrustManager) trustManagers[0]; 58 | } catch (Exception e) { 59 | e.printStackTrace(); 60 | } 61 | 62 | return trustManager; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/model/Messages.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.model; 2 | 3 | import com.google.gson.JsonElement; 4 | import com.google.gson.annotations.SerializedName; 5 | import lombok.Builder; 6 | import lombok.Getter; 7 | import lombok.Setter; 8 | 9 | import java.io.Serializable; 10 | 11 | import static cn.travellerr.onebottelegram.onebotWebsocket.onebotSerialize.OnebotAction.GSON; 12 | 13 | 14 | public class Messages { 15 | @Getter 16 | @Setter 17 | public static class BaseMessage implements Serializable { 18 | @SerializedName("type") 19 | String type; 20 | 21 | @SerializedName("data") 22 | Data data; 23 | 24 | public JsonElement toJson() { 25 | return GSON.toJsonTree(this); 26 | } 27 | 28 | } 29 | 30 | @Getter 31 | @Setter 32 | public static class Text extends BaseMessage { 33 | public Text() { 34 | this.type = "text"; 35 | } 36 | 37 | public Text(String text) { 38 | this.type = "text"; 39 | this.data = Data.builder().text(text).build(); 40 | } 41 | } 42 | 43 | @Getter 44 | @Setter 45 | public static class Image extends BaseMessage { 46 | public Image() { 47 | this.type = "image"; 48 | } 49 | 50 | public Image(String file) { 51 | this.type = "image"; 52 | this.data = Data.builder().file(file).build(); 53 | } 54 | } 55 | 56 | @Getter 57 | @Setter 58 | public static class Record extends BaseMessage { 59 | public Record() { 60 | this.type = "record"; 61 | } 62 | 63 | public Record(String file) { 64 | this.type = "record"; 65 | this.data = Data.builder().file(file).build(); 66 | } 67 | } 68 | 69 | @Getter 70 | @Setter 71 | public static class At extends BaseMessage { 72 | public At() { 73 | this.type = "at"; 74 | } 75 | 76 | public At(Long qq) { 77 | this.type = "at"; 78 | this.data = Data.builder().qq(qq).build(); 79 | } 80 | } 81 | 82 | @Getter 83 | @Setter 84 | public static class Reply extends BaseMessage { 85 | public Reply() { 86 | this.type = "reply"; 87 | } 88 | 89 | public Reply(Integer id) { 90 | this.type = "reply"; 91 | this.data = Data.builder().id(id).build(); 92 | } 93 | } 94 | 95 | @Builder 96 | @Getter 97 | @Setter 98 | public static class Data { 99 | @SerializedName("text") 100 | String text; 101 | 102 | @SerializedName("file") 103 | String file; 104 | 105 | @SerializedName("qq") 106 | Long qq; 107 | 108 | @SerializedName("id") 109 | Integer id; 110 | } 111 | } -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/TelegramOnebotAdapter.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram; 2 | 3 | import cn.travellerr.onebottelegram.command.CommandHandler; 4 | import cn.travellerr.onebottelegram.config.Config; 5 | import cn.travellerr.onebottelegram.config.ConfigGenerator; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; 9 | import org.springframework.boot.context.properties.ConfigurationPropertiesScan; 10 | import org.springframework.context.ApplicationListener; 11 | import org.springframework.core.env.ConfigurableEnvironment; 12 | import org.springframework.core.env.MapPropertySource; 13 | 14 | import java.util.Collections; 15 | 16 | @SpringBootApplication 17 | @ConfigurationPropertiesScan 18 | public class TelegramOnebotAdapter { 19 | 20 | public static final String VERSION = "0.0.8"; 21 | public static TelegramOnebotAdapter INSTANCE = new TelegramOnebotAdapter(); 22 | public static Config config; 23 | public static long startTime = System.currentTimeMillis(); 24 | 25 | public static void main(String[] args) { 26 | SpringApplication springApplication = new SpringApplication(TelegramOnebotAdapter.class); 27 | springApplication.setBanner((environment, sourceClass, out) -> { 28 | out.println(""" 29 | _____ _ \s 30 | |_ _|___ | | ___ __ _ _ __ __ _ _ __ ___ \s 31 | | | / _ \\| | / _ \\ / _` || '__|/ _` || '_ ` _ \\\s 32 | | || __/| || __/| (_| || | | (_| || | | | | | 33 | |_| \\___||_| \\___| \\__, ||_| \\__,_||_| |_| |_| 34 | |___/ \s 35 | _ _ _ \s 36 | / \\ __| | __ _ _ __ | |_ ___ _ __ \s 37 | / _ \\ / _` | / _` || '_ \\ | __|/ _ \\| '__| \s 38 | / ___ \\| (_| || (_| || |_) || |_| __/| | \s 39 | /_/ \\_\\\\__,_| \\__,_|| .__/ \\__|\\___||_| \s 40 | |_| \s 41 | """); 42 | out.println("Tele-KiraLink v" + VERSION); 43 | }); 44 | springApplication.addListeners((ApplicationListener) event -> { 45 | config = ConfigGenerator.loadConfig(); 46 | ConfigurableEnvironment environment = event.getEnvironment(); 47 | environment.getPropertySources().addFirst(new MapPropertySource("customPort", 48 | Collections.singletonMap("server.port", config.getOnebot().getPort()))); 49 | }); 50 | 51 | springApplication.run(args); 52 | CommandHandler.startCommandConsole(); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/webui/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.webui; 2 | 3 | import cn.travellerr.onebottelegram.TelegramOnebotAdapter; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.security.config.Customizer; 7 | import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; 8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 9 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 10 | import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; 11 | import org.springframework.security.core.userdetails.User; 12 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 13 | import org.springframework.security.crypto.password.PasswordEncoder; 14 | import org.springframework.security.provisioning.InMemoryUserDetailsManager; 15 | import org.springframework.security.web.SecurityFilterChain; 16 | 17 | @Configuration 18 | @EnableWebSecurity 19 | @EnableMethodSecurity() 20 | public class WebSecurityConfig { 21 | 22 | @Bean 23 | public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 24 | http.authorizeHttpRequests(auth -> auth 25 | .requestMatchers(TelegramOnebotAdapter.config.getOnebot().getPath()).permitAll() 26 | .requestMatchers("/ws/**").permitAll() 27 | .anyRequest().authenticated()) 28 | .httpBasic(Customizer.withDefaults()); 29 | // .addFilterBefore(new OncePerRequestFilter() { 30 | // @Override 31 | // protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException { 32 | // System.out.println("Received request: " + request.getMethod() + " " + request.getRequestURI()); 33 | // filterChain.doFilter(request, response); 34 | // } 35 | // }, SecurityContextHolderAwareRequestFilter.class); 36 | http.csrf(AbstractHttpConfigurer::disable); 37 | http.rememberMe(rememberMe -> rememberMe 38 | .tokenValiditySeconds(86400*7) // 7天 39 | ); 40 | 41 | return http.build(); 42 | } 43 | 44 | 45 | @Bean 46 | public InMemoryUserDetailsManager userDetailsService() { 47 | return new InMemoryUserDetailsManager( 48 | User.withUsername(TelegramOnebotAdapter.config.getSpring().getWebui().getUserName()) 49 | .password(passwordEncoder().encode(TelegramOnebotAdapter.config.getSpring().getWebui().getPassword())) 50 | .roles("ADMIN") 51 | .build() 52 | ); 53 | } 54 | 55 | @Bean 56 | public PasswordEncoder passwordEncoder(){ 57 | // 使用BCrypt加密密码 58 | return new BCryptPasswordEncoder(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/webui/api/ApiController.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.webui.api; 2 | 3 | import cn.chahuyun.hibernateplus.HibernateFactory; 4 | import cn.hutool.json.JSONArray; 5 | import cn.travellerr.onebotApi.Text; 6 | import cn.travellerr.onebottelegram.command.CommandHandler; 7 | import cn.travellerr.onebottelegram.converter.TelegramToOnebot; 8 | import cn.travellerr.onebottelegram.hibernate.entity.Group; 9 | import cn.travellerr.onebottelegram.hibernate.entity.Message; 10 | import cn.travellerr.onebottelegram.onebotWebsocket.onebotSerialize.OnebotAction; 11 | import cn.travellerr.onebottelegram.telegramApi.TelegramApi; 12 | import cn.travellerr.onebottelegram.webui.entity.BotInfo; 13 | import com.google.gson.JsonArray; 14 | import org.springframework.web.bind.annotation.*; 15 | 16 | import java.util.Comparator; 17 | import java.util.List; 18 | import java.util.Map; 19 | 20 | @RestController 21 | @RequestMapping("/api") 22 | public class ApiController { 23 | @GetMapping("/bot-info") 24 | public BotInfo getBotInfo(@RequestParam(value = "withAvatar", defaultValue = "false") boolean withAvatar) { 25 | return new BotInfo(TelegramApi.getMeResponse, TelegramApi.botAvatar, withAvatar); 26 | } 27 | 28 | @GetMapping("/bot-contacts") 29 | public List getBotContacts() { 30 | return HibernateFactory.selectList(Group.class); 31 | } 32 | 33 | @PostMapping("/bot-contacts/send-msg") 34 | public boolean sendMsgToContact(@RequestBody Map request) { 35 | try { 36 | String msg = (String) request.get("msg"); 37 | long contactId = ((Number) request.get("contactId")).longValue(); 38 | Boolean isGroup = (Boolean) request.get("isGroup"); 39 | Text text = new Text(msg); 40 | JSONArray array = new JSONArray(); 41 | array.add(text); 42 | OnebotAction.sendMessage("0", contactId, array.toString(), isGroup); 43 | return true; 44 | } catch (Exception e) { 45 | e.printStackTrace(); 46 | return false; 47 | } 48 | } 49 | 50 | @PostMapping("/toa/command") 51 | public String useCommand(@RequestBody Map request) { 52 | String command = (String) request.get("command"); 53 | 54 | return CommandHandler.INSTANCE.handleCommand(command); 55 | } 56 | 57 | @PostMapping("/toa/chat-history") 58 | public String getChatHistory(@RequestBody Map request) { 59 | int limit = ((Number) request.get("limit")).intValue(); 60 | List messages = HibernateFactory.selectList(Message.class); 61 | int toIndex = Math.min(messages.size(), limit); 62 | messages = messages.subList(messages.size() - toIndex, messages.size()); 63 | messages.sort(Comparator.comparing(Message::getCreateTime)); 64 | if (!messages.isEmpty()) { 65 | JsonArray realMessages = new JsonArray(); 66 | messages.forEach(message -> realMessages.add(TelegramToOnebot.handleTextMessage(message.getMessageString()))); 67 | return realMessages.toString(); 68 | } 69 | return new JsonArray().toString(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /src/main/kotlin/cn/travellerr/onebotApi/MessageApi.kt: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebotApi 2 | 3 | import kotlinx.serialization.SerialName 4 | import kotlinx.serialization.Serializable 5 | 6 | @Serializable 7 | data class GroupMessage( 8 | @SerialName("time") 9 | val time: Long, 10 | 11 | @SerialName("self_id") 12 | val self_id: Long, 13 | 14 | @SerialName("post_type") 15 | val post_type: String, 16 | 17 | @SerialName("message_type") 18 | val message_type: String, 19 | 20 | @SerialName("sub_type") 21 | val sub_type: String, 22 | 23 | @SerialName("message_id") 24 | val message_id: Int, 25 | 26 | @SerialName("group_id") 27 | val group_id: Long, 28 | 29 | @SerialName("user_id") 30 | val user_id: Long, 31 | 32 | @SerialName("anonymous") 33 | val anonymous: Anonymous?, 34 | 35 | 36 | @SerialName("raw_message") 37 | val raw_message: String, 38 | 39 | @SerialName("font") 40 | val font: Int, 41 | 42 | @SerialName("sender") 43 | val sender: Sender? = null 44 | ) 45 | 46 | @Serializable 47 | data class PrivateMessage( 48 | @SerialName("time") 49 | val time: Long, 50 | 51 | @SerialName("self_id") 52 | val self_id: Long, 53 | 54 | @SerialName("post_type") 55 | val post_type: String, 56 | 57 | @SerialName("message_type") 58 | val message_type: String, 59 | 60 | @SerialName("sub_type") 61 | val sub_type: String, 62 | 63 | @SerialName("message_id") 64 | val message_id: Int, 65 | 66 | @SerialName("user_id") 67 | val user_id: Long, 68 | 69 | @SerialName("raw_message") 70 | val raw_message: String, 71 | 72 | @SerialName("font") 73 | val font: Int, 74 | 75 | @SerialName("sender") 76 | val sender: Sender? = null, 77 | 78 | ) 79 | 80 | @Serializable 81 | data class Data( 82 | val echo: String, 83 | val message: String? = null, 84 | val retcode: Int = 0, 85 | val status: String = "ok", 86 | val wording: String? = null 87 | ) { 88 | constructor(echo: String) : this(echo, null, 0, "ok", null) 89 | 90 | constructor(echo: String, status: Boolean) : this(echo, null, 0, if (status) "ok" else "failed", null) 91 | 92 | companion object { 93 | 94 | fun parse(json: String): Data { 95 | return Json.decodeFromString(serializer(), json) 96 | } 97 | } 98 | 99 | override fun toString() : String { 100 | return Json.encodeToString(serializer(), this) 101 | } 102 | } 103 | 104 | 105 | interface ArrayMessage{ 106 | val type: String 107 | } 108 | 109 | @Serializable 110 | data class Text( 111 | override val type: String = "text", 112 | val data: TextData 113 | ) : ArrayMessage { 114 | constructor(text: String) : this("text", TextData(text)) 115 | override fun toString() : String { 116 | return Json.encodeToString(serializer(), this) 117 | } 118 | } 119 | 120 | @Serializable 121 | data class At( 122 | override val type: String = "at", 123 | val data: AtData 124 | ) : ArrayMessage { 125 | constructor(userId: Long) : this("at", AtData(userId)) 126 | } 127 | 128 | @Serializable 129 | data class Image( 130 | override val type: String = "image", 131 | val data: File 132 | ) : ArrayMessage { 133 | constructor(file: String) : this("image", File(file)) 134 | } 135 | 136 | @Serializable 137 | data class Reply( 138 | override val type: String = "reply", 139 | val data: Id 140 | ) : ArrayMessage { 141 | constructor(messageId: Long) : this("reply", Id(messageId)) 142 | } -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/config/Config.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.config; 2 | 3 | import cn.chahuyun.hibernateplus.DriveType; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | import java.io.Serializable; 10 | import java.util.Map; 11 | 12 | 13 | @Data 14 | @Builder 15 | @AllArgsConstructor 16 | @NoArgsConstructor 17 | @ConfigEntity(name = "config", filePath = "./") 18 | public class Config implements Serializable { 19 | 20 | private telegram telegram; 21 | private onebot onebot; 22 | private spring spring; 23 | private command command; 24 | 25 | 26 | @Data 27 | @Builder 28 | @AllArgsConstructor 29 | @NoArgsConstructor 30 | public static class telegram implements Serializable { 31 | 32 | private Config.telegram.bot bot; 33 | private Config.telegram.webhook webhook; 34 | 35 | @Data 36 | @Builder 37 | @AllArgsConstructor 38 | @NoArgsConstructor 39 | public static class bot implements Serializable { 40 | private String token; 41 | private String username; 42 | private Config.telegram.bot.proxy proxy; 43 | private boolean useTranslator; 44 | 45 | @Data 46 | @Builder 47 | @AllArgsConstructor 48 | @NoArgsConstructor 49 | public static class proxy implements Serializable { 50 | private String host; 51 | private int port; 52 | private String username; 53 | private String secret; 54 | private String type; 55 | } 56 | 57 | 58 | } 59 | 60 | @Data 61 | @Builder 62 | @AllArgsConstructor 63 | @NoArgsConstructor 64 | public static class webhook implements Serializable { 65 | private String certPath; 66 | private String secret; 67 | private String url; 68 | private int port; 69 | private boolean useWebhook; 70 | } 71 | } 72 | 73 | @Data 74 | @Builder 75 | @AllArgsConstructor 76 | @NoArgsConstructor 77 | public static class onebot implements Serializable { 78 | private String ip; 79 | private String path; 80 | private int port; 81 | private String token; 82 | private boolean useArray; 83 | private boolean banGroupUser; 84 | private String groupUserWarning; 85 | private boolean picBase64; 86 | private int silkSampleRate; 87 | } 88 | 89 | @Data 90 | @Builder 91 | @AllArgsConstructor 92 | @NoArgsConstructor 93 | public static class spring implements Serializable { 94 | private Config.spring.database database; 95 | private Config.spring.webui webui; 96 | private String ffmpegPath; 97 | 98 | 99 | @Data 100 | @Builder 101 | @AllArgsConstructor 102 | @NoArgsConstructor 103 | public static class database implements Serializable { 104 | private DriveType dataType; 105 | private String mysqlUrl; 106 | private String mysqlUser; 107 | private String mysqlPassword; 108 | } 109 | 110 | @Data 111 | @Builder 112 | @AllArgsConstructor 113 | @NoArgsConstructor 114 | public static class webui implements Serializable { 115 | private String userName; 116 | private String password; 117 | } 118 | } 119 | 120 | @Data 121 | @Builder 122 | @AllArgsConstructor 123 | @NoArgsConstructor 124 | public static class command implements Serializable { 125 | private String prefix; 126 | private Map menu; 127 | private Map commandMap; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /.github/workflows/gradle.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | # This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time 6 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle 7 | 8 | name: Java CI with Gradle 9 | 10 | on: 11 | push: 12 | branches: [ "master" ] 13 | pull_request: 14 | branches: [ "master" ] 15 | workflow_dispatch: 16 | 17 | jobs: 18 | build: 19 | 20 | runs-on: ubuntu-latest 21 | permissions: 22 | contents: read 23 | 24 | steps: 25 | - uses: actions/checkout@v4 26 | - name: Set up JDK 17 27 | uses: actions/setup-java@v4 28 | with: 29 | java-version: '17' 30 | distribution: 'temurin' 31 | 32 | # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. 33 | # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md 34 | - name: Setup Gradle 35 | uses: gradle/actions/setup-gradle@af1da67850ed9a4cedd57bfd976089dd991e2582 # v4.0.0 36 | with: 37 | gradle-version: '8.0' 38 | 39 | - name: Build with Gradle 8.0 40 | run: gradle build 41 | 42 | - name: Upload build artifacts 43 | uses: actions/upload-artifact@v4 44 | with: 45 | name: build-artifacts 46 | path: ./build/libs/ 47 | 48 | # NOTE: The Gradle Wrapper is the default and recommended way to run Gradle (https://docs.gradle.org/current/userguide/gradle_wrapper.html). 49 | # If your project does not have the Gradle Wrapper configured, you can use the following configuration to run Gradle with a specified version. 50 | # 51 | # - name: Setup Gradle 52 | # uses: gradle/actions/setup-gradle@af1da67850ed9a4cedd57bfd976089dd991e2582 # v4.0.0 53 | # with: 54 | # gradle-version: '8.9' 55 | # 56 | # - name: Build with Gradle 8.9 57 | # run: gradle build 58 | 59 | prepare_release: 60 | needs: build 61 | runs-on: ubuntu-latest 62 | steps: 63 | - name: Download artifacts 64 | uses: actions/download-artifact@v4 65 | with: 66 | name: build-artifacts 67 | path: output 68 | 69 | - name: Set tag name 70 | id: set_tag_name 71 | run: echo "::set-output name=tag_name::v$(ls output/Tele-KiraLink-*.jar | grep -v 'plain' | grep -oP '(?<=KiraLink-)[^-]+' | sed 's/\.jar$//')" 72 | 73 | 74 | - name: Create Release 75 | id: create_release 76 | uses: actions/create-release@v1 77 | env: 78 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 79 | with: 80 | tag_name: ${{ steps.set_tag_name.outputs.tag_name }} 81 | release_name: Tele-KiraLink ${{ steps.set_tag_name.outputs.tag_name }} 82 | draft: true 83 | 84 | - name: Upload Release Assets 85 | run: | 86 | for file in output/*; do 87 | if [ -f "$file" ]; then 88 | asset_name=$(basename "$file") 89 | echo "Uploading ${asset_name}" 90 | GITHUB_UPLOAD_URL=${{ steps.create_release.outputs.upload_url }} 91 | GITHUB_UPLOAD_URL="${GITHUB_UPLOAD_URL%\{*}" 92 | GITHUB_UPLOAD_URL="${GITHUB_UPLOAD_URL%\?*}" 93 | curl \ 94 | -X POST \ 95 | -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ 96 | -H "Content-Type: application/octet-stream" \ 97 | --data-binary @"${file}" \ 98 | "${GITHUB_UPLOAD_URL}?name=${asset_name}&label=${asset_name}" 99 | else 100 | echo "Expected a file in output, but found something else." 101 | fi 102 | done 103 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/hibernate/entity/Group.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.hibernate.entity; 2 | 3 | import cn.chahuyun.hibernateplus.HibernateFactory; 4 | import cn.hutool.core.util.StrUtil; 5 | import jakarta.persistence.*; 6 | import lombok.AllArgsConstructor; 7 | import lombok.Builder; 8 | import lombok.Data; 9 | import lombok.NoArgsConstructor; 10 | 11 | import java.util.ArrayList; 12 | import java.util.Arrays; 13 | import java.util.List; 14 | import java.util.stream.Collectors; 15 | 16 | @Data 17 | @AllArgsConstructor 18 | @NoArgsConstructor 19 | @Builder 20 | @Table(name = "`Group`") 21 | @Entity 22 | public class Group { 23 | @Id 24 | private Long groupId; 25 | 26 | private String groupName; 27 | 28 | private String groupDescription; 29 | 30 | private int memberCount; 31 | 32 | @Builder.Default 33 | private int maxMemberCount = 2000; 34 | 35 | @Column(length = 4096) 36 | private String memberIds; 37 | 38 | @Column(length = 4096) 39 | private String memberUserNames; 40 | 41 | @Transient 42 | private List membersIdList; 43 | 44 | @Transient 45 | private List membersUserNameList; 46 | 47 | 48 | 49 | 50 | public List getMembersIdList() { 51 | this.membersIdList = new ArrayList<>(); 52 | if (StrUtil.isNotBlank(memberIds)) { 53 | for (String s : memberIds.split(",")) { 54 | membersIdList.add(Long.parseLong(s)); 55 | } 56 | } else { 57 | membersIdList = new ArrayList<>(); 58 | } 59 | return membersIdList; 60 | } 61 | 62 | public void setMembersId(List membersIdList) { 63 | this.membersIdList = membersIdList; 64 | this.memberIds = membersIdList.stream() 65 | .map(Object::toString) 66 | .collect(Collectors.joining(",")); 67 | } 68 | 69 | public void addMemberId(Long member) { 70 | this.membersIdList = getMembersIdList(); 71 | if (membersIdList!= null && membersIdList.contains(member)) { 72 | return; 73 | } 74 | membersIdList.add(member); 75 | this.memberIds = membersIdList.stream() 76 | .map(Object::toString) 77 | .collect(Collectors.joining(",")); 78 | 79 | HibernateFactory.merge(this); 80 | } 81 | 82 | public void removeMemberId(Long member) { 83 | this.membersIdList = getMembersIdList(); 84 | membersIdList.remove(member); 85 | this.memberIds = membersIdList.stream() 86 | .map(Object::toString) 87 | .collect(Collectors.joining(",")); 88 | } 89 | 90 | 91 | public List getMemberUsernamesList() { 92 | this.membersUserNameList = new ArrayList<>(); 93 | if (StrUtil.isNotBlank(memberUserNames)) { 94 | membersUserNameList.addAll(Arrays.asList(memberUserNames.split(","))); 95 | } else { 96 | membersUserNameList = new ArrayList<>(); 97 | } 98 | return membersUserNameList; 99 | } 100 | 101 | public void setMemberUsernames(List membersUserNameList) { 102 | this.membersUserNameList = membersUserNameList; 103 | this.memberUserNames = membersUserNameList.stream() 104 | .map(Object::toString) 105 | .collect(Collectors.joining(",")); 106 | } 107 | 108 | public void addMemberUsernames(String member) { 109 | this.membersUserNameList = getMemberUsernamesList(); 110 | if (membersUserNameList!= null && membersUserNameList.contains(member)) { 111 | return; 112 | } 113 | membersUserNameList.add(member); 114 | System.out.println("new member was found: " + member); 115 | this.memberUserNames = membersUserNameList.stream() 116 | .map(Object::toString) 117 | .collect(Collectors.joining(",")); 118 | 119 | HibernateFactory.merge(this); 120 | } 121 | 122 | public void removeMemberUsernames(String member) { 123 | this.membersUserNameList = getMemberUsernamesList(); 124 | membersUserNameList.remove(member); 125 | this.memberUserNames = membersUserNameList.stream() 126 | .map(Object::toString) 127 | .collect(Collectors.joining(",")); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/main/resources/static/css/index.css: -------------------------------------------------------------------------------- 1 | :root { 2 | --sidebar-width: 280px; 3 | --primary-color: #2c3e50; 4 | --secondary-color: #3498db; 5 | } 6 | 7 | body { 8 | margin: 0; 9 | display: flex; 10 | height: 100vh; 11 | font-family: 'Segoe UI', sans-serif; 12 | } 13 | 14 | /* 左侧侧边栏 */ 15 | #sidebar { 16 | width: var(--sidebar-width); 17 | background: var(--primary-color); 18 | color: white; 19 | transition: 0.3s; 20 | position: relative; 21 | } 22 | 23 | #sidebar.active { 24 | } 25 | 26 | /* 折叠按钮 */ 27 | #toggle-btn { 28 | position: absolute; 29 | right: -40px; 30 | top: 20px; 31 | 32 | border: none; 33 | color: white; 34 | padding: 10px; 35 | cursor: pointer; 36 | border-radius: 0 5px 5px 0; 37 | } 38 | 39 | /* 机器人信息区域 */ 40 | .bot-info { 41 | padding: 20px; 42 | } 43 | 44 | .avatar { 45 | width: 130px; 46 | height: 130px; 47 | border-radius: 50%; 48 | margin: 0 auto; 49 | display: block; 50 | } 51 | 52 | /* 控制台区域 */ 53 | #console { 54 | flex: 1; 55 | background: #ecf0f1; 56 | display: flex; 57 | flex-direction: column; 58 | } 59 | 60 | /* 消息显示区域 */ 61 | .log-area { 62 | flex: 1; 63 | padding: 20px; 64 | overflow-y: auto; 65 | background: white; 66 | margin: 10px; 67 | border-radius: 5px; 68 | } 69 | 70 | /* 输入控制区域 */ 71 | .input-container { 72 | padding: 20px; 73 | background: white; 74 | margin: 10px; 75 | border-radius: 5px; 76 | display: flex; 77 | gap: 10px; 78 | } 79 | 80 | /* 功能选择菜单 */ 81 | .function-menu { 82 | position: relative; 83 | display: inline-block; 84 | } 85 | 86 | .menu-content { 87 | display: none; 88 | position: absolute; 89 | bottom: 100%; 90 | background: white; 91 | box-shadow: 0 2px 5px rgba(0,0,0,0.2); 92 | min-width: 200px; 93 | z-index: 1; 94 | } 95 | 96 | .show { display: block; } 97 | 98 | /* 新增移动端样式 */ 99 | @media screen and (max-width: 60rem) { 100 | :root { 101 | --sidebar-width: 100%; /* 移动端侧边栏全宽 */ 102 | --avatar-size: 80px; /* 缩小头像尺寸 */ 103 | } 104 | 105 | body { 106 | flex-direction: column; 107 | height: auto; 108 | min-height: 100vh; 109 | } 110 | 111 | #toggle-btn { 112 | position: fixed; 113 | right: 20px; 114 | bottom: 20px; 115 | background: var(--secondary-color); 116 | border-radius: 50%; 117 | width: 50px; 118 | height: 50px; 119 | box-shadow: 0 4px 12px rgba(0,0,0,0.2); 120 | z-index: 3000; 121 | transition: transform 0.3s; 122 | } 123 | 124 | #sidebar { 125 | position: fixed; 126 | top: -100%; 127 | left: 0; 128 | right: 0; 129 | height: auto; 130 | max-height: 80vh; 131 | overflow-y: auto; 132 | transition: top 0.3s; 133 | } 134 | 135 | #sidebar.active { 136 | top: 0; 137 | left: 0; 138 | } 139 | 140 | .bot-info { 141 | padding: 15px; 142 | text-align: center; 143 | } 144 | 145 | .avatar { 146 | width: var(--avatar-size); 147 | height: var(--avatar-size); 148 | } 149 | 150 | #console { 151 | margin-top: 60px; /* 为移动端顶部留出空间 */ 152 | min-height: calc(100vh - 60px); 153 | } 154 | 155 | .log-area { 156 | margin: 5px; 157 | padding: 10px; 158 | font-size: 30px; 159 | } 160 | 161 | .input-container { 162 | flex-direction: column; 163 | padding: 10px; 164 | margin: 5px; 165 | } 166 | 167 | .function-menu { 168 | order: -1; /* 将菜单按钮移到最前 */ 169 | align-self: flex-start; 170 | } 171 | 172 | #contact-list { 173 | width: 100%; 174 | max-height: 150px; 175 | overflow-y: auto; 176 | } 177 | 178 | /* 添加在移动端媒体查询内 */ 179 | #toggle-btn::after { 180 | font-size: 24px; 181 | position: absolute; 182 | left: 50%; 183 | top: 50%; 184 | transform: translate(-50%, -50%); 185 | } 186 | 187 | .log-entry { 188 | font-size: 0.5em; 189 | padding: 8px; 190 | line-height: 1.4; 191 | } 192 | 193 | .mobile-contact-list { 194 | position: fixed; 195 | top: 0; 196 | left: 0; 197 | right: 0; 198 | bottom: 0; 199 | background: white; 200 | z-index: 2000; 201 | padding: 20px; 202 | } 203 | } -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/command/CommandHandler.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.command; 2 | 3 | import cn.chahuyun.hibernateplus.HibernateFactory; 4 | import cn.travellerr.onebottelegram.TelegramOnebotAdapter; 5 | import cn.travellerr.onebottelegram.config.ConfigGenerator; 6 | import cn.travellerr.onebottelegram.hibernate.entity.Message; 7 | import cn.travellerr.onebottelegram.webui.api.LogWebSocketHandler; 8 | import org.jline.reader.LineReader; 9 | import org.jline.reader.LineReaderBuilder; 10 | import org.jline.reader.impl.history.DefaultHistory; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | 14 | import java.util.List; 15 | import java.util.Locale; 16 | import java.util.concurrent.CompletableFuture; 17 | import java.util.concurrent.ExecutorService; 18 | import java.util.concurrent.Executors; 19 | import java.util.concurrent.atomic.AtomicBoolean; 20 | 21 | public class CommandHandler { 22 | 23 | public static final CommandHandler INSTANCE = new CommandHandler(); 24 | 25 | private final ExecutorService executorService = Executors.newCachedThreadPool(); 26 | 27 | private static final Logger log = LoggerFactory.getLogger(CommandHandler.class); 28 | 29 | public static void startCommandConsole() { 30 | CommandHandler commandHandler = new CommandHandler(); 31 | DefaultHistory history = new DefaultHistory(); 32 | LineReader reader = LineReaderBuilder.builder() 33 | .history(history) 34 | .build(); 35 | 36 | // Start a new thread to read input from the console 37 | 38 | CompletableFuture.runAsync(() -> { 39 | while (!Thread.currentThread().isInterrupted()) { 40 | String command = reader.readLine("> "); 41 | log.info(commandHandler.handleCommand(command)); 42 | } 43 | }, commandHandler.executorService); 44 | 45 | } 46 | 47 | public String handleCommand(String command) { 48 | // 解析指令 49 | String[] parts = command.split(" "); 50 | String action = parts[0].toLowerCase(Locale.ROOT); 51 | String[] args = new String[parts.length - 1]; 52 | System.arraycopy(parts, 1, args, 0, args.length); 53 | 54 | if (action.startsWith("/")) { 55 | action = action.substring(1); 56 | } 57 | 58 | // 执行相应的操作 59 | return switch (action) { 60 | case "test" -> test(args); 61 | case "reload" -> reloadConfig(); 62 | case "cleanchathistory" -> clean(); 63 | case "gc" -> { 64 | System.gc(); 65 | yield "Garbage collection triggered."; 66 | } 67 | case "help" -> "Available commands: test, reload, help, stop, cleanChatHistory, gc"; 68 | case "stop" -> { 69 | new Thread(() -> { 70 | try { 71 | Thread.sleep(1000); 72 | executorService.shutdown(); 73 | System.exit(0); 74 | } catch (InterruptedException e) { 75 | Thread.currentThread().interrupt(); 76 | } 77 | }).start(); 78 | yield "Stopping Telegram OneBot Adapter..."; 79 | } 80 | default -> "Unknown command: " + action; 81 | }; 82 | } 83 | 84 | private String clean() { 85 | List messages = HibernateFactory.selectList(Message.class); 86 | new Thread(() -> { 87 | AtomicBoolean deleteSuccess = new AtomicBoolean(true); 88 | messages.forEach(m -> deleteSuccess.set(HibernateFactory.delete(m))); 89 | messages.forEach(m -> deleteSuccess.set(HibernateFactory.delete(m))); 90 | if (deleteSuccess.get()) { 91 | log.info("Chat history cleaned successfully."); 92 | LogWebSocketHandler.broadcast("Chat history cleaned successfully."); 93 | } else { 94 | log.error("Failed to clean chat history."); 95 | LogWebSocketHandler.broadcast("Failed to clean chat history."); 96 | } 97 | }).start(); 98 | 99 | 100 | return "Cleaning chat history, total messages: " + messages.size() + ", please wait..."; 101 | } 102 | 103 | private String reloadConfig() { 104 | TelegramOnebotAdapter.config = ConfigGenerator.loadConfig(); 105 | return TelegramOnebotAdapter.config.getCommand().getCommandMap().toString(); 106 | } 107 | 108 | private String test(String[] args) { 109 | if (args.length > 0) { 110 | return "Hello, " + String.join(" ", args) + "!"; 111 | } else { 112 | return "Hello!"; 113 | } 114 | } 115 | } -------------------------------------------------------------------------------- /src/main/kotlin/cn/travellerr/onebotApi/SubClassApi.kt: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebotApi 2 | 3 | import kotlinx.serialization.SerialName 4 | import kotlinx.serialization.Serializable 5 | import kotlinx.serialization.serializer 6 | 7 | interface OnebotSubClassApi { 8 | companion object { 9 | fun parse(json: String): OnebotSubClassApi { 10 | return Json.decodeFromString(serializer(), json) 11 | } 12 | } 13 | } 14 | 15 | interface Group { 16 | val group_id: Long 17 | val group_name: String 18 | val member_count: Int 19 | val max_member_count: Int 20 | } 21 | 22 | interface Member { 23 | val group_id: Long 24 | val user_id: Long 25 | val nickname: String 26 | val card: String 27 | val sex: String 28 | val age: Int 29 | val area: String 30 | val joinTime: Int 31 | val last_sent_time: Int 32 | val level: String 33 | val role: String 34 | val unfriendly: Boolean 35 | val title: String 36 | val title_expire_time: Int 37 | val card_changeable: Boolean 38 | } 39 | 40 | @Serializable 41 | data class Friend ( 42 | @SerialName("user_id") 43 | val userId: Long, 44 | 45 | @SerialName("nickname") 46 | val nickname: String, 47 | 48 | @SerialName("remark") 49 | val remark: String 50 | ) : OnebotSubClassApi { 51 | companion object { 52 | fun parse(json: String): Friend { 53 | return Json.decodeFromString(serializer(), json) 54 | } 55 | } 56 | } 57 | 58 | @Serializable 59 | data class GroupInfo ( 60 | @SerialName("group_id") 61 | override val group_id: Long, 62 | 63 | @SerialName("group_name") 64 | override val group_name: String, 65 | 66 | @SerialName("member_count") 67 | override val member_count: Int, 68 | 69 | @SerialName("max_member_count") 70 | override val max_member_count: Int 71 | ) : OnebotSubClassApi, Group { 72 | companion object { 73 | fun parse(json: String): GroupInfo { 74 | return Json.decodeFromString(serializer(), json) 75 | } 76 | } 77 | } 78 | 79 | 80 | @Serializable 81 | data class MemberInfo ( 82 | @SerialName("group_id") 83 | override val group_id: Long, 84 | 85 | @SerialName("user_id") 86 | override val user_id: Long, 87 | 88 | @SerialName("nickname") 89 | override val nickname: String, 90 | 91 | @SerialName("card") 92 | override val card: String, 93 | 94 | @SerialName("sex") 95 | override val sex: String, 96 | 97 | @SerialName("age") 98 | override val age: Int, 99 | 100 | @SerialName("area") 101 | override val area: String, 102 | 103 | @SerialName("join_time") 104 | override val joinTime: Int, 105 | 106 | @SerialName("last_sent_time") 107 | override val last_sent_time: Int, 108 | 109 | @SerialName("level") 110 | override val level: String, 111 | 112 | @SerialName("role") 113 | override val role: String, 114 | 115 | @SerialName("unfriendly") 116 | override val unfriendly: Boolean, 117 | 118 | @SerialName("title") 119 | override val title: String, 120 | 121 | @SerialName("title_expire_time") 122 | override val title_expire_time: Int, 123 | 124 | @SerialName("card_changeable") 125 | override val card_changeable: Boolean 126 | ) : OnebotSubClassApi, Member { 127 | companion object { 128 | fun parse(json: String): MemberInfo { 129 | return Json.decodeFromString(serializer(), json) 130 | } 131 | } 132 | } 133 | 134 | @Serializable 135 | data class Sender ( 136 | @SerialName("user_id") 137 | val user_id: Long, 138 | 139 | @SerialName("nickname") 140 | val nickname: String, 141 | 142 | @SerialName("card") 143 | val card: String? = null, 144 | 145 | @SerialName("sex") 146 | val sex: String, 147 | 148 | @SerialName("age") 149 | val age: Int, 150 | 151 | @SerialName("area") 152 | val area: String? = null, 153 | 154 | @SerialName("level") 155 | val level: String? = null, 156 | 157 | @SerialName("role") 158 | val role: String? = null, 159 | 160 | @SerialName("title") 161 | val title: String? = null 162 | ) { 163 | 164 | companion object { 165 | fun parse(json: String): Sender { 166 | return Json.decodeFromString(serializer(), json) 167 | } 168 | } 169 | 170 | override fun toString(): String { 171 | return Json.encodeToString(serializer(), this) 172 | } 173 | } 174 | 175 | 176 | @Serializable 177 | data class Anonymous( 178 | @SerialName("id") 179 | val id: Long, 180 | 181 | @SerialName("name") 182 | val name: String, 183 | 184 | @SerialName("flag") 185 | val flag: String 186 | ) { 187 | companion object { 188 | fun parse(json: String): Anonymous { 189 | return Json.decodeFromString(serializer(), json) 190 | } 191 | } 192 | } 193 | 194 | @Serializable 195 | data class TextData( 196 | val text: String 197 | ) 198 | 199 | @Serializable 200 | data class AtData( 201 | val qq: Long, 202 | ) 203 | 204 | @Serializable 205 | data class File( 206 | val file: String 207 | ) 208 | 209 | @Serializable 210 | data class Id( 211 | val id: Long 212 | ) -------------------------------------------------------------------------------- /src/main/kotlin/cn/travellerr/onebotApi/ResponseApi.kt: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebotApi 2 | 3 | import kotlinx.serialization.SerialName 4 | import kotlinx.serialization.Serializable 5 | 6 | interface OnebotResponseApi 7 | 8 | @Serializable 9 | data class GetVersionInfo( 10 | @SerialName("app_name") 11 | val app_name: String, 12 | 13 | @SerialName("app_version") 14 | val app_version: String, 15 | 16 | @SerialName("protocol_version") 17 | val protocol_version: String 18 | ) : OnebotResponseApi{ 19 | companion object { 20 | const val API = "/get_version_info" 21 | 22 | fun parse(json: String): GetVersionInfo { 23 | return Json.decodeFromString(serializer(), json) 24 | } 25 | } 26 | 27 | override fun toString() : String { 28 | print(Json.encodeToString(serializer(), this)) 29 | return Json.encodeToString(serializer(), this) 30 | } 31 | } 32 | 33 | @Serializable 34 | data class GetLoginInfo( 35 | @SerialName("user_id") 36 | val user_id: Long, 37 | 38 | @SerialName("nickname") 39 | val nickname: String 40 | ) : OnebotResponseApi{ 41 | companion object { 42 | const val API = "/get_login_info" 43 | 44 | fun parse(json: String): GetLoginInfo { 45 | return Json.decodeFromString(serializer(), json) 46 | } 47 | } 48 | 49 | override fun toString() : String { 50 | return Json.encodeToString(serializer(), this) 51 | } 52 | } 53 | 54 | @Serializable 55 | data class GetStatus( 56 | @SerialName("online") 57 | val online: Boolean, 58 | 59 | @SerialName("good") 60 | val good: Boolean 61 | ) : OnebotResponseApi{ 62 | companion object { 63 | const val API = "/get_status" 64 | 65 | fun parse(json: String): GetStatus { 66 | return Json.decodeFromString(serializer(), json) 67 | } 68 | } 69 | } 70 | 71 | @Serializable 72 | data class GetFriendList( 73 | val friend_list: List 74 | ) : OnebotResponseApi{ 75 | companion object { 76 | const val API = "/get_friend_list" 77 | 78 | fun parse(json: String): GetFriendList { 79 | return Json.decodeFromString(serializer(), json) 80 | } 81 | } 82 | } 83 | 84 | @Serializable 85 | data class GetGroupList( 86 | @SerialName("group_list") 87 | val groupInfo_list: List 88 | ) : OnebotResponseApi{ 89 | companion object { 90 | const val API = "/get_group_list" 91 | 92 | fun parse(json: String): GetGroupList { 93 | return Json.decodeFromString(serializer(), json) 94 | } 95 | } 96 | } 97 | 98 | 99 | @Serializable 100 | data class GetGroupInfoResponse ( 101 | @SerialName("group_id") 102 | override val group_id: Long, 103 | 104 | @SerialName("group_name") 105 | override val group_name: String, 106 | 107 | @SerialName("member_count") 108 | override val member_count: Int, 109 | 110 | @SerialName("max_member_count") 111 | override val max_member_count: Int 112 | ): OnebotResponseApi, Group { 113 | companion object { 114 | const val API = "/get_group_info" 115 | 116 | fun parse(json: String): GetGroupInfoResponse { 117 | return Json.decodeFromString(serializer(), json) 118 | } 119 | } 120 | } 121 | 122 | @Serializable 123 | data class SendMessageResponse( 124 | @SerialName("message_id") 125 | val message_id: Long 126 | ) : OnebotResponseApi{ 127 | companion object { 128 | const val API = "/send_msg" 129 | 130 | fun parse(json: String): SendMessageResponse { 131 | return Json.decodeFromString(serializer(), json) 132 | } 133 | } 134 | } 135 | 136 | @Serializable 137 | data class GetGroupMemberInfoResponse( 138 | @SerialName("group_id") 139 | override val group_id: Long, 140 | 141 | @SerialName("user_id") 142 | override val user_id: Long, 143 | 144 | @SerialName("nickname") 145 | override val nickname: String, 146 | 147 | @SerialName("card") 148 | override val card: String, 149 | 150 | @SerialName("sex") 151 | override val sex: String, 152 | 153 | @SerialName("age") 154 | override val age: Int, 155 | 156 | @SerialName("area") 157 | override val area: String, 158 | 159 | @SerialName("join_time") 160 | override val joinTime: Int, 161 | 162 | @SerialName("last_sent_time") 163 | override val last_sent_time: Int, 164 | 165 | @SerialName("level") 166 | override val level: String, 167 | 168 | @SerialName("role") 169 | override val role: String, 170 | 171 | @SerialName("unfriendly") 172 | override val unfriendly: Boolean, 173 | 174 | @SerialName("title") 175 | override val title: String, 176 | 177 | @SerialName("title_expire_time") 178 | override val title_expire_time: Int, 179 | 180 | @SerialName("card_changeable") 181 | override val card_changeable: Boolean 182 | ) : OnebotResponseApi, Member { 183 | companion object { 184 | fun parse(json: String): GetGroupMemberInfoResponse { 185 | return Json.decodeFromString(serializer(), json) 186 | } 187 | } 188 | } 189 | 190 | @Serializable 191 | data class GetGroupMemberListResponse( 192 | @SerialName("member_list") 193 | val memberList: List 194 | ) : OnebotResponseApi { 195 | companion object { 196 | const val API = "/get_group_member_list" 197 | 198 | fun parse(json: String): GetGroupMemberListResponse { 199 | return Json.decodeFromString(serializer(), json) 200 | } 201 | } 202 | } -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/onebotWebsocket/OneBotWebSocketHandler.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.onebotWebsocket; 2 | 3 | import cn.travellerr.onebottelegram.TelegramOnebotAdapter; 4 | import cn.travellerr.onebottelegram.onebotWebsocket.onebotSerialize.OnebotAction; 5 | import cn.travellerr.onebottelegram.telegramApi.TelegramApi; 6 | import com.fasterxml.jackson.core.JsonFactory; 7 | import com.fasterxml.jackson.core.StreamReadConstraints; 8 | import com.fasterxml.jackson.databind.JsonNode; 9 | import com.fasterxml.jackson.databind.ObjectMapper; 10 | import com.google.gson.JsonObject; 11 | import org.jetbrains.annotations.NotNull; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import org.springframework.stereotype.Component; 15 | import org.springframework.web.socket.CloseStatus; 16 | import org.springframework.web.socket.TextMessage; 17 | import org.springframework.web.socket.WebSocketSession; 18 | import org.springframework.web.socket.handler.TextWebSocketHandler; 19 | 20 | import java.io.IOException; 21 | import java.util.Map; 22 | import java.util.Set; 23 | import java.util.concurrent.ConcurrentHashMap; 24 | 25 | @Component 26 | public class OneBotWebSocketHandler extends TextWebSocketHandler { 27 | 28 | public static OneBotWebSocketHandler INSTANCE = new OneBotWebSocketHandler(); 29 | 30 | private static final Logger log = LoggerFactory.getLogger(OneBotWebSocketHandler.class); 31 | public static final Set sessions = ConcurrentHashMap.newKeySet(); 32 | private final ObjectMapper objectMapper = new ObjectMapper(JsonFactory.builder().streamReadConstraints(StreamReadConstraints.builder() 33 | .maxStringLength(102400000).build()).build()); 34 | 35 | @Override 36 | public void afterConnectionEstablished(@NotNull WebSocketSession session) { 37 | if (!isValidAccessToken(session)) { 38 | log.warn("无效的 accessToken,拒绝连接: {}", session.getId()); 39 | try { 40 | session.close(CloseStatus.BAD_DATA); 41 | } catch (IOException e) { 42 | log.error("关闭连接失败", e); 43 | } 44 | return; 45 | } 46 | sessions.add(session); 47 | log.info("新的 OneBot 客户端连接: {}", session.getId()); 48 | try { 49 | JsonObject metaMessage = new JsonObject(); 50 | metaMessage.addProperty("time", System.currentTimeMillis() / 1000); 51 | metaMessage.addProperty("meta_event_type", "lifecycle"); 52 | metaMessage.addProperty("post_type", "meta_event"); 53 | metaMessage.addProperty("sub_type", "connect"); 54 | metaMessage.addProperty("self_id", TelegramApi.getMeResponse.user().id()); 55 | log.info("TKL发送meta消息: {}", metaMessage); 56 | session.sendMessage(new TextMessage(metaMessage.toString())); 57 | } catch (IOException e) { 58 | log.error("发送meta消息失败", e); 59 | } 60 | } 61 | 62 | private boolean isValidAccessToken(WebSocketSession session) { 63 | String query = session.getUri() != null ? session.getUri().getQuery() : null; 64 | String token = ""; 65 | 66 | if (query != null && !query.isEmpty()) { 67 | for (String param : query.split("&")) { 68 | if (param.startsWith("access_token=")) { 69 | token = param.substring("access_token=".length()); 70 | break; 71 | } 72 | } 73 | } 74 | 75 | if (token.isEmpty()) { 76 | String authHeader = session.getHandshakeHeaders().getFirst("Authorization"); 77 | if (authHeader != null && authHeader.startsWith("Bearer ")) { 78 | token = authHeader.substring("Bearer ".length()); 79 | } 80 | } 81 | String expectedToken = TelegramOnebotAdapter.config.getOnebot().getToken(); 82 | if (!expectedToken.equals(token)) { 83 | log.warn("access_token 不匹配: {}", token); 84 | return false; 85 | } 86 | return true; 87 | } 88 | 89 | @Override 90 | protected void handleTextMessage(@NotNull WebSocketSession session, TextMessage message) { 91 | try { 92 | JsonNode payload = objectMapper.readTree(message.getPayload()); 93 | log.info("TKL收到到消息 <-- {}", payload); 94 | 95 | // 处理 OneBot 协议消息(示例:处理心跳) 96 | if (payload.has("meta_event_type") && 97 | "heartbeat".equals(payload.get("meta_event_type").asText())) { 98 | handleHeartbeat(session, payload); 99 | } else { 100 | OnebotAction.handleAction(session, message.getPayload()); 101 | } 102 | 103 | } catch (IOException e) { 104 | log.error("消息解析失败", e); 105 | } 106 | } 107 | 108 | 109 | private void handleHeartbeat(WebSocketSession session, JsonNode payload) { 110 | try { 111 | Map response = Map.of( 112 | "time", payload.get("time").asLong(), 113 | "interval", 5000, 114 | "status", Map.of("online", true) 115 | ); 116 | session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response))); 117 | } catch (IOException e) { 118 | log.error("心跳响应失败", e); 119 | } 120 | } 121 | 122 | @Override 123 | public void afterConnectionClosed(@NotNull WebSocketSession session, @NotNull CloseStatus status) { 124 | sessions.remove(session); 125 | log.info("OneBot 客户端断开: {} - {}", session.getId(), status); 126 | } 127 | 128 | // 广播消息给所有客户端 129 | public static void broadcast(String message) { 130 | sessions.forEach(session -> { 131 | try { 132 | if (session.isOpen()) { 133 | session.sendMessage(new TextMessage(message)); 134 | } 135 | } catch (IOException e) { 136 | log.error("广播消息失败", e); 137 | } 138 | }); 139 | } 140 | 141 | 142 | 143 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tele-KiraLink 2 | 3 | ![](https://img.shields.io/badge/OneBot-11-black?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHAAAABwCAMAAADxPgR5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAxQTFRF////29vbr6+vAAAAk1hCcwAAAAR0Uk5T////AEAqqfQAAAKcSURBVHja7NrbctswDATQXfD//zlpO7FlmwAWIOnOtNaTM5JwDMa8E+PNFz7g3waJ24fviyDPgfhz8fHP39cBcBL9KoJbQUxjA2iYqHL3FAnvzhL4GtVNUcoSZe6eSHizBcK5LL7dBr2AUZlev1ARRHCljzRALIEog6H3U6bCIyqIZdAT0eBuJYaGiJaHSjmkYIZd+qSGWAQnIaz2OArVnX6vrItQvbhZJtVGB5qX9wKqCMkb9W7aexfCO/rwQRBzsDIsYx4AOz0nhAtWu7bqkEQBO0Pr+Ftjt5fFCUEbm0Sbgdu8WSgJ5NgH2iu46R/o1UcBXJsFusWF/QUaz3RwJMEgngfaGGdSxJkE/Yg4lOBryBiMwvAhZrVMUUvwqU7F05b5WLaUIN4M4hRocQQRnEedgsn7TZB3UCpRrIJwQfqvGwsg18EnI2uSVNC8t+0QmMXogvbPg/xk+Mnw/6kW/rraUlvqgmFreAA09xW5t0AFlHrQZ3CsgvZm0FbHNKyBmheBKIF2cCA8A600aHPmFtRB1XvMsJAiza7LpPog0UJwccKdzw8rdf8MyN2ePYF896LC5hTzdZqxb6VNXInaupARLDNBWgI8spq4T0Qb5H4vWfPmHo8OyB1ito+AysNNz0oglj1U955sjUN9d41LnrX2D/u7eRwxyOaOpfyevCWbTgDEoilsOnu7zsKhjRCsnD/QzhdkYLBLXjiK4f3UWmcx2M7PO21CKVTH84638NTplt6JIQH0ZwCNuiWAfvuLhdrcOYPVO9eW3A67l7hZtgaY9GZo9AFc6cryjoeFBIWeU+npnk/nLE0OxCHL1eQsc1IciehjpJv5mqCsjeopaH6r15/MrxNnVhu7tmcslay2gO2Z1QfcfX0JMACG41/u0RrI9QAAAABJRU5ErkJggg==) 4 | 5 | 基于 [OneBot](https://github.com/botuniverse/onebot/blob/main/README.md) 的 Telegram机器人Onebot v11 Java实现端 6 | 7 | ## 底层 8 | - [Java Telegram Bot API](https://github.com/pengrad/java-telegram-bot-api): Telegram Bot API的Java实现 9 | 10 | ## 兼容性 11 | 完全兼容Onebot-v11协议,可与Onebot-v11协议的框架相连接,实现大部分功能 12 | 13 | 使用SpringBoot框架,可直接打包为jar文件在`Jdk17`环境下运行 14 | 15 | 提供Onebot-v11正向Websocket方式连接该项目。 16 | 17 | Telegram适配器支持以下连接方式: 18 | 19 | - [x] 纯http轮询 getmsg获取信息 20 | 21 | 22 | 支持连接 [Mirai-Overflow](https://github.com/MrXiaoM/Overflow) 23 | 24 | 其他项目暂未测试 25 | 26 | 可以与支持onebotV11适配器的项目相连接使用 27 | 28 | ## 配置指南 29 | 30 | ~~该项目目前仅支持[数组格式](https://github.com/botuniverse/onebot-11/blob/master/message/array.md)消息转发/接收,请确保你的框架支持该格式~~ 31 | 32 | ~~后续会逐渐适配其他格式,若有问题请移步issue提出~~ 33 | 34 | 该项目支持数组格式与cq码格式 35 | 36 | 支持proxy代理(HTTP(未测试)/SOCKS 账密),若有需要请在config.yml中配置 37 | 38 | 下方的需配置 均为config.yml的配置项,配置项右侧有注释解释和格式例子 39 | 40 | ```yaml 41 | command: 42 | commandMap: 43 | start: 开始 44 | help: 帮助 45 | [Telegram发送内容]: [转发至Onebot内容] 46 | prefix: [指令前缀 默认为"/"] 47 | onebot: 48 | ip: 0.0.0.0 49 | path: [Onebot ws连接路径] 50 | port: [Onebot ws连接端口] 51 | token: [Onebot token] 52 | useArray: [是否启用Array消息 true/false] 53 | spring: 54 | database: 55 | dataType: [数据库类型, H2/SQLITE/MYSQL] 56 | mysqlPassword: [数据库密码, 若使用H2/SQLITE可不填] 57 | mysqlUrl: [数据库连接url, 若使用H2/SQLITE可不填] 58 | mysqlUser: [数据库用户名, 若使用H2/SQLITE可不填] 59 | jackson: 60 | dateformat: yyyy-MM-dd HH:mm:ss 61 | timezone: Asia/Shanghai 62 | telegram: 63 | bot: 64 | proxy: 65 | host: [代理IP地址,不建议纯域名] 66 | port: [代理端口] 67 | secret: [代理密码] 68 | type: [HTTP/SOCKS/DIRECT] 69 | username: [代理账号] 70 | token: [你的bot token] 71 | username: [你的bot 用户名,随意设置] 72 | ``` 73 | 74 | ### 功能 75 | 76 | - [ ] HTTP API 77 | - [ ] 反向 HTTP POST 78 | - [x] 正向 WebSocket 79 | - [ ] 反向 WebSocket 80 | - [ ] 连接多个ws地址 81 | - [x] 网页控制台 82 | - [x] 后台操作收发消息 83 | - [x] 代理支持 84 | - [x] Telegram聊天信息区分用户和群组 85 | 86 | 87 | ### 实现 88 | 89 | > [!TIP] 90 | > 下列表格中的✅表示已实现,❌表示未实现,✅❓表示已实现但未测试 91 | 92 |
93 | 已实现 API 94 | 95 | #### 符合 OneBot 标准的 API 96 | 97 | | API | 功能 | 实现情况 | 98 | |--------------------------|:-------------:|:------:| 99 | | /send_private_msg | [发送私聊消息] | ✅ | 100 | | /send_group_msg | [发送群消息] | ✅ | 101 | | /send_msg | [发送消息] | ✅ | 102 | | /delete_msg | [撤回信息] | ✅ | 103 | | /set_group_kick | [群组踢人] | ✅❓ | 104 | | /set_group_ban | [群组单人禁言] | ✅ | 105 | | /set_group_whole_ban | [群组全员禁言] | ❌ | 106 | | /set_group_admin | [群组设置管理员] | ✅ | 107 | | /set_group_card | [设置群名片(群备注)] | ✅❓ | 108 | | /set_group_name | [设置群名] | ✅❓ | 109 | | /set_group_leave | [退出群组] | ✅❓ | 110 | | /set_group_special_title | [设置群组专属头衔] | ✅ | 111 | | /set_friend_add_request | [处理加好友请求] | ❌ | 112 | | /set_group_add_request | [处理加群请求/邀请] | ❌ | 113 | | /get_login_info | [获取登录号信息] | ✅ | 114 | | /get_stranger_info | [获取陌生人信息] | ❌ | 115 | | /get_friend_list | [获取好友列表] | ✅ | 116 | | /get_group_info | [获取群信息] | ✅ | 117 | | /get_group_list | [获取群列表] | ✅ | 118 | | /get_group_member_info | [获取群成员信息] | ✅ | 119 | | /get_group_member_list | [获取群成员列表] | ✅ | 120 | | /get_group_honor_info | [获取群荣誉信息] | ❌ | 121 | | /can_send_image | [检查是否可以发送图片] | ❌ | 122 | | /can_send_record | [检查是否可以发送语音] | ❌ | 123 | | /get_version_info | [获取版本信息] | ✅ | 124 | | /set_restart | [重启协议端] | ❌ | 125 | | /.handle_quick_operation | [对事件执行快速操作] | ❌ | 126 | | /get_image | [获取图片信息] | ❌ | 127 | | /get_msg | [获取消息] | ✅ | 128 | | /get_status | [获取状态] | ✅ | 129 | 130 | 131 |
132 | 133 |
134 | 已实现 Event 135 | 136 | #### 符合 OneBot 标准的事件 137 | 138 | | 事件类型 | 事件描述 | 实现情况 | 139 | |------|:-----------:|:----:| 140 | | 消息事件 | [私聊信息] | ✅ | 141 | | 消息事件 | [群消息] | ✅ | 142 | | 通知事件 | [群文件上传] | ❌ | 143 | | 通知事件 | [群管理员变动] | ❌ | 144 | | 通知事件 | [群成员减少] | ❌ | 145 | | 通知事件 | [群成员增加] | ❌ | 146 | | 通知事件 | [群禁言] | ❌ | 147 | | 通知事件 | [好友添加] | ❌ | 148 | | 通知事件 | [群消息撤回] | ❌ | 149 | | 通知事件 | [好友消息撤回] | ❌ | 150 | | 请求事件 | [加好友请求] | ❌ | 151 | | 请求事件 | [加群请求/邀请] | ❌ | 152 | 153 | 154 |
155 | 156 |
157 | 已实现 Message 158 | 159 | #### 符合 OneBot 标准的消息 160 | 161 | | 消息类型 | 收情况 | 发情况 | 162 | |------------|:---:|:---:| 163 | | 纯文本 | ✅ | ✅ | 164 | | 图片 | ✅ | ✅ | 165 | | 图文混合(图片描述) | ✅ | ✅ | 166 | | 语音 | ❌ | ✅ | 167 | | 声文混合(语音描述) | ❌ | ✅ | 168 | | 短视频 | ❌ | ❌ | 169 | | at某人 | ✅ | ✅ | 170 | | 回复 | ✅ | ✅ | 171 | 172 |
173 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/config/ConfigGenerator.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.config; 2 | 3 | import cn.chahuyun.hibernateplus.DriveType; 4 | import org.yaml.snakeyaml.DumperOptions; 5 | import org.yaml.snakeyaml.Yaml; 6 | import org.yaml.snakeyaml.nodes.Tag; 7 | import org.yaml.snakeyaml.representer.Representer; 8 | 9 | import java.io.*; 10 | import java.nio.file.Files; 11 | import java.nio.file.Path; 12 | import java.util.ArrayList; 13 | import java.util.LinkedHashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | 17 | import static org.reflections.Reflections.log; 18 | 19 | public class ConfigGenerator { 20 | 21 | public static Config loadConfig() { 22 | try { 23 | ConfigEntity entity = Config.class.getAnnotation(ConfigEntity.class); 24 | Path configPath = Path.of(entity.filePath(), entity.name() + ".yml"); 25 | 26 | Config defaultConfig = createDefaultConfig(); 27 | 28 | if (!Files.exists(configPath)) { 29 | Files.createDirectories(configPath.getParent()); 30 | writeConfig(configPath, defaultConfig); 31 | log.warn("生成默认配置文件,请修改并重启: {}", configPath); 32 | System.exit(0); 33 | } 34 | 35 | Config existingConfig = readConfig(configPath); 36 | Config mergedConfig = mergeConfigs(defaultConfig, deepCopy(existingConfig)); 37 | 38 | if (!mergedConfig.toString().equals(existingConfig.toString())) { 39 | writeConfig(configPath, mergedConfig); 40 | log.info("更新的配置文件"); 41 | return mergedConfig; 42 | } else { 43 | log.info("配置文件加载成功"); 44 | return existingConfig; 45 | } 46 | } catch (Exception e) { 47 | log.error("加载配置失败", e); 48 | throw new IllegalStateException("加载配置失败", e); 49 | } 50 | } 51 | 52 | private static Config deepCopy(Config config) throws IOException, ClassNotFoundException { 53 | try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); 54 | ObjectOutputStream out = new ObjectOutputStream(byteOut)) { 55 | out.writeObject(config); 56 | try (ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); 57 | ObjectInputStream in = new ObjectInputStream(byteIn)) { 58 | return (Config) in.readObject(); 59 | } 60 | } 61 | } 62 | 63 | private static Config mergeConfigs(Config defaultConfig, Config existingConfig) { 64 | // 将配置对象转换为Map结构 65 | Map defaultMap = convertToMap(defaultConfig); 66 | Map existingMap = convertToMap(existingConfig); 67 | 68 | // 递归合并Map 69 | Map mergedMap = mergeMaps(defaultMap, existingMap); 70 | 71 | // 将合并后的Map转回Config对象 72 | return createYaml().loadAs(createYaml().dump(mergedMap), Config.class); 73 | } 74 | 75 | /** 76 | * 将Config对象转为可修改的Map(解决不可变集合问题) 77 | */ 78 | private static Map convertToMap(Object obj) { 79 | Yaml yaml = new Yaml(); 80 | String yamlStr = yaml.dumpAsMap(obj); 81 | return yaml.load(yamlStr); 82 | } 83 | 84 | /** 85 | * 递归合并两个Map结构 86 | */ 87 | @SuppressWarnings("unchecked") 88 | private static Map mergeMaps(Map defaultMap, Map existingMap) { 89 | Map result = new LinkedHashMap<>(existingMap); 90 | 91 | defaultMap.forEach((key, defaultValue) -> { 92 | Object existingValue = result.get(key); 93 | 94 | if (existingValue == null) { 95 | // 添加新字段 96 | result.put(key, defaultValue); 97 | } else if (defaultValue instanceof Map && existingValue instanceof Map) { 98 | // 递归合并嵌套Map 99 | result.put(key, mergeMaps( 100 | (Map) defaultValue, 101 | (Map) existingValue 102 | )); 103 | } else if (defaultValue instanceof List && existingValue instanceof List) { 104 | // 合并List策略:保留现有元素,添加默认中不存在的新元素 105 | List mergedList = mergeLists( 106 | (List) defaultValue, 107 | (List) existingValue 108 | ); 109 | result.put(key, mergedList); 110 | } 111 | // 其他类型保持现有值 112 | }); 113 | 114 | return result; 115 | } 116 | 117 | /** 118 | * 合并List策略示例(根据需求调整) 119 | */ 120 | private static List mergeLists(List defaultList, List existingList) { 121 | List result = new ArrayList<>(existingList); 122 | 123 | // 添加默认列表中不存在的新元素 124 | defaultList.stream() 125 | .filter(item -> !result.contains(item)) 126 | .forEach(result::add); 127 | 128 | return result; 129 | } 130 | 131 | private static Config createDefaultConfig() { 132 | return Config.builder() 133 | .telegram(Config.telegram.builder() 134 | .bot(Config.telegram.bot.builder() 135 | .token("123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11") 136 | .username("bot_username") 137 | .useTranslator(false) 138 | .proxy(Config.telegram.bot.proxy.builder() 139 | .host("127.0.0.1") 140 | .port(-1) 141 | .secret("") 142 | .username("") 143 | .type("DIRECT") 144 | .build()).build()) 145 | .webhook(Config.telegram.webhook.builder() 146 | .certPath("[未完善,请勿使用]") 147 | .secret("[Unfinished, do not use]") 148 | .port(6700) 149 | .url("127.0.0.1") 150 | .useWebhook(false) 151 | .build()).build()) 152 | .onebot(Config.onebot.builder() 153 | .ip("0.0.0.0") 154 | .path("/ws") 155 | .port(6700) 156 | .token("123456") 157 | .useArray(true) 158 | .banGroupUser(true) 159 | .groupUserWarning("") 160 | .picBase64(true) 161 | .silkSampleRate(24000) 162 | .build()) 163 | .spring(Config.spring.builder() 164 | .database(Config.spring.database.builder() 165 | .dataType(DriveType.MYSQL) 166 | .mysqlUrl("jdbc:mysql://localhost:3306") 167 | .mysqlUser("root") 168 | .mysqlPassword("root") 169 | .build()) 170 | .webui(Config.spring.webui.builder() 171 | .userName("admin") 172 | .password("pwd") 173 | .build()) 174 | .ffmpegPath("") 175 | .build()) 176 | .command(Config.command.builder() 177 | .prefix("/") 178 | .commandMap(Map.of()) 179 | .menu(Map.of()) 180 | .build()) 181 | .build(); 182 | } 183 | 184 | private static void writeConfig(Path path, Config config) throws IOException { 185 | Yaml yaml = createYaml(); 186 | try (Writer writer = Files.newBufferedWriter(path)) { 187 | yaml.dump(config, writer); 188 | } 189 | } 190 | 191 | private static Config readConfig(Path path) throws IOException { 192 | Yaml yaml = createYaml(); 193 | try (Reader reader = Files.newBufferedReader(path)) { 194 | return yaml.loadAs(reader, Config.class); 195 | } 196 | } 197 | 198 | private static Yaml createYaml() { 199 | DumperOptions options = new DumperOptions(); 200 | options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); 201 | options.setIndent(2); 202 | options.setPrettyFlow(true); 203 | 204 | Representer representer = new Representer(options); 205 | representer.getPropertyUtils().setSkipMissingProperties(true); 206 | representer.addClassTag(Config.class, Tag.MAP); 207 | 208 | return new Yaml(representer, options); 209 | } 210 | } -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | if ! command -v java >/dev/null 2>&1 137 | then 138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 139 | 140 | Please set the JAVA_HOME variable in your environment to match the 141 | location of your Java installation." 142 | fi 143 | fi 144 | 145 | # Increase the maximum file descriptors if we can. 146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 147 | case $MAX_FD in #( 148 | max*) 149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 150 | # shellcheck disable=SC2039,SC3045 151 | MAX_FD=$( ulimit -H -n ) || 152 | warn "Could not query maximum file descriptor limit" 153 | esac 154 | case $MAX_FD in #( 155 | '' | soft) :;; #( 156 | *) 157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 158 | # shellcheck disable=SC2039,SC3045 159 | ulimit -n "$MAX_FD" || 160 | warn "Could not set maximum file descriptor limit to $MAX_FD" 161 | esac 162 | fi 163 | 164 | # Collect all arguments for the java command, stacking in reverse order: 165 | # * args from the command line 166 | # * the main class name 167 | # * -classpath 168 | # * -D...appname settings 169 | # * --module-path (only if needed) 170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 171 | 172 | # For Cygwin or MSYS, switch paths to Windows format before running java 173 | if "$cygwin" || "$msys" ; then 174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 176 | 177 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 178 | 179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 180 | for arg do 181 | if 182 | case $arg in #( 183 | -*) false ;; # don't mess with options #( 184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 185 | [ -e "$t" ] ;; #( 186 | *) false ;; 187 | esac 188 | then 189 | arg=$( cygpath --path --ignore --mixed "$arg" ) 190 | fi 191 | # Roll the args list around exactly as many times as the number of 192 | # args, so each arg winds up back in the position where it started, but 193 | # possibly modified. 194 | # 195 | # NB: a `for` loop captures its iteration list before it begins, so 196 | # changing the positional parameters here affects neither the number of 197 | # iterations, nor the values presented in `arg`. 198 | shift # remove old arg 199 | set -- "$@" "$arg" # push replacement arg 200 | done 201 | fi 202 | 203 | 204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 206 | 207 | # Collect all arguments for the java command: 208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 209 | # and any embedded shellness will be escaped. 210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 211 | # treated as '${Hostname}' itself on the command line. 212 | 213 | set -- \ 214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 215 | -classpath "$CLASSPATH" \ 216 | org.gradle.wrapper.GradleWrapperMain \ 217 | "$@" 218 | 219 | # Stop when "xargs" is not available. 220 | if ! command -v xargs >/dev/null 2>&1 221 | then 222 | die "xargs is not available" 223 | fi 224 | 225 | # Use "xargs" to parse quoted args. 226 | # 227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 228 | # 229 | # In Bash we could simply go: 230 | # 231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 232 | # set -- "${ARGS[@]}" "$@" 233 | # 234 | # but POSIX shell has neither arrays nor command substitution, so instead we 235 | # post-process each arg (as a line of input to sed) to backslash-escape any 236 | # character that might be a shell metacharacter, then use eval to reverse 237 | # that process (while maintaining the separation between arguments), and wrap 238 | # the whole thing up as a single "set" statement. 239 | # 240 | # This will of course break if any of these variables contains a newline or 241 | # an unmatched quote. 242 | # 243 | 244 | eval "set -- $( 245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 246 | xargs -n1 | 247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 248 | tr '\n' ' ' 249 | )" '"$@"' 250 | 251 | exec "$JAVACMD" "$@" 252 | -------------------------------------------------------------------------------- /src/main/resources/static/js/UpdateInformation.js: -------------------------------------------------------------------------------- 1 | // 修改顶部侧边栏切换逻辑 2 | let isMobile = window.matchMedia("(max-width: 50em)").matches; 3 | let sidebar = document.getElementById('sidebar'); 4 | // let toggleBtn = document.getElementById('toggle-btn'); 5 | 6 | // 统一管理侧边栏状态 7 | function toggleSidebar() { 8 | if(isMobile) { 9 | sidebar.classList.toggle('active'); 10 | document.body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : ''; 11 | toggleBtn.innerHTML = sidebar.classList.contains('active') ? '▼' : '▲'; 12 | } else { 13 | sidebar.classList.toggle('active'); 14 | sidebar.style.marginLeft = sidebar.classList.contains('active') ? '-280px' : '0'; 15 | toggleBtn.innerHTML = sidebar.classList.contains('active') ? '▶' : '◀'; 16 | } 17 | } 18 | 19 | // 响应式检测 20 | window.addEventListener('resize', () => { 21 | isMobile = window.matchMedia("(max-width: 60rem)").matches; 22 | toggleBtn.innerHTML = sidebar.classList.contains('active') ? (isMobile ? '▼' : '▶') : (isMobile ? '▲' : '◀'); 23 | }); 24 | 25 | // 修改原有事件监听 26 | toggleBtn.addEventListener('click', toggleSidebar); 27 | 28 | // 防止滚动穿透 29 | document.body.addEventListener('touchmove', (e) => { 30 | if(sidebar.classList.contains('active')) { 31 | e.preventDefault(); 32 | } 33 | }, { passive: false }); 34 | 35 | async function fetchBotInfo(isFirst) { 36 | try { 37 | const response = await fetch(`/api/bot-info${isFirst ? '?withAvatar=1' : ''}`); 38 | if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); 39 | const botInfo = await response.json(); 40 | 41 | document.querySelector('.bot-info h2').textContent = botInfo.firstName; 42 | document.querySelector('.bot-info h4').textContent = botInfo.name; 43 | if (isFirst) { 44 | document.querySelector('.avatar').src = botInfo.avatarUrl.startsWith("file:///") 45 | ? await fetch(botInfo.avatarUrl) 46 | .then(res => res.blob()) 47 | .then(blob => new Promise((resolve, reject) => { 48 | const reader = new FileReader(); 49 | reader.onloadend = () => resolve(reader.result); 50 | reader.onerror = reject; 51 | reader.readAsDataURL(blob); 52 | })) 53 | : botInfo.avatarUrl; 54 | } 55 | document.getElementById('uptime').textContent = botInfo.uptime; 56 | } catch (error) { 57 | console.error('获取机器人信息失败:', error); 58 | document.getElementById('latency').textContent = '--'; 59 | } 60 | } 61 | 62 | document.addEventListener('DOMContentLoaded', () => { 63 | fetchBotInfo(true); 64 | fetchChatHistory(); 65 | setInterval(() => fetchBotInfo(false), 5000); 66 | }); 67 | 68 | function toggleMenu() { 69 | document.getElementById('menuContent').classList.toggle('show'); 70 | } 71 | 72 | async function selectFunction(type) { 73 | const contactList = document.getElementById('contact-list'); 74 | if (type === 'message') { 75 | contactList.style.display = 'block'; 76 | try { 77 | const response = await fetch('/api/bot-contacts'); 78 | if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); 79 | const contacts = await response.json(); 80 | contactList.innerHTML = contacts.map(contact => ` 81 | 87 | `).join(''); 88 | contactList.style.maxHeight = '150px'; 89 | contactList.style.overflowY = 'auto'; 90 | } catch (error) { 91 | console.error('Error fetching contacts:', error); 92 | } 93 | } else if(type === 'quick') { 94 | const commands = "Available commands: test, reload, help, stop, cleanChatHistory, gc" 95 | .replace("Available commands: ", "") 96 | .split(", ") 97 | .map(command => command.trim()); 98 | const contactList = document.getElementById('contact-list'); 99 | contactList.style.display = 'block'; 100 | contactList.innerHTML = commands.map(command => ` 101 | 106 | `).join(''); 107 | } else { 108 | selectedContact = -1; 109 | contactList.style.display = 'none'; 110 | } 111 | toggleMenu(); 112 | } 113 | 114 | async function quickCommand(command) { 115 | const log = document.getElementById('log-container'); 116 | const map = new Map(); 117 | map.set("command", command); 118 | const response = await sendPostRequest(map, '/api/toa/command'); 119 | log.innerHTML += `
[发送] ${new Date().toLocaleTimeString()} - ${command}
`; 120 | log.innerHTML += `
[返回] ${new Date().toLocaleTimeString()} - ${response}
`; 121 | log.scrollTop = log.scrollHeight; 122 | } 123 | 124 | let selectedContact = -1, selectedContactName = ''; 125 | 126 | async function sendMessage() { 127 | const input = document.getElementById('input-field'); 128 | const log = document.getElementById('log-container'); 129 | if (input.value.trim() === '') { 130 | return; 131 | } 132 | let response; 133 | let value = input.value.trim(); 134 | 135 | input.value = ''; 136 | if (selectedContact !== -1) { 137 | const map = new Map(); 138 | map.set('contactId', selectedContact); 139 | map.set("msg", value); 140 | map.set("isGroup", true) 141 | if (await sendPostRequest(map, '/api/bot-contacts/send-msg')) { 142 | log.innerHTML += `
[发送至 ${selectedContactName}] ${new Date().toLocaleTimeString()} - ${value}
`; 143 | } else { 144 | log.innerHTML += `
[发送失败!] ${new Date().toLocaleTimeString()} - ${value}
`; 145 | } 146 | 147 | } else { 148 | const map = new Map(); 149 | map.set("command", value); 150 | response = await sendPostRequest(map, 'api/toa/command'); 151 | 152 | log.innerHTML += `
[发送] ${new Date().toLocaleTimeString()} - ${value}
`; 153 | log.innerHTML += `
[返回] ${new Date().toLocaleTimeString()} - ${response}
`; 154 | } 155 | input.value = ''; 156 | log.scrollTop = log.scrollHeight; 157 | } 158 | 159 | function setContact(groupId, groupName) { 160 | selectedContact = groupId; 161 | selectedContactName = groupName; 162 | document.getElementById('contact-list').style.display = 'none'; 163 | } 164 | 165 | async function sendPostRequest(data, url) { 166 | try { 167 | console.log(JSON.stringify(Object.fromEntries(data))); 168 | const response = await fetch(url, { 169 | method: 'POST', 170 | headers: { 'Content-Type': 'application/json' }, 171 | credentials: 'include', // 启用 Cookie 172 | body: JSON.stringify(Object.fromEntries(data)) 173 | }); 174 | if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); 175 | return await response.text(); 176 | } catch (error) { 177 | console.error('Error sending POST request:', error); 178 | } 179 | } 180 | 181 | let ws; 182 | 183 | function connectWebSocket() { 184 | ws = new WebSocket(`ws://${location.host}/ws/logs`); 185 | 186 | ws.onopen = function() { 187 | console.log('WebSocket connection established.'); 188 | }; 189 | 190 | ws.onmessage = function(event) { 191 | const logContainer = document.getElementById('log-container'); 192 | const shouldScroll = logContainer.scrollTop + logContainer.clientHeight === logContainer.scrollHeight; 193 | const newEntry = document.createElement('div'); 194 | newEntry.className = 'log-entry'; 195 | newEntry.textContent = event.data; 196 | logContainer.appendChild(newEntry); 197 | if (shouldScroll) { 198 | logContainer.scrollTop = logContainer.scrollHeight; 199 | } 200 | }; 201 | 202 | ws.onclose = function() { 203 | console.warn('WebSocket connection closed. Attempting to reconnect...'); 204 | setTimeout(connectWebSocket, 5000); // Retry connection after 5 seconds 205 | }; 206 | 207 | ws.onerror = function(error) { 208 | console.error('WebSocket error:', error); 209 | ws.close(); 210 | }; 211 | } 212 | 213 | // Initialize WebSocket connection 214 | connectWebSocket(); 215 | 216 | async function fetchChatHistory() { 217 | try { 218 | const response = await fetch('/api/toa/chat-history', { 219 | method: 'POST', 220 | headers: { 'Content-Type': 'application/json' }, 221 | credentials: 'include', // 启用 Cookie 222 | body: JSON.stringify({ limit: 50 }), 223 | }); 224 | if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); 225 | const history = await response.json(); 226 | 227 | const logContainer = document.getElementById('log-container'); 228 | history.forEach(entry => { 229 | const logEntry = document.createElement('div'); 230 | logEntry.className = 'log-entry'; 231 | logEntry.textContent = entry; 232 | logContainer.appendChild(logEntry); 233 | }); 234 | logContainer.scrollTop = logContainer.scrollHeight; 235 | } catch (error) { 236 | console.error('Error fetching chat history:', error); 237 | } 238 | 239 | } -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/telegramApi/TelegramApi.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.telegramApi; 2 | 3 | import cn.hutool.json.JSONArray; 4 | import cn.hutool.json.JSONObject; 5 | import cn.travellerr.onebottelegram.config.Config; 6 | import cn.travellerr.onebottelegram.converter.TelegramToOnebot; 7 | import com.pengrad.telegrambot.TelegramBot; 8 | import com.pengrad.telegrambot.UpdatesListener; 9 | import com.pengrad.telegrambot.model.*; 10 | import com.pengrad.telegrambot.request.*; 11 | import com.pengrad.telegrambot.response.GetMeResponse; 12 | import com.pengrad.telegrambot.utility.BotUtils; 13 | import io.micrometer.common.util.StringUtils; 14 | import okhttp3.Credentials; 15 | import okhttp3.OkHttpClient; 16 | import okhttp3.Request; 17 | import okhttp3.Response; 18 | import org.slf4j.Logger; 19 | import org.slf4j.LoggerFactory; 20 | import org.springframework.stereotype.Component; 21 | 22 | import java.io.File; 23 | import java.io.IOException; 24 | import java.io.InputStream; 25 | import java.net.Authenticator; 26 | import java.net.InetSocketAddress; 27 | import java.net.PasswordAuthentication; 28 | import java.net.Proxy; 29 | import java.nio.charset.StandardCharsets; 30 | import java.nio.file.Files; 31 | import java.nio.file.Path; 32 | import java.nio.file.Paths; 33 | import java.nio.file.StandardCopyOption; 34 | import java.util.Date; 35 | import java.util.List; 36 | import java.util.Objects; 37 | 38 | import static cn.travellerr.onebottelegram.TelegramOnebotAdapter.config; 39 | 40 | 41 | @Component 42 | public class TelegramApi { 43 | 44 | private static final String token = config.getTelegram().getBot().getToken(); 45 | 46 | private static final String username = config.getTelegram().getBot().getUsername(); 47 | 48 | public static GetMeResponse getMeResponse; 49 | 50 | // Telegram bot 头像,URL链接或本地目录 51 | public static String botAvatar; 52 | 53 | public static TelegramBot bot; 54 | 55 | public static OkHttpClient okHttpClient; 56 | 57 | private static final Logger log = LoggerFactory.getLogger(TelegramApi.class); 58 | 59 | public static void init() { 60 | okHttpClient = createBot(); 61 | log.info("Telegram bot 开始运行: " + username); 62 | 63 | try { 64 | getMeResponse = bot.execute(new GetMe()); 65 | } catch (Exception e) { 66 | log.error("Telegram bot 信息获取失败: " + e.getMessage()); 67 | retryGetMeResponse(); 68 | } 69 | 70 | log.info("Telegram bot 信息: " + getMeResponse); 71 | fetchAndSaveBotAvatar(okHttpClient); 72 | 73 | /* if (config.getTelegram().getWebhook().isUseWebhook()) { 74 | setupWebhook(); 75 | return; 76 | }*/ 77 | 78 | // log.info("Telegram bot Webhook 未启用, 使用长轮询模式"); 79 | log.info("Telegram bot 使用长轮询模式"); 80 | setupLongPolling(); 81 | // WebSocketMessage.init(); 82 | } 83 | 84 | private static void retryGetMeResponse() { 85 | boolean flag = false; 86 | while (!flag) { 87 | for (int i = 1; i <= 5; i++) { 88 | try { 89 | log.info("尝试重新获取 Telegram bot 信息: " + i + "/5"); 90 | getMeResponse = bot.execute(new GetMe()); 91 | flag = true; 92 | break; 93 | } catch (Exception e1) { 94 | log.error("Telegram bot 信息获取失败: " + e1.getMessage()); 95 | } 96 | } 97 | if (!flag) { 98 | log.info("Telegram bot 信息获取失败超过最大次数(5/5), 60秒后重试"); 99 | try { 100 | Thread.sleep(60000); 101 | } catch (InterruptedException e1) { 102 | log.error("Telegram bot 信息获取中断: " + e1.getMessage()); 103 | } 104 | } else { 105 | log.info("Telegram bot 信息获取成功"); 106 | } 107 | } 108 | } 109 | 110 | private static void fetchAndSaveBotAvatar(OkHttpClient okHttpClient) { 111 | new Thread(() -> { 112 | try { 113 | UserProfilePhotos photos = bot.execute(new GetUserProfilePhotos(getMeResponse.user().id())).photos(); 114 | if (photos != null && photos.photos().length > 0) { 115 | botAvatar = bot.getFullFilePath(bot.execute(new GetFile(photos.photos()[0][0].fileId())).file()); 116 | saveBotAvatarToFile(okHttpClient); 117 | } else { 118 | log.info("Telegram bot 头像: 无"); 119 | } 120 | } catch (Exception e) { 121 | log.error("获取 Telegram bot 头像失败: " + e.getMessage()); 122 | } 123 | }).start(); 124 | } 125 | 126 | private static void saveBotAvatarToFile(OkHttpClient okHttpClient) { 127 | try (Response response = okHttpClient.newCall(new Request.Builder().url(botAvatar).build()).execute(); 128 | InputStream in = Objects.requireNonNull(response.body()).byteStream()) { 129 | Path path = Paths.get("bot_avatar.jpg"); 130 | Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING); 131 | log.info("Telegram bot 头像已保存至本地: bot_avatar.jpg"); 132 | botAvatar = path.toAbsolutePath().toString(); 133 | log.info("Telegram bot 头像: " + botAvatar.substring(0, 50) + "..."); 134 | } catch (IOException e) { 135 | log.error("保存 Telegram bot 头像失败: " + e.getMessage()); 136 | } 137 | } 138 | 139 | private static void setupWebhook() { 140 | SetWebhook setWebhook = new SetWebhook() 141 | .url(config.getTelegram().getWebhook().getUrl() + ":" + config.getTelegram().getWebhook().getPort() + "/api/telegram/webhook") 142 | .certificate(new File(config.getTelegram().getWebhook().getCertPath())) 143 | .secretToken(config.getTelegram().getWebhook().getSecret()); 144 | 145 | String response = bot.execute(setWebhook).description(); 146 | log.info("Telegram bot Webhook 设置成功: " + config.getTelegram().getWebhook().getUrl() + "/api/telegram/webhook"); 147 | log.info("Telegram bot Webhook 设置返回: " + response); 148 | } 149 | 150 | private static void setupLongPolling() { 151 | bot.setUpdatesListener(updates -> { 152 | new Thread(() -> updates.forEach(update -> { 153 | System.out.println(BotUtils.toJson(update)); 154 | Update newUpdate = callbackToMessage(update); 155 | TelegramToOnebot.forwardToOnebot(newUpdate); 156 | })).start(); 157 | return UpdatesListener.CONFIRMED_UPDATES_ALL; 158 | }, Throwable::fillInStackTrace); 159 | } 160 | 161 | private static OkHttpClient createBot() { 162 | bot = new TelegramBot(token); 163 | 164 | Config.telegram.bot.proxy proxy = config.getTelegram().getBot().getProxy(); 165 | 166 | if (proxy.getPort() != -1) { 167 | Proxy.Type proxyType = switch (proxy.getType()) { 168 | case "SOCKS5", "SOCKS4", "VMESS", "SOCKS" -> Proxy.Type.SOCKS; 169 | case "HTTP", "HTTPS" -> Proxy.Type.HTTP; 170 | default -> { 171 | log.error("代理类型错误"); 172 | yield Proxy.Type.DIRECT; 173 | } 174 | }; 175 | 176 | OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder() 177 | .hostnameVerifier(SSLSocketClient.getHostnameVerifier()) 178 | .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager()) 179 | .proxy(new Proxy(proxyType, new InetSocketAddress(proxy.getHost(), proxy.getPort()))); 180 | 181 | if (StringUtils.isNotEmpty(proxy.getUsername()) && StringUtils.isNotEmpty(proxy.getSecret())) { 182 | clientBuilder.proxyAuthenticator((route, response) -> { 183 | String credential = Credentials.basic(proxy.getUsername().strip(), proxy.getSecret().strip(), StandardCharsets.UTF_8); 184 | return response.request().newBuilder().header("Proxy-Authorization", credential).build(); 185 | }); 186 | 187 | Authenticator.setDefault(new Authenticator() { 188 | @Override 189 | protected PasswordAuthentication getPasswordAuthentication() { 190 | return new PasswordAuthentication(proxy.getUsername().strip(), proxy.getSecret().strip().toCharArray()); 191 | } 192 | }); 193 | 194 | log.info("代理已启用: " + proxy.getHost() + ":" + proxy.getPort()); 195 | } 196 | 197 | bot = new TelegramBot.Builder(token).okHttpClient(clientBuilder.build()).build(); 198 | 199 | return clientBuilder.build(); 200 | } else { 201 | bot = new TelegramBot.Builder(token).okHttpClient(new OkHttpClient.Builder().hostnameVerifier((hostname, session) -> true).build()).build(); 202 | } 203 | 204 | return new OkHttpClient(); 205 | } 206 | 207 | private static Update callbackToMessage(Update update) { 208 | if (update.callbackQuery() != null) { 209 | JSONObject object = new JSONObject(BotUtils.toJson(update)); 210 | 211 | CallbackQuery callbackQuery = update.callbackQuery(); 212 | 213 | object.set("callback_query", null); 214 | int message_id = callbackQuery.id().hashCode(); 215 | User user = callbackQuery.from(); 216 | Chat chat = callbackQuery.maybeInaccessibleMessage().chat(); 217 | long date = new Date().getTime() / 1000; 218 | String text = callbackQuery.data(); 219 | List entities = List.of(new MessageEntity[]{ 220 | new MessageEntity(MessageEntity.Type.bot_command, 0, text.length()) 221 | }); 222 | 223 | JSONObject messageObject = new JSONObject(new Message()); 224 | messageObject.set("message_id", message_id); 225 | messageObject.set("from", new JSONObject(BotUtils.toJson(user))); 226 | messageObject.set("chat", new JSONObject(BotUtils.toJson(chat))); 227 | messageObject.set("date", date); 228 | messageObject.set("text", config.getCommand().getPrefix()+text); 229 | messageObject.set("entities", new JSONArray(BotUtils.toJson(entities))); 230 | 231 | object.set("message", messageObject); 232 | 233 | EditMessageText editMessageText = new EditMessageText(callbackQuery.maybeInaccessibleMessage().chat().id(), callbackQuery.maybeInaccessibleMessage().messageId(), "正在执行 " + text + " 指令...").replyMarkup(TelegramToOnebot.buildMenuButtons()); 234 | bot.execute(editMessageText); 235 | 236 | 237 | return BotUtils.parseUpdate(object.toString()); 238 | } else { 239 | return update; 240 | } 241 | } 242 | 243 | 244 | } 245 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/converter/AudioConverter.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.converter; 2 | 3 | import cn.travellerr.onebottelegram.TelegramOnebotAdapter; 4 | import io.github.kasukusakura.silkcodec.SilkCoder; 5 | 6 | import java.io.*; 7 | import java.net.URL; 8 | import java.nio.file.Files; 9 | import java.nio.file.Path; 10 | import java.util.Base64; 11 | 12 | public class AudioConverter { 13 | 14 | private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(AudioConverter.class); 15 | 16 | /** 17 | * 将音频路径转换为可用的音频文件 18 | * @param audioPath 音频路径(支持 http、base64://、file:// 或普通文件路径) 19 | * @return 处理后的音频文件路径,如果失败则返回 null 20 | */ 21 | public static String convertToTelegramAudio(String audioPath) { 22 | try { 23 | // 检查音频路径类型 24 | InputStream audioStream = getAudioStream(audioPath); 25 | if (audioStream == null) { 26 | log.error("无法获取音频流: {}", audioPath); 27 | return null; 28 | } 29 | 30 | 31 | String audioFormat = detectAudioFormat(audioStream); 32 | if (isSupportedFormat(audioFormat)) { 33 | // 直接支持的格式 34 | log.info("音频格式已支持,无需转换"); 35 | return ""; 36 | } 37 | log.info("检测到音频格式: {}", audioFormat); 38 | 39 | 40 | // 创建临时文件 41 | Path tempFile; 42 | if ("silk".equalsIgnoreCase(audioFormat)) { 43 | tempFile = convertSilkToPcm(audioPath); 44 | audioFormat = "pcm"; 45 | } else { 46 | tempFile = createTempAudioFile(audioStream); 47 | } 48 | 49 | if (tempFile == null) { 50 | log.error("无法创建临时音频文件"); 51 | return null; 52 | } 53 | 54 | // 如果需要转换格式 55 | Path convertedFile = tempFile; 56 | if (!isSupportedFormat(audioFormat)) { 57 | if ("pcm".equalsIgnoreCase(audioFormat)) { 58 | // 如果是 PCM 格式,转换为 OGG 59 | convertedFile = convertToOgg(tempFile, true); 60 | } else { 61 | // 其他格式转换为 OGG 62 | convertedFile = convertToOgg(tempFile); 63 | } 64 | if (convertedFile == null) { 65 | log.error("音频格式转换失败"); 66 | return null; 67 | } 68 | // 删除原始临时文件 69 | Files.deleteIfExists(tempFile); 70 | } 71 | 72 | log.info("音频处理完成: {}", convertedFile); 73 | return convertedFile.toString(); 74 | 75 | } catch (Exception e) { 76 | log.error("音频转换过程中发生错误", e); 77 | return null; 78 | } 79 | } 80 | 81 | 82 | 83 | private static InputStream getAudioStream(String audioPath) { 84 | try { 85 | if (audioPath.startsWith("http")) { 86 | // URL 音频 87 | URL url = new URL(audioPath); 88 | return url.openStream(); 89 | } else if (audioPath.startsWith("base64://")) { 90 | // Base64 编码的音频 91 | byte[] bytes = Base64.getDecoder().decode(audioPath.substring(9)); 92 | return new ByteArrayInputStream(bytes); 93 | } else { 94 | // 文件路径 95 | String filePath = audioPath.replaceFirst("^file://", ""); 96 | File file = new File(filePath); 97 | if (file.exists()) { 98 | return new FileInputStream(file); 99 | } else { 100 | log.error("音频文件不存在: {}", filePath); 101 | return null; 102 | } 103 | } 104 | } catch (Exception e) { 105 | log.error("获取音频流失败: {}", e.getMessage()); 106 | return null; 107 | } 108 | } 109 | 110 | private static Path createTempAudioFile(InputStream audioStream) { 111 | try { 112 | Path tempFile = Files.createTempFile("telegram_audio_", ".tmp"); 113 | 114 | // 将音频流写入临时文件 115 | Files.copy(audioStream, tempFile, java.nio.file.StandardCopyOption.REPLACE_EXISTING); 116 | audioStream.close(); 117 | 118 | return tempFile; 119 | } catch (Exception e) { 120 | log.error("创建临时音频文件失败: {}", e.getMessage()); 121 | return null; 122 | } 123 | } 124 | 125 | private static String detectAudioFormat(InputStream stream) { 126 | try { 127 | // 读取文件头来检测格式 128 | byte[] header = new byte[12]; 129 | stream.read(header); 130 | 131 | // 检测常见音频格式 132 | if (isMp3(header)) { 133 | return "mp3"; 134 | } else if (isOgg(header)) { 135 | return "ogg"; 136 | } else if (isWav(header)) { 137 | return "wav"; 138 | } else if (isFlac(header)) { 139 | return "flac"; 140 | } else if (isM4a(header)) { 141 | return "m4a"; 142 | } else if (isAac(header)) { 143 | return "aac"; 144 | } else if (isSilk(header)) { 145 | return "silk"; 146 | } else { 147 | return "unknown"; 148 | } 149 | } catch (Exception e) { 150 | log.error("音频格式检测失败: {}", e.getMessage()); 151 | return "unknown"; 152 | } 153 | } 154 | 155 | private static boolean isMp3(byte[] header) { 156 | return header.length >= 3 && 157 | header[0] == (byte) 0xFF && 158 | (header[1] & 0xE0) == 0xE0; 159 | } 160 | 161 | private static boolean isOgg(byte[] header) { 162 | return header.length >= 4 && 163 | header[0] == 'O' && 164 | header[1] == 'g' && 165 | header[2] == 'g' && 166 | header[3] == 'S'; 167 | } 168 | 169 | private static boolean isWav(byte[] header) { 170 | return header.length >= 12 && 171 | header[0] == 'R' && 172 | header[1] == 'I' && 173 | header[2] == 'F' && 174 | header[3] == 'F' && 175 | header[8] == 'W' && 176 | header[9] == 'A' && 177 | header[10] == 'V' && 178 | header[11] == 'E'; 179 | } 180 | 181 | private static boolean isFlac(byte[] header) { 182 | return header.length >= 4 && 183 | header[0] == 'f' && 184 | header[1] == 'L' && 185 | header[2] == 'a' && 186 | header[3] == 'C'; 187 | } 188 | 189 | private static boolean isM4a(byte[] header) { 190 | return header.length >= 8 && 191 | header[4] == 'f' && 192 | header[5] == 't' && 193 | header[6] == 'y' && 194 | header[7] == 'p'; 195 | } 196 | 197 | private static boolean isSilk(byte[] header) { 198 | return header.length >= 10 && 199 | header[1] == '#' && 200 | header[2] == '!' && 201 | header[3] == 'S' && 202 | header[4] == 'I' && 203 | header[5] == 'L' && 204 | header[6] == 'K' && 205 | header[7] == '_' && 206 | header[8] == 'V' && 207 | header[9] == '3'; 208 | } 209 | 210 | private static boolean isAac(byte[] header) { 211 | return header.length >= 2 && 212 | (header[0] == (byte) 0xFF && (header[1] & 0xF0) == 0xF0); 213 | } 214 | 215 | 216 | private static boolean isSupportedFormat(String format) { 217 | return "mp3".equalsIgnoreCase(format) || "ogg".equalsIgnoreCase(format); 218 | } 219 | 220 | private static Path convertToOgg(Path inputFile) { 221 | return convertToOgg(inputFile, false); 222 | } 223 | 224 | public static Path convertToOgg(Path inputFile, boolean isPcm) { 225 | try { 226 | String ffmpegPath = cn.travellerr.onebottelegram.TelegramOnebotAdapter.config.getSpring().getFfmpegPath(); 227 | if (ffmpegPath == null || ffmpegPath.trim().isEmpty()) { 228 | log.error("FFmpeg 路径未配置"); 229 | return null; 230 | } 231 | 232 | Path outputFile = Files.createTempFile("converted_audio_", ".ogg"); 233 | 234 | // 构建 FFmpeg 命令 235 | ProcessBuilder pb; 236 | if (isPcm) { 237 | pb = new ProcessBuilder( 238 | ffmpegPath, 239 | "-f", "s16le", 240 | "-ar", String.valueOf(TelegramOnebotAdapter.config.getOnebot().getSilkSampleRate() > 0 241 | ? TelegramOnebotAdapter.config.getOnebot().getSilkSampleRate() 242 | : 24000), 243 | "-ac", "1", 244 | "-i", inputFile.toString(), 245 | "-c:a", "libvorbis", 246 | "-q:a", "4", 247 | "-y", 248 | outputFile.toString() 249 | ); 250 | 251 | } else { 252 | pb = new ProcessBuilder( 253 | ffmpegPath, 254 | "-i", inputFile.toString(), 255 | "-c:a", "libvorbis", 256 | "-q:a", "4", 257 | "-y", // 覆盖输出文件 258 | outputFile.toString() 259 | ); 260 | } 261 | 262 | pb.redirectErrorStream(true); 263 | Process process = pb.start(); 264 | 265 | // 读取 FFmpeg 输出 266 | try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { 267 | String line; 268 | while ((line = reader.readLine()) != null) { 269 | log.debug("FFmpeg: {}", line); 270 | } 271 | } 272 | 273 | int exitCode = process.waitFor(); 274 | if (exitCode != 0) { 275 | log.error("FFmpeg 转换失败,退出码: {}", exitCode); 276 | Files.deleteIfExists(outputFile); 277 | return null; 278 | } 279 | if (isPcm) { 280 | Files.deleteIfExists(inputFile); 281 | } 282 | 283 | log.info("音频转换成功: {} -> {}", inputFile.getFileName(), outputFile.getFileName()); 284 | return outputFile; 285 | 286 | } catch (Exception e) { 287 | log.error("音频转换过程中发生错误: {}", e.getMessage()); 288 | return null; 289 | } 290 | } 291 | 292 | public static Path convertSilkToPcm(String path) { 293 | try (InputStream inputStream = getAudioStream(path)){ 294 | File tempFile = Files.createTempFile("silk_converted_", ".pcm").toFile(); 295 | 296 | try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tempFile))) { 297 | SilkCoder.decode(inputStream, outputStream, true, 24000, 20); 298 | 299 | outputStream.flush(); 300 | } 301 | log.info("Silk 转 PCM 成功: {}", tempFile.getAbsolutePath()); 302 | return tempFile.toPath(); 303 | } catch (IOException | UnsupportedOperationException e) { 304 | log.error("Silk 转 PCM 失败: ", e); 305 | return null; 306 | } 307 | } 308 | } 309 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/converter/TelegramToOnebot.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.converter; 2 | 3 | import cn.chahuyun.hibernateplus.HibernateFactory; 4 | import cn.hutool.core.codec.Base64Encoder; 5 | import cn.hutool.core.date.DateUtil; 6 | import cn.hutool.json.JSONArray; 7 | import cn.hutool.json.JSONObject; 8 | import cn.travellerr.onebotApi.*; 9 | import cn.travellerr.onebottelegram.TelegramOnebotAdapter; 10 | import cn.travellerr.onebottelegram.hibernate.HibernateUtil; 11 | import cn.travellerr.onebottelegram.hibernate.entity.Group; 12 | import cn.travellerr.onebottelegram.hibernate.entity.Message; 13 | import cn.travellerr.onebottelegram.model.Messages; 14 | import cn.travellerr.onebottelegram.onebotWebsocket.OneBotWebSocketHandler; 15 | import cn.travellerr.onebottelegram.telegramApi.TelegramApi; 16 | import cn.travellerr.onebottelegram.webui.api.LogWebSocketHandler; 17 | import com.google.gson.JsonArray; 18 | import com.pengrad.telegrambot.model.Chat; 19 | import com.pengrad.telegrambot.model.PhotoSize; 20 | import com.pengrad.telegrambot.model.Update; 21 | import com.pengrad.telegrambot.model.request.InlineKeyboardButton; 22 | import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup; 23 | import com.pengrad.telegrambot.model.request.ReplyParameters; 24 | import com.pengrad.telegrambot.request.GetChatMemberCount; 25 | import com.pengrad.telegrambot.request.GetFile; 26 | import com.pengrad.telegrambot.request.SendMessage; 27 | import okhttp3.Request; 28 | import okhttp3.Response; 29 | import org.slf4j.Logger; 30 | import org.slf4j.LoggerFactory; 31 | import org.springframework.boot.ApplicationArguments; 32 | import org.springframework.boot.ApplicationRunner; 33 | import org.springframework.stereotype.Component; 34 | 35 | import java.io.InputStream; 36 | import java.util.*; 37 | import java.util.regex.Matcher; 38 | import java.util.regex.Pattern; 39 | 40 | @Component 41 | public class TelegramToOnebot implements ApplicationRunner { 42 | 43 | public static final Map messageIdToChatId = new java.util.LinkedHashMap<>(1024, 0.75f, true) { 44 | @Override 45 | protected boolean removeEldestEntry(Map.Entry eldest) { 46 | return size() > 512; 47 | } 48 | }; 49 | 50 | 51 | private static final Logger log = LoggerFactory.getLogger(TelegramToOnebot.class); 52 | 53 | public static void forwardToOnebot(Update update) { 54 | if (update.message() != null&&(update.message().text() != null || update.message().photo() != null)) { 55 | 56 | messageIdToChatId.put(update.message().messageId(), update.message().chat().id()); 57 | 58 | // 截取"@"前消息 59 | String realMessage = Optional.ofNullable(update.message().text()) 60 | .orElse(Optional.ofNullable(update.message().caption()).orElse("")) 61 | .replace("@" + TelegramApi.getMeResponse.user().username(), "") 62 | .trim(); 63 | 64 | long fromId = Math.abs(update.message().from().id()); 65 | 66 | String username = update.message().from().username(); 67 | 68 | String firstName = update.message().from().firstName(); 69 | 70 | if (username == null) { 71 | username = update.message().from().firstName(); 72 | } 73 | 74 | if (realMessage.toLowerCase(Locale.ROOT).equals("/toamenu")) { 75 | 76 | log.info("内置菜单指令,已自动处理"); 77 | 78 | TelegramApi.bot.execute( 79 | new SendMessage(update.message().chat().id(), "菜单") 80 | .replyMarkup(buildMenuButtons()) 81 | .replyParameters(new ReplyParameters(update.message().messageId(), update.message().chat().id())) 82 | ); 83 | return; 84 | } 85 | 86 | JSONObject object; 87 | realMessage = serializeCommand(realMessage); 88 | 89 | JSONArray message = new JSONArray(); 90 | 91 | if (update.message().messageThreadId() != null) { 92 | Reply reply = new Reply(update.message().messageThreadId()); 93 | message.add(reply); 94 | } 95 | 96 | if (update.message().photo() != null) { 97 | for (PhotoSize photo : getEveryPhoto(update.message().photo())) { 98 | String filePath = TelegramApi.bot.getFullFilePath( 99 | TelegramApi.bot.execute(new GetFile(photo.fileId())).file() 100 | ); 101 | 102 | try { 103 | Image image; 104 | if (TelegramOnebotAdapter.config.getOnebot().isPicBase64()) { 105 | try (Response response = TelegramApi.okHttpClient.newCall(new Request.Builder().url(filePath).build()).execute(); 106 | InputStream in = Objects.requireNonNull(response.body()).byteStream()) { 107 | image = new Image("base64://" + Base64Encoder.encode(in.readAllBytes())); 108 | } 109 | } else { 110 | image = new Image(filePath); 111 | } 112 | message.add(image); 113 | } catch (Exception e) { 114 | log.error("Failed to retrieve image: {}", e.getMessage()); 115 | } 116 | } 117 | } 118 | 119 | message.add(new Text(realMessage)); 120 | 121 | if (update.message().chat().type().equals(Chat.Type.group) || update.message().chat().type().equals(Chat.Type.supergroup)) { 122 | Group group; 123 | 124 | if (!(update.message().senderChat() == null)) { 125 | if (TelegramOnebotAdapter.config.getOnebot().isBanGroupUser()) { 126 | log.info("根据配置设置,已打断群组身份发送消息的转发"); 127 | if (!TelegramOnebotAdapter.config.getOnebot().getGroupUserWarning().isEmpty() && realMessage.startsWith(TelegramOnebotAdapter.config.getCommand().getPrefix())) { 128 | SendMessage sendMessage = new SendMessage(update.message().chat().id(), TelegramOnebotAdapter.config.getOnebot().getGroupUserWarning()); 129 | sendMessage.replyParameters(new ReplyParameters(update.message().messageId(), update.message().chat().id())); 130 | TelegramApi.bot.execute(sendMessage); 131 | } 132 | return; 133 | } 134 | username = update.message().senderChat().username(); 135 | fromId = Math.abs(update.message().senderChat().id()); 136 | firstName = update.message().senderChat().title(); 137 | } 138 | 139 | group = HibernateFactory.selectOne(Group.class, update.message().chat().id()); 140 | 141 | if (group == null) { 142 | int memberCount = TelegramApi.bot.execute(new GetChatMemberCount(update.message().chat().id())).count(); 143 | group = Group.builder() 144 | .groupId(update.message().chat().id()) 145 | .groupName(update.message().chat().title()) 146 | .memberCount(memberCount) 147 | .build(); 148 | } 149 | group.addMemberId(fromId); 150 | group.addMemberUsernames(username); 151 | HibernateFactory.merge(group); 152 | 153 | if (realMessage.contains("@")) { 154 | List atList = new ArrayList<>(); 155 | List messageList = new ArrayList<>(); 156 | Matcher matcher = Pattern.compile("@(\\S+?)(\\s|$)").matcher(realMessage); 157 | 158 | final var membersIdList = group.getMembersIdList(); 159 | final var memberUsernameList = group.getMemberUsernamesList(); 160 | 161 | int lastIndex = 0; 162 | while (matcher.find()) { 163 | int index = memberUsernameList.indexOf(matcher.group(1)); 164 | if (index != -1) { 165 | atList.add(membersIdList.get(index)); 166 | String msg = realMessage.substring(lastIndex, matcher.start()).trim(); 167 | if (!messageList.isEmpty()) { 168 | msg = " " + msg; 169 | } 170 | messageList.add(msg); 171 | lastIndex = matcher.end(); 172 | } 173 | messageList.add(" "+realMessage.substring(lastIndex).trim()); 174 | } 175 | 176 | message = new JSONArray(); 177 | for (int i = 0; i < messageList.size(); i++) { 178 | Text messageObject = new Text(messageList.get(i)); 179 | if (!messageObject.getData().getText().isEmpty()) { 180 | message.add(messageObject); 181 | } 182 | if (i < atList.size()) { 183 | At atObject = new At(atList.get(i)); 184 | message.add(atObject); 185 | } 186 | } 187 | } 188 | 189 | Sender groupSender = new Sender(fromId, username, firstName, "unknown", 0, "虚拟地区", "0", "member", ""); 190 | GroupMessage groupMessage = new GroupMessage(System.currentTimeMillis(), TelegramApi.getMeResponse.user().id(), "message", "group", "normal", update.message().messageId(), -update.message().chat().id(), fromId, null, realMessage, 0, groupSender); 191 | 192 | object = new JSONObject(groupMessage); 193 | } else { 194 | Sender sender = new Sender(fromId, username, firstName, "unknown", 0, null, null, null, null); 195 | PrivateMessage privateMessage = new PrivateMessage(System.currentTimeMillis(), TelegramApi.getMeResponse.user().id(), "message", "private", "friend", update.message().messageId(), fromId, realMessage, 0, sender); 196 | object = new JSONObject(privateMessage); 197 | } 198 | 199 | if (!TelegramOnebotAdapter.config.getOnebot().isUseArray()) { 200 | object.set("message", arrayMessageToString(message)); 201 | } else { 202 | object.set("message", message); 203 | } 204 | 205 | log.info("发送消息至 Onebot --> {}", object); 206 | 207 | HibernateFactory.merge(new Message(update.message(), object.toString())); 208 | OneBotWebSocketHandler.broadcast(object.toString()); 209 | LogWebSocketHandler.broadcast(handleTextMessage(object.toString())); 210 | } 211 | } 212 | 213 | private static List getEveryPhoto(PhotoSize[] photo) { 214 | List photos = new ArrayList<>(); 215 | for (int i = photo.length-1; i >= 0; i--) { 216 | if (i == photo.length-1 && photo[i] != null) { 217 | photos.add(photo[i]); 218 | continue; 219 | } 220 | if (photo[i] != null && !photo[i].fileId().equals(photo[i + 1].fileId()) 221 | && !photo[i].fileUniqueId().startsWith(photo[i + 1].fileUniqueId().substring(0, photo[i + 1].fileUniqueId().length() - 1))) { 222 | photos.add(photo[i]); 223 | } 224 | } 225 | return photos; 226 | } 227 | 228 | public static InlineKeyboardMarkup buildMenuButtons() { 229 | Map keyboardButtons = new LinkedHashMap<>(TelegramOnebotAdapter.config.getCommand().getMenu()); 230 | 231 | List buttons = keyboardButtons.entrySet().stream() 232 | .map(entry -> { 233 | InlineKeyboardButton button = new InlineKeyboardButton(entry.getKey()); 234 | if (entry.getValue().matches("^http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?$")) { 235 | button.url(entry.getValue()); 236 | } else { 237 | button.callbackData(entry.getValue()); 238 | } 239 | return button; 240 | }) 241 | .toList(); 242 | 243 | InlineKeyboardButton[][] buttonArray = new InlineKeyboardButton[(keyboardButtons.size() + 2) / 3][]; 244 | for (int i = 0; i < buttonArray.length; i++) { 245 | buttonArray[i] = buttons.subList(i * 3, Math.min((i + 1) * 3, keyboardButtons.size())).toArray(new InlineKeyboardButton[0]); 246 | } 247 | 248 | return new InlineKeyboardMarkup(buttonArray); 249 | } 250 | 251 | private static String serializeCommand(String realMessage) { 252 | String tempStr = String.copyValueOf(realMessage.toCharArray()); 253 | Map commandMap = TelegramOnebotAdapter.config.getCommand().getCommandMap(); 254 | String prefix = TelegramOnebotAdapter.config.getCommand().getPrefix(); 255 | for (Map.Entry entry : commandMap.entrySet()) { 256 | String key = prefix+entry.getKey(); 257 | String value = prefix+entry.getValue(); 258 | tempStr = tempStr.replace(key + ' ', value + ' '); 259 | 260 | if (tempStr.endsWith(key)) { 261 | int lastIndex = tempStr.lastIndexOf(key); 262 | tempStr = tempStr.substring(0, lastIndex) + value + tempStr.substring(lastIndex + key.length()); 263 | } 264 | } 265 | 266 | return tempStr; 267 | } 268 | 269 | public static String arrayMessageToString(JSONArray arrayMessage) { 270 | StringBuilder message = new StringBuilder(); 271 | for (int i = 0; i < arrayMessage.size(); i++) { 272 | JSONObject messageObject = arrayMessage.getJSONObject(i); 273 | if (messageObject.getStr("type").equals("text")) { 274 | message.append(specialCharacterEscape(messageObject.getJSONObject("data").getStr("text"))); 275 | } else if (messageObject.getStr("type").equals("at")) { 276 | message.append("[CQ:at,qq=").append(specialCharacterEscape(messageObject.getJSONObject("data").getStr("qq"))).append("]"); 277 | } else if(messageObject.getStr("type").equals("image")) { 278 | message.append("[CQ:image,file=").append(specialCharacterEscape(messageObject.getJSONObject("data").getStr("file"))).append("]"); 279 | } 280 | } 281 | return message.toString(); 282 | } 283 | 284 | public static String stringMessageToArray(String message) { 285 | JsonArray arrayMessage = new JsonArray(); 286 | Matcher matcher = Pattern.compile("\\[CQ:(\\S+?)(,\\S+)?]").matcher(message); 287 | int lastIndex = 0; 288 | while (matcher.find()) { 289 | String msg = message.substring(lastIndex, matcher.start()); 290 | if (!msg.isEmpty()) { 291 | Messages.Text messageObject = new Messages.Text(specialCharacterUnescape(msg)); 292 | arrayMessage.add(messageObject.toJson()); 293 | } 294 | lastIndex = matcher.end(); 295 | String type = matcher.group(1); 296 | String data = matcher.group(2); 297 | if (type.equals("at")) { 298 | Messages.At atObject = new Messages.At(Long.parseLong(data.substring(4))); 299 | arrayMessage.add(atObject.toJson()); 300 | } else if (type.equals("image")) { 301 | Messages.Image imageObject = new Messages.Image(data.substring(5)); 302 | arrayMessage.add(imageObject.toJson()); 303 | } else if (type.equals("record")) { 304 | Messages.Record recordObject = new Messages.Record(data.substring(5)); 305 | arrayMessage.add(recordObject.toJson()); 306 | } 307 | } 308 | String msg = message.substring(lastIndex); 309 | if (!msg.isEmpty()) { 310 | Messages.Text messageObject = new Messages.Text(specialCharacterUnescape(msg)); 311 | arrayMessage.add(messageObject.toJson()); 312 | } 313 | return arrayMessage.toString(); 314 | } 315 | 316 | private static String specialCharacterEscape(String message) { 317 | return message.replace("&", "&") 318 | .replace("[", "[") 319 | .replace("]", "]") 320 | .replace(",", ","); 321 | } 322 | 323 | private static String specialCharacterUnescape(String message) { 324 | return message.replace(",", ",") 325 | .replace("]", "]") 326 | .replace("[", "[") 327 | .replace("&", "&"); 328 | } 329 | 330 | @Override 331 | public void run(ApplicationArguments args) { 332 | log.info("Telegram to Onebot converter is running..."); 333 | HibernateUtil.init(TelegramOnebotAdapter.INSTANCE); 334 | TelegramApi.init(); 335 | } 336 | 337 | 338 | public static String handleTextMessage(String message) { 339 | final JSONObject jsonObject = new JSONObject(message); 340 | if (jsonObject.isNull("sender")) { 341 | LogWebSocketHandler.broadcast(jsonObject.toString()); 342 | return jsonObject.toString(); 343 | } 344 | boolean isGroup = jsonObject.getInt("group_id") != null; 345 | 346 | StringBuilder stringBuilder = new StringBuilder(); 347 | stringBuilder.append(DateUtil.format(new Date(jsonObject.getLong("time")), "yyyy-MM-dd HH:mm:ss")).append(" "); 348 | stringBuilder.append("["); 349 | if (isGroup) { 350 | stringBuilder.append("群组").append(jsonObject.getInt("group_id")).append(" "); 351 | } else { 352 | stringBuilder.append("私聊 "); 353 | } 354 | stringBuilder.append(jsonObject.getJSONObject("sender").getStr("card")).append("(") 355 | .append(jsonObject.getJSONObject("sender").getStr("user_id")).append(")]: ") 356 | .append(TelegramToOnebot.arrayMessageToString(jsonObject.getJSONArray("message"))); 357 | 358 | return stringBuilder.toString(); 359 | } 360 | } 361 | -------------------------------------------------------------------------------- /src/main/java/cn/travellerr/onebottelegram/onebotWebsocket/onebotSerialize/OnebotAction.java: -------------------------------------------------------------------------------- 1 | package cn.travellerr.onebottelegram.onebotWebsocket.onebotSerialize; 2 | 3 | import cn.chahuyun.hibernateplus.HibernateFactory; 4 | import cn.hutool.core.date.DateUtil; 5 | import cn.travellerr.onebotApi.*; 6 | import cn.travellerr.onebottelegram.TelegramOnebotAdapter; 7 | import cn.travellerr.onebottelegram.converter.AudioConverter; 8 | import cn.travellerr.onebottelegram.converter.LanguageCode; 9 | import cn.travellerr.onebottelegram.converter.TelegramToOnebot; 10 | import cn.travellerr.onebottelegram.converter.Translator; 11 | import cn.travellerr.onebottelegram.hibernate.entity.Group; 12 | import cn.travellerr.onebottelegram.model.ApiRequest; 13 | import cn.travellerr.onebottelegram.model.Messages; 14 | import cn.travellerr.onebottelegram.telegramApi.TelegramApi; 15 | import com.google.gson.*; 16 | import com.pengrad.telegrambot.model.*; 17 | import com.pengrad.telegrambot.model.request.ChatAction; 18 | import com.pengrad.telegrambot.model.request.ParseMode; 19 | import com.pengrad.telegrambot.model.request.ReplyParameters; 20 | import com.pengrad.telegrambot.request.SendMessage; 21 | import com.pengrad.telegrambot.request.*; 22 | import com.pengrad.telegrambot.response.BaseResponse; 23 | import com.pengrad.telegrambot.response.GetChatResponse; 24 | import com.pengrad.telegrambot.response.SendResponse; 25 | import org.springframework.web.socket.TextMessage; 26 | import org.springframework.web.socket.WebSocketMessage; 27 | import org.springframework.web.socket.WebSocketSession; 28 | 29 | import java.io.File; 30 | import java.nio.file.Files; 31 | import java.nio.file.Paths; 32 | import java.util.*; 33 | 34 | import static org.reflections.Reflections.log; 35 | 36 | public class OnebotAction { 37 | 38 | public static final Gson GSON = new Gson(); 39 | 40 | public static void handleAction(WebSocketSession session, String payload) { 41 | ApiRequest.BaseApiRequest jsonObject = GSON.fromJson(payload, ApiRequest.BaseApiRequest.class); 42 | String action = jsonObject.getAction(); 43 | String echo = jsonObject.getEcho(); 44 | try { 45 | long groupId, userId; 46 | int msgId; 47 | String message, title, groupName; 48 | ApiRequest.Params params = jsonObject.getParams(); 49 | 50 | switch (action) { 51 | case "get_version_info": 52 | session.sendMessage(message(echo, new GetVersionInfo("Tele-KiraLink", TelegramOnebotAdapter.VERSION, "v11"))); 53 | log.info("发送消息至 Onebot --> {}", new GetVersionInfo("Tele-KiraLink", TelegramOnebotAdapter.VERSION, "v11")); 54 | break; 55 | case "get_login_info": 56 | session.sendMessage(message(echo, new GetLoginInfo(TelegramApi.getMeResponse.user().id(), TelegramApi.getMeResponse.user().username()))); 57 | break; 58 | case "get_friend_list": 59 | session.sendMessage(getFriendList(echo)); 60 | break; 61 | case "get_group_list": 62 | session.sendMessage(getGroupList(echo)); 63 | break; 64 | case "get_group_member_list": 65 | groupId = -Math.abs(params.getGroupId()); 66 | session.sendMessage(getGroupMemberList(echo, groupId)); 67 | break; 68 | case "get_group_info": 69 | groupId = -Math.abs(params.getGroupId()); 70 | session.sendMessage(getGroupInfo(echo, groupId)); 71 | break; 72 | case "get_group_member_info": 73 | groupId = -params.getGroupId(); 74 | userId = params.getUserId(); 75 | session.sendMessage(getGroupMemberInfo(echo, groupId, userId)); 76 | break; 77 | case "get_msg": 78 | msgId = params.getMessageId(); 79 | session.sendMessage(getMsg(echo, msgId)); 80 | break; 81 | case "set_group_ban": 82 | groupId = -params.getGroupId(); 83 | userId = params.getUserId(); 84 | int duration = params.getDuration() == 0 ? 0 : Math.max(params.getDuration(), 30); 85 | session.sendMessage(setGroupBan(groupId, userId, duration)); 86 | break; 87 | case "delete_msg": 88 | msgId = params.getMessageId(); 89 | session.sendMessage(deleteMessage(echo, msgId)); 90 | break; 91 | case "send_group_msg": 92 | groupId = -params.getGroupId(); 93 | message = params.getMessage().toString(); 94 | session.sendMessage(sendMessage(echo, groupId, message, true)); 95 | break; 96 | case "send_private_msg": 97 | userId = params.getUserId(); 98 | message = params.getMessage().toString(); 99 | session.sendMessage(sendMessage(echo, userId, message, false)); 100 | break; 101 | case "send_msg": 102 | userId = params.getUserId(); 103 | groupId = -params.getGroupId(); 104 | message = params.getMessage().toString(); 105 | boolean isPrivate = userId != -1L; 106 | long targetId = isPrivate ? userId : groupId; 107 | session.sendMessage(sendMessage(echo, targetId, message, !isPrivate)); 108 | break; 109 | case "set_group_special_title": 110 | groupId = -params.getGroupId(); 111 | userId = params.getUserId(); 112 | title = params.getSpecialTitle(); 113 | TelegramApi.bot.execute(new SendChatAction(groupId, ChatAction.typing)); 114 | TelegramApi.bot.execute(new PromoteChatMember(groupId, userId).canManageChat(true)); 115 | TelegramApi.bot.execute(new SetChatAdministratorCustomTitle(groupId, userId, title)); 116 | break; 117 | case "set_group_name": 118 | groupId = -params.getGroupId(); 119 | groupName = params.getGroupName(); 120 | TelegramApi.bot.execute(new SetChatTitle(groupId, groupName)); 121 | break; 122 | case "set_group_kick": 123 | groupId = -params.getGroupId(); 124 | userId = params.getUserId(); 125 | BaseResponse response = TelegramApi.bot.execute(new BanChatMember(groupId, userId).untilDate(30)); 126 | System.out.println(response.description()); 127 | break; 128 | case "set_group_admin": 129 | groupId = -params.getGroupId(); 130 | userId = params.getUserId(); 131 | TelegramApi.bot.execute(new PromoteChatMember(groupId, userId).canManageChat(true)); 132 | break; 133 | case "get_avatar": 134 | userId = params.getUserId(); 135 | UserProfilePhotos userProfilePhotos = TelegramApi.bot.execute(new GetUserProfilePhotos(userId)).photos(); 136 | String avatarId = ""; 137 | 138 | if (userProfilePhotos != null && userProfilePhotos.photos().length > 0) { 139 | com.pengrad.telegrambot.model.PhotoSize[] photoSizes = userProfilePhotos.photos()[0]; 140 | if (photoSizes.length > 2) { 141 | avatarId = TelegramApi.bot.getFullFilePath( 142 | TelegramApi.bot.execute(new GetFile(photoSizes[2].fileId())).file() 143 | ); 144 | } 145 | } 146 | 147 | JsonObject obj = data(echo, true); 148 | obj.addProperty("message", avatarId); 149 | session.sendMessage(new TextMessage(obj.toString())); 150 | break; 151 | case "get_status": 152 | JsonObject statusObject = data(echo, true); 153 | statusObject.addProperty("online", true); 154 | statusObject.addProperty("good", true); 155 | session.sendMessage(new TextMessage(statusObject.toString())); 156 | break; 157 | default: 158 | log.error("未知的 OneBot 消息: {}", action); 159 | JsonObject object = GSON.fromJson(new Data(echo, "", 1404, "failed", "").toString(), JsonObject.class); 160 | object.add("data", JsonNull.INSTANCE); 161 | session.sendMessage(new TextMessage(object.toString())); 162 | break; 163 | } 164 | } catch (Exception e) { 165 | log.error("处理 OneBot 消息失败", e); 166 | } 167 | } 168 | 169 | private static WebSocketMessage getMsg(String echo, int msgId) { 170 | JsonObject msg; 171 | try { 172 | msg = HibernateFactory.selectOne(cn.travellerr.onebottelegram.hibernate.entity.Message.class, msgId) 173 | .getMessage(); 174 | } catch (NullPointerException e) { 175 | log.error("获取消息失败: {}", e.getMessage()); 176 | return new TextMessage(data(echo, "", 1404, "failed", "").toString()); 177 | } 178 | msg.remove("self_id"); 179 | msg.remove("post_type"); 180 | msg.remove("sub_type"); 181 | msg.remove("font"); 182 | msg.remove("raw_message"); 183 | msg.remove("user_id"); 184 | try { 185 | msg.remove("anonymous"); 186 | msg.remove("group_id"); 187 | } catch (Exception ignored) { 188 | } 189 | msg.add("real_id", msg.get("message_id")); 190 | return new TextMessage( 191 | data(echo, "", 0, "ok", "", msg).toString() 192 | ); 193 | 194 | } 195 | 196 | private static WebSocketMessage setGroupBan(long groupId, long userId, int duration) { 197 | BaseResponse response; 198 | if (duration != 0) { 199 | int offset = (int) (DateUtil.offsetSecond(new Date(), duration).getTime() / 1000); 200 | response = TelegramApi.bot.execute(new RestrictChatMember(groupId, userId, new ChatPermissions().canSendMessages(false).canPinMessages(false).canSendPhotos(false).canSendVideos(false)).untilDate(offset)); 201 | } else { 202 | response = TelegramApi.bot.execute(new RestrictChatMember(groupId, userId, new ChatPermissions() 203 | .canSendMessages(true) 204 | .canSendAudios(true) 205 | .canSendDocuments(true) 206 | .canSendPhotos(true) 207 | .canSendVideos(true) 208 | .canSendVideoNotes(true) 209 | .canSendVoiceNotes(true) 210 | .canSendPolls(true) 211 | .canSendOtherMessages(true) 212 | .canAddWebPagePreviews(true) 213 | .canChangeInfo(true) 214 | .canInviteUsers(true) 215 | .canPinMessages(true) 216 | .canManageTopics(true) 217 | .canPostStories(true) 218 | .canEditStories(true) 219 | .canDeleteStories(true))); 220 | } 221 | boolean status = response.isOk(); 222 | 223 | return new TextMessage(data("0", status).toString()); 224 | } 225 | 226 | 227 | private static WebSocketMessage getGroupInfo(String echo, long groupId) { 228 | ChatFullInfo info = TelegramApi.bot.execute(new GetChat(groupId)).chat(); 229 | int count = TelegramApi.bot.execute(new GetChatMemberCount(groupId)).count(); 230 | JsonObject object = data(echo); 231 | object.add("data", GSON.toJsonTree(new GroupInfo(Math.abs(groupId), info.title(), count, 2000))); 232 | 233 | return new TextMessage(object.toString()); 234 | } 235 | 236 | 237 | private static TextMessage message(String echo, Object message) { 238 | JsonObject object = data(echo); 239 | JsonElement messages = GSON.toJsonTree(message); 240 | object.add("data", messages); 241 | log.info("发送消息至 Onebot --> {}", object); 242 | return new TextMessage(object.toString()); 243 | } 244 | 245 | private static TextMessage deleteMessage(String echo, int msgId) { 246 | long chatId = TelegramToOnebot.messageIdToChatId.get(msgId); 247 | System.out.println("删除消息: " + chatId + " " + msgId); 248 | TelegramApi.bot.execute(new DeleteMessage(chatId, Math.toIntExact(msgId))); 249 | JsonObject object = data(echo); 250 | object.add("data", new JsonArray()); 251 | log.info("发送消息至 Onebot --> {}", object); 252 | return new TextMessage(object.toString()); 253 | } 254 | 255 | private static TextMessage getFriendList(String echo) { 256 | JsonObject object = data(echo); 257 | Friend friend = new Friend(0, "Tele-KiraLink", "Tele-KiraLink"); 258 | List friends = List.of(friend); 259 | JsonArray messages = GSON.toJsonTree(friends).getAsJsonArray(); 260 | object.add("data", messages); 261 | 262 | log.info("发送消息至 Onebot --> {}", object); 263 | return new TextMessage(object.toString()); 264 | } 265 | 266 | public static TextMessage getGroupList(String echo) { 267 | JsonObject object = data(echo); 268 | 269 | List groupList = HibernateFactory.selectList(Group.class); 270 | 271 | if (groupList == null) { 272 | object.add("data", GSON.toJsonTree(new GetGroupList(List.of()))); 273 | return new TextMessage(object.toString()); 274 | } 275 | 276 | List groupInfoList = new ArrayList<>(); 277 | 278 | for (Group group : groupList) { 279 | groupInfoList.add(new GroupInfo(-group.getGroupId(), group.getGroupName(), group.getMemberCount(), group.getMaxMemberCount())); 280 | } 281 | 282 | JsonArray messages = GSON.toJsonTree(groupInfoList).getAsJsonArray(); 283 | 284 | object.add("data", messages); 285 | log.info("发送消息至 Onebot --> {}", object); 286 | return new TextMessage(object.toString()); 287 | 288 | } 289 | 290 | private static TextMessage getGroupMemberList(String echo, long groupId) { 291 | JsonObject object = data(echo); 292 | Group group = HibernateFactory.selectOne(Group.class, groupId); 293 | if (group == null) { 294 | object.add("data", GSON.toJsonTree(new GetGroupMemberListResponse(List.of()))); 295 | return new TextMessage(object.toString()); 296 | } 297 | 298 | List membersIdList = group.getMembersIdList(); 299 | List memberInfoList = new ArrayList<>(); 300 | for (Long memberId : membersIdList) { 301 | memberInfoList.add(getChatMember(groupId, memberId)); 302 | } 303 | 304 | JsonArray messages = GSON.toJsonTree(memberInfoList).getAsJsonArray(); 305 | object.add("data", messages); 306 | log.info("发送消息至 Onebot --> {}", object); 307 | return new TextMessage(object.toString()); 308 | } 309 | 310 | private static TextMessage getGroupMemberInfo(String echo, long groupId, long memberId) { 311 | JsonObject object = data(echo); 312 | 313 | getChatMember(groupId, memberId); 314 | MemberInfo memberInfo = getChatMember(groupId, memberId); 315 | 316 | 317 | object.add("data", GSON.toJsonTree(memberInfo)); 318 | log.info("发送消息至 Onebot --> {}", object); 319 | return new TextMessage(object.toString()); 320 | } 321 | 322 | public static TextMessage sendMessage(String echo, long chatId, String messageStr, boolean isGroup) { 323 | String realMessage = messageStr; 324 | System.out.println(realMessage); 325 | if (!TelegramOnebotAdapter.config.getOnebot().isUseArray()) { 326 | realMessage = TelegramToOnebot.stringMessageToArray(messageStr); 327 | } 328 | 329 | JsonArray messageArray = JsonParser.parseString(realMessage).getAsJsonArray(); 330 | 331 | LanguageCode languageCode = LanguageCode.ZH_HANS; 332 | 333 | StringBuilder sb = new StringBuilder(); 334 | SendPhoto photo = null; 335 | SendVoice audio = null; 336 | String convertedAudioPath = null; 337 | ReplyParameters replyParameters = null; 338 | 339 | for(JsonElement m : messageArray) { 340 | Messages.BaseMessage baseMessage = GSON.fromJson(m.toString(), Messages.BaseMessage.class); 341 | 342 | 343 | switch (baseMessage.getType()) { 344 | case "at": 345 | Long userId = baseMessage.getData().getQq(); 346 | String username, firstName; 347 | 348 | if (isGroup) { 349 | User user = TelegramApi.bot.execute(new GetChatMember(chatId, userId)).chatMember().user(); 350 | languageCode = LanguageCode.parseLanguageCode(user.languageCode()); 351 | username = user.username(); 352 | firstName = user.firstName(); 353 | } else { 354 | ChatFullInfo fullInfo = TelegramApi.bot.execute(new GetChat(chatId)).chat(); 355 | userId = chatId; 356 | username = fullInfo.username(); 357 | firstName = fullInfo.firstName(); 358 | } 359 | 360 | sb.append(username != null ? "@" + username : "" + firstName + ""); 361 | break; 362 | case "text": 363 | String message = baseMessage.getData().getText(); 364 | if (!message.startsWith("html://")) { 365 | message = message 366 | .replace("&", "&") 367 | .replace("<", "<") 368 | .replace(">", ">") 369 | .replace("\"", """); 370 | } else { 371 | message = message.substring(7); 372 | } 373 | if (TelegramOnebotAdapter.config.getTelegram().getBot().isUseTranslator() && !languageCode.equals(LanguageCode.ZH_HANS)) { 374 | message = Translator.Trans(languageCode, message); 375 | } 376 | sb.append(message); 377 | break; 378 | case "image": 379 | String imageFilePath = baseMessage.getData().getFile(); 380 | if (imageFilePath.startsWith("http")) { 381 | photo = new SendPhoto(chatId, imageFilePath); 382 | } else if(imageFilePath.startsWith("base64://")) { 383 | byte[] bytes = Base64.getDecoder().decode(imageFilePath.substring(9)); 384 | photo = new SendPhoto(chatId, bytes); 385 | } else { 386 | File file = new File(imageFilePath.replaceFirst("^file://", "")); 387 | photo = new SendPhoto(chatId, file); 388 | } 389 | break; 390 | case "reply": 391 | replyParameters = new ReplyParameters(baseMessage.getData().getId()); 392 | break; 393 | case "record": 394 | if (TelegramOnebotAdapter.config.getSpring().getFfmpegPath().isEmpty()) { 395 | sb.append("[未配置ffmpeg,无法发送语音消息]"); 396 | break; 397 | } 398 | String recordFilePath = baseMessage.getData().getFile(); 399 | if (recordFilePath == null || recordFilePath.isEmpty()) { 400 | sb.append("[语音消息文件路径为空]"); 401 | break; 402 | } 403 | convertedAudioPath = AudioConverter.convertToTelegramAudio(recordFilePath); 404 | if (convertedAudioPath != null) { 405 | if (convertedAudioPath.isEmpty()) { 406 | if (recordFilePath.startsWith("http")) { 407 | audio = new SendVoice(chatId, recordFilePath); 408 | } else if(recordFilePath.startsWith("base64://")) { 409 | byte[] bytes = Base64.getDecoder().decode(recordFilePath.substring(9)); 410 | audio = new SendVoice(chatId, bytes); 411 | } 412 | else { 413 | File file = new File(recordFilePath.replaceFirst("^file://", "")); 414 | audio = new SendVoice(chatId, file); 415 | } 416 | continue; 417 | } 418 | File audioFile = new File(convertedAudioPath); 419 | if (audioFile.exists()) { 420 | audio = new SendVoice(chatId, audioFile); 421 | } else { 422 | sb.append("[音频文件不存在]"); 423 | } 424 | } else { 425 | sb.append("[无法转换语音消息]"); 426 | } 427 | 428 | } 429 | } 430 | 431 | String text = sb.toString(); 432 | SendResponse response; 433 | 434 | if (photo != null) { 435 | photo.caption(text); 436 | photo.parseMode(ParseMode.HTML); 437 | if (replyParameters != null) { 438 | photo.replyParameters(replyParameters); 439 | } 440 | 441 | response = TelegramApi.bot.execute(photo); 442 | } else if (audio != null) { 443 | audio.caption(text); 444 | audio.parseMode(ParseMode.HTML); 445 | if (replyParameters != null) { 446 | audio.replyParameters(replyParameters); 447 | } 448 | 449 | response = TelegramApi.bot.execute(audio); 450 | 451 | try { 452 | if (convertedAudioPath != null && !convertedAudioPath.isEmpty()) { 453 | Files.deleteIfExists(Paths.get(convertedAudioPath)); 454 | } 455 | } catch (Exception e) { 456 | log.error("删除临时音频文件失败", e); 457 | } 458 | 459 | } else { 460 | SendMessage request = new SendMessage(chatId, text); 461 | request.parseMode(ParseMode.HTML); 462 | if (replyParameters != null) { 463 | request.replyParameters(replyParameters); 464 | } 465 | 466 | response = TelegramApi.bot.execute(request); 467 | } 468 | 469 | 470 | 471 | if (!response.isOk()) { 472 | JsonObject obj = new JsonObject(); 473 | obj.addProperty("error_code", response.description()); 474 | int messageId = TelegramApi.bot.execute(new SendMessage(chatId, "发送失败: " + response.description())).message().messageId(); 475 | 476 | new Thread(() -> { 477 | try { 478 | Thread.sleep(10000); 479 | TelegramApi.bot.execute(new DeleteMessage(chatId, messageId)); 480 | } catch (Exception e) { 481 | log.error("删除失败", e); 482 | } 483 | }).start(); 484 | 485 | log.info("发送消息至 Onebot --> {}", obj); 486 | return new TextMessage(data(echo, "", 1404, "failed", "", null).toString()); 487 | } else { 488 | TelegramToOnebot.messageIdToChatId.put(response.message().messageId(), isGroup ? -Math.abs(chatId) : Math.abs(chatId)); 489 | 490 | JsonObject obj = new JsonObject(); 491 | obj.addProperty("message_id", response.message().messageId()); 492 | JsonObject object = data(echo, "", 0, "ok", "", obj); 493 | log.info("发送消息至 Onebot --> {}", object); 494 | return new TextMessage(object.toString()); 495 | } 496 | } 497 | 498 | 499 | 500 | 501 | public static MemberInfo getChatMember(long groupId, long memberId) { 502 | ChatMember chat = TelegramApi.bot.execute(new GetChatMember(groupId, memberId)).chatMember(); 503 | if (chat == null) { 504 | Group group = HibernateFactory.selectOne(Group.class, groupId); 505 | GetChatResponse response = TelegramApi.bot.execute(new GetChat(groupId)); 506 | if (response.chat() == null) { 507 | HibernateFactory.delete(group); 508 | return null; 509 | } 510 | return null; 511 | } 512 | String title = "", status = chat.status().toString(); 513 | String username = chat.user().username(); 514 | if (username == null) { 515 | username = chat.user().firstName(); 516 | } 517 | if (chat.canPromoteMembers()) { 518 | status="creator"; 519 | } 520 | return new MemberInfo(Math.abs(groupId), memberId, username, chat.user().firstName(), "unknown", 0, "虚拟地区", 0, 0, "0",levelConverter(status),false , title,0 ,chat.canChangeInfo()); 521 | } 522 | 523 | 524 | private static String levelConverter(String memberStatus) { 525 | return switch (memberStatus) { 526 | case "creator" -> "owner"; 527 | case "administrator" -> "admin"; 528 | default -> "member"; 529 | }; 530 | } 531 | 532 | private static JsonObject data(String echo) { 533 | return data(echo, "", 0, "ok", ""); 534 | } 535 | 536 | private static JsonObject data(String echo, boolean status) { 537 | return data(echo, "", 0, status ? "ok" : "failed", ""); 538 | } 539 | 540 | private static JsonObject data(String echo, String message, int retcode, String status, String wording) { 541 | return data(echo, message, retcode, status, wording, null); 542 | } 543 | 544 | private static JsonObject data(String echo, String message, int retcode, String status, String wording, JsonElement data) { 545 | JsonObject obj = JsonParser.parseString(new Data(echo, message, retcode, status, wording).toString()).getAsJsonObject(); 546 | obj.add("data", Objects.requireNonNullElse(data, JsonNull.INSTANCE)); 547 | return obj; 548 | } 549 | } 550 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------