update.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package tg
  2. import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
  3. type FileId string
  4. type Update struct {
  5. tgbotapi.Update
  6. }
  7. // The type represents general update channel.
  8. type UpdateChan struct {
  9. chn chan Update
  10. }
  11. // Return new update channel.
  12. func NewUpdateChan() *UpdateChan {
  13. ret := &UpdateChan{}
  14. ret.chn = make(chan *Update)
  15. return ret
  16. }
  17. func (updates *UpdateChan) Chan() chan *Update {
  18. return updates.chn
  19. }
  20. // Send an update to the channel.
  21. // Returns true if the update was sent.
  22. func (updates *UpdateChan) Send(u *Update) bool {
  23. defer recover()
  24. if updates == nil || updates.chn == nil {
  25. return false
  26. }
  27. updates.chn <- u
  28. return true
  29. }
  30. // Read an update from the channel.
  31. func (updates *UpdateChan) Read() *Update {
  32. if updates == nil || updates.chn == nil {
  33. return nil
  34. }
  35. return <-updates.chn
  36. }
  37. // Returns true if the channel is closed.
  38. func (updates *UpdateChan) Closed() bool {
  39. return updates==nil || updates.chn == nil
  40. }
  41. // Close the channel. Used in defers.
  42. func (updates *UpdateChan) Close() {
  43. if updates == nil || updates.chn == nil {
  44. return
  45. }
  46. chn := updates.chn
  47. updates.chn = nil
  48. close(chn)
  49. }
  50. func (u Update) HasDocument() bool {
  51. return u != nil &&
  52. u.Message != nil &&
  53. u.Message.Document != nil
  54. }
  55. func (u Update) DocumentId() FileId {
  56. return FileId(u.Update.Message.Document.FileID)
  57. }
  58. func (u *Update) DocumentName() string {
  59. return u.Message.Document.FileName
  60. }
  61. func (u Update) DocumentSize() int {
  62. return u.Message.Document.FileSize
  63. }
  64. func (u Update) DocumentMimeType() string {
  65. return u.Message.Document.MimeType
  66. }
  67. func (u Update) HasPhotos() bool {
  68. return u.Message != nil && u.Message.Photo != nil &&
  69. len(u.Message.Photo) != 0
  70. }
  71. func (u Update) PhotoIds() []FileId {
  72. ret := make([]FileId, len(u.Message.Photo))
  73. for i, photo := range u.Message.Photo {
  74. ret[i] = FileId(photo.FileID)
  75. }
  76. return ret
  77. }