handle.go 1.6 KB

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