In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "how to use Python to do a Telegram news Bot". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Introduction
Telegram is now a global popular real-time messaging application, which is characterized by security and high efficiency. In addition to sending messages to each other, you can also create bot on it to automatically perform some tasks.
In this tutorial, we will create a Datanews-based news bot using Python and Telegram's bot API.
Brief introduction of Telegram API
We will use the official python-telegram-botApi, which greatly simplifies the work of developing Bot, and through some official examples, it is easy to learn and master, here is an example:
From telegram.ext import Updater, CommandHandlerUSAGE ='/ greet-Greet meteorologists def start (update, context): update.message.reply_text (USAGE) def greet_command (update, context): update.message.reply_text (f'Hello {context.args [0]}!') def main (): updater = Updater ("TOKEN", use_context=True) dp = updater.dispatcher # on different commands-answer in Telegram dp.add_handler (CommandHandler ("start", start)) dp.add_handler (CommandHandler ("greet") Greet_command)) # Start the Bot updater.start_polling () updater.idle () if _ _ name__ = ='_ main__': main ()
This small code snippet creates a bot to identify two commands:
/ start-Bot will respond to the help page according to this command
The / greet- command takes a parameter, such as Datanews, and returns Hello Datanews!
Take a look at the meaning of each line of code:
Main method
Def main (): updater = Updater ("TOKEN", use_context=True) dp = updater.dispatcher dp.add_handler (CommandHandler ("start", start)) dp.add_handler (CommandHandler ("greet", greet_command)) updater.start_polling () updater.idle ()
This method configures some parameters necessary for Bot to work, especially the instance of the Update class. It is important to note that you need a token of Telegram to use the API of Telegram Bot. You can check the official guide to creating Bot here.
Back in the code, the purpose of Updater is to pass updates to Dispatcher, and when the latter receives an update, it handles some callback requests specified by the user, each managed by a program.
When a message is received that meets certain conditions, although these conditions depend on the program, they can also be defined by the developer, and as far as we are concerned, we have two examples of task processing.
Dp.add_handler (CommandHandler ("start", start)) dp.add_handler (CommandHandler ("greet", greet_command))
Each of the above processes a command to support our Bot's / start and / greet
Then we invoke the start_polling command.
Updater.start_polling ()
This command causes our bot to process updates periodically, and this parameter creates two processes internally, one to poll for updates from the Telegram server, and the other to be handled by the scheduler.
The following line ensures that our bot can handle various interrupt signals correctly
Updater.idle
Now let's discuss two callback functions that handle the bot command:
Def start (update, context): update.message.reply_text (USAGE) def greet_command (update, context): update.message.reply_text (f'Hello {context.args [0]}!')
Each of the above methods requires two parameters:
Update received an update from the Telegram server
Context contains some useful parameters and information. For example, it has a user_data dictionary for storing user-related information.
In addition, each parameter returns a message to the user.
Datanews API introduction
Datanews is an API, news aggregator and other website used to retrieve and monitor news from thousands of news sources. It collects and processes hundreds of thousands of news data every day, and of course, it also provides flexible and easy to use API to retrieve these news articles.
For our small project, we only need a small portion of API, especially what we want bot to do:
Return the news content according to the keywords entered by the user
Return news content based on a specific news source
These use case requirements can be handled with an entry-/ headlines, and you can learn more about APIofficial documentation in the link below.
Program implementation
First, we will define a callback function that handles the / start command
Def get_usage (): return''This bot allows you to query news articles from Datanews API.Available commands:/help, / start-show this help message./search-retrieve news articles containing. Example: "/ search covid" / publisher-retrieve newest articles by publisher. Example: "/ publisher techcrunch.com"' 'def help_command (update, context): update.message.reply_markdown (get_usage ())
As you can see, this implementation is very similar to the one we demonstrated above. We simply return a help message to the user. You can notice that our bot supports four commands. Let's discuss the other two:
Def search_command (update, context): def fetcher (query): return datanews.headlines (query, size=10, sortBy='date', page=0, language='en') _ fetch_data (update, context, fetcher) def publisher_command (update, context): def fetcher (query): return datanews.headlines (source=query, size=10, sortBy='date', page=0, language='en') _ fetch_data (update, context, fetcher)
These methods all look very simple, they all use the / headlinesAPI we discussed earlier, the only difference is the parameter we passed to Datanews API: search_command retrieves articles that match a particular query, while Publisher_command extracts all articles published from a particular source, of which we only survive 10 recent articles.
Def _ fetch_data (update, context, fetcher): if not context.args: help_command (update Context) return query ='"+''.join (context.args) +'" result = fetcher (query) if not result ['hits']: update.message.reply_text (' No news is good news') return last_message = update.message for article in reversed (result ['hits']): text = article [' title'] +':'+ article ['url'] last_message = last_message.reply_text (text)
This method simply checks the specific parameters entered by the user, takes the data from the Datanews API and sorts it back to the user.
We make sure that we use "surround the query" so that Datanews returns all articles that contain the full query, not just one word.
We also need to make sure that we deal with situations where articles cannot be queried, in which case it is bullshit that bot does not respond.
The content we send to the user must ensure that the last item of the sorted content is the latest content.
With these features, let's take a look at the main program:
Def main (): updater = Updater (token='TOKEN') updater.dispatcher.add_handler (CommandHandler ('start', help_command)) updater.dispatcher.add_handler (CommandHandler (' help', help_command)) updater.dispatcher.add_handler (CommandHandler ('search', search_command)) updater.dispatcher.add_handler (CommandHandler (' publisher', publisher_command)) updater.dispatcher.add_handler (MessageHandler (Filters.text & Filters.regex (pattern=re.compile ('help')) Re.IGNORECASE), help_command)) updater.start_polling () updater.idle ()
This program looks very similar to the previous example, except for the following major differences:
Updater.dispatcher.add_handler (MessageHandler (Filters.text & Filters.regex (pattern=re.compile ('help', re.IGNORECASE)), help_command))
MessageHandler is used to get user input, you can think of it as a similar function of CommandHandler, it can handle any message that meets the specified filter, in our six types, we want to return the help information to the user when the user input information contains help.
Therefore, we have a fully programmed news robot.
This is the end of the content of "how to use Python to make a Telegram News Bot". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.