DEV Community

Jane
Jane

Posted on • Updated on

Automate sending good night text to your loved one's telegram with a simple python script :P

I was just googling around on how to automate sending daily message to a telegram user. Most of the results are leading to sending the message to a bot (which is subscribed by user) - in short it is when a user connects to a specific bot and that bot sends message to the user. Another thing is the telegram feature of scheduling the message but it does not have the option to repeat the schedule daily. These are not what I want at all. What I want is to automate sending a message from my own account to a specific user and do it daily.

After a more thorough search, I finally found a python library telethon that makes sending message to telegram user very simple with a few line of codes. I will describe below the process I went through.

First, we will need our telegram api_id and api_hash. Please keep in mind that it must not be shared with anyone else as it is a bridge to our authentication.
To get that, you need to login here: https://my.telegram.org/auth?to=apps using your phone number with the country code. Then you will ask to provide the confirmation code. If you never generate the app configuration before, you will need to enter some information. Then you can proceed to get your api_id and api_hash which will then be used to authorize your identity to send the message. You should have something as the image below.

Telegram authentication keys

api_id and api_hash will be used to establish telegram client. And after that, we can start the client and perform any api functions.

from telethon import TelegramClient, events, sync

client = TelegramClient('session_name', api_id, api_hash)
client.start()
Enter fullscreen mode Exit fullscreen mode

Just a side note, I set values of my api_id and api_hash to the environment variables and took it later as following:

import os

api_id = os.getenv("TELEGRAM_API_ID")
api_hash = os.getenv("TELEGRAM_API_HASH") 
Enter fullscreen mode Exit fullscreen mode

Then, it is a matter of calling the client function which in this case is send_massage. It is as easy as following:

client.send_message(username, randomize_message())
Enter fullscreen mode Exit fullscreen mode

username is the target (receiver) with @ sign as prefix. For example @janesoo

Then comes to how to set the script to send the message daily. For this, I used python library schedule. I set a specific hour and did a random for minute (so the receiver won't suspect if it's automated LOL) but overall it is in this piece here:

schedule.every().day.at(f"00:{randomize_minute()}").do(send_message)

while True:
    schedule.run_pending()
    time.sleep(1)

Enter fullscreen mode Exit fullscreen mode

The last while True is to make sure that the code keeps running.

One last note is that, when you run the application for the first time, you will be prompt to enter your phone number and confirmation code. However, you will be kept logged in on your host machine for sometime (longer time) and you don't have to do it even after you stop the application and run again.

And with that, we can easily send a daily message to any telegram users.

Here is the full script:

import os
import schedule
import time
import random

from telethon import TelegramClient, events, sync

MESSAGES = [
    "good night!",
    "good night ;)",
    "dobrou noc!",
    "dobrou noc ;)"
]

#in order to get the info below you need to request here: https://my.telegram.org/apps
api_id = os.getenv("TELEGRAM_API_ID")
api_hash = os.getenv("TELEGRAM_API_HASH") 

#this is a telegram username with @ as prefix
username = os.getenv("TARGET_TELEGRAM_USERNAME")

client = TelegramClient('session_name', api_id, api_hash)
client.start()


def randomize_minute():
    return random.randint(0,59)

def randomize_message():
    return random.choice(MESSAGES)

def send_message():
    try: 
        client.send_message(username, randomize_message())
    except Exception as e:
        print(e)    

schedule.every().day.at(f"00:{randomize_minute()}").do(send_message)

while True:
    schedule.run_pending()
    time.sleep(1)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)