feat: Telegram Channel (#2901)

- Ability to configure telegram bots as a channel in chatwoot
- Receive a message sent to the telegram bot in chatwoot
- Ability to reply to telegram users from chatwoot
- Receive attachment messages in chatwoot

fixes: #1843
This commit is contained in:
Sojan Jose
2021-09-10 00:00:52 +05:30
committed by GitHub
parent 9c4ce9af35
commit 671c5c931f
32 changed files with 648 additions and 65 deletions

View File

@@ -0,0 +1,89 @@
# == Schema Information
#
# Table name: channel_telegram
#
# id :bigint not null, primary key
# bot_name :string
# bot_token :string not null
# created_at :datetime not null
# updated_at :datetime not null
# account_id :integer not null
#
# Indexes
#
# index_channel_telegram_on_bot_token (bot_token) UNIQUE
#
class Channel::Telegram < ApplicationRecord
self.table_name = 'channel_telegram'
EDITABLE_ATTRS = [:bot_token].freeze
has_one :inbox, as: :channel, dependent: :destroy
belongs_to :account
before_validation :ensure_valid_bot_token, on: :create
validates :account_id, presence: true
validates :bot_token, presence: true, uniqueness: true
before_save :setup_telegram_webhook
def name
'Telegram'
end
def has_24_hour_messaging_window?
false
end
def telegram_api_url
"https://api.telegram.org/bot#{bot_token}"
end
def send_message_on_telegram(message, chat_id)
response = HTTParty.post("#{telegram_api_url}/sendMessage",
body: {
chat_id: chat_id,
text: message
})
response.parsed_response['result']['message_id'] if response.success?
end
def get_telegram_profile_image(user_id)
# get profile image from telegram
response = HTTParty.get("#{telegram_api_url}/getUserProfilePhotos", query: { user_id: user_id })
return nil unless response.success?
photos = response.parsed_response['result']['photos']
return if photos.blank?
get_telegram_file_path(photos.first.last['file_id'])
end
def get_telegram_file_path(file_id)
response = HTTParty.get("#{telegram_api_url}/getFile", query: { file_id: file_id })
return nil unless response.success?
"https://api.telegram.org/file/bot#{bot_token}/#{response.parsed_response['result']['file_path']}"
end
private
def ensure_valid_bot_token
response = HTTParty.get("#{telegram_api_url}/getMe")
unless response.success?
errors.add(:bot_token, 'invalid token')
return
end
self.bot_name = response.parsed_response['result']['username']
end
def setup_telegram_webhook
HTTParty.post("#{telegram_api_url}/deleteWebhook")
response = HTTParty.post("#{telegram_api_url}/setWebhook",
body: {
url: "#{ENV['FRONTEND_URL']}/webhooks/telegram/#{bot_token}"
})
errors.add(:bot_token, 'error setting up the webook') unless response.success?
end
end