Search code examples
pythontelegrampython-telegram-bottelethon

How to run python script on a server?


Well, I am a beginner in python programming language and a backend developer. And I have written this python script using Telethon to auto-reply to my messages that are from the Telegram app.

from telethon import TelegramClient, events
message = "Sorry, I'll be away until next week!"

api_id = 2******
api_hash = 'ffb5**********************'

client = TelegramClient('anon', api_id, api_hash)

@client.on(events.NewMessage)
async def my_event_handler(event):
    if event.is_private:
        await event.respond(message)

client.start()
client.run_until_disconnected()

This is just a simple script and it has no practical help. I will change it later based on my interests. When I run the script on my computer it is working as long as my computer is working. And I want to run that script always so that it can reply to messages even I am offline. And I think I need to run my code on some free servers.

The question:

Can you suggest to me some step by step tutorials or articles that fulfill my interests? (Consider that I am absolutely a beginner to server stuff.)


Solution

  • You can just run the process in background.
    By running the following for instance (on unix based systems):

    python <script_name> &
    

    For a more robust solution that supports auto-restart upon failures, boot, etc.. consider PM2 or Supervisord

    Here is an example command (using the PM2 route)

    pm2 start <script> --interpreter=python