<?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 Thuta Tun on Medium]]></title>
        <description><![CDATA[Stories by Thuta Tun on Medium]]></description>
        <link>https://medium.com/@thutatun533?source=rss-f17e6b7b56b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aZuoenzziYbseNg2ZsVveA.png</url>
            <title>Stories by Thuta Tun on Medium</title>
            <link>https://medium.com/@thutatun533?source=rss-f17e6b7b56b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 09:08:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thutatun533/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[Load Testing My Node.js API with k6]]></title>
            <link>https://medium.com/@thutatun533/load-testing-my-node-js-api-with-k6-2e8ff04546bb?source=rss-f17e6b7b56b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e8ff04546bb</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[stress-testing]]></category>
            <category><![CDATA[grafana-k6]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Thuta Tun]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 11:12:56 GMT</pubDate>
            <atom:updated>2025-11-22T11:12:56.930Z</atom:updated>
            <content:encoded><![CDATA[<p>As an engineer focusing on backend development, it’s important to understand how our APIs behave under real-world conditions. It’s not enough for endpoints to work in isolation — we need to know how they perform when multiple users hit them at once, or when unexpected scenarios occur. That’s why I started using k6 for load testing: to make sure my e-commerce backend can handle spikes in traffic, and to catch issues before they reach production. Here’s how I approach this kind of testing in my workflow.</p><h4>Why I Chose k6</h4><p>I’ve tried a few load testing tools, but k6 stands out for a couple of reasons:</p><ul><li>It’s scriptable in JavaScript, which makes it easy to write realistic user flows.</li><li>The CLI is straightforward, and the output is easy to interpret.</li><li>It’s open source and integrates well with CI/CD if I want to automate tests later.</li></ul><h4>Project Setup</h4><p>My backend is a Node.js app with endpoints for user registration, login, browsing items, cart management, orders, and payments. Pretty standard stuff for a small e-commerce project.</p><p>To install k6, please refer to this official k6 <a href="https://grafana.com/docs/k6/latest/set-up/install-k6/">docs</a>.</p><h4>Writing the Test Script</h4><p>Here’s the <em>test.js</em> I put together. The idea is to simulate multiple users going through typical actions: landing on the homepage, registering, logging in, browsing, adding to cart, placing orders, and making payments.</p><pre>import http from &#39;k6/http&#39;;<br>import { sleep, group } from &#39;k6&#39;;<br><br>export let options = {<br>    vus: 10,<br>    duration: &#39;10s&#39;,<br>};<br><br>const BASE_URL = &#39;http://localhost:3002&#39;;<br><br>function randomPhone() { return &#39;09&#39; + Math.floor(100000000 + Math.random() * 900000000); }<br>function randomName() { const names = [&#39;Aung&#39;, &#39;Mya&#39;, &#39;Soe&#39;, &#39;Hla&#39;, &#39;Zaw&#39;, &#39;Win&#39;, &#39;Nyein&#39;, &#39;Htet&#39;, &#39;Sanda&#39;, &#39;Khin&#39;]; return names[Math.floor(Math.random() * names.length)] + Math.floor(Math.random() * 1000); }<br>function randomPassword() { return &#39;pw&#39; + Math.floor(Math.random() * 10000); }<br>function randomItemId() { return Math.floor(1 + Math.random() * 5); }<br><br>export default function () {<br>    let phone = randomPhone();<br>    let name = randomName();<br>    let password = randomPassword();<br>    let orderId = null;<br>    let amount = null;<br>    let otp = &#39;123456&#39;;<br><br>    group(&#39;Landing&#39;, function () {<br>        http.get(`${BASE_URL}/homepage`);<br>        http.get(`${BASE_URL}/items`);<br>        http.get(`${BASE_URL}/homepage`);<br>        http.get(`${BASE_URL}/items/${randomItemId()}`);<br>    });<br><br>    group(&#39;Register/Login/OTP&#39;, function () {<br>        let res = http.post(`${BASE_URL}/register`, JSON.stringify({ phone, name, password }), { headers: { &#39;Content-Type&#39;: &#39;application/json&#39; } });<br>        let loginOk = http.post(`${BASE_URL}/login`, JSON.stringify({ phone, password }), { headers: { &#39;Content-Type&#39;: &#39;application/json&#39; } });<br>        let otpReq = http.post(`${BASE_URL}/otp/request`, JSON.stringify({ phone }), { headers: { &#39;Content-Type&#39;: &#39;application/json&#39; } });<br>        let otpOk = http.post(`${BASE_URL}/otp/verify`, JSON.stringify({ phone, otp }), { headers: { &#39;Content-Type&#39;: &#39;application/json&#39; } });<br>    });<br><br>    group(&#39;Browse and Cart&#39;, function () {<br>        http.get(`${BASE_URL}/homepage`);<br>        http.get(`${BASE_URL}/items`);<br>        for (let i = 0; i &lt; 3; i++) {<br>            http.get(`${BASE_URL}/items/${randomItemId()}`);<br>        }<br>        let validItemId = randomItemId();<br>        http.post(`${BASE_URL}/cart`, JSON.stringify({ phone, itemId: validItemId, quantity: 1 }), { headers: { &#39;Content-Type&#39;: &#39;application/json&#39; } });<br>        http.get(`${BASE_URL}/cart?phone=${phone}`);<br>    });<br><br>    group(&#39;Order and Payment&#39;, function () {<br>        let orderItemId = randomItemId();<br>        http.post(`${BASE_URL}/cart`, JSON.stringify({ phone, itemId: orderItemId, quantity: 1 }), { headers: { &#39;Content-Type&#39;: &#39;application/json&#39; } });<br>        let orderRes = http.post(`${BASE_URL}/orders`, JSON.stringify({ phone }), { headers: { &#39;Content-Type&#39;: &#39;application/json&#39; } });<br>        if (orderRes.status === 200) {<br>            let order;<br>            try { order = JSON.parse(orderRes.body); } catch {}<br>            if (order) {<br>                orderId = order.id;<br>                amount = order.total;<br>                http.post(`${BASE_URL}/transactions`, JSON.stringify({ phone, orderId, amount }), { headers: { &#39;Content-Type&#39;: &#39;application/json&#39; } });<br>            }<br>        }<br>    });<br><br>    group(&#39;List and Random&#39;, function () {<br>        http.get(`${BASE_URL}/orders`);<br>        http.get(`${BASE_URL}/transactions`);<br>        http.get(`${BASE_URL}/orders`);<br>        http.get(`${BASE_URL}/transactions`);<br>        http.get(`${BASE_URL}/random`);<br>        http.post(`${BASE_URL}/random`, {});<br>    });<br><br>    sleep(Math.random() * 2);<br>}</pre><p>A few things I like about this approach:</p><ul><li>Each group represents a logical part of the user journey.</li><li>Random data makes the test more realistic.</li><li>I can easily add or tweak scenarios as the API evolves.</li></ul><h4>Covering Edge Cases</h4><p>It’s not enough to just test the happy path. I also want to see how the API handles weird or unexpected input. For example:</p><ul><li>Registering the same phone number twice.</li><li>Logging in with the wrong password.</li><li>Adding an invalid item to the cart.</li><li>Placing an order with an empty cart.</li><li>Trying to pay with the wrong amount.</li></ul><p>Here’s how I check for duplicate registration:</p><pre>group(&#39;Register Same Phone Twice&#39;, function () {<br>    let phone = randomPhone();<br>    let name = randomName();<br>    let password = randomPassword();<br>    http.post(`${BASE_URL}/register`, JSON.stringify({ phone, name, password }), { headers: { &#39;Content-Type&#39;: &#39;application/json&#39; } });<br>    let res = http.post(`${BASE_URL}/register`, JSON.stringify({ phone, name, password }), { headers: { &#39;Content-Type&#39;: &#39;application/json&#39; } });<br>    if (res.status !== 400) {<br>        console.error(&#39;Expected error for duplicate registration!&#39;);<br>    }<br>});</pre><h4>Running the Test</h4><p>With the server running, I just do:</p><pre>k6 run test.js</pre><p>The output gives me a quick overview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lPsln1mTlFzLC5mxXnwOA.png" /></figure><p>What these numbers mean:</p><ul><li><strong>http_req_duration</strong>: How long each HTTP request took (average, min, median, max, and percentiles). Lower is better.</li><li><strong>{ expected_response:true }</strong>: Duration for requests that got the expected response (filtered subset).</li><li><strong>http_req_failed</strong>: Percentage and count of requests that failed (non-2xx/3xx status or network errors). You want this as close to 0% as possible.</li><li><strong>http_reqs</strong>: Total number of HTTP requests made during the test, and the average per second.</li></ul><p><strong>EXECUTION</strong></p><ul><li><strong>iteration_duration</strong>: How long each test iteration took (average, min, median, max, percentiles).</li><li><strong>iterations</strong>: Total number of completed test iterations (how many times the default function ran), and per second.</li><li><strong>vus</strong>: Number of active virtual users at any time (min and max during the test).</li><li><strong>vus_max</strong>: The maximum number of virtual users configured.</li></ul><p><strong>NETWORK</strong></p><ul><li><strong>data_received</strong>: Total and per-second amount of data received from the server.</li><li><strong>data_sent</strong>: Total and per-second amount of data sent to the server.</li></ul><p>These metrics help me quickly spot slow endpoints, error rates, and how much load my API is handling.</p><h4>Conclusion</h4><p>This e-commerce API is just a demo, but it’s the perfect playground for exploring what k6 can do. By using a realistic backend — even a simple one — I can push my endpoints, test different scenarios, and see exactly how my API responds under load. The main goal here isn’t to build a production-ready shop, but to show how k6 helps backend engineers catch issues early and build more reliable systems. If you want to get hands-on with load testing, setting up a demo project like this is a great way to start.</p><p>For more details, check out the <a href="https://grafana.com/docs/k6/latest/">k6 docs</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*pqaImx4hfDYeoHeMiHS-pA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e8ff04546bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Talking to Your Users: A Friendly Guide to OneSignal Push Notifications]]></title>
            <link>https://medium.com/@thutatun533/talking-to-your-users-a-friendly-guide-to-onesignal-push-notifications-d30a2f6767f9?source=rss-f17e6b7b56b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d30a2f6767f9</guid>
            <dc:creator><![CDATA[Thuta Tun]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 16:44:29 GMT</pubDate>
            <atom:updated>2025-11-20T16:44:29.734Z</atom:updated>
            <content:encoded><![CDATA[<p>As developers, we sometimes get so focused on building features that we forget to talk to our users. Push notifications are like a gentle tap on the shoulder, saying “Hey, something you care about is happening!”</p><p>I’ve set up this in most of my projects, and I want to share a clean, effective way to handle transactional and push notifications using OneSignal and Go. Below is the production-ready Go code I use, followed by a clear explanation of the concepts that make it work seamlessly.</p><h4>The Implementation</h4><p>Here is the clean, well-tested function we use to dispatch notifications. It’s designed to target a specific user across all their devices.</p><pre>func SendTransactionalNotification(external_user_id, heading, content string, data map[string]any) error {<br>    // Validate and fetch credentials<br>    apiKey := os.Getenv(&quot;ONESIGNAL_NOTI_API_KEY&quot;)<br>    appID := os.Getenv(&quot;ONESIGNAL_NOTI_APP_ID&quot;)<br>    if apiKey == &quot;&quot; || appID == &quot;&quot; {<br>        return fmt.Errorf(&quot;OneSignal API key or App ID not set&quot;)<br>    }<br><br>    // Construct the payload<br>    payload := map[string]any{<br>        &quot;app_id&quot;: appID,<br>        &quot;include_aliases&quot;: map[string]any{<br>            &quot;external_id&quot;: []string{external_user_id},<br>        },<br>        &quot;headings&quot;:       map[string]string{&quot;en&quot;: heading},<br>        &quot;contents&quot;:       map[string]string{&quot;en&quot;: content},<br>        &quot;target_channel&quot;: &quot;push&quot;,<br>    }<br>    if data != nil {<br>        payload[&quot;data&quot;] = data // For passing structured data to the app<br>    }<br><br>    // Execute the API request<br>    jsonPayload, err := json.Marshal(payload)<br>    if err != nil {<br>        return err<br>    }<br>    req, err := http.NewRequest(&quot;POST&quot;, &quot;https://api.onesignal.com/notifications&quot;, bytes.NewBuffer(jsonPayload))<br>    if err != nil {<br>        return err<br>    }<br>    req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>    req.Header.Set(&quot;Authorization&quot;, &quot;Basic &quot;+apiKey)<br><br>    client := &amp;http.Client{}<br>    resp, err := client.Do(req)<br>    if err != nil {<br>        return err<br>    }<br>    defer resp.Body.Close()<br><br>    if resp.StatusCode != http.StatusOK &amp;&amp; resp.StatusCode != http.StatusCreated {<br>        body, _ := io.ReadAll(resp.Body)<br>        return fmt.Errorf(&quot;OneSignal API error: %s, Body: %s&quot;, resp.Status, string(body))<br>    }<br>    return nil<br>}</pre><p><strong>Prerequisites:</strong> Ensure your OneSignal App ID and API Key are configured as environment variables. This function expects them to be present and valid.</p><h4>Core Concept: Mapping Users to Devices</h4><p>The power of this approach lies in using the external_user_id. To understand why, we need to clarify the two primary identifiers in the OneSignal model:</p><ul><li>external_user_id: This is your system’s unique identifier for a user (e.g., usr_abc123 from your database). It represents the logical entity — the person with the account.</li><li>player_id (or subscription_id): This is OneSignal’s identifier for a specific app installation on a device. It represents a physical endpoint—a single phone, tablet, or browser.</li></ul><p>The critical step happens on your client application (mobile or web). Upon user login, your app must register the device with OneSignal and associate its unique player_id with the user’s external_user_id.</p><h4>A Practical Scenario: Multi-Device Management</h4><p>Consider a user, let’s call her Priya. She has an account in your system with the ID priya_786.</p><ol><li>Priya installs your app on her personal phone. OneSignal assigns this installation a player_id of dev_123.</li><li>She logs in. Your app sends a call to OneSignal: <em>“Associate </em>player_id: dev_123 <em>with </em>external_user_id: priya_786<em>.&quot;</em></li><li>Later, she also logs into your web app on her desktop. This creates a new player_id, dev_456. Your web app sends a similar call: <em>&quot;Associate </em>player_id: dev_456<em> with </em>external_user_id: priya_786 <em>.&quot;</em></li></ol><p>OneSignal now maintains a mapping that knows Priya (priya_786) is reachable on two devices.</p><p>When you invoke <em>SendTransactionalNotification</em> with external_user_id: “priya_786”, you are instructing OneSignal to deliver the notification to all devices linked to that ID. The service handles the fan-out, sending the push to both dev_123(her phone) and dev_456 (her desktop) automatically.</p><p>This flow can be visualized in the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/0*qeqpcG6Hb4vYxcmO" /></figure><h4>Wrapping Up</h4><p>So, what have we learned? Sending push notifications doesn’t have to be complicated. With the Go code we walked through, you have a ready-to-use tool to send messages to your users.</p><p>The most important thing to remember is this: always send notifications to the user, not the device.</p><p>By using your own external_user_id, you tell OneSignal, “Send this to Sarah.” OneSignal then handles the hard work of finding all of Sarah&#39;s devices—her phone, her laptop, her tablet—and making sure the message gets to every single one.</p><p>This method is simple, reliable, and automatically handles everyday situations like when a user gets a new phone. You don’t have to worry about the details. Just focus on telling your users what they need to know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*I8e4zdxqE9ASj481.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d30a2f6767f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Haow I Built a Telegram Bot for OTP Authentication in Node.js (Production-Ready)]]></title>
            <link>https://medium.com/@thutatun533/haow-i-built-a-telegram-bot-for-otp-authentication-in-node-js-production-ready-64eb0f494d74?source=rss-f17e6b7b56b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/64eb0f494d74</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Thuta Tun]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 20:00:26 GMT</pubDate>
            <atom:updated>2025-02-05T20:00:26.778Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I Built a Telegram Bot for OTP Authentication in Node.js (Production-Ready)</h3><p>When I first built a Telegram bot for OTP authentication, I was focused on proving the concept rather than making it “production-ready”. While my initial version worked, it had some major flaws — users had to manually enter their phone numbers, which led to errors and potential security issues. Plus, the system wasn’t scalable since it relied on inefficient polling instead of webhooks.</p><p>After learning from those mistakes, I completely revamped my approach. This new implementation is <strong>more secure, user-friendly, and optimized for production</strong>. Here’s how I built it, the challenges I faced, and why it’s now a solid solution.</p><h3>Why Telegram for OTP Authentication?</h3><p>Most OTP-based authentication systems rely on email or SMS. However, SMS can be unreliable due to carrier issues, and email often ends up in spam folders. Telegram offers a great alternative because:</p><ul><li>It allows direct, <strong>instant</strong> message delivery.</li><li>Users don’t need to manually type their phone numbers — Telegram’s built-in <strong>contact sharing</strong> feature ensures accuracy.</li><li>It’s <strong>cost-effective</strong>, avoiding SMS fees.</li><li>Security is enhanced since we link accounts based on verified Telegram numbers.</li></ul><p>This method significantly improves both usability and security.</p><h3>Building the Telegram Bot</h3><h3>Step 1: Setting Up the Bot</h3><p>I used node-telegram-bot-api, a popular Node.js library for interacting with Telegram’s Bot API. First, I initialized the bot and set up a webhook connection.</p><pre>const TelegramBot = require(&quot;node-telegram-bot-api&quot;);<br>const bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, {<br>  webHook: true,<br>});</pre><p>This ensures our bot only responds when a user interacts, reducing unnecessary polling requests.</p><h3>Step 2: Connecting to MongoDB</h3><p>Since user data needs to be persistent, I connected the bot to MongoDB.</p><pre>const connectDB = require(&quot;../config/db&quot;);<br>connectDB()<br>  .then(() =&gt; console.log(&quot;Database connected for Telegram bot&quot;))<br>  .catch(error =&gt; console.error(&quot;Failed to connect database:&quot;, error.message));</pre><p>This helps store and manage linked phone numbers efficiently.</p><h3>Step 3: Handling Contact Sharing</h3><p>Instead of asking users to manually enter their phone numbers, I utilized Telegram’s <strong>request_contact</strong> feature. This prevents typos and ensures the phone number comes directly from Telegram.</p><pre>bot.onText(/\/start/, (msg) =&gt; {<br>  const chatId = msg.chat.id;<br>  <br>  User.findOne({ telegramUserId: msg.from.id })<br>    .then((user) =&gt; {<br>      if (user) {<br>        bot.sendMessage(chatId, &quot;You are already registered. Please log in.&quot;);<br>      } else {<br>        bot.sendMessage(<br>          chatId,<br>          &quot;Please share your Telegram number by clicking the button below.&quot;,<br>          {<br>            reply_markup: {<br>              keyboard: [<br>                [{ text: &quot;Share Your Contact&quot;, request_contact: true }],<br>              ],<br>              resize_keyboard: true,<br>              one_time_keyboard: true,<br>            },<br>          }<br>        );<br>      }<br>    })<br>    .catch((error) =&gt; console.error(&quot;Error checking user registration:&quot;, error));<br>});</pre><p>This creates a button that lets users share their contact info with a single tap.</p><h3>Step 4: Linking the User’s Telegram ID and Phone Number</h3><p>Once the user shares their contact, the bot saves their <strong>phone number</strong> and <strong>Telegram ID</strong> in the database.</p><pre>const handleContact = async (chatId, contact) =&gt; {<br>  const phoneNumber = contact.phone_number.startsWith(&quot;+&quot;)<br>    ? contact.phone_number.slice(1)<br>    : contact.phone_number;<br>  const telegramUserId = contact.user_id || chatId;<br>  <br>  try {<br>    const existingUser = await User.findOne({ phoneNumber });<br>    if (existingUser) {<br>      bot.sendMessage(chatId, &quot;This number is already linked to an account.&quot;);<br>      return;<br>    }<br><br>    const user = new User({ phoneNumber, telegramUserId });<br>    await user.save();<br><br>    bot.sendMessage(chatId, &quot;Your account has been successfully linked.&quot;);<br>  } catch (error) {<br>    console.error(&quot;Error during account linking:&quot;, error);<br>    bot.sendMessage(chatId, &quot;An error occurred. Please try again later.&quot;);<br>  }<br>};</pre><p>This prevents duplicate registrations and ensures each phone number is uniquely linked to a Telegram account.</p><h3>Step 5: Error Handling and UX Improvements</h3><p>To enhance the user experience, I added clear error messages when something goes wrong. For example:</p><pre>bot.on(&quot;message&quot;, (msg) =&gt; {<br>  if (msg.text &amp;&amp; msg.text.startsWith(&quot;/&quot;)) return;<br><br>  const chatId = msg.chat.id;<br><br>  if (msg.contact) {<br>    handleContact(chatId, msg.contact);<br>  } else {<br>    bot.sendMessage(<br>      chatId,<br>      &quot;Please use the provided button to share your contact. Restart with /start and try again.&quot;<br>    );<br>  }<br>});</pre><p>This prevents users from sending random messages instead of sharing their contacts.</p><h3>Why This is Now Production-Ready</h3><p>Compared to my initial version, this new approach is <strong>far more reliable</strong> and <strong>scalable</strong>. Here’s why:</p><p>✅ <strong>More Secure:</strong> Contact sharing ensures the phone number is real and linked to the user’s Telegram account.</p><p>✅ <strong>Better User Experience:</strong> A simple tap replaces manual phone number entry.</p><p>✅ <strong>Scalable &amp; Efficient:</strong> Webhooks reduce unnecessary API calls, improving performance.</p><p>✅ <strong>Improved Error Handling:</strong> Users receive clear guidance when something goes wrong.</p><h3>Final Thoughts</h3><p>Building this Telegram bot was a learning experience. Initially, I focused too much on functionality without thinking about security and scalability. But after refining my approach, I now have a production-ready system that is <strong>efficient, secure, and user-friendly</strong>.</p><p>If you’re considering building an OTP system without relying on SMS, <strong>Telegram bots are a fantastic alternative</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*F4lA0aIsLHFsx_l9cm4JWw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64eb0f494d74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Web Crawler that Saves Data to Google Drive]]></title>
            <link>https://medium.com/@thutatun533/building-a-web-crawler-that-saves-data-to-google-drive-9321af7b95d1?source=rss-f17e6b7b56b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9321af7b95d1</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Thuta Tun]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 12:11:23 GMT</pubDate>
            <atom:updated>2025-01-30T12:11:23.621Z</atom:updated>
            <content:encoded><![CDATA[<p>As developers, we often find ourselves needing to extract content from websites — whether it’s links, images, or plain text. So, I decided to build a <strong>web crawler</strong> that not only crawls websites but also saves the data directly to your <strong>Google Drive</strong>. Here’s how it works and why I think it’s worth checking out.</p><h3>Key Features:</h3><ul><li><strong>Asynchronous Crawling:</strong> Using aiohttp and asyncio, the crawler runs efficiently, even with large sites, by fetching data asynchronously.</li><li><strong>Data Extraction:</strong> It grabs <strong>links</strong>, <strong>images</strong>, and <strong>text</strong> from the pages it crawls.</li><li><strong>Google Drive Integration:</strong> All extracted data is saved automatically to a Google Drive folder, eliminating the need to manually organize the files.</li><li><strong>Simple Setup:</strong> Just provide a URL, set up Google Drive access, and run the script. The crawler takes care of the rest.</li></ul><p>I’ve made the setup process as simple as possible, and the best part is that you can start scraping websites and saving data in no time. If you’re someone who regularly needs to gather website data and store it, this tool could be a real time-saver.</p><p>Check out the project on GitHub, and feel free to give it a try: <a href="https://github.com/ThutaCodes/webspider">https://github.com/ThutaCodes/webspider</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*VS_6Dgg84cgkO1eDiLt-1g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9321af7b95d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Telegram Bot-Based OTP Login System with Node.js: Guide for Future Projects]]></title>
            <link>https://medium.com/@thutatun533/creating-a-telegram-bot-based-otp-login-system-with-node-js-guide-for-future-projects-b5710528c12a?source=rss-f17e6b7b56b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5710528c12a</guid>
            <category><![CDATA[otp-login-system]]></category>
            <category><![CDATA[telegram-bot-integration]]></category>
            <category><![CDATA[authentication-nodejs]]></category>
            <category><![CDATA[otp-sign-up-system]]></category>
            <category><![CDATA[user-authentication-api]]></category>
            <dc:creator><![CDATA[Thuta Tun]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 18:30:26 GMT</pubDate>
            <atom:updated>2024-11-12T18:30:26.039Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently set up a Node.js-based OTP login system using a Telegram bot instead of the usual SMS or email approach. It’s a simple yet secure system that leverages Telegram to send OTPs directly to users for authentication. This method is especially handy in regions where Telegram is popular and can be easily adapted for account sign-up verification as well (Like in my country, Myanmar)! Here’s the process I used — writing it down here means I’ll have a go-to guide for myself, and hopefully, it’s helpful for others too.</p><p><strong>Step 1: Setting Up the Project Structure</strong></p><p>I started with a standard Node.js setup using Express for the HTTP server and a few other essentials:</p><ul><li><strong>node-telegram-bot-api</strong>: For connecting with the Telegram bot.</li><li><strong>bcryptjs</strong>: To securely hash and compare OTPs.</li><li><strong>mongoose</strong>: For MongoDB, to store user data and OTPs.</li></ul><p>You can install these by running the following commands:</p><pre>npm install node-telegram-bot-api bcryptjs mongoose</pre><p>With that done, I was ready to dive into the bot setup.</p><p><strong>Step 2: Creating and Connecting the Telegram Bot</strong></p><p>First, I created a new bot through Telegram’s BotFather, which provided a unique bot token. After adding this to my .env variables, I initialized the bot like this:</p><pre>const TelegramBot = require(&quot;node-telegram-bot-api&quot;);<br>const bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, { polling: true });</pre><p>Using polling here allows the bot to continuously listen for messages — perfect for a small to mid-sized project.</p><p><strong>Step 3: Linking Users’ Phone Numbers</strong></p><p>To identify users, I set up the bot to ask for their phone number. When a user starts the bot with the /start command, it sends them a prompt asking them to reply with their phone number. Here’s the code for this:</p><pre>bot.onText(/\/start/, (msg) =&gt; {<br>  const chatId = msg.chat.id;<br><br>  bot.sendMessage(<br>    chatId,<br>    &quot;Please reply with your phone number to link your account (e.g., +959123456789).&quot;<br>  );<br><br>  bot.once(&quot;message&quot;, async (msg) =&gt; {<br>    const phoneNumber = msg.text.trim();<br>    const telegramUserId = msg.from.id;<br><br>    // Query database to find the user<br>    const user = await User.findOne({ phoneNumber });<br>    if (user) {<br>      await User.findOneAndUpdate(<br>        { phoneNumber },<br>        { telegramUserId }<br>      );<br>      bot.sendMessage(chatId, &quot;Account successfully linked.&quot;);<br>    } else {<br>      bot.sendMessage(chatId, &quot;Phone number not found. Please try again.&quot;);<br>    }<br>  });<br>});</pre><p>If a matching user is found in the database, it stores their Telegram ID, which lets us send OTPs to their Telegram for login or sign-up verification.</p><p><strong>Step 4: Generating and Sending the OTP</strong></p><p>To keep things secure, I used a basic OTP generator to create a six-digit code, or you can ask ChatGPT to create a basic OTP generator (or just use mine):</p><pre>const generateOTP = () =&gt; Math.floor(100000 + Math.random() * 900000).toString();</pre><p>This OTP has to be hashed using bcryptjs and saved in the database with an expiration time. When a login or sign-up request is made, the OTP is sent directly to the user’s Telegram ID, making it quick and convenient:</p><pre>if (user.telegramUserId) {<br>  bot.sendMessage(<br>    user.telegramUserId,<br>    `Your OTP code is ${otp}. It will expire in 3 minutes.`<br>  );<br>}</pre><p>This way, users get their OTP securely through Telegram instead of SMS or email or WhatsApp.</p><p><strong>Step 5: Verifying the OTP</strong></p><p>To complete the login or sign-up, users enter the OTP, which is then compared to the hashed version in the database. If the OTP matches and hasn’t expired, they’re authenticated. Here’s the verification snippet:</p><pre>// otp is valid; grant access<br>const isMatch = await bcrypt.compare(otp, user.otp);<br>if (isMatch &amp;&amp; user.otpExpiresAt &gt; new Date()) {<br>}</pre><p>Expired or incorrect OTPs will prompt users to request a new one, and once verified, the OTP and expiration fields are cleared.</p><p><strong>Here are some of the results:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2Z5aYkqN3Cpvr_UrWo0Hg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*OwOrH463KGqAvfNL8ojAtg.png" /></figure><p><strong>My thoughts:</strong></p><p>It’s really common to see WhatsApp, email or SMS used for sending OTPs since it’s widely available and has a massive user base. But why not give Telegram a shot? From my experience, it’s simpler to set up for backend integration, and it even allows for more flexibility with bot-based interactions.</p><p>Telegram’s open API and easy-to-use bot interface made the process smooth and efficient — no need to worry about extra SDKs or navigating complex restrictions. Plus, for anyone familiar with JavaScript, integrating a Telegram bot with Node.js feels intuitive and straightforward.</p><p>If you’re building a project where user authentication is key, this approach with Telegram is definitely worth a try. It’s fast, effective, and comes with a few advantages that are harder to get with other messaging platforms!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5710528c12a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>