@@ -11,7 +11,10 @@ import (
1111 "sync"
1212 "time"
1313
14+ th "github.com/mymmrac/telego/telegohandler"
15+
1416 "github.com/mymmrac/telego"
17+ "github.com/mymmrac/telego/telegohandler"
1518 tu "github.com/mymmrac/telego/telegoutil"
1619
1720 "github.com/sipeed/picoclaw/pkg/bus"
@@ -24,7 +27,8 @@ import (
2427type TelegramChannel struct {
2528 * BaseChannel
2629 bot * telego.Bot
27- config config.TelegramConfig
30+ commands TelegramCommander
31+ config * config.Config
2832 chatIDs map [string ]int64
2933 transcriber * voice.GroqTranscriber
3034 placeholders sync.Map // chatID -> messageID
@@ -41,13 +45,14 @@ func (c *thinkingCancel) Cancel() {
4145 }
4246}
4347
44- func NewTelegramChannel (cfg config.TelegramConfig , bus * bus.MessageBus ) (* TelegramChannel , error ) {
48+ func NewTelegramChannel (cfg * config.Config , bus * bus.MessageBus ) (* TelegramChannel , error ) {
4549 var opts []telego.BotOption
50+ telegramCfg := cfg .Channels .Telegram
4651
47- if cfg .Proxy != "" {
48- proxyURL , parseErr := url .Parse (cfg .Proxy )
52+ if telegramCfg .Proxy != "" {
53+ proxyURL , parseErr := url .Parse (telegramCfg .Proxy )
4954 if parseErr != nil {
50- return nil , fmt .Errorf ("invalid proxy URL %q: %w" , cfg .Proxy , parseErr )
55+ return nil , fmt .Errorf ("invalid proxy URL %q: %w" , telegramCfg .Proxy , parseErr )
5156 }
5257 opts = append (opts , telego .WithHTTPClient (& http.Client {
5358 Transport : & http.Transport {
@@ -56,15 +61,16 @@ func NewTelegramChannel(cfg config.TelegramConfig, bus *bus.MessageBus) (*Telegr
5661 }))
5762 }
5863
59- bot , err := telego .NewBot (cfg .Token , opts ... )
64+ bot , err := telego .NewBot (telegramCfg .Token , opts ... )
6065 if err != nil {
6166 return nil , fmt .Errorf ("failed to create telegram bot: %w" , err )
6267 }
6368
64- base := NewBaseChannel ("telegram" , cfg , bus , cfg .AllowFrom )
69+ base := NewBaseChannel ("telegram" , telegramCfg , bus , telegramCfg .AllowFrom )
6570
6671 return & TelegramChannel {
6772 BaseChannel : base ,
73+ commands : NewTelegramCommands (bot , cfg ),
6874 bot : bot ,
6975 config : cfg ,
7076 chatIDs : make (map [string ]int64 ),
@@ -88,31 +94,45 @@ func (c *TelegramChannel) Start(ctx context.Context) error {
8894 return fmt .Errorf ("failed to start long polling: %w" , err )
8995 }
9096
97+ bh , err := telegohandler .NewBotHandler (c .bot , updates )
98+ if err != nil {
99+ return fmt .Errorf ("failed to create bot handler: %w" , err )
100+ }
101+
102+ bh .HandleMessage (func (ctx * th.Context , message telego.Message ) error {
103+ c .commands .Help (ctx , message )
104+ return nil
105+ }, th .CommandEqual ("help" ))
106+ bh .HandleMessage (func (ctx * th.Context , message telego.Message ) error {
107+ return c .commands .Start (ctx , message )
108+ }, th .CommandEqual ("start" ))
109+
110+ bh .HandleMessage (func (ctx * th.Context , message telego.Message ) error {
111+ return c .commands .Show (ctx , message )
112+ }, th .CommandEqual ("show" ))
113+
114+ bh .HandleMessage (func (ctx * th.Context , message telego.Message ) error {
115+ return c .commands .List (ctx , message )
116+ }, th .CommandEqual ("list" ))
117+
118+ bh .HandleMessage (func (ctx * th.Context , message telego.Message ) error {
119+ return c .handleMessage (ctx , & message )
120+ }, th .AnyMessage ())
121+
91122 c .setRunning (true )
92123 logger .InfoCF ("telegram" , "Telegram bot connected" , map [string ]interface {}{
93124 "username" : c .bot .Username (),
94125 })
95126
127+ go bh .Start ()
128+
96129 go func () {
97- for {
98- select {
99- case <- ctx .Done ():
100- return
101- case update , ok := <- updates :
102- if ! ok {
103- logger .InfoC ("telegram" , "Updates channel closed, reconnecting..." )
104- return
105- }
106- if update .Message != nil {
107- c .handleMessage (ctx , update )
108- }
109- }
110- }
130+ <- ctx .Done ()
131+ bh .Stop ()
111132 }()
112133
113134 return nil
114135}
115-
116136func (c * TelegramChannel ) Stop (ctx context.Context ) error {
117137 logger .InfoC ("telegram" , "Stopping Telegram bot..." )
118138 c .setRunning (false )
@@ -166,30 +186,27 @@ func (c *TelegramChannel) Send(ctx context.Context, msg bus.OutboundMessage) err
166186 return nil
167187}
168188
169- func (c * TelegramChannel ) handleMessage (ctx context.Context , update telego.Update ) {
170- message := update .Message
189+ func (c * TelegramChannel ) handleMessage (ctx context.Context , message * telego.Message ) error {
171190 if message == nil {
172- return
191+ return fmt . Errorf ( "message is nil" )
173192 }
174193
175194 user := message .From
176195 if user == nil {
177- return
196+ return fmt . Errorf ( "message sender (user) is nil" )
178197 }
179198
180- userID := fmt .Sprintf ("%d" , user .ID )
181- senderID := userID
199+ senderID := fmt .Sprintf ("%d" , user .ID )
182200 if user .Username != "" {
183- senderID = fmt .Sprintf ("%s |%s" , userID , user .Username )
201+ senderID = fmt .Sprintf ("%d |%s" , user . ID , user .Username )
184202 }
185203
186204 // 检查白名单,避免为被拒绝的用户下载附件
187- if ! c .IsAllowed (userID ) && ! c . IsAllowed ( senderID ) {
205+ if ! c .IsAllowed (senderID ) {
188206 logger .DebugCF ("telegram" , "Message rejected by allowlist" , map [string ]interface {}{
189- "user_id" : userID ,
190- "username" : user .Username ,
207+ "user_id" : senderID ,
191208 })
192- return
209+ return nil
193210 }
194211
195212 chatID := message .Chat .ID
@@ -222,7 +239,7 @@ func (c *TelegramChannel) handleMessage(ctx context.Context, update telego.Updat
222239 content += message .Caption
223240 }
224241
225- if message . Photo != nil && len (message .Photo ) > 0 {
242+ if len (message .Photo ) > 0 {
226243 photo := message .Photo [len (message .Photo )- 1 ]
227244 photoPath := c .downloadPhoto (ctx , photo .FileID )
228245 if photoPath != "" {
@@ -231,7 +248,7 @@ func (c *TelegramChannel) handleMessage(ctx context.Context, update telego.Updat
231248 if content != "" {
232249 content += "\n "
233250 }
234- content += fmt . Sprintf ( "[image: photo]" )
251+ content += "[image: photo]"
235252 }
236253 }
237254
@@ -252,15 +269,15 @@ func (c *TelegramChannel) handleMessage(ctx context.Context, update telego.Updat
252269 "error" : err .Error (),
253270 "path" : voicePath ,
254271 })
255- transcribedText = fmt . Sprintf ( "[voice (transcription failed)]" )
272+ transcribedText = "[voice (transcription failed)]"
256273 } else {
257274 transcribedText = fmt .Sprintf ("[voice transcription: %s]" , result .Text )
258275 logger .InfoCF ("telegram" , "Voice transcribed successfully" , map [string ]interface {}{
259276 "text" : result .Text ,
260277 })
261278 }
262279 } else {
263- transcribedText = fmt . Sprintf ( "[voice]" )
280+ transcribedText = "[voice]"
264281 }
265282
266283 if content != "" {
@@ -278,7 +295,7 @@ func (c *TelegramChannel) handleMessage(ctx context.Context, update telego.Updat
278295 if content != "" {
279296 content += "\n "
280297 }
281- content += fmt . Sprintf ( "[audio]" )
298+ content += "[audio]"
282299 }
283300 }
284301
@@ -290,7 +307,7 @@ func (c *TelegramChannel) handleMessage(ctx context.Context, update telego.Updat
290307 if content != "" {
291308 content += "\n "
292309 }
293- content += fmt . Sprintf ( "[file]" )
310+ content += "[file]"
294311 }
295312 }
296313
@@ -338,7 +355,8 @@ func (c *TelegramChannel) handleMessage(ctx context.Context, update telego.Updat
338355 "is_group" : fmt .Sprintf ("%t" , message .Chat .Type != "private" ),
339356 }
340357
341- c .HandleMessage (senderID , fmt .Sprintf ("%d" , chatID ), content , mediaPaths , metadata )
358+ c .HandleMessage (fmt .Sprintf ("%d" , user .ID ), fmt .Sprintf ("%d" , chatID ), content , mediaPaths , metadata )
359+ return nil
342360}
343361
344362func (c * TelegramChannel ) downloadPhoto (ctx context.Context , fileID string ) string {
0 commit comments