communicate_telegram_job.rb 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class CommunicateTelegramJob < ApplicationJob
  3. retry_on StandardError, attempts: 4, wait: lambda { |executions|
  4. executions * 120.seconds
  5. }
  6. def perform(article_id)
  7. article = Ticket::Article.find(article_id)
  8. # set retry count
  9. article.preferences['delivery_retry'] ||= 0
  10. article.preferences['delivery_retry'] += 1
  11. ticket = Ticket.lookup(id: article.ticket_id)
  12. log_error(article, "Can't find ticket.preferences for Ticket.find(#{article.ticket_id})") if !ticket.preferences
  13. log_error(article, "Can't find ticket.preferences['telegram'] for Ticket.find(#{article.ticket_id})") if !ticket.preferences['telegram']
  14. log_error(article, "Can't find ticket.preferences['telegram']['chat_id'] for Ticket.find(#{article.ticket_id})") if !ticket.preferences['telegram']['chat_id']
  15. if ticket.preferences['telegram'] && ticket.preferences['telegram']['bid']
  16. channel = Telegram.bot_by_bot_id(ticket.preferences['telegram']['bid'])
  17. end
  18. if !channel
  19. channel = Channel.lookup(id: ticket.preferences['channel_id'])
  20. end
  21. log_error(article, "No such channel for bot #{ticket.preferences['bid']} or channel id #{ticket.preferences['channel_id']}") if !channel
  22. # log_error(article, "Channel.find(#{channel.id}) isn't a telegram channel!") if channel.options[:adapter] !~ /\Atelegram/i
  23. log_error(article, "Channel.find(#{channel.id}) has not telegram api token!") if channel.options[:api_token].blank?
  24. begin
  25. api = TelegramAPI.new(channel.options[:api_token])
  26. chat_id = ticket.preferences[:telegram][:chat_id]
  27. result = api.sendMessage(chat_id, article.body)
  28. me = api.getMe
  29. article.attachments.each do |file|
  30. parts = file.filename.split(%r{^(.*)(\..+?)$})
  31. t = Tempfile.new([parts[1], parts[2]])
  32. t.binmode
  33. t.write(file.content)
  34. t.rewind
  35. api.sendDocument(chat_id, t.path.to_s)
  36. end
  37. rescue => e
  38. log_error(article, e.message)
  39. return
  40. end
  41. Rails.logger.debug { "result info: #{result}" }
  42. # only private, group messages. channel messages do not have from key
  43. if result['from'] && result['chat']
  44. # fill article with message info
  45. article.from = "@#{result['from']['username']}"
  46. article.to = "@#{result['chat']['username']}"
  47. article.preferences['telegram'] = {
  48. date: result['date'],
  49. from_id: result['from']['id'],
  50. chat_id: result['chat']['id'],
  51. message_id: result['message_id']
  52. }
  53. else
  54. # fill article with message info (telegram channel)
  55. article.from = "@#{me['username']}"
  56. article.to = "#{result['chat']['title']} Channel"
  57. article.preferences['telegram'] = {
  58. date: result['date'],
  59. from_id: me['id'],
  60. chat_id: result['chat']['id'],
  61. message_id: result['message_id']
  62. }
  63. end
  64. # set delivery status
  65. article.preferences['delivery_status_message'] = nil
  66. article.preferences['delivery_status'] = 'success'
  67. article.preferences['delivery_status_date'] = Time.zone.now
  68. article.message_id = "telegram.#{result['message_id']}.#{result['chat']['id']}"
  69. article.save!
  70. Rails.logger.info "Send telegram message to: '#{article.to}' (from #{article.from})"
  71. article
  72. end
  73. def log_error(local_record, message)
  74. local_record.preferences['delivery_status'] = 'fail'
  75. local_record.preferences['delivery_status_message'] = message.encode!('UTF-8', 'UTF-8', invalid: :replace, replace: '?')
  76. local_record.preferences['delivery_status_date'] = Time.zone.now
  77. local_record.save
  78. Rails.logger.error message
  79. if local_record.preferences['delivery_retry'] > 3
  80. Ticket::Article.create(
  81. ticket_id: local_record.ticket_id,
  82. content_type: 'text/plain',
  83. body: "Unable to send telegram message: #{message}",
  84. internal: true,
  85. sender: Ticket::Article::Sender.find_by(name: 'System'),
  86. type: Ticket::Article::Type.find_by(name: 'note'),
  87. preferences: {
  88. delivery_article_id_related: local_record.id,
  89. delivery_message: true,
  90. },
  91. updated_by_id: 1,
  92. created_by_id: 1,
  93. )
  94. end
  95. raise message
  96. end
  97. end