© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
S. BhatPractical Docker with Pythonhttps://doi.org/10.1007/978-1-4842-7815-4_3

3. Building the Python App

Sathyajith Bhat1  
(1)
Bangalore, Karnataka, India
 

For many people getting into programming, one of their first issues is figuring out what they can build. Programming is seldom learned by just reading. Many people think they can read couple of guides and look at the syntax and then easily learn how to program. But programming takes hands-on practice.

For this reason, this book includes a sample Python project. The project is not very complicated at the start, but it’s easy to continue working further on the project, extending and customizing it as you gain experience.

About the Project

Note

This book assumes you have basic knowledge of Python and have Python 3.6 or above installed.

To help you get acquainted with Docker, the book teaches you how to take an existing Python app, run it from the Python command line, introduce different Docker components, and then transition the app into a containerized image.

The Python app is a simple application with a bot interface using Telegram Messenger to fetch the last 10 stories from Reddit. Using Telegram, you can subscribe to a list of subreddits. The web application will check the subscribed subreddits for new posts and, if it finds new topics, it will publish the topics to the bot interface. That interface will deliver the message to Telegram Messenger, when requested by the user.

Initially, you will not be saving the preferences (i.e., the subreddit subscriptions) and will focus on getting the bot up and running. Once things are working fine, you will learn how to save the preferences to a text file and, eventually, to a database.

Setting Up Telegram Messenger

Before you can proceed, you need a Telegram Messenger account. To sign up, go to https://telegram.org, download the application for the platform of your choice, and install it. Once it’s running, you will be asked to provide a cell phone number. Telegram uses this to validate your account. Enter your cell phone number, as shown in Figure 3-1.
../images/463857_2_En_3_Chapter/463857_2_En_3_Fig1_HTML.png
Figure 3-1

Telegram signup page

Once you enter your number, you should get a one-time password to log in. Enter the one-time password and sign in, as shown in Figure 3-2.
../images/463857_2_En_3_Chapter/463857_2_En_3_Fig2_HTML.png
Figure 3-2

Telegram’s one-time password

BotFather: Telegram’s Bot Creation Interface

Telegram uses a bot called “BotFather” as its interface for creating new bots and updating them. To get started with BotFather, in the search panel type BotFather. From the chat window, type /start.

This will trigger BotFather to provide an introductory set of messages, as shown in Figure 3-3.
../images/463857_2_En_3_Chapter/463857_2_En_3_Fig3_HTML.png
Figure 3-3

BotFather’s options

Creating the Bot with BotFather

You will be using BotFather to generate a new bot. Start by typing /newbot in Telegram Messenger. This will trigger a series of questions that you need to answer (most of them are straightforward). Due to Telegram’s restrictions, the username for a bot must always end with bot. This means that you might not get your desired username (see Figure 3-4).
../images/463857_2_En_3_Chapter/463857_2_En_3_Fig4_HTML.png
Figure 3-4

Telegram bot ready for action

Along with the link to the documentation, you will notice that Telegram has issued a token. HTTP is a stateless protocol—the webserver does not know and does not keep track of who is requesting the resource. The client needs to identify itself so that the webserver can identify the client, authorize it, and serve the request. Telegram uses the API token (henceforth, referred to as <token>, including in the code samples) as a way of identifying and authorizing bots.

Caution

The token is extremely sensitive. If it’s leaked online, anyone can post messages as your bot. Do not check it in with your version control or publish it anywhere!

When working with APIs you are not familiar with, it’s always good to use a good tool to test and explore the endpoints instead of typing the code right away. Some examples of REST API test tools include Insomnia, Postman, and curl.

Telegram’s Bot API documentation is available at https://core.telegram.org/bots/api. To make a request, you have to include the <token>. The general URL is as follows:

https://api.telegram.org/bot<token>/METHOD_NAME

Let’s try a sample API request that confirms the token is working as expected. Telegram Bot API provides a /getMe endpoint for testing the auth token. You can try it, first without the token, as shown in Listing 3-1.
curl https://api.telegram.org/bot/getMe
{
  "ok": false,
  "error_code": 404,
  "description": "Not Found"
}
Listing 3-1

Making a curl Request to Telegram API Without a Token

Without the bot token, Telegram doesn’t honor the request. Now try the token, as shown in Listing 3-2.
curl https://api.telegram.org/bot<token>/getMe
{
  "ok": true,
  "result": {
    "id": 495637361,
    "is_bot": true,
    "first_name": "SubRedditFetcherBot",
    "username": "SubRedditFetcher_Bot"
  }
}
Listing 3-2

Making a curl Request to Telegram API with a Valid Token

You can see that, with the proper token, Telegram identifies and authorizes the bot. This confirms that the bot token is proper, and you can go ahead with the app.

Newsbot: The Python App

Newsbot is a Python script that interacts with the bot with the help of the Telegram Bot API. Newsbot does the following things:
  • Continuously polls the Telegram API for new updates being posted to the bot.

  • If the keyword for fetching new updates was detected, it fetches the news from the selected subreddits.

Behind the scenes, Newsbot handles these scenarios:
  • If there’s a new message starting with /start or /help, it shows simple help text about what to do.

  • If there’s a message starting with /sources followed by a list of subreddits, it accepts them as the subreddits from the applicable Reddit posts.

Newsbot depends on a couple of Python libraries;
  • Praw or Python Reddit API Wrapper, for fetching posts from subreddits.

  • Requests, one of the most popular Python libraries for providing a simpler, cleaner API for making HTTP requests.

Getting Started with Newsbot

To get started with Newsbot, download the source code of the bot. The source code is available on the GitHub repository of the book, at https://github.com/Apress/practical-docker-with-python.

