how to tips   0   3
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 and 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. cd4bfb6f ee82 4131 acfb e9a2cb17d307 169x300.jpeg - 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. botfather 300x174.png- Now like any other bot, this bot understands few pre-defined commands. Start with /start . You will be presented with other commands. botfather 1 271x300.png- 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. bot in telegram channel 300x269.png  
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. WhatsApp Image   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: - News India: For latest news in Hindi and English every few Hours : t.me/newsindiachannel - The Python Django (group): Discussions about Django : t.me/thepythondjango - Government Jobs Bulletin: Latest Government Jobs in India: t.me/govtjb   Feel free to comment in case of any issue.
how to tips   0   3

0 thoughts on 'How To Create Completely Automated Telegram Channel With Python'
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: