channels_telegram_controller.rb 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class ChannelsTelegramController < ApplicationController
  3. prepend_before_action :authenticate_and_authorize!, except: [:webhook]
  4. skip_before_action :verify_csrf_token, only: [:webhook]
  5. def index
  6. assets = {}
  7. channel_ids = []
  8. Channel.where(area: 'Telegram::Bot').reorder(:id).each do |channel|
  9. assets = channel.assets(assets)
  10. channel_ids.push channel.id
  11. end
  12. render json: {
  13. assets: assets,
  14. channel_ids: channel_ids
  15. }
  16. end
  17. def add
  18. begin
  19. channel = TelegramHelper.create_or_update_channel(params[:api_token], params)
  20. rescue => e
  21. raise Exceptions::UnprocessableEntity, e.message
  22. end
  23. render json: channel
  24. end
  25. def update
  26. channel = Channel.find_by(id: params[:id], area: 'Telegram::Bot')
  27. begin
  28. channel = TelegramHelper.create_or_update_channel(params[:api_token], params, channel)
  29. rescue => e
  30. raise Exceptions::UnprocessableEntity, e.message
  31. end
  32. render json: channel
  33. end
  34. def enable
  35. channel = Channel.find_by(id: params[:id], area: 'Telegram::Bot')
  36. channel.active = true
  37. channel.save!
  38. render json: {}
  39. end
  40. def disable
  41. channel = Channel.find_by(id: params[:id], area: 'Telegram::Bot')
  42. channel.active = false
  43. channel.save!
  44. render json: {}
  45. end
  46. def destroy
  47. channel = Channel.find_by(id: params[:id], area: 'Telegram::Bot')
  48. channel.destroy
  49. render json: {}
  50. end
  51. def webhook
  52. raise Exceptions::UnprocessableEntity, 'bot id is missing' if params['bid'].blank?
  53. channel = TelegramHelper.bot_by_bot_id(params['bid'])
  54. raise Exceptions::UnprocessableEntity, 'bot not found' if !channel
  55. if channel.options[:callback_token] != params['callback_token']
  56. raise Exceptions::UnprocessableEntity, 'invalid callback token'
  57. end
  58. telegram = TelegramHelper.new(channel.options[:api_token])
  59. begin
  60. telegram.to_group(params, channel.group_id, channel)
  61. rescue Exceptions::UnprocessableEntity => e
  62. Rails.logger.error e.message
  63. end
  64. render json: {}, status: :ok
  65. end
  66. end