<?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 Calixte Mayoraz on Medium]]></title>
        <description><![CDATA[Stories by Calixte Mayoraz on Medium]]></description>
        <link>https://medium.com/@calixtemayoraz?source=rss-5768624cd15e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WX03gtw-EvJPwH8B</url>
            <title>Stories by Calixte Mayoraz on Medium</title>
            <link>https://medium.com/@calixtemayoraz?source=rss-5768624cd15e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 22:26:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@calixtemayoraz/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[Combining Deep Learning and Random Forests in Tensorflow]]></title>
            <link>https://medium.com/@calixtemayoraz/combining-deep-learning-and-random-forests-in-tensorflow-3ec940a3797b?source=rss-5768624cd15e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ec940a3797b</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Calixte Mayoraz]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 17:07:31 GMT</pubDate>
            <atom:updated>2023-02-21T17:07:31.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RXHdIp-wBgi8A1r7" /><figcaption>Photo by <a href="https://unsplash.com/@wolfgang_hasselmann?utm_source=medium&amp;utm_medium=referral">Wolfgang Hasselmann</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ve been working on a project for the last few months for anomaly detection, and have needed to classify Time-Sequences into various classes. To accomplish this, I was drawn to the elegant solution of using the <a href="https://medium.com/ai%C2%B3-theory-practice-business/understanding-autoencoders-part-i-116ed2272d35">Autoencoder architecture</a>. However, In general, I’m also a big fan of Random Forests for classification (more so than neural nets) because of their fast convergence to results and robustness.</p><p>I have been using scikit-learn’s implementation of the algorithm since my university days, but yesterday, I discovered that Google have added a <a href="https://www.tensorflow.org/decision_forests/api_docs/python/tfdf">Decision Forest module</a> in their tensorflow arsenal, so I just <em>had </em>to give it a spin.</p><p>Let’s go through a quick example to show you the capabilities of this new library, and how you can combine a trained neural network and random forest and use them as a <strong>single model!</strong></p><p>First, I’ll just quickly go over what we’ll be doing here before actually diving in. We’ll be crudely classifying weather patterns for 24 hour windows. This will be done in four parts:</p><ol><li>Preprocess our input data to get some nice looking tensors fed into our autoencoder (I’ll go over this part quite quickly)</li><li>Train an autoencoder to extract some features from these sequences</li><li>Train a random forest on encoded data to predict the type of weather it’s seeing.</li><li>Combine the two models into one and get some predictions.</li></ol><blockquote>Note: Feel free to follow along in the following <a href="https://colab.research.google.com/drive/1TE5HAvdZIh7eAZSLTP_o67cOWSU5Cgcc?usp=sharing">Google Colab Notebook</a>!</blockquote><h4>Step 1 : Preprocessing</h4><p>Let’s get started with a <a href="https://www.kaggle.com/datasets/muthuj7/weather-dataset">simple dataset from Kaggle</a>. This is a dataset with hourly readings of temperature, pressure, humidity, wind, etc… with also hourly descriptions of the weather, which is what we will be predicting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*mNmFmQQdOX6e5c-9YaRgmg.png" /><figcaption>So many super-specific names for the weather…</figcaption></figure><p>I’m going to keep only 7 columns I need, and rename a few of the “Summary” classes (since there are a lot of kind-of unique ones…) to some more simple ones. So we have a dataset that has more balanced data, and only keeping numeric data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*5iYE-m-MSIlK13NIcBifAg.png" /><figcaption>better…</figcaption></figure><p>I’ll split my train/validate/test datasets and preprocess them all in the same way. My labels were also transformed into numeric form using scikit-learn’s LabelEncoder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*rR9qMGE5lzvymRDDzqpTXA.png" /><figcaption>DataFrame in, numpy arrays out</figcaption></figure><p>The coolest function in here is the sliding window view. This creates (in the blink of an eye) a sliding window of my time data. So now, instead of having a big 57871 x 7 matrix (57871 time steps, 7 features), we now have a 57848 x 24 x 7 matrix. (57871 – 23 = 57848). Basically, 57848 windows of 24 time steps and 7 features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*Oa5TjeH64XLI6n48iStpdg.png" /><figcaption>illustration of the windowing process</figcaption></figure><p>Look at it like this: instead of having a long roll of paper with all of the time steps one after another, you have a pile of sheets of paper with 24 time steps on each. Each subsequent sheet is shifted by one time step, with the new time step for that sheet added at the bottom.</p><p>For each sheet, the ground truth is set to be the most frequent class for that sheet (line 21). We use scipy’s mode function to find the most frequent class in the time-window and collapse that down as the class for that sequence.</p><p>Now, we can prepare some tensorflow datasets (I <strong>love </strong>using these!) remembering that the input data and target data for an autoencoder should be the same. The model has to find a way to “compress” the input data to a small vector and be able to reconstruct it as best it can afterwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*jDLtQs_0zDn0fGa65scs3g.png" /></figure><p>We’re ready to start training!</p><h4>Step 2: Train the autoencoder</h4><p>For this example, I’m using a very primitive LSTM autoencoder: Just one LSTM to encode, one LSTM to decode. We still have to add a RepeatVector in the middle to get compatible shapes in the output, but it works great.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*Z8xxSTK241Bf3Uv10DwpeQ.png" /></figure><p>And let’s send this bad-boy on its way to train! (If you’re on Google Colab, I strongly suggest using a TPU-powered environment, the speed boost is astonishing). For me, this took about fifty minutes (30s per epoch, 100 epochs)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*1MuoNts53rhGdRiNE1AY3w.png" /></figure><h4>Step 3: Training the Random Forest</h4><p>Let’s recap. We have data that is formatted as windows of 24x7 that we are trying to classify. Our autoencoder crushes it down to a 24-long vector, before expanding it back to a 24x7 window. What we’re going to do now is take the data as it comes out of the encoder, and feed <em>that</em> into a Random Forest for classification. So to get our input data for the random forest, we have to first encode it. And to only encode data, we have to reconstruct just the encoder from our trained autoencoder and (predict) encode our training data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*-GztaGPueNJ_o7Hp9lXxJw.png" /><figcaption>alright! our encoder crunched down a 24x7 matrix into a 24-long array</figcaption></figure><p>From here, we can create and train a Random Forest (with basic settings). I’m sure that even the most Neural-Net afficionado will have to admit that this two-liner is quite elegant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*9t12Fmb3kZJcue5Gv39Ctw.png" /><figcaption>3 minutes to train… and people ask me why I love Random Forests…</figcaption></figure><p>And now… the coolest part begins.</p><h4>Part 4: Combine the Encoder and Random Forest together</h4><p>The really neat thing about this tensorflow Decision Forest library is that they follow the keras API to a tee, which means that chaining them up with other models is a breeze.</p><p>I mean…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*SZ5DhzYwrUrg-h0t5vKh6Q.png" /><figcaption>Yep! that’s it!</figcaption></figure><p>Since the RF model was trained on data that came out of the encoder model, it knows what input shapes it’s supposed to receive, and it already figured out the output classes from the ones it saw in the training set.</p><p>One thing to note: the predict() function from the RandomForestModel (and by consequence, our full model) returns probabilities for each of the classes. So to get raw predictions, you’ll have to use an argmax function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*fJmHQNPpR2YwjbosXV8F6Q.png" /></figure><p>And finally, we can see our results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*JURAHvk_7IefldH3AK2s5g.png" /></figure><p>Yeah, it’s not perfect, but hey, it’s getting close! Obviously it gets a bit mixed up between “Partly Cloudy”, “Mostly Cloudy”, and “Overcast” because these can be quite similar (and “Partly Cloudy” is more frequent) but there you have it!</p><h4>Conclusion</h4><p>That’s it! A quick way to combine two different species of machine learning into one model that you can use in a single line to get predictions, and save to disk in one file! No more saving two models and not being sure if they are both from the same training version!</p><h4>Note</h4><p>Obviously, if you want to retrain the encoder, you’ll have to retrain the whole autoencoder, and use the newly encoded data from that model to train the RandomForest again. I wonder if there would be a way to just train everything in a single go…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ec940a3797b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step guide to build a Telegram Chatbot with a simple WebApp UI using Python]]></title>
            <link>https://medium.com/@calixtemayoraz/step-by-step-guide-to-build-a-telegram-chatbot-with-a-simple-webapp-ui-using-python-44dca453522f?source=rss-5768624cd15e------2</link>
            <guid isPermaLink="false">https://medium.com/p/44dca453522f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[chatbot-development]]></category>
            <category><![CDATA[web-app-development]]></category>
            <dc:creator><![CDATA[Calixte Mayoraz]]></dc:creator>
            <pubDate>Fri, 04 Nov 2022 22:43:41 GMT</pubDate>
            <atom:updated>2022-11-04T22:45:25.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WWXynNbC3xoIkTYr" /><figcaption>Photo by <a href="https://unsplash.com/@artnok?utm_source=medium&amp;utm_medium=referral">Nicolas Picard</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I started working on a project to help people discover craft beers using a Telegram Chatbot. To do this, the user needs to input their taste preferences along several types of tastes. I wanted to implement a UI with sliders to get this info from the user as intuitively as possible. Now, Telegram have done an incredible job at developing the chatbot backend to support Web-Apps, however the documentation (which is still under development) is at the time of writing this tutorial, <em>very </em>basic. So, I powered through it for a few days and thought I’d write a tutorial to help anyone in need for their future projects.</p><p>Let’s make a simple chatbot that takes some input from a web-app, and stores it for later use.</p><blockquote><strong>I’m assuming you have at least some basic knowledge of the following:</strong></blockquote><blockquote>Command-line stuff, Python, pip, Telegram, git, HTML/javascript</blockquote><h3>Creating the bot</h3><p>First things first, let’s talk to <a href="https://telegram.me/BotFather">botfather</a> to create our bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*yJbNkdGdsDQ-OPrGkSwYng.png" /></figure><p>Now we can start working on the bot. Let’s create a new folder for our code and install a few dependencies right off the bat.</p><pre># create our project<br>mkdir web_interfacer_bot<br>cd web_interfacer_bot</pre><pre># Install some dependencies that we will need<br>pip install <em>python_telegram_bot</em>~=20.0a4<br>pip install <em>python-dotenv</em>~=0.21.0</pre><p>And now we are ready to start coding. Let’s create an environment file to keep our sensitive information (like the bot token) in. Create a “.env” file at the root of your project and paste in your bot username (that you defined) and the bot token (given by botfather) inside like so:</p><pre>BOT_USERNAME=webapp_interfacer_bot<br>BOT_TOKEN=1234567:ASDFASDFASDFsdjfhjskdfg9wexchgfsj45635</pre><p>Now, we can create a python file that will load these environment variables from file (if it exists) or from the system environment variables (like when we are deploying). I’m calling it <em>credentials.py.</em></p><pre><em>&quot;&quot;&quot;credentials.py&quot;&quot;&quot;<br>import </em>os<br><em>if </em>os.path.exists(&quot;.env&quot;):<br>    <em># if we see the .env file, load it<br>    from </em>dotenv <em>import </em>load_dotenv<br>    load_dotenv()<br><br><em># now we have them as a handy python strings!<br></em>BOT_TOKEN = os.getenv(&#39;BOT_TOKEN&#39;)<br>BOT_USERNAME = os.getenv(&#39;BOT_USERNAME&#39;)</pre><p>Okay, now we can REALLY get down to making a bot. I’m using the boilerplate approach from <a href="https://github.com/python-telegram-bot/python-telegram-bot/wiki">python-telegram-bot</a>, if you are unfamiliar with this framework, I <strong>highly </strong>suggest you take a read. Their tutorials are extremely well written and the rest of this tutorial will be easier to understand if this is your first bot.</p><p>Create a file called “app.py” and copy/paste the following section inside:</p><pre><em>&quot;&quot;&quot;app.py&quot;&quot;&quot;<br>from </em>telegram <em>import </em>Update, KeyboardButton, ReplyKeyboardMarkup, WebAppInfo<br><em>from </em>telegram.ext <em>import </em>ApplicationBuilder, CallbackContext, CommandHandler, MessageHandler, filters<br><em>from </em>credentials <em>import </em>BOT_TOKEN, BOT_USERNAME<br><em>import </em>json<br><br><em>async def </em>launch_web_ui(update: Update, callback: CallbackContext):<br>    <em># For now, let&#39;s just acknowledge that we received the command<br>    await </em>update.effective_chat.send_message(&quot;I hear you loud and clear !&quot;)<br><br><br><em>if </em>__name__ == &#39;__main__&#39;:<br>    <em># when we run the script we want to first create the bot from the token:<br>    </em>application = ApplicationBuilder().token(BOT_TOKEN).build()<br><br>    <em># and let&#39;s set a command listener for /start to trigger our Web UI<br>    </em>application.add_handler(CommandHandler(&#39;start&#39;, launch_web_ui))<br><br>    <em># and send the bot on its way!<br>    print</em>(f&quot;Your bot is listening! Navigate to http://t.me/{BOT_USERNAME} to interact with it!&quot;)<br>    application.run_polling()</pre><p>And sure enough, if we run this python script and follow the link displayed on screen:</p><pre>Your bot is listening! Navigate to <a href="http://t.me/webapp_interfacer_bot">http://t.me/webapp_interfacer_bot</a> to interact with it!</pre><p>we can interact with our bot!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*fwC5SuJN1JGRrpW-QmBArw.png" /></figure><h3>Getting the bot to show a Web-App</h3><p>I won’t sugar-coat it, Web-Apps in Telegram aren’t a walk in the park. For starters, there are three kinds of triggers to start web apps, and we will only be exploring one in this tutorial:</p><ul><li><strong>Inline or Menu button Web-Apps — </strong>these are launched in Telegram, and then talk to an external server to handle anything the user does. Your bot must then handle any interaction with this third party to acknowledge to the user the results. (We won’t be discussing them in this tutorial, they are more complex)</li><li><strong>Keyboard button Web-Apps — </strong>these are launched in Telegram and return data directly to the bot, without a need for a specialized server to handle the response from the user. <strong>This is what we will be using</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GkkcblWtacVAYb_kFozmZQ.jpeg" /><figcaption>Three different types of buttons to launch Web-Apps (from <a href="https://core.telegram.org/bots/webapps">https://core.telegram.org/bots/webapps</a>)</figcaption></figure><p>First things first, let’s just <em>proof-of-concept</em> this bad boy with a simple web-page. Update the <em>launch_web_ui </em>method in “app.py” to look like this:</p><pre><em>async def </em>launch_web_ui(update: Update, callback: CallbackContext):<br>    <em># For now, we just display google.com...<br>    </em>kb = [<br>        [KeyboardButton(&quot;Show me Google!&quot;, web_app=WebAppInfo(&quot;https://google.com&quot;))]<br>    ]<br>    <em>await </em>update.message.reply_text(&quot;Let&#39;s do this...&quot;, reply_markup=ReplyKeyboardMarkup(kb))</pre><p>Let’s talk to our bot again and see what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*AEI2nrkBQjsqrQStXOCGyQ.png" /></figure><p>And if we click the keyboard button…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*c-AgbsiM6FFDKIWX1-KRVw.png" /></figure><p>Alright! This seems to be working nicely! Now, all we need to do is design our own web-app and display it instead of the google homepage!</p><h3>Designing the Web-App</h3><p>Let’s do something quick and dirty using AngularJS.</p><blockquote><strong>Disclaimer</strong> : Yes I know, AngularJS is outdated, but for tiny frontend projects like that, I actually really enjoy using it, kind of like some vamped up JQuery… For your project, the “how” doesn’t really matter that much, all that matters is that you have a web-app that can send a “sendData” command with the inputted data. More below:</blockquote><p>Okay, I’ll create a file called “index.html” and develop some simple interface to show you the basic idea:</p><pre>&lt;html <em>ng-app</em>=&quot;custom-webapp-ui&quot; <em>lang</em>=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    <em>&lt;!-- Load the Telegram Library --&gt;<br>    </em>&lt;script <em>src</em>=&quot;https://telegram.org/js/telegram-web-app.js&quot;&gt;&lt;/script&gt;<br>    <em>&lt;!--Load the AngularJS Library--&gt;<br>    </em>&lt;script <em>src</em>=&quot;https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script&gt;<br>      <em>//initialize the AngularJS stuff...<br>      </em>angular.<em>module</em>(&quot;custom-webapp-ui&quot;, []).controller(&#39;CustomUIController&#39;, <em>function CustomUIController</em>($scope) {<br>        <em>//init our slider values that we will display<br>        </em>$scope.foods = [<br>                { name: &quot;fruits&quot;, value: 5 },<br>                { name: &quot;vegetables&quot;, value: 5 },<br>                { name: &quot;meat&quot;, value: 5 },<br>                { name: &quot;dairy&quot;, value: 5 }<br>            ];<br>      });<br>    &lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body <em>ng-controller</em>=&quot;CustomUIController&quot;&gt;<br>    &lt;div <em>ng-repeat</em>=&quot;food in foods&quot;&gt;<br>      &lt;div <em>style</em>=&quot;width: 100px; display: inline-block&quot;&gt;{{food.name}} : {{food.value}}&lt;/div&gt;<br>      &lt;input <em>style</em>=&quot;display: inline-block&quot; <em>type</em>=&quot;range&quot; <em>min</em>=&quot;1&quot; <em>max</em>=&quot;10&quot; <em>ng-model</em>=&quot;food.value&quot; <em>value</em>=&quot;{{food.value}}&quot;&gt;<br>    &lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>This gives us a very basic interface to work with :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*fDhWW5GelGwweWGPBWuVfw.gif" /></figure><p>Now we bump into another issue, this needs to be hosted online somewhere…</p><h3>Deploying the Web App online using GitLab Pages</h3><blockquote><strong>Note</strong>: This approach is merely here to get results fast. Feel free to host your Web-App anywhere you like, and however you prefer! Just remember to use HTTPS, the chatbot will not work with HTTP pages.</blockquote><p>The easiest way to get this up and running ASAP is to use GitLab Pages. All you need is a (free) GitLab account, and to set up your repository there. Make sure the repository is public so that your web interface can be accessed by anyone (including your bot!)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*Rt6PcKyNAScemgtk_Evosw.png" /></figure><p>You <a href="https://gitlab.com/calixtemayoraz/web-interfacer-bot">can check my repository for this example</a> to compare notes if you need to.</p><blockquote><strong>IMPORTANT: </strong>do <strong>NOT </strong>add the .env file to the repository! If anyone but you gets a hold of the bot token, they can do whatever they want with it!</blockquote><p>Next, to ensure that our “index.html” is loaded into GitLab pages, we need to add a CI file. Create a “.gitlab-ci.yml” file in your project repository, and paste the following inside:</p><pre>pages:<br>  stage: deploy<br>  script:<br>    - cp index.html public<br>  artifacts:<br>    paths:<br>      - public<br>  only:<br>    - master</pre><p>Now, when you push code to the master branch, it will make “index.html” available at <a href="https://calixtemayoraz.gitlab.io/web-interfacer-bot/">https://&lt;your-username&gt;.gitlab.io/&lt;project-slug&gt;/</a> (which we can now access from the bot !)</p><h3>Linking Everything Together</h3><p>Alright this is getting interesting! If we get back to our python code, let’s just modify it a tad to show our Web-App instead of Google:</p><pre><em>async def </em>launch_web_ui(update: Update, callback: CallbackContext):<br>    <em># display our web-app!<br>    </em>kb = [<br>        [KeyboardButton(<br>            &quot;Show me my Web-App!&quot;, <br>           web_app=WebAppInfo(&quot;https://calixtemayoraz.gitlab.io/web-interfacer-bot/&quot;) # obviously, set yours here.<br>        )]<br>    ]<br>    <em>await </em>update.message.reply_text(&quot;Let&#39;s do this...&quot;, reply_markup=ReplyKeyboardMarkup(kb))</pre><p>Let’s see the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*KxRzoGvfOhPmlinctWnHlw.png" /><figcaption>Awwwhhh yissss</figcaption></figure><p>Now, we are really <strong>getting somewhere</strong>!</p><p>All we need now is to correctly send data back to the bot from the Web-App and to correctly parse it on the bot’s side.</p><h4>Make the Web-App send data back to the bot</h4><p>We just need to add a few things, namely the “submit” button (which telegram handily provides for us) and bind a function to send the data when it is pressed. If we modify the script in our “index.html” file:</p><pre><em>//initialize the AngularJS stuff...<br></em>angular.<em>module</em>(&quot;custom-webapp-ui&quot;, []).controller(&#39;CustomUIController&#39;, <em>function CustomUIController</em>($scope) {<br>  <em>//init our slider values that we will display<br>  </em>$scope.foods = [<br>          { name: &quot;fruits&quot;, value: 5 },<br>          { name: &quot;vegetables&quot;, value: 5 },<br>          { name: &quot;meat&quot;, value: 5 },<br>          { name: &quot;dairy&quot;, value: 5 }<br>      ];</pre><pre>  <em>//initialize the &quot;save&quot; button<br>  const </em>mainButton = window.Telegram.WebApp.MainButton;<br>  mainButton.text = &quot;Save Preferences&quot;;<br>  mainButton.enable();<br>  mainButton.show();</pre><pre>  <em>// and make it send the &quot;foods&quot; object (as JSON string) back to the backend<br>  </em>mainButton.onClick(<em>function</em>(){<br>    window.Telegram.WebApp.sendData(JSON.stringify($scope.foods));<br>  })<br>});</pre><p>And with these few lines of code, when we deploy our code and run the bot again…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*zYa6vzJT4Dl9WLE6uDSUOQ.png" /><figcaption>We get a nice “save” button at the bottom!</figcaption></figure><p>Moreover, when we click the “save preferences” button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*h8BMCV_IVtNs12tU_IdGwg.png" /><figcaption>Something got sent back! We just need to catch it.</figcaption></figure><p>I don’t know about you, but at this stage, I was getting tingles…</p><blockquote><strong>It’s important to note </strong>that any information you pass back from the UI to the bot needs to be serialized as a string (4096 bytes max) so any heavy stuff like images, etc should be handled differently.</blockquote><h4>Handling the Response data from the bot’s side</h4><p>We are so close! All we need now is to handle a “service message” on the bot’s side to get the data sent back from the Web-App. Let’s add a simple method that just spits back the data sent from the user as a proof-of-concept:</p><pre><em>async def </em>web_app_data(update: Update, context: CallbackContext):<br>    data = json.loads(update.message.web_app_data.data)<br>    <em>await </em>update.message.reply_text(&quot;Your data was:&quot;)<br>    <em>for </em>result <em>in </em>data:<br>        <em>await </em>update.message.reply_text(f&quot;{result[&#39;name&#39;]}: {result[&#39;value&#39;]}&quot;)</pre><p>and add a listener to trigger this method when we get a response from the web-app:</p><pre>application.add_handler(MessageHandler(filters.StatusUpdate.WEB_APP_DATA, web_app_data))</pre><p>Finally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*gYAyvdFv2s6McOpBMRhLSw.gif" /><figcaption>There you go!</figcaption></figure><p>There you have it! End-to-end development of a very basic bot that opens a Web-App, allowing the user to enter info in a JavaScript environment and sending back the data to the bot. More specifically we saw:</p><ul><li>How to create a bot with botfather</li><li>Make a simple reply to commands</li><li>Display a web page from a KeyboardButton</li><li>Design a basic UI for user input</li><li>Send user inputted data back to the bot</li><li>Parse that information in the bot to use afterwards</li></ul><p>Hope this tutorial was helpful to you!</p><p>If you want, feel free to <a href="https://gitlab.com/calixtemayoraz/web-interfacer-bot">clone my repository</a> for this project to get it running on your environment and pick it apart if you need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44dca453522f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>