How to programmatically upload files to Telegram?

8,572

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".

Share:
8,572

Related videos on Youtube

Fabian Röling
Author by

Fabian Röling

[email protected] t.me/Fabian42 YouTube: bit.ly/2MxqIPs Atmos: bit.ly/2ZrByMp Reddit: bit.ly/3qBWVIv I update all gamingSE posts ≥2 to MC 1.x.0. Currently busy, will catch up later. My best posts IDs for bit.ly links Thinking outside the blox Crash game for time travel! 2kKlXYj Death loop: 2mjqbXp Boom! Awake! 2mcEv3H Do you exist? 2mh5V8L Hidden messages: 2kN5Ed8 Abuse gamerule for logging: 2kniyi4 Of cake and integrals: 2miBdw1 (2. answer better) Execute them! 2kdEVpU Group NBT tags: 2mfFss5 # of items, not item entities: 2kgc700 From score to hearts: 2kniaQE Backwards filter: 2kNfr2T I put in effort, so you don't have to Kill all the mobs! 2kN5Kl0 Break all the blocks! 2kNbcV3 Place on all the blocks! 34cMajC Rotate in all the directions! 2lSk1x5 Being thorough Warning about 1.13+: 2mfFBvD (especially comments) Most unlikely snowman: 2khBZIT When water isn't water: 2kB8NwS Ghast-safe blocks in Nether: 2shMX5d What counts as kill? 2lRuqJo How many recipes possible? 2lWu5Fa Pushable comparator input: 2kLVWrE Who shot it? 2mbkpa3 Keep furnace busy: 2lWu8Rm Research&amp;documentation data modify: 2kljdR5 Default NBT types: 2lUzFZ2 NBT in JSON: 2kB92bg All about languages: 2QnHhyD hoverEvent show_item: 2mjmBwx Mob farms high or low? 2kycVO9 Light: 2lVaMvY Fastest arrow: 2khCoen Flight acceleration: 2klj00f Pickaxe-resistant blocks: 2kluK2M Silence! 2mdQ0rG Lightning inside: 2lPUnJo Programming&amp;redstone Evil redstone: 3dkFmVn Fibonacci: 2lQkzDG Dynamically sized array: 3a1R4mv Swap wires vertically: 2mbkrPd (5 answers) Raycasting: 2t3mWab Detect rectangles: 2mhDc3I One-commands: 3eC2XlL Binary search: 3aSUVCd Block check optimisation: 2yfTjVm Many pulses: 2O71I2j Shoot TNT from your face! 2kLgqAM Shoot arrows from your face… in multiplayer! 2kNRGYH Modded item sorter: 2miBPBP Ridden by who? 2sFCb91 TP to any coordinates with /trigger: 2miBRcV Signal halver: 2kNRN6z XP halver: 2kKmERp Cycling through 4 outputs: 2lRuJUy Veinminer concept 2lRuKYC and implementation 2w93Ild Q&amp;As Auto-upload files to Telegram: 2kmH4jk Auto-move items in Minecraft chests: 2kincxE Qs Far future CMB: 2kmH8j4 CP violation: 2lWcpcN Random maximum: 2kLWb62 TinyTask for Linux: 2lPp0ic Video editor for Linux: 2lWuZl2 Auto-create Takeouts: 2lWuZBy Custom Notepad++ menu: 2mizoPG Combine lists better: 2kivgP3 Watched&amp;ignored tags: 2mhDk3c Tag&amp;question edits: 2kKFtnz Hold mails if question in review: 2mhDl7g

Updated on September 18, 2022

