Oleg Oleg - 4 months ago 43
C# Question

Telegram bot: how to do self update?

I have a Telegram account and created Telegram bot to do some actions on remote machines.
It works ok.
I fixed some codes in the bot and want to update all bots on all computers?

I.e. the bot understands command "/update" but how to pass the new .exe from my computer to all bots and do self-update?

Answer

I have also written such a bot with a self-update mechanism.

To Update the bot I just have to send the new .exe over Telegram, but any other method works fine.

Basically, I do the following:

  • Call getFile with the file_id to get the path.
  • Start a new Process with a different executable. In my case I also pass the URL of the file download.
  • Exit the old process.
  • The new process replaces the old executable and (re-)starts the bot.

On windows, you can't change a .exe while it is running.

Edit:

I run my bot as windows service, which makes things a bit more complicated, but also easier:

  • Before I exit the process, I tell the scm that the service has stopped.
  • After updating, I start the service again over the scm, not with CreateProcess.

If the bot runs as SYSTEM user, permissions/UAC are not a problem. Otherwise allow the service user to write the executable and start the process.

If you run the program from desktop, then UAC can be a problem: If run as admin, you are fine. Processes started inherit the admin access. If not run as admin... Well the user your bot runs on requires write access to the executable.