feat(im): add Telegram platform integration

Add Telegram Bot API adapter supporting both webhook and long-polling
modes with streaming replies via editMessageText, file download via
getFile API, and timing-safe secret token verification.
This commit is contained in:
nullkey
2026-03-24 16:48:13 +08:00
committed by lyingbug
parent f0c6d0752a
commit aea0a97be3
12 changed files with 625 additions and 12 deletions
+39
View File
@@ -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)
+5 -2
View File
@@ -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
}
+4 -3
View File
@@ -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.
+403
View File
@@ -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
}
+116
View File
@@ -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
}
+9
View File
@@ -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 ""
}