<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sourav Adhikari on Medium]]></title>
        <description><![CDATA[Stories by Sourav Adhikari on Medium]]></description>
        <link>https://medium.com/@sourav90.adhikari?source=rss-6e608a17bf20------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*gt69aty1W7XFEMqssuZ2GQ.png</url>
            <title>Stories by Sourav Adhikari on Medium</title>
            <link>https://medium.com/@sourav90.adhikari?source=rss-6e608a17bf20------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:44:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sourav90.adhikari/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Plotting Google Sheets data in Python with Folium]]></title>
            <link>https://medium.com/data-science/plotting-crowdsourced-data-with-google-sheets-and-folium-6c9edbef2bb8?source=rss-6e608a17bf20------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c9edbef2bb8</guid>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[web-mapping]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[folium]]></category>
            <dc:creator><![CDATA[Sourav Adhikari]]></dc:creator>
            <pubDate>Sat, 18 Apr 2020 00:00:00 GMT</pubDate>
            <atom:updated>2020-04-23T13:07:44.639Z</atom:updated>
            <content:encoded><![CDATA[<h4>Real-time plotting of Google sheet data on a web app with Flask</h4><p>In this code through we will try to emulate the workflow where volunteers across the world will be reporting earthquakes through a Google Sheet, and the data will be updated real-time on a web map.</p><p>The web platform will be created using the <strong><em>Flask </em></strong>web framework for <strong>Python</strong> and the data will be plotted using the excellent <strong><em>Folium</em></strong> library, which is a python wrapper for <strong>Leaflet JS.</strong> The data will be retrieved from a Google sheet using the <strong><em>gspread</em></strong><em> </em>library which is a python wrapper for <strong>Google sheets API.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ihWPszfK7q_auRVFV7AiQ.png" /><figcaption>World map of earthquakes, 1900–2017 (Source: Wikimedia Commons)</figcaption></figure><p>This code through should work fine with Linux and macOS systems. For users with Windows systems, only the commands being run in the terminal needs to be modified.</p><h3>Setting up the virtual environment and installing necessary packages</h3><ul><li>Create a project folder : mkdir flask_webmap</li><li>cd into the folder and set up a virtual environment</li><li>We will be using the virtualenv as our choice of virtual environment tool. Create an environment named venv by running virtualenv venv inside your project directory</li><li>Activate the environment by running source venv/bin/activate</li><li>Install the required modules by running python -m pip install -U Flask folium gspread</li></ul><h3>Registering our app with Google to use the Google Sheets API</h3><p>To access data from Google sheets we need to register our app with the Google Sheets API. To do so follow these steps</p><ul><li>Open this <a href="https://console.developers.google.com/">Google console link </a>from a web browser</li><li>In the Google console dashboard, click on New Project link found at the top bar</li><li>Give your project a name and click on Create</li><li>Click on the <strong>Enable APIs and services</strong></li><li>From the new page that opens listing the various APIs available, select the Google Sheets API and enable it</li><li>Once the API is enabled click on the <strong>Create credentials</strong> alert that appears</li><li>Fill in the necessary details: Select <strong>Web server</strong> for the question <strong>Where will you be calling the API from?</strong></li><li>In the next section enter any name for the <strong>Service account</strong>. The role option could be left blank but select <strong>JSON</strong> as your key type and click on continue</li><li>A new JSON file with your credentials will get downloaded</li><li>Copy the JSON file to your project directory</li></ul><h3>Setting up a minimal Flask app</h3><ul><li>Create a new Python file by running touch app.py</li><li>Open the python file in your editor of choice and create a minimal Flask app</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d3b15eb361921e9773767a464260e3a/href">https://medium.com/media/2d3b15eb361921e9773767a464260e3a/href</a></iframe><ul><li>In your terminal export the Flask app environment variable by running export FLASK_APP=app</li><li>The default environment set to production. Change this to development by running FLASK_ENV=development flask run</li><li>Run flask run to start the app</li><li>The new app should now be available at <em>localhost:5000/</em></li><li>The page should print the “Hello World” message</li></ul><h3>Creating a Google sheet with seed data</h3><ul><li>Create a new google sheet</li><li>For the purpose of this exercise, a subset of the earthquake location data by USGS was saved in a sheet. To view the original data visit this <a href="https://www.kaggle.com/usgs/earthquake-database#database.csv">link</a>. To download the google sheet click on this <a href="https://docs.google.com/spreadsheets/d/1x2bVUzH5cnzcDJXnleGteT5zCEytczDAghcRe0Z9WuU/edit?usp=sharing">link</a></li></ul><h3>Accessing the Google sheet data</h3><p>To access this data using the <em>gspread</em> library</p><ul><li>Create a new python file: touch read_sheet.py</li><li>And copy the following code</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f18e665de7a04608c2061ba3a0af423/href">https://medium.com/media/6f18e665de7a04608c2061ba3a0af423/href</a></iframe><h4>Understanding the code</h4><ol><li>First, we define the globals for authorization. Replace the ‘NAME-OF-JSON-FILE-WITH-CREDENTIALS’ with the name of the JSON file downloaded Google API console.</li><li>Then we open the google sheet in which the data is stored using its URL</li><li>Next, we get the specific worksheet in which the data is stored using its index location. The first sheet is indexed ‘0’</li><li>Lastly, we define a new function which gets all the records from that specific worksheet and returns it</li></ol><h3>Testing the Google Sheet access</h3><ul><li>Re-open the <em>app.py </em>and replace the code with the following code</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5e165789e94d405e3eb72e491466751/href">https://medium.com/media/c5e165789e94d405e3eb72e491466751/href</a></iframe><ul><li>flask run from your terminal</li><li><em>localhost:5000</em> should now return a JSON representation of the data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/0*7blQovk4Dzb0McFa.png" /></figure><h3>Plotting the map</h3><p>Now that we have verified the access to the Google Sheets data, let us plot the data on a map.</p><ul><li>touch plot_map.py from your terminal</li><li>Open the <em>plot_map.py</em> file and copy the following code</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c4bb74d8205e6e65d83eb78f3248d98/href">https://medium.com/media/1c4bb74d8205e6e65d83eb78f3248d98/href</a></iframe><h4>Understanding the code</h4><ol><li>First, we define the basemap_layer function which plots a basic map using the folium.Map(). The map is set to use all default values except for the <strong>min_zoom</strong> attribute which is set to 2</li><li>Next, we define a function to plot the earthquake locations using the folium.Marker(), and add it to the parent map generated in the previous step</li></ol><h3>Rendering the map from the Flask app</h3><p>Open the app.py file and copy the following code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/485849ddccc3630e1b4e29cff9aeb634/href">https://medium.com/media/485849ddccc3630e1b4e29cff9aeb634/href</a></iframe><h4>Understanding the code</h4><ol><li>From the previously created <em>plot_map.py</em> file we import the <strong>basemap_layer</strong> and <strong>earthquake_plot</strong> functions</li><li>Inside the flask app view first, we create the map by calling the basemap_layer() function</li><li>To the map generated in step 2, we add the location of the earthquake generated by calling the earthquake_plot() function. The map from step 2 and earthquakes data is supplied as arguments</li><li>The map is saved as <em>map.html</em> in the <em>templates</em> folder</li><li>Lastly, we return the <em>index.html</em></li></ol><h3>Creating the index.html file</h3><ul><li>mkdir templates and touch templates/index.html</li><li>Open the <em>index.html</em> and copy the following code</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d5bd7e9698cd5bf445961b6311a1cc8/href">https://medium.com/media/9d5bd7e9698cd5bf445961b6311a1cc8/href</a></iframe><h4>Understanding the code</h4><ol><li>We create the <em>index.html</em> file within the <em>templates</em> folder</li><li>In the body of the HTML boilerplate, we include the <em>map.html</em> generated from the flask view using the Jinja templating engine</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TQfK5nx_EOJhMNqn.png" /><figcaption>The map view generated by the Flask app</figcaption></figure><h3>How does this map help in plotting crowdsourced data?</h3><p>The interesting aspect of this application is, that since the mapping function is called from within the Flask view, API call to the data is made every time the web map is refreshed in the browser. Thus any new record added to the Google sheet is rendered <strong>real-time </strong>by the application on page refresh.</p><p>So let’s try out this functionality. We all know about the 2015 Nepal earthquake. Let’s update the data in the sheet.</p><p>To find Nepal’s coordinates visit <a href="http://www.latlong.net/">latlong.net</a> and type Nepal in the search box. Copy the Latitude and Longitude values to the Google sheet.</p><p><a href="https://en.wikipedia.org/wiki/April_2015_Nepal_earthquake">Wikipedia</a> also suggests that the Magnitude of the earthquake was 7.8. So, populate the <strong>Magnitude</strong> column with this value.</p><p>Now return to the map view and refresh the page. You will find that a marker for the new location has been added to the map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xJ7JM6dMbslkwHDI.png" /><figcaption>The refreshed map view after adding the new data</figcaption></figure><p>That will be it for this code through. If you find this post to be handy please show your appreciation by leaving a clap or a comment.</p><p><em>Originally published at </em><a href="https://www.sourav90.in/2020/04/18/plotting-crowdsourced-data-with-google-sheets-and-folium.html"><em>https://www.sourav90.in</em></a><em> on April 18, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c9edbef2bb8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/plotting-crowdsourced-data-with-google-sheets-and-folium-6c9edbef2bb8">Plotting Google Sheets data in Python with Folium</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a contextual chatbot in Telegram with Python, Github & Heroku — part 2]]></title>
            <link>https://medium.com/analytics-vidhya/designing-a-contextual-chatbot-in-telegram-with-python-github-heroku-part-2-8e444c8a8386?source=rss-6e608a17bf20------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e444c8a8386</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[heroku]]></category>
            <dc:creator><![CDATA[Sourav Adhikari]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 11:18:00 GMT</pubDate>
            <atom:updated>2020-04-13T16:18:24.348Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing a contextual chatbot in Telegram with Python, Github &amp; Heroku — part 2</h3><p>In the <a href="https://medium.com/@sourav90.adhikari/designing-a-contextual-chatbot-in-telegram-with-python-github-heroku-part-1-39e24e7c7723">last part</a>, we figured out how to set up the coding environment and wrote the Python script that actually runs the bot logic. In this part, we will create a new app in Heroku, set up a webhook in the Python script and push the local git repository to remote git that we had set up. Finally, we will set up our Heroku app to directly access the Github repository and deploy the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*ApUS9pOCktYiM4qnXGDLQg.jpeg" /><figcaption>The bot in action</figcaption></figure><h3>Creating a new app in Heroku</h3><p>Heroku is a cloud application platform that operates as a PaaS (Platform as a Service). It enables developers to build, run and operate applications entirely in the cloud. If you do not have a free Heroku developer account, you can create one by following this <a href="https://signup.heroku.com/">link</a>.</p><p>Log in to your Heroku account and your app dashboard will be presented to you. The app dashboard showcases all your apps and lets you manage them. To create a new app click on ‘New’ on the top right corner and select ‘Create new app’ from the dropdown</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y0ThCD6-cMUA2R15XfqxfA.png" /></figure><p>In the next step, enter a name for the app and click ‘Create app’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9UoX8mbshQnPUbnR9oaJw.png" /></figure><p>Once the app is successfully created, you will be taken to the app management screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWBl2_JAzKr8E3Ty-FOpWw.png" /></figure><p>This page allows you to deploy your app, view logs etc. among other operations. We will return to this page later on.</p><h3><strong>Setting up webhook</strong></h3><p>A webhook is an HTTP push API, which is used to deliver data to other applications in real-time. This is an improvement over typical HTTP push APIs since there is no need for frequent pushing to emulate the real-time feel. The Telegram bot API provides inbuilt methods to set up a webhook.</p><p>To set up the webhook open the python script where you have been writing the bot logic and append the following code in the main function only. The rest of the file remains as it is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/096d508baf5b2605328e38c222c83701/href">https://medium.com/media/096d508baf5b2605328e38c222c83701/href</a></iframe><h4>Explaining the appended code</h4><p>Line 6: Set the name of the app that you created in Heroku in the last section to the APPNAME variable</p><p>Line 27–30: Start a webhook by calling the updater.start_webhook() method and set the arguments to the values as shown in the example</p><p>Line 31: Set the webhook by calling the updater.set.Webhook() method and pass the URL of the Heroku app as shown in the example</p><p>Line 36: Comment out the updater.start_polling() method. This is no longer required since webhook has been set</p><p>Line 39: Comment out the updater.idle() method as well.</p><h3>Pushing the code to Github repository</h3><p>We are now ready to push our code to the Github repo. But first three additional files need to be created</p><ul><li>requirements.txt : This file lists all the python packages that will be installed by Heroku in its environment. We have been already working within a virtual environment, and to create this file just type the following command from the terminal</li></ul><pre>pip freeze &gt; requirements.txt</pre><ul><li>Procfile : All Heroku apps include a Procfile. The Procfile specifies the commands that are to be executed by the app on start up. It typically follows this format :</li></ul><pre>&lt;process type&gt;: &lt;command&gt;</pre><p>Create the Procfile by running touch Procfile</p><p>Open this Procfile in your editor and add web: python telegram_bot.py</p><ul><li>.gitignore: This file maintains a list of all the files that do not need to be pushed to the Github repo. Typically this will contain all local environment files. Since we have been using a virtualenv named venv our file should list</li></ul><pre>venv/<br>.venv<br>venv.bak</pre><p>Once these three files have been created, issued these commands from your terminal</p><pre>git add .<br>git commit -m &quot;first commit&quot;<br>git push -u origin master</pre><p>All the files in your local git repo will be now available in your remote Github repository.</p><h3>Deploying the app on Heroku</h3><p>Now return to your Heroku app page. Under the ‘<strong>Deploy</strong>’ tab, three deployment methods will be listed. We will select the <strong>Github method</strong>.</p><p>Give the necessary permissions to Heroku to access your Github profile. Once the authorization has been set up, search for the name of your repository from the search bar and click on ‘<strong>Connect</strong>’.</p><p>Once the repository has been connected to the Heroku app, click on ‘<strong>Deploy branch</strong>’ under the ‘<strong>Manual deploy</strong>’ section, pointing to the ‘<strong>main</strong>’ branch. The app will now build itself and if all the steps are followed correctly, your bot will be hosted.</p><p><strong>Please note</strong> that visiting your app URL will return a ‘<strong>404: page not found</strong>’ error but that is alright since the script does not necessarily return anything. If problems are encountered while starting the app, visiting the URL will display the error message.</p><p>So, that’s it for this tutorial. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e444c8a8386" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/designing-a-contextual-chatbot-in-telegram-with-python-github-heroku-part-2-8e444c8a8386">Designing a contextual chatbot in Telegram with Python, Github &amp; Heroku — part 2</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a contextual chatbot in Telegram with Python, Github & Heroku — part 1]]></title>
            <link>https://medium.com/analytics-vidhya/designing-a-contextual-chatbot-in-telegram-with-python-github-heroku-part-1-39e24e7c7723?source=rss-6e608a17bf20------2</link>
            <guid isPermaLink="false">https://medium.com/p/39e24e7c7723</guid>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Sourav Adhikari]]></dc:creator>
            <pubDate>Fri, 10 Apr 2020 15:11:17 GMT</pubDate>
            <atom:updated>2020-04-18T17:32:19.207Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing a contextual chatbot in Telegram with Python, Github &amp; Heroku — part 1</h3><p>Telegram bots are third-party applications that run inside the application. Users can interact with bots by sending them messages, commands and inline requests. Contextual chatbots are a category bots that communicate only through inline requests. They are contextual since they maintain a context and the users can only navigate the pre-defined context. These are especially useful in providing customer service. In this post, we will look at how to design such bots in Telegram using Python.</p><p>This will consist of two parts. In the first part, we will register our bot with Telegram, set up our local coding environment and write the code for the bot. In the second part, we will discuss how to host the bot on Heroku which is cloud-based service useful for hosting small web-based applications.</p><h3>Registering a new bot with Telegram</h3><p>To register a new bot go to the Telegram app on your phone and follow these steps:<br>1. In the search bar search for the “BotFather”. “BotFather” is a bot that will assist you in creating and managing all your bots<br>2. Start BotFather and type /help. This brings up all the possible commands that this bot can handle<br>3. Type /newbot or click on this command from this list<br>4. Follow the instructions for setting up a new bot which is basically choosing a name and username for your bot. [Tip: Pick a username which is relevant to what your bot can do]<br>5. Once the bot is successfully created the BotFather will return a token to access HTTP API. Save this token securely with you. We will be using this token to authorize our bot from within the python script</p><h3>Setting up a new Python virtual environment</h3><p>It is good practice to create virtual environments for python projects. A virtual environment helps to keep dependencies required by different projects separate. A virtual environment also helps to easily create a <em>requirements.txt </em>file, which is used by Heroku to create its python environment in the cloud.</p><p>While there are few choices for virtual environment tools, we will be using virtualenv for our project. Follow these steps to create a Python virtual environment using virtualenv</p><ul><li>open your terminal in macOS or Linux and create a new project directory</li></ul><pre>mkdir telegram-bot &amp;&amp; cd telegram-bot</pre><ul><li>check that virtualenv is installed in your system. If virtualenv is installed this command will return the installation path else it won’t return anything. If it is not installed you can install it using the methods mentioned in this <a href="https://virtualenv.pypa.io/en/latest/installation.html">link</a></li></ul><pre>virtualenv --v</pre><ul><li>create a new virtual environment and activate it</li></ul><pre>virtualenv venv<br>source venv/bin/activate</pre><p>While you can use any name for your environment, venv is a convention that is commonly used. Once the environment is active proceed to install the required python packages for the project</p><p>We will be using the <a href="https://github.com/python-telegram-bot/python-telegram-bot"><em>python-telegram-bot</em></a> library for this project. This library provides a pure Python interface for the <a href="https://core.telegram.org/bots/api">Telegram Bot API</a>. To install this library use the following command</p><pre>python -m pip install -U python-telegram-bot</pre><h3>Initialising a Git repository in the project folder</h3><p>A git repository needs to be initialised in the project folder as Heroku uses a local git repository to deploy the code in their cloud service. While typically the Heroku remote is added to the local git repository to push the commit, for this project we will add a remote from Github, and further connect the Github repository to the Heroku app.</p><p>To initialise a local git repository, in your project folder</p><pre>git init</pre><p>Also, create a .gitignore file. The .gitignore file lists the name of those files that should be ignored from all commits. We can update this file later</p><pre>touch .gitignore</pre><p>Now we will be creating a new repository in Github. Visit your Github account and create a new repository. You can either make the repository public or private. We will assume that the name of Github repository you have created is the same as your project folder. Once the repository is created copy its URL.</p><p>Now we need to connect our local repository with our newly created Github repository.</p><pre>git remote add origin URL-to-your-Github-repository</pre><p>Once the connection to the remote repository has been established</p><pre>git pull origin master</pre><p>The local repository is now ready to push commits to the Github repository</p><h3>Writing the Python app</h3><p>Hurray! Now we can finally start writing the Python script for the bot. This bot will have a very simple design. There is this very famous scikit-learn <a href="https://scikit-learn.org/stable/tutorial/machine_learning_map/index.html">machine learning map</a> available which can help data scientists decide on which estimator to try depending on the data. While the original map is extensive for this tutorial we only adapt the classification segment (other segments are clustering, regression and dimensionality reduction).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*wE2cx_F_Q1PGbgmJfASAKg.png" /><figcaption>Flowchart for Classification (<a href="https://scikit-learn.org/stable/tutorial/machine_learning_map/index.html">https://scikit-learn.org/stable/tutorial/machine_learning_map/index.html</a>)</figcaption></figure><p>The script given its size is impossible to host here completely. Please click on this <a href="https://gist.github.com/escapist21/52346423fdeb0b1c49d6ccbb66a9cfe2">link</a> to access the Github gist for this code. Create a new file in your project folder named <em>telegram_bot.py. </em>Open this file in your favourite code editor and paste the code from the file in the Github link.</p><pre>touch telegram_bot.py</pre><h3>Explaining the code</h3><p>Here we will look at parts of the code and try to understand what is happening</p><pre>from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler, ConversationHandler</pre><pre>from telegram import InlineKeyboardButton, InlineKeyboardMarkup<br>import os</pre><p>First, we import the necessary classes from the python-telegram-bot library. The first line imports the various handlers that will be required for this program. You are requested to read up about what these handlers do. The second line imports the modules associated with creating the inline keyboard. Since this is a contextual chatbot, only the inline keyboards will be used to communicate with the bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*ApUS9pOCktYiM4qnXGDLQg.jpeg" /><figcaption>The bot with inline keyboard markup</figcaption></figure><pre>#States<br>FIRST, SECOND = range(2)</pre><pre>#Callback data<br>ONE, TWO, THREE, FOUR, FIVE = range(5)</pre><p>“States” is a list of all conversation steps that will be later used in setting up the <em>ConversationHandler</em>. “Callback data” is a list of callbacks that are returned from the inline keyboard upon pressing on it. The “States” along with the “Callback data” will be returned from various functions that will form our conversation logic. Here we just initialize these variables for later use.</p><pre>def start(update, context):<br>    fname = update.message.from_user.first_name</pre><pre>    # Build inline keyboard<br>    keyboard1 = [InlineKeyboardButton(&quot;&lt;100K samples&quot;,<br>                                      callback_data=str(ONE))]<br>    keyboard2 = [InlineKeyboardButton(&quot;&gt;100K samples&quot;,<br>                                      callback_data=str(TWO))]<br>    <br>    # create reply keyboard markup<br>    reply_markup = InlineKeyboardMarkup([keyboard1, keyboard2])</pre><pre>    # send message with text and appended inline keyboard<br>    update.message.reply_text(<br>        &quot;Welcome {}. Let&#39;s figure out the best possible classifier for you data.\n\nHow many samples do you have?&quot;.format(fname),<br>        reply_markup=reply_markup<br>    )<br>    # tell ConversationHandler that we are in state &#39;FIRST&#39; now<br>    return FIRST<br>.<br>.<br>.</pre><pre>def end(update,context):<br>    &quot;&quot;&quot;Returns &#39;ConversationHandler.END&#39;, which tells the CoversationHandler that the conversation is over&quot;&quot;&quot;<br>    query = update.callback_query<br>    query.answer()<br>    query.edit_message_text(<br>        &quot;Goodbye, and all the best\n\nIf you need my help again click on /start&quot;<br>    )<br>    return ConversationHandler.END</pre><p>the start() function is the first function that is called from within the <em>ConversationHandler</em> that we will define later. It is activated in response to the /start command. Once the <em>ConversationHandler</em> is activated it uses the “State” and “Callback data” variable returned from each function to control the conversation flow.</p><p>Following the start() function are the other functions that are called as part of the conversation each having a unique inline keyboard, appended message text and returning a “State” and “Callback data”. Refer to the script to study these functions.</p><p>These functions are followed by the end() function. The end function is called when the logic flow within the <em>ConversationHandler</em> reaches the end of the conversation. It returns the <em>ConversationHandler.END</em> signal, which effectively terminates the conversation.</p><pre>def main():<br>    #setting to appropriate values<br>    TOKEN = &quot;YOUR ACCESS TOKEN&quot;<br>    # set up updater<br>    updater = Updater(token=TOKEN, use_context=True)<br>    # set up dispatcher<br>    dispatcher = updater.dispatcher<br>    #print a message to terminal to log successful start<br>    print(&quot;Bot started&quot;)</pre><pre>    # Set up ConversationHandler with states FIRST and SECOND<br>    conv_handler = ConversationHandler(<br>        entry_points=[CommandHandler(command=&#39;start&#39;,<br>                                     callback=start)],<br>        states={<br>            FIRST: [CallbackQueryHandler(linear_svc, pattern=&#39;^&#39; + str(ONE) + &#39;$&#39;),<br>                   .<br>                   .<br>                   .<br>                   ],<br>            SECOND: [CallbackQueryHandler(end, pattern=&#39;^&#39; + str(ONE) + &#39;$&#39;),<br>                   .<br>                   .<br>                   .<br>                   ]<br>                },<br>            fallbacks=[CommandHandler(command=&#39;start&#39;,<br>                                      callback=start)]<br>        )</pre><pre>    # add ConversationHandler to dispatcher<br>    dispatcher.add_handler(conv_handler)<br>    <br>    # start the bot<br>    updater.start_polling()</pre><pre>    # run the bot until Ctrl+C is pressed<br>    updater.idle()<br></pre><p>The <em>Updater</em> class continuously fetches new updates from Telegram and passes it to the <em>Dispatcher</em> class. Once the <em>Updater</em> object is created, it is used to create a <em>Dispatcher</em> object and they are then linked together in a queue. Different types of Handlers can be registered with the Dispatcher, which then sorts all the updates received from Telegram according to the registered Handlers. For example, here we add a <em>ConversationHandler</em> to the dispatcher.</p><p>The <em>ConversationHandler</em> manages four collections of other handlers. In this example, three such collections are used namely <em>entry_points</em>, <em>states</em> and <em>fallbacks</em>.</p><p>The <em>entry_point </em>collection is a list used to initiate the conversation. In this example, a <em>CommandHandler</em> class is used which responds to the ‘start’ command.</p><p>The <em>states</em> collection is a dictionary containing the different conversation steps and one or more associated handlers. In this example, all the conversation steps are associated with <em>CallbackQueryHandler </em>since all our updates from the app are in the form of callbacks associated with pressing an inline keyboard button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*QaI0w1j1lMeSs8n1MPF6sQ.jpeg" /></figure><p>The flowchart on the left is used to design the conversation steps as defined in the <em>states</em> collection.</p><p>The <em>fallbacks</em> collection is a list that is used if the user currently in conversation returns an update which is not of the expected type. For example, a text update is sent when the expected update was a command. This prevents the bot from breaking.</p><p>Click on this <a href="https://vimeo.com/405917388">link</a> to watch a video of the bot in action</p><p>Run the python file from the terminal by typing python telegram_bot.py and your bot will spring to life ready to converse with you.</p><p>That will be it for this long post. For the second part of this tutorial click on this <a href="https://medium.com/@sourav90.adhikari/designing-a-contextual-chatbot-in-telegram-with-python-github-heroku-part-2-8e444c8a8386">link</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39e24e7c7723" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/designing-a-contextual-chatbot-in-telegram-with-python-github-heroku-part-1-39e24e7c7723">Designing a contextual chatbot in Telegram with Python, Github &amp; Heroku — part 1</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>