telegram.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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 = 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 { |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. }
  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 { |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. }
  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. [:message, :edited_message].each { |key|
  130. next if !params[key]
  131. next if !params[key][:message_id]
  132. message_id = params[key][:message_id]
  133. break
  134. }
  135. if message_id
  136. [:message, :edited_message].each { |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. }
  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_attributes(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_attributes(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. [:text, :caption].each { |area|
  217. next if !params[:message]
  218. next if !params[:message][area]
  219. title = params[:message][area]
  220. break
  221. }
  222. if title == '-'
  223. [:sticker, :photo, :document, :voice].each { |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. }
  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 { |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. }
  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',
  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/png;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] || 'sticker',
  432. preferences: {
  433. 'Mime-Type' => params[:message][:sticker][:mime_type],
  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. Rails.logger.debug 'import message'
  450. # prevent multible update
  451. if !params[:edited_message]
  452. return if Ticket::Article.find_by(message_id: Telegram.message_id(params))
  453. end
  454. # update article
  455. if params[:edited_message]
  456. article = Ticket::Article.find_by(message_id: Telegram.message_id(params))
  457. return if !article
  458. params[:message] = params[:edited_message]
  459. user = to_user(params)
  460. to_article(params, user, article.ticket, channel, article)
  461. return article
  462. end
  463. # send welcome message and don't create ticket
  464. text = params[:message][:text]
  465. if text.present? && text =~ %r{^/start}
  466. message(params[:message][:chat][:id], channel.options[:welcome] || 'You are welcome! Just ask me something!')
  467. return
  468. # find ticket and close it
  469. elsif text.present? && text =~ %r{^/end}
  470. user = to_user(params)
  471. ticket = Ticket.where(customer_id: user.id).order(:updated_at).first
  472. ticket.state = Ticket::State.find_by(name: 'closed')
  473. ticket.save!
  474. return
  475. end
  476. ticket = nil
  477. # use transaction
  478. Transaction.execute(reset_user_id: true) do
  479. user = to_user(params)
  480. ticket = to_ticket(params, user, group_id, channel)
  481. to_article(params, user, ticket, channel)
  482. end
  483. ticket
  484. end
  485. def from_article(article)
  486. message = nil
  487. Rails.logger.debug "Create telegram personal message from article to '#{article[:to]}'..."
  488. message = {}
  489. # TODO: create telegram message here
  490. Rails.logger.debug message.inspect
  491. message
  492. end
  493. def get_state(channel, telegram_update, ticket = nil)
  494. message = telegram_update['message']
  495. message_user = user(message)
  496. # no changes in post is from page user it self
  497. if channel.options[:bot][:id].to_s == message_user[:id].to_s
  498. if !ticket
  499. return Ticket::State.find_by(name: 'closed') if !ticket
  500. end
  501. return ticket.state
  502. end
  503. state = Ticket::State.find_by(default_create: true)
  504. return state if !ticket
  505. return ticket.state if ticket.state.id == state.id
  506. Ticket::State.find_by(default_follow_up: true)
  507. end
  508. def download_file(file_id)
  509. document = @api.getFile(file_id)
  510. url = "https://api.telegram.org/file/bot#{@token}/#{document['file_path']}"
  511. UserAgent.get(
  512. url,
  513. {},
  514. {
  515. open_timeout: 20,
  516. read_timeout: 40,
  517. },
  518. )
  519. end
  520. end