How to programmatically upload files to Telegram?

Solution 1:

I found a solution! The official client probably doesn't allow it (all known command line arguments are unofficially documented here), but for Linux and Mac (and probably also Linux subsystem on Windows), there is an unofficial command line interface for Telegram called "tg": https://github.com/vysheng/tg
It doesn't mention in its description that it can also send files, but in a Github issue someone wrote that there is the send_file function. In general it's not too well documented, but calling it with --help and entering help inside the program gives a lot of info, the rest can be figured out by fiddling with the parameters and trying different things.
This is the solution I came up with that way:

Preparation

  • Install tg like the readme file says. It didn't work rightaway for me on Debian due to a bug, but as said in this bug report comment, installing libssl1.0-dev is a workaround for that bug: Execute sudo apt install libssl1.0-dev between ./configure and make.
  • Log in with your Telegram account: bin/telegram-cli to start the interactive program, enter phone number (with country code, so in my case starting with +49), enter login code.
  • Now use another Telegram client to send a message in the target chat (or alternatively receive a message there). That adds the chat's name to the program's internal chat list. If multiple chats with the same name exist, it seems to pick the most recently added one. I have not found a way to message a chat by ID.
    That's it for the setup, quit exits the program.

Uploading files programmatically

Now files can be uploaded by giving a send_file command to the program with --execute, which makes it execute that command and then quit automatically:

/path/to/tg/bin/telegram-cli --exec 'send_file <chat> <filename>'

<chat> is the chat's name.
<filename> is the path to the file.
/path/to/tg should be obvious.

Example usage

I'll use something like this to upload a backup of my Google Drive folder to Telegram after I've created it with p7zip:

for filename in ~/drive_backup/drive.zip.*; do ~/tg/bin/telegram-cli --exec 'send_file Backup_chat '"$filename"; done

This uploads all files whose names start with "drive.zip." (.001, .002 etc.) in the folder ~/drive_backup to the Telegram chat "Backup_chat".