If you’re familiar with Git, you can clone the repo using the following command:
git clone https://github.com/Apress/practical-docker-with-python.git
As an alternative, you can click the green Code button and choose Download ZIP from the GitHub repository page to get the source code. Once you have cloned the repo or extracted the ZIP, change to the directory containing the source code by typing the following command:
cd practical-docker-with-python/source-code/chapter-3/python-app
Now install the dependencies. To do this, type the following:
pip3 install -r requirements.txt

pip (Pip Installs Packages) is a package manager that installs Python libraries. pip is included with Python 2.7.9 and later, and Python 3.4 and later. pip3 indicates that you are installing libraries for Python 3. If pip is not installed, install it before proceeding.

The -r flag tells pip to install the required packages from requirements.txt.

pip will check, download, and install the dependencies. If all goes well, you should see the output in Listing 3-3.
Collecting praw==3.6.0 (from -r requirements.txt (line 1))
  Downloading praw-3.6.0-py2.py3-none-any.whl (74kB)
Collecting requests==2.18.4 (from -r requirements.txt (line 2))
[...]
Installing collected packages: requests, update-checker, decorator, six, praw
Successfully installed decorator-4.0.11 praw-3.6.0 requests-2.18.4 six-1.10.0 update-checker-0.16
Listing 3-3

The Output from a Successful pip Install

If some packages were already installed, pip will not reinstall them and will inform you that the dependency is installed with a "Requirement already satisfied" message.

Running Newsbot

Let’s start the bot. The bot requires an authentication token from Telegram that you created previously (referred to as <token>). This needs to be set to an environment variable named as NBT_ACCESS_TOKEN . Without this token, the bot will not run. To set this token, open a terminal and enter the following command, depending on your platform.

Windows users:
setx NBT_ACCESS_TOKEN <token>
Linux and macOS users:
export NBT_ACCESS_TOKEN=<token>
Now, start the Python script by typing the following command:
python newsbot.py
If all’s well, you should be seeing periodic OK messages, as shown in Listing 3-4. This means that Newsbot is running and is actively listening for updates.
python newsbot.py
INFO: get_updates - received response: {'ok': True, 'result': []}
INFO: get_updates - received response: {'ok': True, 'result': []}
INFO: get_updates - received response: {'ok': True, 'result': []}
INFO: get_updates - received response: {'ok': True, 'result': []}
INFO: get_updates - received response: {'ok': True, 'result': []}
INFO: get_updates - received response: {'ok': True, 'result': []}
Listing 3-4

Output from Newsbot When It Is Running and Listening to Messages from Telegram

Sending Messages to Newsbot

In this section, you try to send a message to Newsbot to see if it accepts requests. From the BotFather window, click the link to the bot (alternatively, you can also search using the bot username). Click the Start button. This will trigger a /start command, which will be intercepted by the bot.

Notice that the log window shows the incoming request and the outgoing message being sent, as indicated in Listing 3-5.
INFO: get_updates - received response: {'ok': True, 'result': []}
INFO: get_updates - received response: {'ok': True, 'result': []}
INFO: get_updates - received response: {'ok': True, 'result': []}
INFO: get_updates - received response: {'ok': True, 'result': [{'update_id': 720594461, 'message': {'message_id': 5, 'from': {'id': 7342383, 'is_bot': False, 'first_name': 'Sathya', 'last_name': 'Bhat', 'username': 'sathyabhat', 'language_code': 'en-US'}, 'chat': {'id': 7342383, 'first_name': 'Sathya', 'last_name': 'Bhat', 'username': 'sathyabhat', 'type': 'private'}, 'date': 1516558659, 'text': '/start', 'entities': [{'offset': 0, 'length': 6, 'type': 'bot_command'}]}}]}
INFO: handle_incoming_messages - Chat text received: /start
INFO: post_message - posting
                    Hi! This is a News Bot which fetches news from subreddits. Use "/source" to select a subreddit source.
 Example "/source programming, games" fetches news from r/programming, r/games.
 Use "/fetch" for the bot to go ahead and fetch the news. At the moment, bot will fetch total of 10 posts from all subreddits
                 to 7342383
INFO: get_updates - received response: {'ok': True, 'result': []}
Listing 3-5

The Newsbot Responding to Commands

Figure 3-5 shows the Telegram Messenger window.
../images/463857_2_En_3_Chapter/463857_2_En_3_Fig5_HTML.png
Figure 3-5

The response from Newsbot to the start message

Try setting a source subreddit. From the Telegram Messenger window, type the following:
/source python
You should get a positive acknowledgement from the bot, saying the source was selected (see Figure 3-6).
../images/463857_2_En_3_Chapter/463857_2_En_3_Fig6_HTML.jpg
Figure 3-6

Sources assigned

Now you can tell the bot to fetch some news. To do this, type:
/fetch
The bot should send an acknowledgement message about fetching the posts. Then it will publish the posts from Reddit (see Figure 3-7).
../images/463857_2_En_3_Chapter/463857_2_En_3_Fig7_HTML.png
Figure 3-7

Newsbot posting the top news from the Python subreddit

The bot works; it’s fetching the top posts as expected. In the next series of chapters, you learn how to move Newsbot to Docker.

Summary

In this chapter, you learned about the details of the book’s Python Project, which is a chatbot. You also learned how to install and configure Telegram Messenger, how to use Telegram’s BotFather to create the bot, how to install the dependencies for the bot and, finally, how to run the bot and ensure that it works correctly. In the next chapter, you dive deep into Docker, learn more about Dockerfiles, and containerize the Newsbot app by writing a Dockerfile for it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.150.163