Comments

  • Fabian Röling
    Fabian Röling almost 2 years

    Since Telegram is an infinite cloud service, I use it as a secondary backup location. I would like to automate this so that I don't have to remember to do it every month (in the last two years I missed about every second monthly backup).
    But I can't find a way to automate any Telegram client without click macros (I would like to have it run silently in the background):

    • ./Telegram --help does nothing except opening the program.
    • I wasn't successful in determining where the argv variable goes from the main method, so I don't know if there even are console arguments.
    • Bots can't access my file system (and that's a good thing).

    I can easily automate packing the files I want into 1.5GB archives using 7z, but I have no idea about how to actually send them. Is there a way to do it without click macros?

    I'm on Debian 9.5 and using the official Linux client from telegram.org.

    • Martin Ueding
      Martin Ueding over 5 years
      Can't you directly use the libmtproto to write a storage backend?
    • Fabian Röling
      Fabian Röling over 5 years
      I don't know, since I don't know that program. Also, I would have to know details about how to send packages to the Telegram servers. At some point I just have a custom client. If you know how to make a minimalistic program for that or whatever your idea was, that would be awesome.
    • Martin Ueding
      Martin Ueding over 5 years
      I don't know the details, but it seems that TDlib is what you want.
    • Fabian Röling
      Fabian Röling over 5 years
      It seems like there is a command line client for Telegram and it can send files, even though it's not in the documentation: github.com/vysheng/tg/issues/458 I'll try that this evening and if it works, write an answer.
    • Fabian Röling
      Fabian Röling about 4 years
      Update: The command line arguments are now officially documented and indeed, there is no way to do it with the official client.
  • Fabian Röling
    Fabian Röling over 5 years
    How would that select a chat?
  • Fabian Röling
    Fabian Röling over 5 years
    There seems to be such a command actually. But there is no documentation for it. If you know more, please comment here: github.com/telegramdesktop/tdesktop/issues/2058 But I'm pretty sure that just a path is not enough, how would it know what chat to send it to? I could actually try just putting a chat ID before or after the path, but that's just a random guess.
  • Juan
    Juan over 5 years
    I have it running. You ask for help, get the proper and right answer and vote -1? O_o Don't count on my help anymore
  • Fabian Röling
    Fabian Röling over 5 years
    Well, how do you send to a specific chat? It can't just send it to a random chat. Do I need an ID, a name or something else? Where do I put that argument?
  • Fabian Röling
    Fabian Röling over 5 years
    I tried it now. It's interactive, I'm supposed to click on a chat. That's not automatic and can't happen in the background. So this post does indeed not answer my queston.
  • Fabian Röling
    Fabian Röling about 4 years
    I tested a bunch of stuff and it seems to work well. Of course the downside is that I would need to install it everywhere for it to work, but I would usually only use it on my laptop anyway.
  • Fabian Röling
    Fabian Röling about 4 years
    Actually, I just now tried restoring files on another system than it has been uploaded to . That doesn't work at all. That makes it useless as a backup system, because if my system is broken and I re-install it, I can't access my files anymore.
  • Fabian Röling
    Fabian Röling about 4 years
    What do you mean with "Of course it has database file import/export feature."? There is no such command in --help or in the Github description.
  • Scrooge McDuck
    Scrooge McDuck about 4 years
    You can export backed up files list and credentials either directly copying the directory at ~/.config/pgpgram to another user's home (be sure to have correct ownership for those file) or you can merge files backed up from another computer into current installation copying ~/.config/pgpgram/files.pkl over and then giving pgpgram --import files.pkl (if you installed from master that won't probably work atm), it's in --help since 23 march commit. Master is not on PyPI because it saw introduced great performance features (when over 5.000 files) which broke search and import though.
  • Scrooge McDuck
    Scrooge McDuck about 4 years
    Usually I do backups copying the directory on a flash drive and import files backed up from other devices to the main machine using --import.
  • Fabian Röling
    Fabian Röling about 4 years
    But then why would I use Telegram at all if I need another medium to sync the information about what was uploaded? And I would need to find another solution to do that automatically, otherwise it's again a manual process.
  • Scrooge McDuck
    Scrooge McDuck about 4 years
    I also use it as a secondary backup solution, that meaning that the tiny pickle file (now an sqlite db) is backed up along with my whole home directory on a physical machine. In general, the program was written to prove that Telegram needed a stronger privacy policy and probably didn't care for privacy all, so new features are only added when needed: since no one came forward asking for public key encryption you get why index rebuilding feature is missing.
  • Scrooge McDuck
    Scrooge McDuck about 4 years
    That's also why import was added just a few months ago, why YouTube integration came out of the blue or why there is still no delete command lol. So, unless project gets funded in some way, you rely on other people needs. Merge requests and issue reporting are always welcomed, though.
  • Scrooge McDuck
    Scrooge McDuck about 4 years
    Neverthless, there is no sign the program will be abandoned soon. Telegram is soaring, I heavily use it and the source is free as in free speech.
  • Suresh
    Suresh almost 4 years
    The message in telegram is "Saved Messages" to my own chat. When i run "bin/telegram-cli --exec 'send_file "Saved Messages" config.log' nothing happens. Is there a way we can name this as Backup_chat.
  • Fabian Röling
    Fabian Röling almost 4 years
    @Suresh You need your own username, without quotes. So in my case it would be msg @Fabian42 "test" or msg @Fabian42 test. Sadly it gives you no feedback if you have the wrong username or one for which the program hasn't seen a message come in or out yet.
  • Fabian Röling
    Fabian Röling almost 3 years
    That is already the preparation step #3 in my answer.