How to create completely automated telegram channel with python

In this article we will see how to create a completely automated telegram channel.

To demonstrate the process we will take through the example of a telegram channel News India (https://t.me/newsindiachannel) created by me which post news every hour.

The automated process of generating content and posting on the channel is divided into three parts.
- Creating telegram channel and bot
- Generating/fetching content using python script
- Posting the content to telegram channel.



Creating telegram channel and Bot:

-Install telegram app from Google Play.

-After you are done with initial setup. Click on menu and create a new channel.

how to create completely automated telegram channel with python


- Make this a public channel so that anybody can search and join it.

- Add first member to it. Your channel is up.

- Now we need to create a bot.

- Search for 'botfather'. This is the bot which help us by creating all bots for us.

how to create completely automated telegram channel with python

- Now like any other bot, this bot understands few pre-defined commands. Start with /start  You will be presented with other commands.

how to create completely automated telegram channel with python
- To create a new bot, use command /newbot .

- You will be asked to choose a name. Choose appropriate name for your bot. Remember name of your bot must end with 'bot'.  For example newsindiachannelbot  in my case.

- If name is available, botfather will provide telegram link of your bot and a token to access HTTP API. Something like this:  923778870:AAH54XXXMBUXXXPz4XX-fbeXXXTXYYYY



Adding bot as Admin:

- Now go to the settings of your channel and click 'Administrators.'.  Click Add administrator.

- You need to search for the bot. For example @yourbotname.

- Congratulations, first step is completed.

how to create completely automated telegram channel with python  



Getting content using python script:

My channel as name suggest will be sharing news headlines every hour. For this I am scrapping Google News page. This is for educational purpose only and it is not recommended to send too many requests to any website without their permission.

Install below packages using pip.

beautifulsoup4==4.6.0
bs4==0.0.1
lxml==3.8.0
python-telegram-bot==6.1.0
requests==2.18.1
urllib3==1.21.1
 

To scrap web page, I am using BeautifulSoup. Lets see the below code.

def get_news_data(starting_url):
    news_data = [] 
    # get complete page on this url
    response = requests.get(starting_url)
    soup = BeautifulSoup(response.text, 'lxml')
    # find all elemens with given class name
    elements = soup.find(attrs={"class": "deQdld"})
    # iterate over the list of elements
    for element in elements:
        data = {}
        news_element = element.find(attrs={"class":"nuEeue hzdq5d ME7ew"})
        if news_element:
            try:
                # get the news url link 
                link = news_element.attrs["href"]
                # get the news text
                text = news_element.string.strip()
            except Exception as e:
                print(e)

            if link and text:            
                data["link"] = link
                data["text"] = text
                news_data.append(data)
    # return the list of news items
    return news_data


Now I have the list of dictionaries where each dictionary have two key value pairs, news text and news link. Now create a complete message to post on the channel from this list of news dictionaries.

def get_msg(news_data):
    msg = "\n\n\n"
    for news_item in news_data:
        text = news_item["text"]
        link = news_item["link"]
        msg += text+'  [<a href="'+link+'">source</a>]'
        msg += "\n\n"
 


Posting the message in channel using bot:

Install the python package python-telegram-bot==6.1.0  using pip. 

Find out the ID of your channel. Use below 2 lines to post the message to your channel.

import telegram
from config import telegram_token_news

# use token generated in first step
bot = telegram.Bot(token=telegram_token_news)
status = bot.send_message(chat_id="@newsindiachannel", text=msg, parse_mode=telegram.ParseMode.HTML)

print(status)


I always recommend to store secrets, password and token in a separate config file. Once you run this script, it will scrap the data from Google news page, parse and format it and post the data to news channel.

how to create completely automated telegram channel with python  

Now you can schedule a cron every hour or every few hours depending on your requirement.

I am using PythonAnyWhere server to host my Django Apps. I have scheduled the above script on python anywhere server.

How to schedule a cron on PythonAnyWhere server.

Complete code for the script above is available on Github.


You may join these telegram channels:
- PythonCircle (group): Discussions about Django : t.me/pythoncircle


Feel free to comment in case of any issue.


Related Articles:
Comparing celery-rabbitmq docker cluster, multi-threading and scrapy framework for 1000 requests
comparing the performance of docker cluster, multi-threaded approach and scrapy framework to send 1000 requests and processing response....
Python Script 10: Collecting one million website links
Collecting one million website links by scraping using requests and BeautifulSoup in Python. Python script to collect one million website urls. Using beautifulsoup to scrape data...
Automatically updating Django website hosted on PythonAnyWhere server with every git push
How to automate the process of updating website hosted on python any where server everytime you commit and push code to git repository....
Iterator and Generators in Python: Explained with example
understanding iterators and generators in python, creating python generators, using generators and iterators in python code...

1 thought on 'How To Create Completely Automated Telegram Channel With Python'
Amit :
Exactly what i was looking for. precisely explained

Leave a comment:


*All Fields are mandatory. **Email Id will not be published publicly.


SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.



Recent Posts:






© pythoncircle.com 2018-2019