telegram.rb 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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 webhook 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 random 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. next if !params[:message]
  225. next if !params[:message][area]
  226. next if !params[:message][area][:emoji]
  227. title = params[:message][area][:emoji]
  228. break
  229. rescue
  230. # just go ahead
  231. title
  232. end
  233. end
  234. if title.length > 60
  235. title = "#{title[0, 60]}..."
  236. end
  237. # find ticket or create one
  238. state_ids = Ticket::State.where(name: %w[closed merged removed]).pluck(:id)
  239. possible_tickets = Ticket.where(customer_id: user.id).where.not(state_id: state_ids).order(:updated_at)
  240. ticket = possible_tickets.find_each.find { |possible_ticket| possible_ticket.preferences[:channel_id] == channel.id }
  241. if ticket
  242. # check if title need to be updated
  243. if ticket.title == '-'
  244. ticket.title = title
  245. end
  246. new_state = Ticket::State.find_by(default_create: true)
  247. if ticket.state_id != new_state.id
  248. ticket.state = Ticket::State.find_by(default_follow_up: true)
  249. end
  250. ticket.save!
  251. return ticket
  252. end
  253. ticket = Ticket.new(
  254. group_id: group_id,
  255. title: title,
  256. state_id: Ticket::State.find_by(default_create: true).id,
  257. priority_id: Ticket::Priority.find_by(default_create: true).id,
  258. customer_id: user.id,
  259. preferences: {
  260. channel_id: channel.id,
  261. telegram: {
  262. bid: params['bid'],
  263. chat_id: params[:message][:chat][:id]
  264. }
  265. },
  266. )
  267. ticket.save!
  268. ticket
  269. end
  270. def to_article(params, user, ticket, channel, article = nil)
  271. if article
  272. Rails.logger.debug { 'Update article from message...' }
  273. else
  274. Rails.logger.debug { 'Create article from message...' }
  275. end
  276. Rails.logger.debug { params.inspect }
  277. Rails.logger.debug { user.inspect }
  278. Rails.logger.debug { ticket.inspect }
  279. UserInfo.current_user_id = user.id
  280. if article
  281. article.preferences[:edited_message] = {
  282. message: {
  283. created_at: params[:message][:date],
  284. message_id: params[:message][:message_id],
  285. from: params[:message][:from],
  286. },
  287. update_id: params[:update_id],
  288. }
  289. else
  290. article = Ticket::Article.new(
  291. ticket_id: ticket.id,
  292. type_id: Ticket::Article::Type.find_by(name: 'telegram personal-message').id,
  293. sender_id: Ticket::Article::Sender.find_by(name: 'Customer').id,
  294. from: user(params)[:username],
  295. to: "@#{channel[:options][:bot][:username]}",
  296. message_id: Telegram.message_id(params),
  297. internal: false,
  298. preferences: {
  299. message: {
  300. created_at: params[:message][:date],
  301. message_id: params[:message][:message_id],
  302. from: params[:message][:from],
  303. },
  304. update_id: params[:update_id],
  305. }
  306. )
  307. end
  308. # add article
  309. if params[:message][:photo]
  310. # find photo with best resolution for us
  311. photo = nil
  312. max_width = 650 * 2
  313. last_width = 0
  314. last_height = 0
  315. params[:message][:photo].each do |file|
  316. if !photo
  317. photo = file
  318. last_width = file['width'].to_i
  319. last_height = file['height'].to_i
  320. end
  321. next if file['width'].to_i >= max_width || file['width'].to_i <= last_width
  322. photo = file
  323. last_width = file['width'].to_i
  324. last_height = file['height'].to_i
  325. end
  326. if last_width > 650
  327. last_width = (last_width / 2).to_i
  328. last_height = (last_height / 2).to_i
  329. end
  330. # download image
  331. result = download_file(photo['file_id'])
  332. if !result.success? || !result.body
  333. raise "Unable for download image from telegram: #{result.code}"
  334. end
  335. body = "<img style=\"width:#{last_width}px;height:#{last_height}px;\" src=\"data:image/png;base64,#{Base64.strict_encode64(result.body)}\">"
  336. if params[:message][:caption]
  337. body += "<br>#{params[:message][:caption].text2html}"
  338. end
  339. article.content_type = 'text/html'
  340. article.body = body
  341. article.save!
  342. return article
  343. end
  344. # add document
  345. if params[:message][:document]
  346. thumb = params[:message][:document][:thumb]
  347. body = '&nbsp;'
  348. if thumb
  349. width = thumb[:width]
  350. height = thumb[:height]
  351. result = download_file(thumb['file_id'])
  352. if !result.success? || !result.body
  353. raise "Unable for download image from telegram: #{result.code}"
  354. end
  355. body = "<img style=\"width:#{width}px;height:#{height}px;\" src=\"data:image/png;base64,#{Base64.strict_encode64(result.body)}\">"
  356. end
  357. document_result = download_file(params[:message][:document][:file_id])
  358. article.content_type = 'text/html'
  359. article.body = body
  360. article.save!
  361. Store.remove(
  362. object: 'Ticket::Article',
  363. o_id: article.id,
  364. )
  365. Store.add(
  366. object: 'Ticket::Article',
  367. o_id: article.id,
  368. data: document_result.body,
  369. filename: params[:message][:document][:file_name],
  370. preferences: {
  371. 'Mime-Type' => params[:message][:document][:mime_type],
  372. },
  373. )
  374. return article
  375. end
  376. # voice
  377. if params[:message][:voice]
  378. body = '&nbsp;'
  379. if params[:message][:caption]
  380. body = "<br>#{params[:message][:caption].text2html}"
  381. end
  382. document_result = download_file(params[:message][:voice][:file_id])
  383. article.content_type = 'text/html'
  384. article.body = body
  385. article.save!
  386. Store.remove(
  387. object: 'Ticket::Article',
  388. o_id: article.id,
  389. )
  390. Store.add(
  391. object: 'Ticket::Article',
  392. o_id: article.id,
  393. data: document_result.body,
  394. filename: params[:message][:voice][:file_path] || "audio-#{params[:message][:voice][:file_id]}.ogg",
  395. preferences: {
  396. 'Mime-Type' => params[:message][:voice][:mime_type],
  397. },
  398. )
  399. return article
  400. end
  401. if params[:message][:sticker]
  402. emoji = params[:message][:sticker][:emoji]
  403. thumb = params[:message][:sticker][:thumb]
  404. body = '&nbsp;'
  405. if thumb
  406. width = thumb[:width]
  407. height = thumb[:height]
  408. result = download_file(thumb['file_id'])
  409. if !result.success? || !result.body
  410. raise "Unable for download image from telegram: #{result.code}"
  411. end
  412. body = "<img style=\"width:#{width}px;height:#{height}px;\" src=\"data:image/webp;base64,#{Base64.strict_encode64(result.body)}\">"
  413. article.content_type = 'text/html'
  414. elsif emoji
  415. article.content_type = 'text/plain'
  416. body = emoji
  417. end
  418. article.body = body
  419. article.save!
  420. if params[:message][:sticker][:file_id]
  421. document_result = download_file(params[:message][:sticker][:file_id])
  422. Store.remove(
  423. object: 'Ticket::Article',
  424. o_id: article.id,
  425. )
  426. Store.add(
  427. object: 'Ticket::Article',
  428. o_id: article.id,
  429. data: document_result.body,
  430. filename: params[:message][:sticker][:file_name] || "#{params[:message][:sticker][:set_name]}.webp",
  431. preferences: {
  432. 'Mime-Type' => 'image/webp', # mime type is not given from Telegram API but this is actually WebP
  433. },
  434. )
  435. end
  436. return article
  437. end
  438. # text
  439. if params[:message][:text]
  440. article.content_type = 'text/plain'
  441. article.body = params[:message][:text]
  442. article.save!
  443. return article
  444. end
  445. raise 'invalid action'
  446. end
  447. def to_group(params, group_id, channel)
  448. # begin import
  449. Rails.logger.debug { 'import message' }
  450. # map channel_post params to message
  451. if params[:channel_post]
  452. return if params[:channel_post][:new_chat_title] # happens when channel title is renamed, we use [:chat][:title] already, safely ignore this.
  453. # note: used .blank? which is a rails method. empty? does not work on integers (values like date, width, height) to check.
  454. # need delete_if to remove any empty hashes, .compact only removes keys with nil values.
  455. params[:message] = {
  456. document: {
  457. file_name: params.dig(:channel_post, :document, :file_name),
  458. mime_type: params.dig(:channel_post, :document, :mime_type),
  459. file_id: params.dig(:channel_post, :document, :file_id),
  460. file_size: params.dig(:channel_post, :document, :filesize),
  461. thumb: {
  462. file_id: params.dig(:channel_post, :document, :thumb, :file_id),
  463. file_size: params.dig(:channel_post, :document, :thumb, :file_size),
  464. width: params.dig(:channel_post, :document, :thumb, :width),
  465. height: params.dig(:channel_post, :document, :thumb, :height)
  466. }.compact
  467. }.delete_if { |_, v| v.blank? },
  468. voice: {
  469. duration: params.dig(:channel_post, :voice, :duration),
  470. mime_type: params.dig(:channel_post, :voice, :mime_type),
  471. file_id: params.dig(:channel_post, :voice, :file_id),
  472. file_size: params.dig(:channel_post, :voice, :file_size)
  473. }.compact,
  474. sticker: {
  475. width: params.dig(:channel_post, :sticker, :width),
  476. height: params.dig(:channel_post, :sticker, :height),
  477. emoji: params.dig(:channel_post, :sticker, :emoji),
  478. set_name: params.dig(:channel_post, :sticker, :set_name),
  479. file_id: params.dig(:channel_post, :sticker, :file_id),
  480. file_path: params.dig(:channel_post, :sticker, :file_path),
  481. thumb: {
  482. file_id: params.dig(:channel_post, :sticker, :thumb, :file_id),
  483. file_size: params.dig(:channel_post, :sticker, :thumb, :file_size),
  484. width: params.dig(:channel_post, :sticker, :thumb, :width),
  485. height: params.dig(:channel_post, :sticker, :thumb, :file_id),
  486. file_path: params.dig(:channel_post, :sticker, :thumb, :file_path)
  487. }.compact
  488. }.delete_if { |_, v| v.blank? },
  489. chat: {
  490. id: params.dig(:channel_post, :chat, :id),
  491. first_name: params.dig(:channel_post, :chat, :title),
  492. last_name: 'Channel',
  493. username: "channel#{params.dig(:channel_post, :chat, :id)}"
  494. },
  495. from: {
  496. id: params.dig(:channel_post, :chat, :id),
  497. first_name: params.dig(:channel_post, :chat, :title),
  498. last_name: 'Channel',
  499. username: "channel#{params.dig(:channel_post, :chat, :id)}"
  500. },
  501. caption: (params.dig(:channel_post, :caption) || {}),
  502. date: params.dig(:channel_post, :date),
  503. message_id: params.dig(:channel_post, :message_id),
  504. text: params.dig(:channel_post, :text),
  505. 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))
  506. }.delete_if { |_, v| v.blank? }
  507. params.delete(:channel_post) # discard unused :channel_post hash
  508. end
  509. # checks if the channel post is being edited, and map it when it is
  510. if params[:edited_channel_post]
  511. # updates on telegram can only be on messages, no attachments
  512. params[:edited_message] = {
  513. chat: {
  514. id: params.dig(:edited_channel_post, :chat, :id),
  515. first_name: params.dig(:edited_channel_post, :chat, :title),
  516. last_name: 'Channel',
  517. username: "channel#{params.dig(:edited_channel_post, :chat, :id)}"
  518. },
  519. from: {
  520. id: params.dig(:edited_channel_post, :chat, :id),
  521. first_name: params.dig(:edited_channel_post, :chat, :title),
  522. last_name: 'Channel',
  523. username: "channel#{params.dig(:edited_channel_post, :chat, :id)}"
  524. },
  525. date: params.dig(:edited_channel_post, :date),
  526. edit_date: params.dig(:edited_channel_post, :edit_date),
  527. message_id: params.dig(:edited_channel_post, :message_id),
  528. text: params.dig(:edited_channel_post, :text)
  529. }
  530. params.delete(:edited_channel_post) # discard unused :edited_channel_post hash
  531. end
  532. # prevent multiple update
  533. if !params[:edited_message]
  534. return if Ticket::Article.find_by(message_id: Telegram.message_id(params))
  535. end
  536. # update article
  537. if params[:edited_message]
  538. article = Ticket::Article.find_by(message_id: Telegram.message_id(params))
  539. return if !article
  540. params[:message] = params[:edited_message]
  541. user = to_user(params)
  542. to_article(params, user, article.ticket, channel, article)
  543. return article
  544. end
  545. # send welcome message and don't create ticket
  546. text = params[:message][:text]
  547. if text.present? && text =~ %r{^/start}
  548. message(params[:message][:chat][:id], channel.options[:welcome] || 'You are welcome! Just ask me something!')
  549. return
  550. # find ticket and close it
  551. elsif text.present? && text =~ %r{^/end}
  552. user = to_user(params)
  553. ticket = Ticket.where(customer_id: user.id).order(:updated_at).first
  554. ticket.state = Ticket::State.find_by(name: 'closed')
  555. ticket.save!
  556. return
  557. end
  558. ticket = nil
  559. # use transaction
  560. Transaction.execute(reset_user_id: true) do
  561. user = to_user(params)
  562. ticket = to_ticket(params, user, group_id, channel)
  563. to_article(params, user, ticket, channel)
  564. end
  565. ticket
  566. end
  567. def from_article(article)
  568. message = nil
  569. Rails.logger.debug { "Create telegram personal message from article to '#{article[:to]}'..." }
  570. message = {}
  571. # TODO: create telegram message here
  572. Rails.logger.debug { message.inspect }
  573. message
  574. end
  575. def get_state(channel, telegram_update, ticket = nil)
  576. message = telegram_update['message']
  577. message_user = user(message)
  578. # no changes in post is from page user it self
  579. if channel.options[:bot][:id].to_s == message_user[:id].to_s
  580. if !ticket
  581. return Ticket::State.find_by(name: 'closed') if !ticket
  582. end
  583. return ticket.state
  584. end
  585. state = Ticket::State.find_by(default_create: true)
  586. return state if !ticket
  587. return ticket.state if ticket.state.id == state.id
  588. Ticket::State.find_by(default_follow_up: true)
  589. end
  590. def download_file(file_id)
  591. document = @api.getFile(file_id)
  592. url = "https://api.telegram.org/file/bot#{@token}/#{document['file_path']}"
  593. UserAgent.get(
  594. url,
  595. {},
  596. {
  597. open_timeout: 20,
  598. read_timeout: 40,
  599. },
  600. )
  601. end
  602. end