<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ telegram - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ telegram - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 26 Jun 2026 22:48:07 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/telegram/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to set up push notifications in your Telegram bot ]]>
                </title>
                <description>
                    <![CDATA[ By Nikita Kholin Telegram is a great platform with lots of great users (I’m a Telegram user myself). And what would be the best way for Telegram users to receive notifications? We can’t know for sure. Maybe they like email or something else. But we c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/telegram-push-notifications-58477e71b2c2/</link>
                <guid isPermaLink="false">66c3605839357f944697662f</guid>
                
                    <category>
                        <![CDATA[ bots ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ telegram ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 12 Feb 2019 22:36:36 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*mN13Q59wDCwvUWCF" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Nikita Kholin</p>
<p>Telegram is a great platform with lots of great users (I’m a Telegram user myself). And what would be the best way for Telegram users to receive notifications? We can’t know for sure. Maybe they like email or something else. But we can guess that sending notifications to Telegram would be pretty convenient.</p>
<p>If you would like to send Telegram notifications from your application, you’ve come to the right place. I’ve added this feature to <a target="_blank" href="https://musicnotifier.com/">my application</a> and I love it.</p>
<p>One quick note. In this article I provide examples of code in Python. But the ideas are not Python-specific and can be translated into another language without any hastle.</p>
<p>So without further ado, let’s dive into how we can do it.</p>
<h3 id="heading-create-a-telegram-bot">Create a Telegram bot</h3>
<p>First of all, you need to create a Telegram bot. To do this you need to use another Telegram bot, <a target="_blank" href="https://telegram.me/botfather">BotFather</a>. Just talk to him (press start).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/K0IHhahp6VR-IJDs8ohcZRxBBlUMaRWuUt4g" alt="Image" width="494" height="675" loading="lazy"></p>
<p>Now you see what it can do. But what interests us is creating a new bot, so that’s what we’re going to choose (<code>/newbot</code>).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/4TCF43Y1rArQcRQb-5F6XblOvTEMXUwWazrd" alt="Image" width="494" height="256" loading="lazy"></p>
<p>You’re quickly going to find out that bot’s name should end with “bot”. And since you’re like me and coming to the game too late, most bot names are already taken.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/yRoEugA8JJ1ccppRU8g3kcy40mGsJqCalzRG" alt="Image" width="494" height="717" loading="lazy"></p>
<p>But eventually, you’re going to find a name for your bot and get an access token we’re going to need.</p>
<p>Now that you have a bot, Telegram users can find and use it. But there is one problem — you can’t associate users that come from Telegram to the users in your application. Let me show you why.</p>
<p>Once a user presses the “Start” button on your bot, you will receive an “update”. You can check all bot’s updates even in your browser by visiting the following URL <code>https://api.telegram.org/bot{bot_token}/getUpdates</code> (don’t forget to use your access token in the URL). Here’s what I got:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/AydGLffhxTaXFcqwj3untIxDVGf-AyGE26pc" alt="Image" width="800" height="43" loading="lazy"></p>
<p>Can’t read anything? Don’t worry. You can fix it by installing some JSON prettifier extension in your browser. I use <a target="_blank" href="https://chrome.google.com/webstore/detail/json-formatter/mhimpmpmffogbmmkmajibklelopddmjf">JSON Formatter</a> for Chrome. It looks so much better.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/iG2V6vR4rqS8Lmw-Cxg5FisuCHU9XAFEquzc" alt="Image" width="800" height="1010" loading="lazy"></p>
<p>So as you can see we don’t get that much information about the person. From this information, we can get their full name. But it would be lucky if the user would provide their full name in your application, and doesn’t guarantee uniqueness of it. So we can’t use that to find a user in your applications.</p>
<p>Another piece of information we get is the username. That is more useful as it is unique between all Telegram users. But most likely you don’t have that available in your applications. So we would need to ask a user to enter their username somewhere in the application. It’s just too much work that I’m not sure anyone would do.</p>
<p>Another option to associate a user would be to ask them to provide the email that they used in your application to the bot. But this has too many flaws: the user can make a typo while entering the email, the user can enter the email of another user and exploit the system. This is just too bad.</p>
<p>Can we do better?</p>
<h3 id="heading-associating-a-user">Associating a user</h3>
<p>Of course we can. To associate the user, we’ll use a technique called <a target="_blank" href="https://core.telegram.org/bots#deep-linking">deep linking</a>.</p>
<p>First, you need to create a random unique token for each user. I’ve used the following code to generate the token using Python:</p>
<pre><code><span class="hljs-keyword">from</span> secrets <span class="hljs-keyword">import</span> token_urlsafetoken = token_urlsafe(<span class="hljs-number">8</span>)token# =&gt; <span class="hljs-string">'uEDbtJFHxKc'</span>
</code></pre><p>Then you need to save that token to be able to find a user with it later. You can save it to your database or use some other place like a cache for example. I have a <code>Notification</code> model so I added a field to a model’s table.</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Notification</span>(<span class="hljs-title">models</span>.<span class="hljs-title">Model</span>):    <span class="hljs-title">user</span> </span>= models.ForeignKey(User, on_delete=models.CASCADE)    # ...    connect_token = models.CharField(max_length=<span class="hljs-number">64</span>, <span class="hljs-literal">null</span>=True)
</code></pre><p>So we’ve generated <code>uEDbtJFHxKc</code> token and saved it. Now we need to use this token in a URL to the telegram bot which the user needs to click to make it all work:</p>
<pre><code>telegram_url = <span class="hljs-string">'https://www.telegram.me'</span>bot_name = <span class="hljs-string">'music_notification_bot'</span>token = <span class="hljs-string">'uEDbtJFHxKc'</span>url = f<span class="hljs-string">'{telegram_url}/{bot_name}?start={token}'</span>
</code></pre><p>Now that we have our URL, <code>'https://telegram.me/music_notification_bot?start=uEDbtJFHxKc'</code>, it’s time to show it to the user. Just display it in any place of your application and wait for the user to click on it.</p>
<p>Once the user takes the bait and clicks “Start” you should receive another update:</p>
<pre><code>{    <span class="hljs-string">"ok"</span>: <span class="hljs-literal">true</span>,    <span class="hljs-string">"result"</span>: [        <span class="hljs-comment">// ...        // previous updates           // ...        {            "update_id": 599162365,            "message": {                "message_id": 174,                "from": { ... },                "chat": { ... },                "date": 1549788357,                "text": "/start uEDbtJFHxKc",                "entities": [ ... ]            }        }    ]}</span>
</code></pre><p>We can finally identify our user. The <code>text</code> field now contains our user token. Let’s go ahead and take it out of this field:</p>
<pre><code>bot_token = <span class="hljs-string">'your_bot_token'</span>updates_url = f<span class="hljs-string">'https://api.telegram.org/bot{bot_token}/getUpdates'</span><span class="hljs-keyword">import</span> requestsresponse = requests.get(updates_url).json()text = response[<span class="hljs-string">'result'</span>][<span class="hljs-number">0</span>][<span class="hljs-string">'message'</span>][<span class="hljs-string">'text'</span>]text# =&gt; <span class="hljs-string">'/start uEDbtJFHxKc'</span>splitted_text = text.split(<span class="hljs-string">' '</span>)# =&gt; [<span class="hljs-string">'/start'</span>, <span class="hljs-string">'uEDbtJFHxKc'</span>]token = splitted_text[<span class="hljs-number">-1</span>]# =&gt; <span class="hljs-string">'uEDbtJFHxKc'</span>
</code></pre><p>This token can be used to find the user. Your implementation depends on the way you saved the token in the first place. But here’s how I do it:</p>
<pre><code>notification = Notification.objects.get(channel=<span class="hljs-string">'telegram'</span>, connect_token=token)user = notification.user
</code></pre><p>So the user had pressed the “Start” button. But they see that nothing happened. Let’s welcome them at least.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/t3LnDt2icX4drb1ZwOr4t0gd8rHaoNhuOxoR" alt="Image" width="800" height="534" loading="lazy"></p>
<p>To welcome the user we need to discover that the user had started a conversation with our bot. There are two options for how we can do that: polling and webhooks.</p>
<p>You already know what polling is. You’ve already done it. Or at least have seen me do it. Once we’ve checked out the <code>https://api.telegram.org/bot{bot_token}/getUpdates</code> page we did one poll. Polling is checking for updates constantly, every 2 seconds for example. This way we can always know when someone interacted with the bot.</p>
<p>Webhooks take a bit of a different direction. Instead of checking every 2 seconds for updates, we just wait for an update to happen. And when it happens Telegram will send a request with the update data to a URL that we specify. This way we can give both our and Telegram servers some rest and just wait for the update to come.</p>
<p>Polling can be better if you’ve got high traffic but, unfortunately, it’s rather an exception so I’ve decided to go with the webhook.</p>
<h3 id="heading-webhooks">Webhooks</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/nn4BJScN-LpTraRBdaaZ6--uBVl7Ikrlfj6E" alt="Image" width="800" height="571" loading="lazy"></p>
<p>Setting a webhook in Telegram is very easy. You just need to send a request to <code>https://api.telegram.org/bot{bot_token}/setWebhook?url={your_server_url}</code>. Opening this link in your browser works too. <code>your_server_url</code> is the URL Telegram will send updates to. Here’s what you should get in the response:</p>
<pre><code>{    <span class="hljs-string">"ok"</span>: <span class="hljs-literal">true</span>,    <span class="hljs-string">"result"</span>: <span class="hljs-literal">true</span>,    <span class="hljs-string">"description"</span>: <span class="hljs-string">"Webhook was set"</span>}
</code></pre><p>If you don’t trust yourself you can visit <code>https://api.telegram.org/bot{bot_token}/getWebhookInfo</code> just to doublecheck that everything is OK. You should see something like this:</p>
<pre><code>{    <span class="hljs-string">"ok"</span>: <span class="hljs-literal">true</span>,    <span class="hljs-string">"result"</span>: {        <span class="hljs-string">"url"</span>: <span class="hljs-string">"https://example.com/your_server_endpoint"</span>,        <span class="hljs-string">"has_custom_certificate"</span>: <span class="hljs-literal">false</span>,        <span class="hljs-string">"pending_update_count"</span>: <span class="hljs-number">0</span>,        <span class="hljs-string">"max_connections"</span>: <span class="hljs-number">40</span>    }}
</code></pre><p>Now. If something is not OK (like you’ve set a wrong URL) you can always delete the webhook by visiting <code>[https://api.telegram.org/bot{bot_token}/deleteWebhook](https://api.telegram.org/bot{bot_token}/deleteWebhook)</code> and then setting the webhook again.</p>
<h3 id="heading-local-development">Local development</h3>
<p>Before continuing I would like to say a few words about local development. Webhooks are not very suitable for it. Webhooks are sent to a URL and most likely you don’t know your computer’s URL. Also, a Telegram webhook requires the URL to be secure (HTTPS).</p>
<p>But there is a solution to this problem: <a target="_blank" href="https://ngrok.com/">ngrok</a>. ngrok is a tool that exposes your local environment to the world. <a target="_blank" href="https://ngrok.com/download">Download ngrok</a>, install it and start it with the port your server is running on. My server is running on <code>8000</code> port so I would need to run in a console</p>
<pre><code>/path/to/ngrok http <span class="hljs-number">8000</span>
</code></pre><p>Then ngrok should give you a URL that you can use to set a webhook up.</p>
<h3 id="heading-welcoming-a-user">Welcoming a user</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/g5chjEivn8kFMGCWNKvl1x5FmYxWRaXlfPgX" alt="Image" width="800" height="533" loading="lazy"></p>
<p>Now that you’re ready to develop, let’s welcome our user — they’re waiting for it.</p>
<p>Once the user clicks “Start”, your Telegram will send an update to your server’s URL. The interesting parts of the update should look like this:</p>
<pre><code>{    <span class="hljs-string">"message"</span>: {        <span class="hljs-string">"chat"</span>: {            <span class="hljs-string">"id"</span>: <span class="hljs-number">457</span>        },        <span class="hljs-string">"text"</span>: <span class="hljs-string">"/start uEDbtJFHxKc"</span>,    }}
</code></pre><p>This is a perfect time to associate the user using message text. There is also an interesting piece of information, chat ID. Chat ID is what we need to send a message to that user. Telegram has an API endpoint to send a message that looks like this <code>https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&amp;text={text}</code>. I’m not sure I need to explain how to use it but here’s what my code that processes the webhook looks like:</p>
<pre><code><span class="hljs-keyword">import</span> jsonimport requestsdef callback(request):    body = json.loads(request.body)    text = body[<span class="hljs-string">'message'</span>][<span class="hljs-string">'text'</span>]    token = text.split(<span class="hljs-string">' '</span>)[<span class="hljs-number">-1</span>]    associate_user_by_token(token)    bot_key = os.environ.get(<span class="hljs-string">'TELEGRAM_API_KEY'</span>)    chat_id = body[<span class="hljs-string">'message'</span>][<span class="hljs-string">'chat'</span>][<span class="hljs-string">'id'</span>]    text = <span class="hljs-string">"Welcome!"</span>    send_message_url = f<span class="hljs-string">'https://api.telegram.org/bot{bot_key}/sendMessage?chat_id={chat_id}&amp;text={text}'</span>    requests.post(send_message_url)
</code></pre><p>If we send a welcome message after the user clicked the famous “Start” button, the user won’t have any second thoughts whether everything is working or not.</p>
<h3 id="heading-pushing-notifications">Pushing notifications</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/xfdeU5lYWIBYfeZ9wjFxW6x1zxjVNLnMvB2P" alt="Image" width="800" height="599" loading="lazy"></p>
<p>Finally, we get to the point why we’re doing all of this — push notifications. You may want to notify the user about some information that happened in your application. For example, someone liked the user’s post or whatever. I use Telegram to notify about <a target="_blank" href="https://musicnotifier.com/">new music releases</a> from the user’s favorite artists.</p>
<p>You already know how to send notifications. You just need to send a message using <code>[https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&amp;text={notification_text}](https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&amp;text={notification_text}.)</code><a target="_blank" href="https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&amp;text={notification_text}.">.</a></p>
<p>Of course, if you’re planning to send notifications not only when the user interacts with the bot, you need to save <code>chat_id</code> in your database.</p>
<p>You might also want to include links or some other formatting in your message. In this case, you would need to add another parameter to the send message URL, <code>parse_mode</code>. There are 2 parsing options: Markdown or HTML. I use Markdown since I find it simpler to use. If you’re not familiar with Markdown you can use HMTL, but I would recommend reading <a target="_blank" href="https://www.markdownguide.org/basic-syntax">how easy Markdown is</a>.</p>
<p>Here’s how the send message URL looks with <code>parse_mode</code> parameter <code>[https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&amp;text={notification_text}&amp;parse_mode=markdown](https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&amp;text={notification_text}&amp;parse_mode=markdown.)</code><a target="_blank" href="https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&amp;text={notification_text}&amp;parse_mode=markdown.">.</a></p>
<p>I add links to new releases to the notifications text like so <code>{release.date}: {release.artist.name} - [{release.title}]({release.url})</code>. You can read more about how to format you messages <a target="_blank" href="https://core.telegram.org/bots/api#formatting-options">here</a>.</p>
<p>Also, there are <a target="_blank" href="https://core.telegram.org/bots/api#sendmessage">more parameters available</a> for the send message URL like <code>disable_notification</code>. There is always a place to explore.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Now you should know how to</p>
<ul>
<li>create a bot in Telegram using BotFather</li>
<li>check for updates (and what is a better way — webhooks or polling)</li>
<li>associate user using deep linking</li>
<li>send a welcome message and continue sending notifications</li>
<li>format messages you send</li>
</ul>
<p>Hopefully, this article was useful to you. This is the fifth part of a series of articles about the <a target="_blank" href="http://musicnotifier.com/">MuN</a>. Stay tuned for part 6. You can find <a target="_blank" href="https://github.com/hmlON/mun">the code of this project</a>, as well as my other projects, on my <a target="_blank" href="https://github.com/hmlON">GitHub page</a>. Leave your comments down below and follow me if you liked this article.</p>
<p><em>Originally published at <a target="_blank" href="https://kholinlabs.com/telegram-push-notifications">https://kholinlabs.com/telegram-push-notifications</a> on February 12, 2019.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ I built a serverless Telegram bot over the weekend. Here’s what I learned. ]]>
                </title>
                <description>
                    <![CDATA[ By Moses Soh I built a Telegram chatbot that sends out a SOS to rescuers when someone is stranded in the rain. It’s written in Python using AWS Lambda, Zappa and Flask. You can try it here. I haven’t added in persistence yet ? but I think some of thi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-server-less-telegram-bot-227f842f4706/</link>
                <guid isPermaLink="false">66c34fd50fa3812cdd5eaa39</guid>
                
                    <category>
                        <![CDATA[ #chatbots ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ serverless ]]>
                    </category>
                
                    <category>
                        <![CDATA[ startup ]]>
                    </category>
                
                    <category>
                        <![CDATA[ telegram ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 25 Sep 2017 06:40:30 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*IU6691dCvEaCl46zvhZMrg.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Moses Soh</p>
<p>I built a Telegram chatbot that sends out a SOS to rescuers when someone is stranded in the rain. It’s written in Python using AWS Lambda, Zappa and Flask.</p>
<p>You can try it <a target="_blank" href="https://t.me/UmbrellaNetworkBot">here</a>. I haven’t added in persistence yet ? but I think some of this here might be useful to anyone else interested in a similar project.</p>
<p>I normally have a hard time getting my fiancée to discuss technology. It’s come to a point where she can’t help but stifle a yawn once I say “code”.</p>
<p>Imagine my surprise this weekend when she asked me — pretty much out of the blue — how much it would cost to make a mobile app.</p>
<p>After losing it for a bit, here’s what I found out.</p>
<h3 id="heading-the-problem"><strong>The problem</strong></h3>
<p>My fiancée’s workplace is close to two MRT stations but there aren’t any covered paths from the MRT stations to her building. When it rains, people without umbrellas get stranded at the stations. She and her colleagues often head down to help friends out, but there are often more people stranded there than they expected.</p>
<p>Her colleagues were discussing if an app could help solve this. Well, I thought that a chatbot might be able to have the same functions (such as sending out request for umbrellas, location sharing, getting replies). And you could avoid convincing people to download another app.</p>
<p>Since I’d been meaning to try out Telegram’s bot APIs for awhile now, I volunteered to help build out a prototype so we could see how interesting this might actually be.</p>
<h3 id="heading-the-chatbot">The chatbot</h3>
<p>I started working on this on Saturday afternoon and went to bed at 2am on Sunday. But I’m really happy to have gone from knowing nothing about the bot APIs to being able to make something like this.</p>
<p><strong>Anyone can request an umbrella.</strong> The bot asks where the person is, how many umbrellas he/she might need, and when they’d like to be picked up (the options are limited so we don’t tax our rescuers too much).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*8fRnEXxnziTXq0_eCPFaJw.gif" alt="Image" width="281" height="500" loading="lazy">
<em>This is what the chatbot does when you request an umbrella</em></p>
<p><strong>People can register to be rescuers.</strong> A little good karma goes a long way ?</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*OTwyQWY2fa8j2-UbRNoR7A.gif" alt="Image" width="281" height="500" loading="lazy">
<em>This is how someone becomes a rescuer</em></p>
<p><strong>Rescuers get notified whenever someone near them is stranded in the rain.</strong> I wanted to make it clear to rescuers whether they were responsible for the request once they had pressed “Yes”.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*HMzdeOZzu7wwGzunxn5rOg.gif" alt="Image" width="281" height="500" loading="lazy">
<em>This is how a rescuer receives and answers a request</em></p>
<p>In the process I learned a few tricks about making the development a lot faster. I spent almost six hours before I managed to find the right tools and a development workflow that worked for me. Building the bot logic took me a much shorter time.</p>
<h3 id="heading-what-i-used">What I used</h3>
<h4 id="heading-aws-lambda">AWS Lambda</h4>
<p>Instead of running a server 24/7, you can host functions in Lambda so that the server only lasts for the lifecycle of the request. It’s great for prototypes since you get 1 million free requests a month.</p>
<h4 id="heading-zappa">Zappa</h4>
<p><a target="_blank" href="https://github.com/Miserlou/Zappa">This</a> automates the steps needed to get your local Python code onto AWS Lambda. It also configures Amazon’s API Gateway so you have a nice HTTPS endpoint to host your chatbot functions.</p>
<h4 id="heading-ngrok">ngrok</h4>
<p><a target="_blank" href="https://ngrok.com/">This</a> makes any local servers reachable via the internet. It’s a great way to prototype web-hooks before actually deploying them to the cloud.</p>
<p>These tools helped me avoid a lot of the headache that goes into making a chatbot (e.g. renting a server, configuring it for HTTPS, figuring out how to make the server non-blocking since this is a chatbot).</p>
<p>Today I’ll show you how I used these tools to develop the chatbot above. Hope this will help someone else on a similar journey.</p>
<h3 id="heading-walkthrough">Walkthrough</h3>
<p>This tutorial assumes that you’re making a chatbot with no knowledge of how Telegram’s bot API works, but with a working knowledge of Flask and Python. If anything seems too simple for you, feel free to skip ahead!</p>
<h4 id="heading-create-a-telegram-bot">Create a Telegram bot</h4>
<p>Visit the <a target="_blank" href="https://t.me/botfather">Botfather</a>. Type <code>/newbot</code> and follow his instructions to set up a new bot.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*j6lJlDAPADGvjhFlhrOQGA.png" alt="Image" width="800" height="129" loading="lazy">
<em>And just like this we have a chatbot setup on Telegram!</em></p>
<p>⚡ <strong>Pro tip:</strong> save the token somewhere, we’ll be using it soon!</p>
<p>Feel free to play around with the bot’s profile picture, about text, and description to give it whatever personality you want. Typing <code>/help</code> with the Botfather gives you the full list of settings you can tweak for your bot.</p>
<h4 id="heading-set-up-a-development-server-with-flask">Set up a development server with Flask</h4>
<p>I worked with <a target="_blank" href="https://github.com/kennethreitz/pipenv">pipenv</a> to manage my project’s Python dependencies. If you’re still using pip and virtualenv I encourage you guys to give this a try. There’s installation instructions at the link.</p>
<p>Next we’ll install <a target="_blank" href="http://flask.pocoo.org/">Flask</a>. We’ll also use the awesome <a target="_blank" href="http://docs.python-requests.org/en/master/">requests</a> library. In your command line type:</p>
<pre><code>pipenv install flaskpipenv install requests
</code></pre><p>After flask is installed, we’ll set up a basic server to test our bot. Copy the following text into a file called <code>server.py</code> .</p>
<p>⚡ <strong>Pro tip:</strong> Make sure you replace <code>&lt;your-bot-tok</code>en&gt; with the API token we got from the Botfather.</p>
<p>Let’s break down what this is doing. Telegram’s API works this way. Firstly, when someone sends your bot a message, that message gets sent to Telegram’s servers. Telegram then forwards us that message to whatever we specify as our web-hook as a POST request.</p>
<p>The function <code>process_update()</code> and the decorator above it says that when anyone POSTs to the domain <code>[http://127.0.0.1:5000](http://127.0.0.1:5000)/&lt;your-bot-tok</code>en&gt; , we will extract the JSON data from it. If it’s a normal text message, it will have th<code>e key m</code>essage in the JSON. We check for that and if it’s a normal message, we reply <code>using process_message(u</code>pdate) .</p>
<p>The function <code>process_message()</code> constructs the payload that the Telegram API is expecting if we want to reply to the message. We basically need to specify our reply text in <code>data["text"]</code> and the chat we’re replying to in <code>data["chat_id"]</code> .</p>
<p>Finally, we send a POST request with this payload to the <a target="_blank" href="https://core.telegram.org/bots/api#sendmessage">Telegram API endpoint for the <code>sendMessage</code> method</a>. This allows us to send a message programmatically.</p>
<p><strong>Time to run the server.</strong> Now in your command prompt type:</p>
<pre><code>pipenv shell
</code></pre><p>This activates the virtual environment and gives us access to Flask. Now we need to run the server locally. Type in the command prompt:</p>
<pre><code><span class="hljs-keyword">export</span> FLASK_APP=server.pyflask run
</code></pre><p>We have a running server! If you didn’t mess with the defaults, this is running at <a target="_blank" href="http://127.0.0.1:5000">http://127.0.0.1:5000</a>/.</p>
<p>Read more at the Flask documentation and <a target="_blank" href="http://flask.pocoo.org/docs/0.12/quickstart/">quick-start</a>.</p>
<p>But this is running locally, and Telegram’s bot API can’t send its POST requests to a local URL. Hence we’ll use <strong>ngrok</strong> to expose this local server to the internet.</p>
<h4 id="heading-use-ngrok-to-make-the-local-server-accessible-on-the-internet">Use ngrok to make the local server accessible on the internet</h4>
<p>Get the package for your operating system from <a target="_blank" href="https://ngrok.com/download">this link on the ngrok website</a>. Once you’ve downloaded and installed it, go to the directory that you unzipped the file into and run the following command in the command prompt.</p>
<pre><code>./ngrok http <span class="hljs-number">5000</span>
</code></pre><p>You’ll see something similar in your command prompt. Now whatever server you’re running on localhost:5000 is exposed at the following URLs.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*ajbuzROMpw1Tpkqhj1BPfQ.png" alt="Image" width="563" height="334" loading="lazy"></p>
<p>⚡ <strong>Pro tip:</strong> Copy the https url, we’re going to use it soon.</p>
<p><strong>Time to let Telegram know what our web-hook address is.</strong> We’ll use the Telegram API again to set our web-hook.</p>
<p>Create a file called <code>webhook.py</code> with the following content:</p>
<p>⚡ <strong>Pro tip:</strong> Remember to replace <code>&lt;your-bot-tok</code>en&gt;<code>; and &lt;your-h</code>ttps-url&gt; !</p>
<p><code>pprint</code> lets us print out nicely formatted JSON data. We send our web-hook URL as a POST request to the <code>[setWebhook](https://core.telegram.org/bots/api#setwebhook)</code> <a target="_blank" href="https://core.telegram.org/bots/api#setwebhook">endpoint</a> of the Telegram API. Now run the following lines in your command prompt:</p>
<pre><code>pipenv install pprintpython webhook.py
</code></pre><p>You should see <code>200</code> and a JSON block with <code>'ok': True</code> .</p>
<h4 id="heading-test-out-your-chatbot">Test out your chatbot</h4>
<p>Now we’re done with setting up our server. Head over to your bot in Telegram, and say hello! If everything’s been set up correctly, you’ll see it reply <code>I can hear you!</code></p>
<p>In the next part of this tutorial, we’ll learn how to deploy this server onto the internet using Zappa and AWS Lambda. Give this a couple of claps if this was helpful for you — I’d love to know if it was. Thanks ?</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
