handle.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package telegram
  2. import (
  3. "context"
  4. "fmt"
  5. )
  6. // handleSingleMessages handle single messages not belongs to group.
  7. func (b *Bot) handleSingleMessages(ctx context.Context, messages []Message) error {
  8. for _, message := range messages {
  9. var blobs map[string][]byte
  10. // download blob if provided
  11. if len(message.Photo) > 0 {
  12. filepath, blob, err := b.downloadFileID(ctx, message.GetMaxPhotoFileID())
  13. if err != nil {
  14. return err
  15. }
  16. blobs = map[string][]byte{filepath: blob}
  17. }
  18. err := b.handler.MessageHandle(ctx, b, message, blobs)
  19. if err != nil {
  20. return err
  21. }
  22. }
  23. return nil
  24. }
  25. // handleGroupMessages handle a message belongs to group.
  26. func (b *Bot) handleGroupMessages(ctx context.Context, groupMessages []Message) error {
  27. captions := make(map[string]string, len(groupMessages))
  28. messages := make(map[string]Message, len(groupMessages))
  29. blobs := make(map[string]map[string][]byte, len(groupMessages))
  30. // Group all captions, blobs and messages
  31. for _, message := range groupMessages {
  32. groupID := *message.MediaGroupID
  33. messages[groupID] = message
  34. if message.Caption != nil {
  35. captions[groupID] += *message.Caption
  36. }
  37. filepath, blob, err := b.downloadFileID(ctx, message.GetMaxPhotoFileID())
  38. if err != nil {
  39. return fmt.Errorf("fail to downloadFileID")
  40. }
  41. if _, found := blobs[groupID]; !found {
  42. blobs[groupID] = make(map[string][]byte)
  43. }
  44. blobs[groupID][filepath] = blob
  45. }
  46. // Handle each group message
  47. for groupID, message := range messages {
  48. // replace Caption with all Caption in the group
  49. caption := captions[groupID]
  50. message.Caption = &caption
  51. err := b.handler.MessageHandle(ctx, b, message, blobs[groupID])
  52. if err != nil {
  53. return err
  54. }
  55. }
  56. return nil
  57. }