automated Telegram Bot to post in your Telegram Channels (Python Script)

If you're the admin of many Telegram channels, you are probably dealing with daily tasks that are repeated everyday. These kind of tasks tend to be boring and time consuming, thus having a bot

to manage them is considered a nice solution. In this tutorial we will explain how to make such bot having a beginner programming knowledge.

 

Step1: Obtain API Credintials

In order to use the Telegram API we need to obtain API ID and API HASH. Go to My Telegram and obtain your pair of ID and HASH. We are going to use them in our script to able to connect to the API.

 

Step2: Install Requirements

Install the latest version of telethon using pip.

pip install telethon

 

Step 3: Import the library and declare variables

Create a new file with .py extention and add the following lines.

from asyncio import sleep   
from telethon import TelegramClient  

API_ID = 0
API_HASH = ''
client = TelegramClient('session', API_ID, API_HASH)
PATH_TO_IMAGE = '/path/to/image'
CAPTION = 'Post Caption'
INTERVAL_BETWEEN_POSTS = 1500

Replace API_ID and API_HASH with the values you got from my.telegram.org. PATH_TO_IMAGE is the path to the image of your channel post. It is recommended to use a png or jpeg file. CAPTION is obviously the caption of your post. INTERVAL_BETWEEN_POSTS is the time script waits in seconds to post the content again in the channel.

Step 4: Add the main script

async def main():
    while True:
        async for dialog in client.iter_dialogs():
            if dialog.is_channel:
                if dialog.entity.admin_rights:
                    await client.send_file(
                        entity=dialog.entity,
                        file=PATH_TO_IMAGE,
                        caption=CAPTION
                    )
            await sleep(1)  # to avoid flooding the API
        await sleep(INTERVAL_BETWEEN_POSTS)

with client:
    client.loop.run_until_complete(main())

The script iterates through all your chats, finds the channels, checks if you are admin in that channel and if all these conditions meet, it will post the content into the channel.

 


272 Comments

Leave a Comment