Fastlane Series: Sending Test Builds to Telegram

Fastlane is an open-source tool that automates building and releasing mobile apps. If you're new to it, start with the official Android setup guide.

This is part of a series about how we automated the distribution of our Android app with Fastlane. In this one: how every test build gets to QA through Telegram, with one click.

The problem

Our team and QA live in a Telegram group. So for test builds, the "distribution" was: build the APK, find it in app/build/outputs, drag it into the chat, and type what changed. Every time, by hand.

Firebase App Distribution and similar tools exist, but our testers didn't want another app. They wanted the build in the chat they already use.

The lane

sendDebug does the whole thing:

DEBUG_APK = "../app/build/outputs/apk/debug/app-debug.apk"

lane :sendDebug do
  gradle(task: "app:assembleDebug")

  # A new name every time, otherwise Telegram may treat it as the same file
  timestamp = (Time.now.to_f * 1000).to_i
  apk_path = File.join(File.dirname(DEBUG_APK), "MyApp-debug-#{timestamp}.apk")
  FileUtils.mv(DEBUG_APK, apk_path)

  changelog = File.read("../CHANGES.md").strip
  server = TelegramHelper.pick_server(apk_path)

  TelegramHelper.send_file(file_path: apk_path, caption: changelog, server: server)
end

The caption comes from CHANGES.md in the project root. Each developer adds a line there (usually a ticket link) when they finish a task. So every build in the chat says exactly what's in it, and the chat history works as a list of all builds.

Setting up the bot

You need two things:

  1. A bot token. Message @BotFather in Telegram, send /newbot, and it gives you a token.
  2. The chat ID. Add the bot to your group, send any message there, and open https://api.telegram.org/bot<TOKEN>/getUpdates. The chat.id in the answer is your chat ID (for groups it's a negative number).

Then load them in the Fastfile:

TELEGRAM_BOT_TOKEN = ENV.fetch("TELEGRAM_BOT_TOKEN")
TELEGRAM_CHAT_ID   = ENV.fetch("TELEGRAM_CHAT_ID")

PUBLIC_SERVER = { url: "https://api.telegram.org", token: TELEGRAM_BOT_TOKEN }

For now, pick_server in the lane above can simply return PUBLIC_SERVER. We'll make it smarter in the 50 MB section below.

The upload

There are Telegram plugins for Fastlane, but I wrote the upload myself, because I needed the message_id of the sent message. With it, we can edit or delete the message later.

The upload is a plain multipart POST to the Bot API `sendDocument` method. Put it in a small helper, fastlane/helpers/telegram_helper.rb:

require "net/http/post/multipart"

module TelegramHelper
  def self.send_file(file_path:, caption:, server:)
    uri = URI("#{server[:url]}/bot#{server[:token]}/sendDocument")

    File.open(file_path, "rb") do |file|
      request = Net::HTTP::Post::Multipart.new(uri.path,
        "chat_id"  => TELEGRAM_CHAT_ID,
        "caption"  => caption,
        "document" => UploadIO.new(file, "application/vnd.android.package-archive", File.basename(file_path))
      )

      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = uri.scheme == "https"
      http.read_timeout = 600
      response = http.request(request)

      message_id = JSON.parse(response.body).dig("result", "message_id")
      UI.success("Sent! message_id: #{message_id}")
      message_id
    end
  end
end

net/http/post/multipart comes from the multipart-post gem, which Fastlane already depends on, so there's nothing extra to install.

Load the helpers at the top of your Fastfile:

Dir[File.join(__dir__, "helpers", "*.rb")].sort.each { |file| load file }

Fixing mistakes: edit and delete

Sent the wrong changelog? Because the lane prints the message_id, we can fix it with two more small lanes:

bundle exec fastlane editTelegramMessage message_id:123 text:"Correct changelog" is_caption:true
bundle exec fastlane deleteTelegramMessage message_id:123

They call the Bot API methods `editMessageCaption` (for a message with a file), `editMessageText` (for a text-only message) and `deleteMessage`. Two limits to know: a bot can only change its own messages, and it can only delete messages that are less than 48 hours old.

The 50 MB wall

The public Bot API (api.telegram.org) only lets bots upload files up to 50 MB. Debug APKs grow past that easily, and then the upload just fails.

The fix is to run your own Telegram Bot API server. It's the same API, but a self-hosted server accepts uploads up to 2000 MB, and you only change the base URL. I explained the setup step by step in How to bypass Telegram bot 50 MB file limit.

We run several of these servers: one on my own server, and a few on old Android phones with Termux that are always on in our office (Turn an old Android phone into a web server). Each server has its own bot, so every server comes with its own token. Any of them can be down, so the lane checks each one first and falls back to the public API:

SELF_HOSTED_SERVERS = [
  { url: ENV.fetch("BOT_SERVER_1_URL"), token: ENV.fetch("BOT_SERVER_1_TOKEN") },
  { url: ENV.fetch("BOT_SERVER_2_URL"), token: ENV.fetch("BOT_SERVER_2_TOKEN") },
]

def self.pick_server(file_path)
  alive = SELF_HOSTED_SERVERS.find { |server| server_alive?(server[:url]) }
  return alive if alive

  if File.size(file_path) >= 50 * 1024 * 1024
    UI.user_error!("Bot servers are down, cannot send a file of 50 MB or more.")
  end

  UI.important("Self-hosted servers are down, falling back to api.telegram.org")
  PUBLIC_SERVER
end

def self.server_alive?(url)
  uri = URI(url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == "https"
  http.open_timeout = http.read_timeout = 5
  JSON.parse(http.get("/").body)   # any JSON answer means the server is up
  true
rescue StandardError
  false
end

One thing to watch: since each server has its own bot, and a bot can only edit or delete its own messages, the edit and delete lanes must use the same server that sent the message. If that server is down later, you'll have to delete the message by hand.

Takeaway

Distribute builds where your team already is. For us that's Telegram, and the whole thing is one lane, one helper, and a bot. If your APKs are over 50 MB, a self-hosted Bot API server removes the limit, and it can run on almost anything — even an old phone in a drawer.