diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts index 523b5f92..2f2d10d8 100644 --- a/frontend/src/api/agent/index.ts +++ b/frontend/src/api/agent/index.ts @@ -182,7 +182,7 @@ export interface IMChannel { id: string; tenant_id?: number; agent_id: string; - platform: 'wecom' | 'feishu' | 'slack'; + platform: 'wecom' | 'feishu' | 'slack' | 'telegram'; name: string; enabled: boolean; mode: 'webhook' | 'websocket'; diff --git a/frontend/src/components/IMChannelPanel.vue b/frontend/src/components/IMChannelPanel.vue index f0f07f3b..9e124cd4 100644 --- a/frontend/src/components/IMChannelPanel.vue +++ b/frontend/src/components/IMChannelPanel.vue @@ -23,7 +23,7 @@
- {{ channel.platform === 'wecom' ? $t('agentEditor.im.wecom') : channel.platform === 'feishu' ? $t('agentEditor.im.feishu') : $t('agentEditor.im.slack') }} + {{ platformLabel(channel.platform) }} {{ channel.name || $t('agentEditor.im.unnamed') }}
@@ -89,6 +89,7 @@ {{ $t('agentEditor.im.wecom') }} {{ $t('agentEditor.im.feishu') }} {{ $t('agentEditor.im.slack') }} + {{ $t('agentEditor.im.telegram') }}
@@ -236,6 +237,28 @@ + + + + @@ -266,7 +289,7 @@ const knowledgeBases = ref<{ id: string; name: string }[]>([]); const defaultCredentials = (): Record => ({}); const formData = ref({ - platform: 'wecom' as 'wecom' | 'feishu' | 'slack', + platform: 'wecom' as 'wecom' | 'feishu' | 'slack' | 'telegram', name: '', mode: 'websocket' as 'webhook' | 'websocket', output_mode: 'stream' as 'stream' | 'full', @@ -274,6 +297,11 @@ const formData = ref({ credentials: defaultCredentials(), }); +function platformLabel(platform: string): string { + const key = `agentEditor.im.${platform}`; + return t(key); +} + async function loadChannels() { loading.value = true; try { @@ -510,6 +538,12 @@ onMounted(() => { background: rgba(224, 30, 90, 0.08); color: #e01e5a; } + + &.telegram { + background: rgba(38, 166, 219, 0.08); + color: #26a6db; + } + } .channel-name { diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 2db1f1e3..438ce9e4 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -3182,10 +3182,11 @@ export default { }, im: { title: 'IM Integration', - description: 'Connect agent to instant messaging platforms like WeCom, Feishu and Slack', + description: 'Connect agent to instant messaging platforms like WeCom, Feishu, Slack and Telegram', wecom: 'WeCom', feishu: 'Feishu', slack: 'Slack', + telegram: 'Telegram', addChannel: 'Add Channel', editChannel: 'Edit Channel', deleteConfirm: 'Are you sure you want to delete this channel? This action cannot be undone.', @@ -3203,6 +3204,7 @@ export default { wecomConsole: 'WeCom Admin', feishuConsole: 'Feishu Open Platform', slackConsole: 'Slack API Console', + telegramConsole: 'Telegram BotFather', modeHint: 'WebSocket is recommended for easier setup', consoleTip: 'to get credentials', fileKnowledgeBase: 'File Storage Knowledge Base', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index f2ba4ab5..2f5b77c7 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -3212,10 +3212,11 @@ export default { }, im: { title: "IM 통합", - description: "에이전트를 WeCom, Feishu, Slack 등 인스턴트 메시징 플랫폼에 연결", + description: "에이전트를 WeCom, Feishu, Slack, Telegram 등 인스턴트 메시징 플랫폼에 연결", wecom: "WeCom", feishu: "Feishu", slack: "Slack", + telegram: "Telegram", addChannel: "채널 추가", editChannel: "채널 편집", deleteConfirm: "이 채널을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.", @@ -3233,6 +3234,7 @@ export default { wecomConsole: "WeCom 관리 콘솔", feishuConsole: "Feishu 개발 플랫폼", slackConsole: "Slack API 콘솔", + telegramConsole: "Telegram BotFather", modeHint: "WebSocket 방식이 설정이 더 간편하여 권장됩니다", consoleTip: "자격 증명 정보를 가져오세요", fileKnowledgeBase: "파일 저장 지식 베이스", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 30321f44..6c22ee7a 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -2845,10 +2845,11 @@ export default { }, im: { title: 'Интеграция IM', - description: 'Подключите агента к платформам мгновенных сообщений, таким как WeCom, Feishu и Slack', + description: 'Подключите агента к платформам мгновенных сообщений, таким как WeCom, Feishu, Slack и Telegram', wecom: 'WeCom', feishu: 'Feishu', slack: 'Slack', + telegram: 'Telegram', addChannel: 'Добавить канал', editChannel: 'Редактировать канал', deleteConfirm: 'Вы уверены, что хотите удалить этот канал? Это действие не может быть отменено.', @@ -2866,6 +2867,7 @@ export default { wecomConsole: 'Консоль WeCom', feishuConsole: 'Платформа Feishu', slackConsole: 'Консоль Slack API', + telegramConsole: 'Telegram BotFather', modeHint: 'Рекомендуется WebSocket — проще настроить', consoleTip: 'для получения учётных данных', fileKnowledgeBase: 'База знаний для файлов', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index ae38980f..3a235db3 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -3157,10 +3157,11 @@ export default { }, im: { title: "IM 集成", - description: "将智能体接入即时通讯平台,支持企业微信、飞书和Slack", + description: "将智能体接入即时通讯平台,支持企业微信、飞书、Slack和Telegram", wecom: "企业微信", feishu: "飞书", slack: "Slack", + telegram: "Telegram", addChannel: "添加渠道", editChannel: "编辑渠道", deleteConfirm: "确定删除该渠道?删除后无法恢复。", @@ -3178,6 +3179,7 @@ export default { wecomConsole: "企业微信管理后台", feishuConsole: "飞书开放平台", slackConsole: "Slack API 控制台", + telegramConsole: "Telegram BotFather", modeHint: "推荐使用 WebSocket 方式接入,配置更简单", consoleTip: "前往获取凭证信息", fileKnowledgeBase: "文件保存知识库", diff --git a/internal/container/container.go b/internal/container/container.go index 84b18bff..24fd66e9 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -56,6 +56,7 @@ import ( imPkg "github.com/Tencent/WeKnora/internal/im" "github.com/Tencent/WeKnora/internal/im/feishu" "github.com/Tencent/WeKnora/internal/im/slack" + "github.com/Tencent/WeKnora/internal/im/telegram" "github.com/Tencent/WeKnora/internal/im/wecom" "github.com/Tencent/WeKnora/internal/infrastructure/docparser" "github.com/Tencent/WeKnora/internal/logger" @@ -1094,6 +1095,44 @@ func registerIMAdapterFactories(imService *imPkg.Service) { } }) + // Register Telegram adapter factory + imService.RegisterAdapterFactory("telegram", func(factoryCtx context.Context, channel *imPkg.IMChannel, msgHandler func(context.Context, *imPkg.IncomingMessage) error) (imPkg.Adapter, context.CancelFunc, error) { + creds, err := parseCredentials(channel.Credentials) + if err != nil { + return nil, nil, fmt.Errorf("parse telegram credentials: %w", err) + } + + botToken := getString(creds, "bot_token") + + mode := channel.Mode + if mode == "" { + mode = "websocket" + } + + switch mode { + case "webhook": + secretToken := getString(creds, "secret_token") + adapter := telegram.NewWebhookAdapter(botToken, secretToken) + return adapter, nil, nil + + case "websocket": + client := telegram.NewLongConnClient(botToken, msgHandler) + + wsCtx, wsCancel := context.WithCancel(context.Background()) + go func() { + if err := client.Start(wsCtx); err != nil && wsCtx.Err() == nil { + logger.Errorf(context.Background(), "[IM] Telegram long polling stopped for channel %s: %v", channel.ID, err) + } + }() + + adapter := telegram.NewAdapter(client, botToken) + return adapter, wsCancel, nil + + default: + return nil, nil, fmt.Errorf("unsupported telegram mode: %s", mode) + } + }) + // Load and start all enabled channels from database if err := imService.LoadAndStartChannels(); err != nil { logger.Warnf(ctx, "[IM] Failed to load channels from database: %v", err) diff --git a/internal/handler/im.go b/internal/handler/im.go index 1b2f303d..8d15ef0d 100644 --- a/internal/handler/im.go +++ b/internal/handler/im.go @@ -11,6 +11,9 @@ import ( "github.com/gin-gonic/gin" ) +// validIMPlatforms is the set of supported IM platforms. +var validIMPlatforms = map[string]bool{"wecom": true, "feishu": true, "slack": true, "telegram": true} + // IMHandler handles IM platform callback requests and channel CRUD. type IMHandler struct { imService *im.Service @@ -53,8 +56,8 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) { return } - if req.Platform != "wecom" && req.Platform != "feishu" && req.Platform != "slack" { - c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom', 'feishu' or 'slack'"}) + if !validIMPlatforms[req.Platform] { + c.JSON(http.StatusBadRequest, gin.H{"error": "platform must be 'wecom', 'feishu', 'slack' or 'telegram'"}) return } diff --git a/internal/im/adapter.go b/internal/im/adapter.go index d1cc2c1c..6fb16e04 100644 --- a/internal/im/adapter.go +++ b/internal/im/adapter.go @@ -11,9 +11,10 @@ import ( type Platform string const ( - PlatformWeCom Platform = "wecom" - PlatformFeishu Platform = "feishu" - PlatformSlack Platform = "slack" + PlatformWeCom Platform = "wecom" + PlatformFeishu Platform = "feishu" + PlatformSlack Platform = "slack" + PlatformTelegram Platform = "telegram" ) // MessageType identifies the kind of IM message. diff --git a/internal/im/telegram/adapter.go b/internal/im/telegram/adapter.go new file mode 100644 index 00000000..65b7e025 --- /dev/null +++ b/internal/im/telegram/adapter.go @@ -0,0 +1,403 @@ +package telegram + +import ( + "bytes" + "context" + "crypto/subtle" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "sync" + "time" + + "github.com/gin-gonic/gin" + + "github.com/Tencent/WeKnora/internal/im" + "github.com/Tencent/WeKnora/internal/logger" +) + +// Compile-time checks. +var ( + _ im.Adapter = (*Adapter)(nil) + _ im.StreamSender = (*Adapter)(nil) + _ im.FileDownloader = (*Adapter)(nil) +) + +// Adapter implements im.Adapter for Telegram Bot API. +type Adapter struct { + botToken string + secretToken string // optional X-Telegram-Bot-Api-Secret-Token for webhook verification + client *LongConnClient +} + +// NewWebhookAdapter creates a Telegram adapter for webhook mode. +func NewWebhookAdapter(botToken, secretToken string) *Adapter { + return &Adapter{ + botToken: botToken, + secretToken: secretToken, + } +} + +// NewAdapter creates a Telegram adapter backed by a long-polling client. +func NewAdapter(client *LongConnClient, botToken string) *Adapter { + return &Adapter{ + botToken: botToken, + client: client, + } +} + +func (a *Adapter) Platform() im.Platform { + return im.PlatformTelegram +} + +func (a *Adapter) HandleURLVerification(c *gin.Context) bool { + return false // Telegram does not require URL verification challenges. +} + +func (a *Adapter) VerifyCallback(c *gin.Context) error { + if a.secretToken == "" { + return nil + } + token := c.GetHeader("X-Telegram-Bot-Api-Secret-Token") + if subtle.ConstantTimeCompare([]byte(token), []byte(a.secretToken)) != 1 { + return fmt.Errorf("invalid secret token") + } + return nil +} + +// telegramUpdate represents an incoming Telegram update (subset of fields). +type telegramUpdate struct { + UpdateID int `json:"update_id"` + Message *telegramMsg `json:"message"` +} + +type telegramMsg struct { + MessageID int `json:"message_id"` + From *telegramUser `json:"from"` + Chat telegramChat `json:"chat"` + Text string `json:"text"` + Document *telegramDoc `json:"document"` + Photo []telegramPhoto `json:"photo"` +} + +type telegramUser struct { + ID int64 `json:"id"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Username string `json:"username"` +} + +type telegramChat struct { + ID int64 `json:"id"` + Type string `json:"type"` // "private", "group", "supergroup", "channel" +} + +type telegramDoc struct { + FileID string `json:"file_id"` + FileName string `json:"file_name"` + FileSize int64 `json:"file_size"` + MimeType string `json:"mime_type"` +} + +type telegramPhoto struct { + FileID string `json:"file_id"` + FileSize int `json:"file_size"` + Width int `json:"width"` + Height int `json:"height"` +} + +func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) { + bodyBytes, err := io.ReadAll(c.Request.Body) + if err != nil { + return nil, fmt.Errorf("read body: %w", err) + } + c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes)) + + var update telegramUpdate + if err := json.Unmarshal(bodyBytes, &update); err != nil { + return nil, fmt.Errorf("parse update: %w", err) + } + + return parseUpdate(&update), nil +} + +func parseUpdate(update *telegramUpdate) *im.IncomingMessage { + if update.Message == nil { + return nil + } + return parseTelegramMessage(update.Message) +} + +func parseTelegramMessage(msg *telegramMsg) *im.IncomingMessage { + if msg == nil { + return nil + } + + chatType := im.ChatTypeDirect + chatID := "" + if msg.Chat.Type == "group" || msg.Chat.Type == "supergroup" { + chatType = im.ChatTypeGroup + chatID = fmt.Sprintf("%d", msg.Chat.ID) + } + + userID := "" + userName := "" + if msg.From != nil { + userID = fmt.Sprintf("%d", msg.From.ID) + userName = strings.TrimSpace(msg.From.FirstName + " " + msg.From.LastName) + if userName == "" { + userName = msg.From.Username + } + } + + incoming := &im.IncomingMessage{ + Platform: im.PlatformTelegram, + UserID: userID, + UserName: userName, + ChatID: chatID, + ChatType: chatType, + MessageID: fmt.Sprintf("%d", msg.MessageID), + MessageType: im.MessageTypeText, + Content: msg.Text, + } + + // For group messages, strip bot mention prefix (e.g., "/command@botname text" -> "text") + if chatType == im.ChatTypeGroup { + content := strings.TrimSpace(msg.Text) + // Remove @bot mentions + if idx := strings.Index(content, " "); idx > 0 && strings.Contains(content[:idx], "@") { + content = strings.TrimSpace(content[idx+1:]) + } + incoming.Content = content + } + + // Handle document + if msg.Document != nil { + incoming.MessageType = im.MessageTypeFile + incoming.FileKey = msg.Document.FileID + incoming.FileName = msg.Document.FileName + incoming.FileSize = msg.Document.FileSize + } + + // Handle photo (use the largest photo) + if len(msg.Photo) > 0 { + largest := msg.Photo[len(msg.Photo)-1] + incoming.MessageType = im.MessageTypeImage + incoming.FileKey = largest.FileID + incoming.FileName = "photo.jpg" + incoming.FileSize = int64(largest.FileSize) + } + + return incoming +} + +// resolveChatID returns ChatID if set, otherwise falls back to UserID (for direct messages). +func resolveChatID(incoming *im.IncomingMessage) string { + if incoming.ChatID != "" { + return incoming.ChatID + } + return incoming.UserID +} + +// ── Send reply ── + +func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error { + return a.sendMessage(ctx, resolveChatID(incoming), reply.Content, "") +} + +func (a *Adapter) sendMessage(ctx context.Context, chatID, text, replyToMessageID string) error { + body := map[string]interface{}{ + "chat_id": chatID, + "text": text, + "parse_mode": "Markdown", + } + if replyToMessageID != "" { + body["reply_to_message_id"] = replyToMessageID + } + + return a.callAPI(ctx, "sendMessage", body) +} + +func (a *Adapter) editMessage(ctx context.Context, chatID, messageID, text string) error { + body := map[string]interface{}{ + "chat_id": chatID, + "message_id": json.Number(messageID), + "text": text, + "parse_mode": "Markdown", + } + return a.callAPI(ctx, "editMessageText", body) +} + +// httpClient is a shared HTTP client with a reasonable timeout for Telegram API calls. +var httpClient = &http.Client{Timeout: 15 * time.Second} + +// callAPI calls the Telegram Bot API, discarding the result. +func (a *Adapter) callAPI(ctx context.Context, method string, body interface{}) error { + return a.callAPIWithResult(ctx, method, body, nil) +} + +// callAPIWithResult calls the Telegram Bot API and optionally decodes the result field. +func (a *Adapter) callAPIWithResult(ctx context.Context, method string, body interface{}, result interface{}) error { + url := fmt.Sprintf("https://api.telegram.org/bot%s/%s", a.botToken, method) + + jsonBody, err := json.Marshal(body) + if err != nil { + return fmt.Errorf("marshal body: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(jsonBody)) + if err != nil { + return fmt.Errorf("create request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + + resp, err := httpClient.Do(req) + if err != nil { + return fmt.Errorf("do request: %w", err) + } + defer resp.Body.Close() + + var apiResp struct { + OK bool `json:"ok"` + Result json.RawMessage `json:"result"` + } + if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil { + return fmt.Errorf("decode response: %w", err) + } + if !apiResp.OK { + return fmt.Errorf("telegram API %s failed: %s", method, string(apiResp.Result)) + } + if result != nil { + if err := json.Unmarshal(apiResp.Result, result); err != nil { + return fmt.Errorf("decode result: %w", err) + } + } + return nil +} + +// ── StreamSender implementation (edit message in-place) ── + +type streamState struct { + mu sync.Mutex + content strings.Builder + msgID string // Telegram message ID of the "thinking" message + chatID string +} + +var ( + streamsMu sync.Mutex + streams = map[string]*streamState{} +) + +func (a *Adapter) StartStream(ctx context.Context, incoming *im.IncomingMessage) (string, error) { + chatID := resolveChatID(incoming) + + // Send initial "thinking" message + body := map[string]interface{}{ + "chat_id": chatID, + "text": "正在思考...", + } + var sentMsg struct { + MessageID int `json:"message_id"` + } + if err := a.callAPIWithResult(ctx, "sendMessage", body, &sentMsg); err != nil { + return "", fmt.Errorf("telegram start stream: %w", err) + } + + msgID := fmt.Sprintf("%d", sentMsg.MessageID) + streamID := fmt.Sprintf("%s:%s", chatID, msgID) + + streamsMu.Lock() + streams[streamID] = &streamState{ + msgID: msgID, + chatID: chatID, + } + streamsMu.Unlock() + + logger.Infof(ctx, "[Telegram] Streaming started: stream_id=%s", streamID) + return streamID, nil +} + +func (a *Adapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMessage, streamID string, content string) error { + if content == "" { + return nil + } + + streamsMu.Lock() + state, ok := streams[streamID] + streamsMu.Unlock() + if !ok { + return fmt.Errorf("unknown stream ID: %s", streamID) + } + + state.mu.Lock() + state.content.WriteString(content) + fullContent := state.content.String() + state.mu.Unlock() + + if err := a.editMessage(ctx, state.chatID, state.msgID, fullContent); err != nil { + // Telegram has rate limits, just log + logger.Warnf(ctx, "[Telegram] Failed to update stream chunk: %v", err) + } + + return nil +} + +func (a *Adapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error { + streamsMu.Lock() + state, ok := streams[streamID] + delete(streams, streamID) + streamsMu.Unlock() + + if !ok { + return nil + } + + state.mu.Lock() + fullContent := state.content.String() + state.mu.Unlock() + + if err := a.editMessage(ctx, state.chatID, state.msgID, fullContent); err != nil { + logger.Warnf(ctx, "[Telegram] Failed to end stream: %v", err) + } + + logger.Infof(ctx, "[Telegram] Streaming ended: stream_id=%s", streamID) + return nil +} + +// ── FileDownloader implementation ── + +func (a *Adapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io.ReadCloser, string, error) { + if msg.FileKey == "" { + return nil, "", fmt.Errorf("file_key is required") + } + + // Get file path via getFile API + var fileInfo struct { + FilePath string `json:"file_path"` + FileSize int64 `json:"file_size"` + } + if err := a.callAPIWithResult(ctx, "getFile", map[string]string{"file_id": msg.FileKey}, &fileInfo); err != nil { + return nil, "", fmt.Errorf("get file info: %w", err) + } + + // Download the file + downloadURL := fmt.Sprintf("https://api.telegram.org/file/bot%s/%s", a.botToken, fileInfo.FilePath) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadURL, nil) + if err != nil { + return nil, "", fmt.Errorf("create download request: %w", err) + } + + resp, err := httpClient.Do(req) + if err != nil { + return nil, "", fmt.Errorf("download file: %w", err) + } + if resp.StatusCode != http.StatusOK { + resp.Body.Close() + return nil, "", fmt.Errorf("download failed with status %d", resp.StatusCode) + } + + return resp.Body, msg.FileName, nil +} diff --git a/internal/im/telegram/longconn.go b/internal/im/telegram/longconn.go new file mode 100644 index 00000000..36373677 --- /dev/null +++ b/internal/im/telegram/longconn.go @@ -0,0 +1,116 @@ +package telegram + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "time" + + "github.com/Tencent/WeKnora/internal/im" + "github.com/Tencent/WeKnora/internal/logger" +) + +// MessageHandler is called when an IM message is received via long polling. +type MessageHandler func(ctx context.Context, msg *im.IncomingMessage) error + +// LongConnClient manages a Telegram long-polling connection. +type LongConnClient struct { + botToken string + handler MessageHandler + offset int + httpClient *http.Client +} + +// NewLongConnClient creates a Telegram long-polling client. +func NewLongConnClient(botToken string, handler MessageHandler) *LongConnClient { + return &LongConnClient{ + botToken: botToken, + handler: handler, + httpClient: &http.Client{Timeout: 35 * time.Second}, + } +} + +// Start begins the long-polling loop. It blocks until ctx is cancelled. +func (c *LongConnClient) Start(ctx context.Context) error { + logger.Infof(ctx, "[IM] Telegram long polling connecting...") + + for { + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + + updates, err := c.getUpdates(ctx) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + logger.Errorf(ctx, "[Telegram] getUpdates error: %v", err) + // Back off on error + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(3 * time.Second): + } + continue + } + + for _, update := range updates { + if update.UpdateID >= c.offset { + c.offset = update.UpdateID + 1 + } + + msg := parseUpdate(&update) + if msg == nil { + continue + } + + if err := c.handler(ctx, msg); err != nil { + logger.Errorf(ctx, "[Telegram] Handle message error: %v", err) + } + } + } +} + +func (c *LongConnClient) getUpdates(ctx context.Context) ([]telegramUpdate, error) { + url := fmt.Sprintf("https://api.telegram.org/bot%s/getUpdates", c.botToken) + + body := map[string]interface{}{ + "offset": c.offset, + "timeout": 30, + "allowed_updates": []string{"message"}, + } + jsonBody, err := json.Marshal(body) + if err != nil { + return nil, err + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(jsonBody)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + var apiResp struct { + OK bool `json:"ok"` + Description string `json:"description"` + Result []telegramUpdate `json:"result"` + } + if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil { + return nil, fmt.Errorf("decode response: %w", err) + } + if !apiResp.OK { + return nil, fmt.Errorf("getUpdates failed: %s", apiResp.Description) + } + + return apiResp.Result, nil +} diff --git a/internal/im/types.go b/internal/im/types.go index d1abe413..2f64829b 100644 --- a/internal/im/types.go +++ b/internal/im/types.go @@ -3,6 +3,7 @@ package im import ( "encoding/json" "fmt" + "strings" "time" "github.com/Tencent/WeKnora/internal/types" @@ -91,6 +92,14 @@ func (ch *IMChannel) computeBotIdentity() string { if appID := str("app_id"); appID != "" { return "feishu:" + appID } + case "telegram": + if botToken := str("bot_token"); botToken != "" { + // Use the bot ID part (before the colon) as identity. + if idx := strings.Index(botToken, ":"); idx > 0 { + return "telegram:" + botToken[:idx] + } + return "telegram:" + botToken + } } return "" }