telegram.rb 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. # Copyright (C) 2012-2015 Zammad Foundation, http://zammad-foundation.org/
  2. class Telegram
  3. attr_accessor :client
  4. =begin
  5. check token and return bot attributes of token
  6. bot = Telegram.check_token('token')
  7. =end
  8. def self.check_token(token)
  9. api = TelegramAPI.new(token)
  10. begin
  11. bot = api.getMe()
  12. rescue
  13. raise 'invalid api token'
  14. end
  15. bot
  16. end
  17. =begin
  18. set webhool for bot
  19. success = Telegram.set_webhook('token', callback_url)
  20. returns
  21. true|false
  22. =end
  23. def self.set_webhook(token, callback_url)
  24. if callback_url.match?(%r{^http://}i)
  25. raise 'webhook url need to start with https://, you use http://'
  26. end
  27. api = TelegramAPI.new(token)
  28. begin
  29. api.setWebhook(callback_url)
  30. rescue
  31. raise 'Unable to set webhook at Telegram, seems to be a invalid url.'
  32. end
  33. true
  34. end
  35. =begin
  36. create or update channel, store bot attributes and verify token
  37. channel = Telegram.create_or_update_channel('token', params)
  38. returns
  39. channel # instance of Channel
  40. =end
  41. def self.create_or_update_channel(token, params, channel = nil)
  42. # verify token
  43. bot = Telegram.check_token(token)
  44. if !channel
  45. if Telegram.bot_duplicate?(bot['id'])
  46. raise 'Bot already exists!'
  47. end
  48. end
  49. if params[:group_id].blank?
  50. raise 'Group needed!'
  51. end
  52. group = Group.find_by(id: params[:group_id])
  53. if !group
  54. raise 'Group invalid!'
  55. end
  56. # generate randam callback token
  57. callback_token = if Rails.env.test?
  58. 'callback_token'
  59. else
  60. SecureRandom.urlsafe_base64(10)
  61. end
  62. # set webhook / callback url for this bot @ telegram
  63. callback_url = "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/api/v1/channels_telegram_webhook/#{callback_token}?bid=#{bot['id']}"
  64. Telegram.set_webhook(token, callback_url)
  65. if !channel
  66. channel = Telegram.bot_by_bot_id(bot['id'])
  67. if !channel
  68. channel = Channel.new
  69. end
  70. end
  71. channel.area = 'Telegram::Bot'
  72. channel.options = {
  73. bot: {
  74. id: bot['id'],
  75. username: bot['username'],
  76. first_name: bot['first_name'],
  77. last_name: bot['last_name'],
  78. },
  79. callback_token: callback_token,
  80. callback_url: callback_url,
  81. api_token: token,
  82. welcome: params[:welcome],
  83. }
  84. channel.group_id = group.id
  85. channel.active = true
  86. channel.save!
  87. channel
  88. end
  89. =begin
  90. check if bot already exists as channel
  91. success = Telegram.bot_duplicate?(bot_id)
  92. returns
  93. channel # instance of Channel
  94. =end
  95. def self.bot_duplicate?(bot_id, channel_id = nil)
  96. Channel.where(area: 'Telegram::Bot').each do |channel|
  97. next if !channel.options
  98. next if !channel.options[:bot]
  99. next if !channel.options[:bot][:id]
  100. next if channel.options[:bot][:id] != bot_id
  101. next if channel.id.to_s == channel_id.to_s
  102. return true
  103. end
  104. false
  105. end
  106. =begin
  107. get channel by bot_id
  108. channel = Telegram.bot_by_bot_id(bot_id)
  109. returns
  110. true|false
  111. =end
  112. def self.bot_by_bot_id(bot_id)
  113. Channel.where(area: 'Telegram::Bot').each do |channel|
  114. next if !channel.options
  115. next if !channel.options[:bot]
  116. next if !channel.options[:bot][:id]
  117. return channel if channel.options[:bot][:id].to_s == bot_id.to_s
  118. end
  119. nil
  120. end
  121. =begin
  122. generate message_id for message
  123. message_id = Telegram.message_id(message)
  124. returns
  125. message_id # 123456@telegram
  126. =end
  127. def self.message_id(params)
  128. message_id = nil
  129. %i[message edited_message].each do |key|
  130. next if !params[key]
  131. next if !params[key][:message_id]
  132. message_id = params[key][:message_id]
  133. break
  134. end
  135. if message_id
  136. %i[message edited_message].each do |key|
  137. next if !params[key]
  138. next if !params[key][:chat]
  139. next if !params[key][:chat][:id]
  140. message_id = "#{message_id}.#{params[key][:chat][:id]}"
  141. end
  142. end
  143. if !message_id
  144. message_id = params[:update_id]
  145. end
  146. "#{message_id}@telegram"
  147. end
  148. =begin
  149. client = Telegram.new('token')
  150. =end
  151. def initialize(token)
  152. @token = token
  153. @api = TelegramAPI.new(token)
  154. end
  155. =begin
  156. client.message(chat_id, 'some message')
  157. =end
  158. def message(chat_id, message)
  159. return if Rails.env.test?
  160. @api.sendMessage(chat_id, message)
  161. end
  162. def user(params)
  163. {
  164. id: params[:message][:from][:id],
  165. username: params[:message][:from][:username],
  166. first_name: params[:message][:from][:first_name],
  167. last_name: params[:message][:from][:last_name]
  168. }
  169. end
  170. def to_user(params)
  171. Rails.logger.debug { 'Create user from message...' }
  172. Rails.logger.debug { params.inspect }
  173. # do message_user lookup
  174. message_user = user(params)
  175. auth = Authorization.find_by(uid: message_user[:id], provider: 'telegram')
  176. # create or update user
  177. login = message_user[:username] || message_user[:id]
  178. user_data = {
  179. login: login,
  180. firstname: message_user[:first_name],
  181. lastname: message_user[:last_name],
  182. }
  183. if auth
  184. user = User.find(auth.user_id)
  185. user.update!(user_data)
  186. else
  187. if message_user[:username]
  188. user_data[:note] = "Telegram @#{message_user[:username]}"
  189. end
  190. user_data[:active] = true
  191. user_data[:role_ids] = Role.signup_role_ids
  192. user = User.create(user_data)
  193. end
  194. # create or update authorization
  195. auth_data = {
  196. uid: message_user[:id],
  197. username: login,
  198. user_id: user.id,
  199. provider: 'telegram'
  200. }
  201. if auth
  202. auth.update!(auth_data)
  203. else
  204. Authorization.create(auth_data)
  205. end
  206. user
  207. end
  208. def to_ticket(params, user, group_id, channel)
  209. UserInfo.current_user_id = user.id
  210. Rails.logger.debug { 'Create ticket from message...' }
  211. Rails.logger.debug { params.inspect }
  212. Rails.logger.debug { user.inspect }
  213. Rails.logger.debug { group_id.inspect }
  214. # prepare title
  215. title = '-'
  216. %i[text caption].each do |area|
  217. next if !params[:message]
  218. next if !params[:message][area]
  219. title = params[:message][area]
  220. break
  221. end
  222. if title == '-'
  223. %i[sticker photo document voice].each do |area|
  224. begin
  225. next if !params[:message]
  226. next if !params[:message][area]
  227. next if !params[:message][area][:emoji]
  228. title = params[:message][area][:emoji]
  229. break
  230. rescue
  231. # just go ahead
  232. title
  233. end
  234. end
  235. end
  236. if title.length > 60
  237. title = "#{title[0, 60]}..."
  238. end
  239. # find ticket or create one
  240. state_ids = Ticket::State.where(name: %w[closed merged removed]).pluck(:id)
  241. ticket = Ticket.where(customer_id: user.id).where.not(state_id: state_ids).order(:updated_at).first
  242. if ticket
  243. # check if title need to be updated
  244. if ticket.title == '-'
  245. ticket.title = title
  246. end
  247. new_state = Ticket::State.find_by(default_create: true)
  248. if ticket.state_id != new_state.id
  249. ticket.state = Ticket::State.find_by(default_follow_up: true)
  250. end
  251. ticket.save!
  252. return ticket
  253. end
  254. ticket = Ticket.new(
  255. group_id: group_id,
  256. title: title,
  257. state_id: Ticket::State.find_by(default_create: true).id,
  258. priority_id: Ticket::Priority.find_by(default_create: true).id,
  259. customer_id: user.id,
  260. preferences: {
  261. channel_id: channel.id,
  262. telegram: {
  263. bid: params['bid'],
  264. chat_id: params[:message][:chat][:id]
  265. }
  266. },
  267. )
  268. ticket.save!
  269. ticket
  270. end
  271. def to_article(params, user, ticket, channel, article = nil)
  272. if article
  273. Rails.logger.debug { 'Update article from message...' }
  274. else
  275. Rails.logger.debug { 'Create article from message...' }
  276. end
  277. Rails.logger.debug { params.inspect }
  278. Rails.logger.debug { user.inspect }
  279. Rails.logger.debug { ticket.inspect }
  280. UserInfo.current_user_id = user.id
  281. if article
  282. article.preferences[:edited_message] = {
  283. message: {
  284. created_at: params[:message][:date],
  285. message_id: params[:message][:message_id],
  286. from: params[:message][:from],
  287. },
  288. update_id: params[:update_id],
  289. }
  290. else
  291. article = Ticket::Article.new(
  292. ticket_id: ticket.id,
  293. type_id: Ticket::Article::Type.find_by(name: 'telegram personal-message').id,
  294. sender_id: Ticket::Article::Sender.find_by(name: 'Customer').id,
  295. from: user(params)[:username],
  296. to: "@#{channel[:options][:bot][:username]}",
  297. message_id: Telegram.message_id(params),
  298. internal: false,
  299. preferences: {
  300. message: {
  301. created_at: params[:message][:date],
  302. message_id: params[:message][:message_id],
  303. from: params[:message][:from],
  304. },
  305. update_id: params[:update_id],
  306. }
  307. )
  308. end
  309. # add article
  310. if params[:message][:photo]
  311. # find photo with best resolution for us
  312. photo = nil
  313. max_width = 650 * 2
  314. last_width = 0
  315. last_height = 0
  316. params[:message][:photo].each do |file|
  317. if !photo
  318. photo = file
  319. last_width = file['width'].to_i
  320. last_height = file['height'].to_i
  321. end
  322. next unless file['width'].to_i < max_width && last_width < file['width'].to_i
  323. photo = file
  324. last_width = file['width'].to_i
  325. last_height = file['height'].to_i
  326. end
  327. if last_width > 650
  328. last_width = (last_width / 2).to_i
  329. last_height = (last_height / 2).to_i
  330. end
  331. # download image
  332. result = download_file(photo['file_id'])
  333. if !result.success? || !result.body
  334. raise "Unable for download image from telegram: #{result.code}"
  335. end
  336. body = "<img style=\"width:#{last_width}px;height:#{last_height}px;\" src=\"data:image/png;base64,#{Base64.strict_encode64(result.body)}\">"
  337. if params[:message][:caption]
  338. body += "<br>#{params[:message][:caption].text2html}"
  339. end
  340. article.content_type = 'text/html'
  341. article.body = body
  342. article.save!
  343. return article
  344. end
  345. # add document
  346. if params[:message][:document]
  347. thumb = params[:message][:document][:thumb]
  348. body = '&nbsp;'
  349. if thumb
  350. width = thumb[:width]
  351. height = thumb[:height]
  352. result = download_file(thumb['file_id'])
  353. if !result.success? || !result.body
  354. raise "Unable for download image from telegram: #{result.code}"
  355. end
  356. body = "<img style=\"width:#{width}px;height:#{height}px;\" src=\"data:image/png;base64,#{Base64.strict_encode64(result.body)}\">"
  357. end
  358. document_result = download_file(params[:message][:document][:file_id])
  359. article.content_type = 'text/html'
  360. article.body = body
  361. article.save!
  362. Store.remove(
  363. object: 'Ticket::Article',
  364. o_id: article.id,
  365. )
  366. Store.add(
  367. object: 'Ticket::Article',
  368. o_id: article.id,
  369. data: document_result.body,
  370. filename: params[:message][:document][:file_name],
  371. preferences: {
  372. 'Mime-Type' => params[:message][:document][:mime_type],
  373. },
  374. )
  375. return article
  376. end
  377. # voice
  378. if params[:message][:voice]
  379. body = '&nbsp;'
  380. if params[:message][:caption]
  381. body = "<br>#{params[:message][:caption].text2html}"
  382. end
  383. document_result = download_file(params[:message][:voice][:file_id])
  384. article.content_type = 'text/html'
  385. article.body = body
  386. article.save!
  387. Store.remove(
  388. object: 'Ticket::Article',
  389. o_id: article.id,
  390. )
  391. Store.add(
  392. object: 'Ticket::Article',
  393. o_id: article.id,
  394. data: document_result.body,
  395. filename: params[:message][:voice][:file_path] || "audio-#{params[:message][:voice][:file_id]}.ogg",
  396. preferences: {
  397. 'Mime-Type' => params[:message][:voice][:mime_type],
  398. },
  399. )
  400. return article
  401. end
  402. if params[:message][:sticker]
  403. emoji = params[:message][:sticker][:emoji]
  404. thumb = params[:message][:sticker][:thumb]
  405. body = '&nbsp;'
  406. if thumb
  407. width = thumb[:width]
  408. height = thumb[:height]
  409. result = download_file(thumb['file_id'])
  410. if !result.success? || !result.body
  411. raise "Unable for download image from telegram: #{result.code}"
  412. end
  413. body = "<img style=\"width:#{width}px;height:#{height}px;\" src=\"data:image/webp;base64,#{Base64.strict_encode64(result.body)}\">"
  414. article.content_type = 'text/html'
  415. elsif emoji
  416. article.content_type = 'text/plain'
  417. body = emoji
  418. end
  419. article.body = body
  420. article.save!
  421. if params[:message][:sticker][:file_id]
  422. document_result = download_file(params[:message][:sticker][:file_id])
  423. Store.remove(
  424. object: 'Ticket::Article',
  425. o_id: article.id,
  426. )
  427. Store.add(
  428. object: 'Ticket::Article',
  429. o_id: article.id,
  430. data: document_result.body,
  431. filename: params[:message][:sticker][:file_name] || "#{params[:message][:sticker][:set_name]}.webp",
  432. preferences: {
  433. 'Mime-Type' => 'image/webp', # mime type is not given from Telegram API but this is actually WebP
  434. },
  435. )
  436. end
  437. return article
  438. end
  439. # text
  440. if params[:message][:text]
  441. article.content_type = 'text/plain'
  442. article.body = params[:message][:text]
  443. article.save!
  444. return article
  445. end
  446. raise 'invalid action'
  447. end
  448. def to_group(params, group_id, channel)
  449. # begin import
  450. Rails.logger.debug { 'import message' }
  451. # map channel_post params to message
  452. if params[:channel_post]
  453. return if params[:channel_post][:new_chat_title] # happens when channel title is renamed, we use [:chat][:title] already, safely ignore this.
  454. # note: used .blank? which is a rails method. empty? does not work on integers (values like date, width, height) to check.
  455. # need delete_if to remove any empty hashes, .compact only removes keys with nil values.
  456. params[:message] = {
  457. document: {
  458. file_name: params.dig(:channel_post, :document, :file_name),
  459. mime_type: params.dig(:channel_post, :document, :mime_type),
  460. file_id: params.dig(:channel_post, :document, :file_id),
  461. file_size: params.dig(:channel_post, :document, :filesize),
  462. thumb: {
  463. file_id: params.dig(:channel_post, :document, :thumb, :file_id),
  464. file_size: params.dig(:channel_post, :document, :thumb, :file_size),
  465. width: params.dig(:channel_post, :document, :thumb, :width),
  466. height: params.dig(:channel_post, :document, :thumb, :height)
  467. }.compact
  468. }.delete_if { |_, v| v.blank? },
  469. voice: {
  470. duration: params.dig(:channel_post, :voice, :duration),
  471. mime_type: params.dig(:channel_post, :voice, :mime_type),
  472. file_id: params.dig(:channel_post, :voice, :file_id),
  473. file_size: params.dig(:channel_post, :voice, :file_size)
  474. }.compact,
  475. sticker: {
  476. width: params.dig(:channel_post, :sticker, :width),
  477. height: params.dig(:channel_post, :sticker, :height),
  478. emoji: params.dig(:channel_post, :sticker, :emoji),
  479. set_name: params.dig(:channel_post, :sticker, :set_name),
  480. file_id: params.dig(:channel_post, :sticker, :file_id),
  481. file_path: params.dig(:channel_post, :sticker, :file_path),
  482. thumb: {
  483. file_id: params.dig(:channel_post, :sticker, :thumb, :file_id),
  484. file_size: params.dig(:channel_post, :sticker, :thumb, :file_size),
  485. width: params.dig(:channel_post, :sticker, :thumb, :width),
  486. height: params.dig(:channel_post, :sticker, :thumb, :file_id),
  487. file_path: params.dig(:channel_post, :sticker, :thumb, :file_path)
  488. }.compact
  489. }.delete_if { |_, v| v.blank? },
  490. chat: {
  491. id: params.dig(:channel_post, :chat, :id),
  492. first_name: params.dig(:channel_post, :chat, :title),
  493. last_name: 'Channel',
  494. username: "channel#{params.dig(:channel_post, :chat, :id)}"
  495. },
  496. from: {
  497. id: params.dig(:channel_post, :chat, :id),
  498. first_name: params.dig(:channel_post, :chat, :title),
  499. last_name: 'Channel',
  500. username: "channel#{params.dig(:channel_post, :chat, :id)}"
  501. },
  502. caption: (params.dig(:channel_post, :caption) ? params.dig(:channel_post, :caption) : {}),
  503. date: params.dig(:channel_post, :date),
  504. message_id: params.dig(:channel_post, :message_id),
  505. text: params.dig(:channel_post, :text),
  506. photo: (params[:channel_post][:photo].map { |photo| { file_id: photo[:file_id], file_size: photo[:file_size], width: photo[:width], height: photo[:height] } } if params.dig(:channel_post, :photo))
  507. }.delete_if { |_, v| v.blank? }
  508. params.delete(:channel_post) # discard unused :channel_post hash
  509. end
  510. # checks if the channel post is being edited, and map it when it is
  511. if params[:edited_channel_post]
  512. # updates on telegram can only be on messages, no attachments
  513. params[:edited_message] = {
  514. chat: {
  515. id: params.dig(:edited_channel_post, :chat, :id),
  516. first_name: params.dig(:edited_channel_post, :chat, :title),
  517. last_name: 'Channel',
  518. username: "channel#{params.dig(:edited_channel_post, :chat, :id)}"
  519. },
  520. from: {
  521. id: params.dig(:edited_channel_post, :chat, :id),
  522. first_name: params.dig(:edited_channel_post, :chat, :title),
  523. last_name: 'Channel',
  524. username: "channel#{params.dig(:edited_channel_post, :chat, :id)}"
  525. },
  526. date: params.dig(:edited_channel_post, :date),
  527. edit_date: params.dig(:edited_channel_post, :edit_date),
  528. message_id: params.dig(:edited_channel_post, :message_id),
  529. text: params.dig(:edited_channel_post, :text)
  530. }
  531. params.delete(:edited_channel_post) # discard unused :edited_channel_post hash
  532. end
  533. # prevent multible update
  534. if !params[:edited_message]
  535. return if Ticket::Article.find_by(message_id: Telegram.message_id(params))
  536. end
  537. # update article
  538. if params[:edited_message]
  539. article = Ticket::Article.find_by(message_id: Telegram.message_id(params))
  540. return if !article
  541. params[:message] = params[:edited_message]
  542. user = to_user(params)
  543. to_article(params, user, article.ticket, channel, article)
  544. return article
  545. end
  546. # send welcome message and don't create ticket
  547. text = params[:message][:text]
  548. if text.present? && text =~ %r{^/start}
  549. message(params[:message][:chat][:id], channel.options[:welcome] || 'You are welcome! Just ask me something!')
  550. return
  551. # find ticket and close it
  552. elsif text.present? && text =~ %r{^/end}
  553. user = to_user(params)
  554. ticket = Ticket.where(customer_id: user.id).order(:updated_at).first
  555. ticket.state = Ticket::State.find_by(name: 'closed')
  556. ticket.save!
  557. return
  558. end
  559. ticket = nil
  560. # use transaction
  561. Transaction.execute(reset_user_id: true) do
  562. user = to_user(params)
  563. ticket = to_ticket(params, user, group_id, channel)
  564. to_article(params, user, ticket, channel)
  565. end
  566. ticket
  567. end
  568. def from_article(article)
  569. message = nil
  570. Rails.logger.debug { "Create telegram personal message from article to '#{article[:to]}'..." }
  571. message = {}
  572. # TODO: create telegram message here
  573. Rails.logger.debug { message.inspect }
  574. message
  575. end
  576. def get_state(channel, telegram_update, ticket = nil)
  577. message = telegram_update['message']
  578. message_user = user(message)
  579. # no changes in post is from page user it self
  580. if channel.options[:bot][:id].to_s == message_user[:id].to_s
  581. if !ticket
  582. return Ticket::State.find_by(name: 'closed') if !ticket
  583. end
  584. return ticket.state
  585. end
  586. state = Ticket::State.find_by(default_create: true)
  587. return state if !ticket
  588. return ticket.state if ticket.state.id == state.id
  589. Ticket::State.find_by(default_follow_up: true)
  590. end
  591. def download_file(file_id)
  592. document = @api.getFile(file_id)
  593. url = "https://api.telegram.org/file/bot#{@token}/#{document['file_path']}"
  594. UserAgent.get(
  595. url,
  596. {},
  597. {
  598. open_timeout: 20,
  599. read_timeout: 40,
  600. },
  601. )
  602. end
  603. end