telegram.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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 =~ %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 = SecureRandom.urlsafe_base64(10)
  58. # set webhook / callback url for this bot @ telegram
  59. callback_url = "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/api/v1/channels_telegram_webhook/#{callback_token}?bid=#{bot['id']}"
  60. Telegram.set_webhook(token, callback_url)
  61. if !channel
  62. channel = Telegram.bot_by_bot_id(bot['id'])
  63. if !channel
  64. channel = Channel.new
  65. end
  66. end
  67. channel.area = 'Telegram::Bot'
  68. channel.options = {
  69. bot: {
  70. id: bot['id'],
  71. username: bot['username'],
  72. first_name: bot['first_name'],
  73. last_name: bot['last_name'],
  74. },
  75. callback_token: callback_token,
  76. callback_url: callback_url,
  77. api_token: token,
  78. welcome: params[:welcome],
  79. }
  80. channel.group_id = group.id
  81. channel.active = true
  82. channel.save!
  83. channel
  84. end
  85. =begin
  86. check if bot already exists as channel
  87. success = Telegram.bot_duplicate?(bot_id)
  88. returns
  89. channel # instance of Channel
  90. =end
  91. def self.bot_duplicate?(bot_id, channel_id = nil)
  92. Channel.where(area: 'Telegram::Bot').each { |channel|
  93. next if !channel.options
  94. next if !channel.options[:bot]
  95. next if !channel.options[:bot][:id]
  96. next if channel.options[:bot][:id] != bot_id
  97. next if channel.id.to_s == channel_id.to_s
  98. return true
  99. }
  100. false
  101. end
  102. =begin
  103. get channel by bot_id
  104. channel = Telegram.bot_by_bot_id(bot_id)
  105. returns
  106. true|false
  107. =end
  108. def self.bot_by_bot_id(bot_id)
  109. Channel.where(area: 'Telegram::Bot').each { |channel|
  110. next if !channel.options
  111. next if !channel.options[:bot]
  112. next if !channel.options[:bot][:id]
  113. return channel if channel.options[:bot][:id].to_s == bot_id.to_s
  114. }
  115. nil
  116. end
  117. =begin
  118. generate message_id for message
  119. message_id = Telegram.message_id(message)
  120. returns
  121. message_id # 123456@telegram
  122. =end
  123. def self.message_id(params)
  124. message_id = nil
  125. [:message, :edited_message].each { |key|
  126. next if !params[key]
  127. next if !params[key][:message_id]
  128. message_id = params[key][:message_id]
  129. break
  130. }
  131. if message_id
  132. [:message, :edited_message].each { |key|
  133. next if !params[key]
  134. next if !params[key][:chat]
  135. next if !params[key][:chat][:id]
  136. message_id = "#{message_id}.#{params[key][:chat][:id]}"
  137. }
  138. end
  139. if !message_id
  140. message_id = params[:update_id]
  141. end
  142. "#{message_id}@telegram"
  143. end
  144. =begin
  145. client = Telegram.new('token')
  146. =end
  147. def initialize(token)
  148. @token = token
  149. @api = TelegramAPI.new(token)
  150. end
  151. =begin
  152. client.message(chat_id, 'some message')
  153. =end
  154. def message(chat_id, message)
  155. return if Rails.env.test?
  156. @api.sendMessage(chat_id, message)
  157. end
  158. def user(params)
  159. {
  160. id: params[:message][:from][:id],
  161. username: params[:message][:from][:username],
  162. first_name: params[:message][:from][:first_name],
  163. last_name: params[:message][:from][:last_name]
  164. }
  165. end
  166. def to_user(params)
  167. Rails.logger.debug 'Create user from message...'
  168. Rails.logger.debug params.inspect
  169. # do message_user lookup
  170. message_user = user(params)
  171. auth = Authorization.find_by(uid: message_user[:id], provider: 'telegram')
  172. # create or update user
  173. login = message_user[:username] || message_user[:id]
  174. user_data = {
  175. login: login,
  176. firstname: message_user[:first_name],
  177. lastname: message_user[:last_name],
  178. }
  179. if auth
  180. user = User.find(auth.user_id)
  181. user.update_attributes(user_data)
  182. else
  183. if message_user[:username]
  184. user_data[:note] = "Telegram @#{message_user[:username]}"
  185. end
  186. user_data[:active] = true
  187. user_data[:role_ids] = Role.signup_role_ids
  188. user = User.create(user_data)
  189. end
  190. # create or update authorization
  191. auth_data = {
  192. uid: message_user[:id],
  193. username: login,
  194. user_id: user.id,
  195. provider: 'telegram'
  196. }
  197. if auth
  198. auth.update_attributes(auth_data)
  199. else
  200. Authorization.create(auth_data)
  201. end
  202. user
  203. end
  204. def to_ticket(params, user, group_id, channel)
  205. UserInfo.current_user_id = user.id
  206. Rails.logger.debug 'Create ticket from message...'
  207. Rails.logger.debug params.inspect
  208. Rails.logger.debug user.inspect
  209. Rails.logger.debug group_id.inspect
  210. # prepare title
  211. title = '-'
  212. [:text, :caption].each { |area|
  213. next if !params[:message]
  214. next if !params[:message][area]
  215. title = params[:message][area]
  216. break
  217. }
  218. if title == '-'
  219. [:sticker, :photo, :document, :voice].each { |area|
  220. begin
  221. next if !params[:message]
  222. next if !params[:message][area]
  223. next if !params[:message][area][:emoji]
  224. title = params[:message][area][:emoji]
  225. break
  226. rescue
  227. # just go ahead
  228. title
  229. end
  230. }
  231. end
  232. if title.length > 60
  233. title = "#{title[0, 60]}..."
  234. end
  235. # find ticket or create one
  236. state_ids = Ticket::State.where(name: %w(closed merged removed)).pluck(:id)
  237. ticket = Ticket.where(customer_id: user.id).where.not(state_id: state_ids).order(:updated_at).first
  238. if ticket
  239. # check if title need to be updated
  240. if ticket.title == '-'
  241. ticket.title = title
  242. end
  243. new_state = Ticket::State.find_by(default_create: true)
  244. if ticket.state_id != new_state.id
  245. ticket.state = Ticket::State.find_by(default_follow_up: true)
  246. end
  247. ticket.save!
  248. return ticket
  249. end
  250. ticket = Ticket.new(
  251. group_id: group_id,
  252. title: title,
  253. state_id: Ticket::State.find_by(default_create: true).id,
  254. priority_id: Ticket::Priority.find_by(default_create: true).id,
  255. customer_id: user.id,
  256. preferences: {
  257. channel_id: channel.id,
  258. telegram: {
  259. bid: params['bid'],
  260. chat_id: params[:message][:chat][:id]
  261. }
  262. },
  263. )
  264. ticket.save!
  265. ticket
  266. end
  267. def to_article(params, user, ticket, channel, article = nil)
  268. if article
  269. Rails.logger.debug 'Update article from message...'
  270. else
  271. Rails.logger.debug 'Create article from message...'
  272. end
  273. Rails.logger.debug params.inspect
  274. Rails.logger.debug user.inspect
  275. Rails.logger.debug ticket.inspect
  276. UserInfo.current_user_id = user.id
  277. if article
  278. article.preferences[:edited_message] = {
  279. message: {
  280. created_at: params[:message][:date],
  281. message_id: params[:message][:message_id],
  282. from: params[:message][:from],
  283. },
  284. update_id: params[:update_id],
  285. }
  286. else
  287. article = Ticket::Article.new(
  288. ticket_id: ticket.id,
  289. type_id: Ticket::Article::Type.find_by(name: 'telegram personal-message').id,
  290. sender_id: Ticket::Article::Sender.find_by(name: 'Customer').id,
  291. from: user(params)[:username],
  292. to: "@#{channel[:options][:bot][:username]}",
  293. message_id: Telegram.message_id(params),
  294. internal: false,
  295. preferences: {
  296. message: {
  297. created_at: params[:message][:date],
  298. message_id: params[:message][:message_id],
  299. from: params[:message][:from],
  300. },
  301. update_id: params[:update_id],
  302. }
  303. )
  304. end
  305. # add article
  306. if params[:message][:photo]
  307. # find photo with best resolution for us
  308. photo = nil
  309. max_width = 650 * 2
  310. last_width = 0
  311. last_height = 0
  312. params[:message][:photo].each { |file|
  313. if !photo
  314. photo = file
  315. last_width = file['width'].to_i
  316. last_height = file['height'].to_i
  317. end
  318. next unless file['width'].to_i < max_width && last_width < file['width'].to_i
  319. photo = file
  320. last_width = file['width'].to_i
  321. last_height = file['height'].to_i
  322. }
  323. if last_width > 650
  324. last_width = (last_width / 2).to_i
  325. last_height = (last_height / 2).to_i
  326. end
  327. # download image
  328. result = download_file(photo['file_id'])
  329. if !result.success? || !result.body
  330. raise "Unable for download image from telegram: #{result.code}"
  331. end
  332. body = "<img style=\"width:#{last_width}px;height:#{last_height}px;\" src=\"data:image/png;base64,#{Base64.strict_encode64(result.body)}\">"
  333. if params[:message][:caption]
  334. body += "<br>#{params[:message][:caption].text2html}"
  335. end
  336. article.content_type = 'text/html'
  337. article.body = body
  338. article.save!
  339. return article
  340. end
  341. # add document
  342. if params[:message][:document]
  343. thumb = params[:message][:document][:thumb]
  344. body = '&nbsp;'
  345. if thumb
  346. width = thumb[:width]
  347. height = thumb[:height]
  348. result = download_file(thumb['file_id'])
  349. if !result.success? || !result.body
  350. raise "Unable for download image from telegram: #{result.code}"
  351. end
  352. body = "<img style=\"width:#{width}px;height:#{height}px;\" src=\"data:image/png;base64,#{Base64.strict_encode64(result.body)}\">"
  353. end
  354. document_result = download_file(params[:message][:document][:file_id])
  355. article.content_type = 'text/html'
  356. article.body = body
  357. article.save!
  358. Store.remove(
  359. object: 'Ticket::Article',
  360. o_id: article.id,
  361. )
  362. Store.add(
  363. object: 'Ticket::Article',
  364. o_id: article.id,
  365. data: document_result.body,
  366. filename: params[:message][:document][:file_name],
  367. preferences: {
  368. 'Mime-Type' => params[:message][:document][:mime_type],
  369. },
  370. )
  371. return article
  372. end
  373. # voice
  374. if params[:message][:voice]
  375. body = '&nbsp;'
  376. if params[:message][:caption]
  377. body = "<br>#{params[:message][:caption].text2html}"
  378. end
  379. document_result = download_file(params[:message][:voice][:file_id])
  380. article.content_type = 'text/html'
  381. article.body = body
  382. article.save!
  383. Store.remove(
  384. object: 'Ticket::Article',
  385. o_id: article.id,
  386. )
  387. Store.add(
  388. object: 'Ticket::Article',
  389. o_id: article.id,
  390. data: document_result.body,
  391. filename: params[:message][:voice][:file_path] || 'audio',
  392. preferences: {
  393. 'Mime-Type' => params[:message][:voice][:mime_type],
  394. },
  395. )
  396. return article
  397. end
  398. if params[:message][:sticker]
  399. emoji = params[:message][:sticker][:emoji]
  400. thumb = params[:message][:sticker][:thumb]
  401. body = '&nbsp;'
  402. if thumb
  403. width = thumb[:width]
  404. height = thumb[:height]
  405. result = download_file(thumb['file_id'])
  406. if !result.success? || !result.body
  407. raise "Unable for download image from telegram: #{result.code}"
  408. end
  409. body = "<img style=\"width:#{width}px;height:#{height}px;\" src=\"data:image/png;base64,#{Base64.strict_encode64(result.body)}\">"
  410. article.content_type = 'text/html'
  411. elsif emoji
  412. article.content_type = 'text/plain'
  413. body = emoji
  414. end
  415. article.body = body
  416. article.save!
  417. if params[:message][:sticker][:file_id]
  418. document_result = download_file(params[:message][:sticker][:file_id])
  419. Store.remove(
  420. object: 'Ticket::Article',
  421. o_id: article.id,
  422. )
  423. Store.add(
  424. object: 'Ticket::Article',
  425. o_id: article.id,
  426. data: document_result.body,
  427. filename: params[:message][:sticker][:file_name] || 'sticker',
  428. preferences: {
  429. 'Mime-Type' => params[:message][:sticker][:mime_type],
  430. },
  431. )
  432. end
  433. return article
  434. end
  435. # text
  436. if params[:message][:text]
  437. article.content_type = 'text/plain'
  438. article.body = params[:message][:text]
  439. article.save!
  440. return article
  441. end
  442. raise 'invalid action'
  443. end
  444. def to_group(params, group_id, channel)
  445. Rails.logger.debug 'import message'
  446. # prevent multible update
  447. if !params[:edited_message]
  448. return if Ticket::Article.find_by(message_id: Telegram.message_id(params))
  449. end
  450. # update article
  451. if params[:edited_message]
  452. article = Ticket::Article.find_by(message_id: Telegram.message_id(params))
  453. return if !article
  454. params[:message] = params[:edited_message]
  455. user = to_user(params)
  456. to_article(params, user, article.ticket, channel, article)
  457. return article
  458. end
  459. # send welcome message and don't create ticket
  460. text = params[:message][:text]
  461. if text.present? && text =~ %r{^/start}
  462. message(params[:message][:chat][:id], channel.options[:welcome] || 'You are welcome! Just ask me something!')
  463. return
  464. # find ticket and close it
  465. elsif text.present? && text =~ %r{^/end}
  466. user = to_user(params)
  467. ticket = Ticket.where(customer_id: user.id).order(:updated_at).first
  468. ticket.state = Ticket::State.find_by(name: 'closed')
  469. ticket.save!
  470. return
  471. end
  472. ticket = nil
  473. # use transaction
  474. Transaction.execute(reset_user_id: true) do
  475. user = to_user(params)
  476. ticket = to_ticket(params, user, group_id, channel)
  477. to_article(params, user, ticket, channel)
  478. end
  479. ticket
  480. end
  481. def from_article(article)
  482. message = nil
  483. Rails.logger.debug "Create telegram personal message from article to '#{article[:to]}'..."
  484. message = {}
  485. # TODO: create telegram message here
  486. Rails.logger.debug message.inspect
  487. message
  488. end
  489. def get_state(channel, telegram_update, ticket = nil)
  490. message = telegram_update['message']
  491. message_user = user(message)
  492. # no changes in post is from page user it self
  493. if channel.options[:bot][:id].to_s == message_user[:id].to_s
  494. if !ticket
  495. return Ticket::State.find_by(name: 'closed') if !ticket
  496. end
  497. return ticket.state
  498. end
  499. state = Ticket::State.find_by(default_create: true)
  500. return state if !ticket
  501. return ticket.state if ticket.state.id == state.id
  502. Ticket::State.find_by(default_follow_up: true)
  503. end
  504. def download_file(file_id)
  505. if Rails.env.test?
  506. result = Result.new(
  507. success: true,
  508. body: 'ok',
  509. data: 'ok',
  510. code: 200,
  511. content_type: 'application/stream',
  512. )
  513. return result
  514. end
  515. document = @api.getFile(file_id)
  516. url = "https://api.telegram.org/file/bot#{@token}/#{document['file_path']}"
  517. UserAgent.get(
  518. url,
  519. {},
  520. {
  521. open_timeout: 20,
  522. read_timeout: 40,
  523. },
  524. )
  525. end
  526. class Result
  527. attr_reader :error
  528. attr_reader :body
  529. attr_reader :data
  530. attr_reader :code
  531. attr_reader :content_type
  532. def initialize(options)
  533. @success = options[:success]
  534. @body = options[:body]
  535. @data = options[:data]
  536. @code = options[:code]
  537. @content_type = options[:content_type]
  538. @error = options[:error]
  539. end
  540. def success?
  541. return true if @success
  542. false
  543. end
  544. end
  545. end