Telegram gem and self-signed certificate

If anyone faced an issue after setting webhooks with self-signed certificate updates do not come to server. This article may help you.

For working with Telegram Bot I use telegram-bot-ruby gem

Here is my rake tasks:

desc 'create ssl' 
  task create_ssl: :environment do
  	cmd = "openssl req \
  -newkey rsa:2048 \
  -sha256 \
  -nodes \
  -keyout %{file_name_key} \
  -x509 \
  -days 365 \
  -out %{file_name_pem} \
  -subj \"/C=%{C}/ST=%{ST}/L=%{L}/O=%{O}/CN=%{host}\"
  " % 
        :file_name_key => 'telegram.key', 
        :file_name_pem => 'telegram.pem', 
        :C => "IT",
        :ST => "state",
        :L => "location",
        :O => "description",
        :host =>  ENV["CERT_HOST"] 
      exec cmd
 desc "set webhook"
  task set_webhook: :environment do do |bot|
		hook_url = ENV["BOT_HOST"] + "/webhooks/telegram"
		puts "Setting webhook url: #{hook_url}"
		resp = bot.api.set_webhook url: hook_url, certificate:'telegram.pem')
		puts resp.inspect

After creation self-signed certificate and then setting webhook I ended up in a situation when I didn’t get update from telegram. I looked at nginx logs and saw following lines:

SSL_do_handshake() failed (SSL: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca:SSL alert number 48) while SSL handshaking

After days of googling I managed to figure out. Turned out

bot.api.set_webhook url: hook_url, certificate:'telegram.pem')

didn’t do a work. It didn’t upload certificate.


I used a curl command:

curl -F "url=https://<HOSTNAME>/webhooks/telegram" -F "certificate=@<FULL_PATH_TO_CERT.pem"<BOT_TOKEN>/setWebhook

After this everything started working properly.