<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" 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/">
<channel>
<title><![CDATA[Automation - Rafael Quintanilha]]></title>
<description><![CDATA[Essays about software engineering, web development, artificial intelligence, quantitative analysis, financial markets, books and tradition.]]></description>
<link>https://rafaelquintanilha.com/topic/automation/</link>
<image><url>https://rafaelquintanilha.com/content/images/2022/12/Logo-Design--2-.png</url><title>Automation - Rafael Quintanilha</title><link>https://rafaelquintanilha.com/topic/automation/</link></image>
<lastBuildDate>Tue, 15 Oct 2024 14:39:33 GMT</lastBuildDate>
<atom:link href="https://rafaelquintanilha.com/topic/automation/rss/" rel="self" type="application/rss+xml"/>
<ttl>60</ttl>
<item>
<title><![CDATA[Reducing churn with Stripe and ChatGPT]]></title>
<description><![CDATA[Leverage ChatGPT to communicate with your customers.]]></description>
<link>https://rafaelquintanilha.com/reducing-churn-with-stripe-and-chatgpt/</link>
<guid isPermaLink="false">670e7da7d8bba20001d2b680</guid>
<category><![CDATA[ChatGPT]]></category><category><![CDATA[Pipedream]]></category><category><![CDATA[Automation]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Mon, 22 Jul 2024 14:38:00 GMT</pubDate>

<content:encoded><![CDATA[<p>Managing a SaaS is <em>hard</em>. Not only you need to develop an idea and battle for its adoption, constantly iterate and listen to user feedback, but also handle the back-office aspect of it. In particular, if you receive money in exchange of offered services, there is a plethora of zones to cover.</p>
<p>We tend to overspend efforts to attract new customers, while existing clients often overlooked. I, for one, am guilty of doing so. It may look counter-intuitive, but your existing customers are the ones you should be looking closer! Reducing churn is a guaranteed way to improve your compounded revenue over time.</p>
<p>Even if you have a customer hooked in a subscription model, the battle is not won. For one reason or another payments fail, and if you are not on top of your recurring customers, you are deemed to leave money in the table.</p>
<p>Automation is key for any small, fast-paced team, which is the standard in the SaaS industry. If you are able to offset boring back-office tasks to <a href="https://pipedream.com?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Pipedream</a>, you gain precious time to invest on your core product.</p>
<p>Today I want to guide you on how to build a pipeline that:</p>
<ol>
<li>Listens to any failed payment events from Stripe;</li>
<li>Uses ChatGPT to transform the often cryptic messages into friendly, human-readable emails;</li>
<li>Sends the email via Postmark.</li>
</ol>
<p>The goal is to give a personal touch to your customers, warming up the relationship when the unexpected happens, without losing the scalability that only an automated AI system can offer. Let's get to it!</p>
<h2 id="connecting-to-stripe">Connecting to Stripe</h2>
<p>For this guide we'll be connecting to Stripe, which is the leading platform for offering subscription-based products online.</p>
<p>Start by creating a new workflow and searching for <strong>Stripe</strong> as trigger. There are several interesting events that you can listen to, and today we'll select <strong>New Failed Payment.</strong></p>
<p><img alt="" loading="lazy" decoding="async" width="1856" height="998" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-15-at-16.49.35@2x.dghR9PGU_23FwT.webp"></p>
<p>Next, you will be prompted to connect your Stripe account. If you don't yet have one, now it's the time to go to the <a href="https://dashboard.stripe.com/apikeys" rel="noopener noreferrer" target="_blank">Developers section and select the API keys tab</a>. I recommend you start by checking the <strong>Test mode</strong> toggle at the top-right corner, so you can test with peace of mind.</p>
<p>Click <strong>Create restricted key</strong> and select the permissions you want to allow. It's always a good practice to make them as restrictive as possible, especially for sensitive matters. <em>Tip: if you are unsure on what to select, allow Read permission for the items on the Permissions column (the one in the left). It's not always clear what is needed for every webhook.</em></p>
<p>After you are done configuring your key, grab its value, add it to Pipedream, and once the connection is configured you will be greeted with a waiting screen.</p>
<p><img alt="" loading="lazy" decoding="async" width="1862" height="1018" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-15-at-17.00.02@2x.BWmtsP0g_1mKT6B.webp"></p>
<p>Great! The connection is successful and now Pipedream is listening to failed payment events.</p>
<h2 id="triggering-a-failed-payment">Triggering a failed payment</h2>
<p>There are several ways to trigger a failed payment, and thankfully it doesn't involve using a real card in production. The simplest solution is to configure a <a href="https://stripe.com/en-br/payments/payment-links" rel="noopener noreferrer" target="_blank">Payment Link</a>. Create one and you should see a portal like this:</p>
<p><img alt="" loading="lazy" decoding="async" width="2258" height="1412" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-15-at-17.05.46@2x.te6Dm5T5_1udGvf.webp"></p>
<p><em>Fun fact</em>: even OpenAI uses Payment Links to manage ChatGPT subscriptions. You really don't need to build it yourself if you don't want to.</p>
<p>Now, Stripe conveniently provides several test card numbers that are wired to trigger specific errors (<a href="https://docs.stripe.com/testing#declined-payments" rel="noopener noreferrer" target="_blank">see the full list</a>). Make sure you pick a card associated with a payment failure, provide any 3-digit number as CVC and select a valid date (anyone in the future is fine). Try to pay and if all goes well the payment will be declined and you should see it show up in Pipedream.</p>
<p><img alt="" loading="lazy" decoding="async" width="1846" height="1648" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-15-at-17.12.05@2x.CRkqGdpr_HeN3.webp"></p>
<p>We have everything we need from Stripe, now onto leveraging AI to extract relevant information from the API.</p>
<h2 id="generating-a-human-friendly-message">Generating a human-friendly message</h2>
<p>Stripe returns a huge JSON with several relevant metadata, including fields like <code>failure_code</code> and <code>failure_message</code>. But it also returns billing details, which holds the user name, email and address.</p>
<p>Technically we could write a code to extract everything needed, but that's a great use-case for an AI model like GPT-4o! Instead of fighting with all possible return cases, we should be able to feed the whole payload to the model and ask for a nicely-formatted JSON output.</p>
<p>In order to do that let's <em>stringify</em> everything in the <code>event</code> object of the trigger step. It's very easy to do it: hook a new step to the trigger and select <strong>Python</strong>. Add the following code:</p>
<figure class="code"><figcaption>python</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="python"><code><span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> handler</span><span style="color:#ECEBE8">(pd: </span><span style="color:#97CCAE">"pipedream"</span><span style="color:#ECEBE8">):</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Reference data from previous steps</span></span>
<span class="line"><span style="color:#ECEBE8">    event </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> pd.steps[</span><span style="color:#97CCAE">"trigger"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"event"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Return data for use in future steps</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> {</span><span style="color:#97CCAE">"event"</span><span style="color:#ECEBE8">: </span><span style="color:#A1C1E4">str</span><span style="color:#EDCC95">(event)</span><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>This is all we need. The result will be a really long string, hard to parse for humans, but hopefully an easy task for an AI!</p>
<p>Let's move forward by hooking a new step: select <strong>OpenAI (ChatGPT)</strong> from the list and next the <strong>Chat</strong> option. Make sure you have your OpenAI API key at hand if you haven't connected to it already.</p>
<p>As of this writing, the most capable ChatGPT model is the GPT-4o. Select it from the dropdown. Next, in <strong>User Message</strong>, pick the <code>event</code> object returned in the previous step. That's how it should look like <code>{{steps.python.$return_value.event}}</code>.</p>
<p>Now, we want the AI to return 3 values:</p>
<ol>
<li>The <em>email address</em> of the user we will contact;</li>
<li>The <em>subject</em> of the email;</li>
<li>The <em>content</em> of the message.</li>
</ol>
<p>This is a great use-case for using the <code>json_object</code> <strong>Response Format</strong>. By selecting this option we <em>force</em> the AI to return a parseable JSON, which will be handy later on.</p>
<p>The only thing left in this step is to write the <strong>System Instructions</strong>, which will nudge the model to answer the way we want. That's what I came up with:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>Your job is to receive a JSON string, which happens when a Stripe payment fails, and craft an email that should feel personal, mention the reason the payment failed, suggest ways to fix it.</span></span>
<span class="line"><span></span></span>
<span class="line"><span>Extract the user email, create the subject, and the message, as it can be consumed by an API.</span></span>
<span class="line"><span></span></span>
<span class="line"><span>The tone of the message should be friendly, without being too much.</span></span>
<span class="line"><span></span></span>
<span class="line"><span>The response should also be in the JSON format and contain the fields: email, subject, message.</span></span></code></pre></figure>
<p><strong>Important:</strong> you need to <em>explicitly</em> say in the system instructions that you want the response as JSON whenever the response format is set to <code>json_object</code>.</p>
<p>Go ahead and test the integration. If all goes well, you can inspect the content:</p>
<p><img alt="" loading="lazy" decoding="async" width="1840" height="1542" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-16-at-10.30.48@2x.DyP5ey1P_23d4CL.webp"></p>
<p>This is a good time for you to adjust the tone of the message to better suit your use-case. You can also experiment with other failures and analyze how the model performs.</p>
<h2 id="parsing-the-ai-generated-json">Parsing the AI-generated JSON</h2>
<p>Once you are happy with the way the AI is crafting the message we are ready to finish the workflow by emailing the user.</p>
<p>Before we connect to <a href="https://pipedream.com/apps/postmark/actions/send-single-email?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Postmark</a>, which is my favorite email delivery service, we need to parse the JSON returned by the GPT model.</p>
<p>Add a new Python step (I named <em>python_json</em>) and paste the following code:</p>
<figure class="code"><figcaption>python</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="python"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> json</span></span>
<span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> handler</span><span style="color:#ECEBE8">(pd: </span><span style="color:#97CCAE">"pipedream"</span><span style="color:#ECEBE8">):</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Reference data from previous steps</span></span>
<span class="line"><span style="color:#ECEBE8">    content </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> pd.steps[</span><span style="color:#97CCAE">"chat"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"$return_value"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"original_messages_with_assistant_response"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">2</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"content"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Return data for use in future steps</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> json.</span><span style="color:#EDCC95">loads(content)</span></span></code></pre></figure>
<p>And now, as easy as that, the JSON is formatted and ready to be consumed by the email API.</p>
<p><img alt="" loading="lazy" decoding="async" width="1840" height="1210" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-16-at-10.36.20@2x.BpXXNAi__1ElvKC.webp"></p>
<h2 id="sending-the-email-with-postmark">Sending the email with Postmark</h2>
<p>Let's wrap up this guide by creating our final step: search for <strong>Postmark</strong> and then select <strong>Send Single Email</strong>. <em>Note: you can also choose Send Email With Template if you already have one configured.</em></p>
<p>The next steps are easy: connect to your Postmark account (you will need an <a href="https://account.postmarkapp.com/api_tokens" rel="noopener noreferrer" target="_blank">API token</a> for a server. It's also a good idea to have a dev server where you can experiment before going live). Finally, all required fields were generated in the previous step, with the exception of the <em>"From" email address</em>, which you should select from your <a href="https://account.postmarkapp.com/signature_domains" rel="noopener noreferrer" target="_blank">Sender Signatures</a> in Postmark.</p>
<p><img alt="" loading="lazy" decoding="async" width="1852" height="1422" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-16-at-10.43.00@2x.CbG9O4Dq_ZEmnc0.webp"></p>
<p>Go ahead and test the integration. The email with the custom AI-generated message will be visible in Postmark.</p>
<p><img alt="" loading="lazy" decoding="async" width="2202" height="1772" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-07-16-at-10.45.13@2x.CqhObnL9_2ngYMn.webp"></p>
<h2 id="next-steps">Next steps</h2>
<p>I hope that this guide sparks your creativity. While we barely touched all possible integrations made possible by Pipedream, a few follow-ups include:</p>
<ul>
<li>Use the same principle but do the reverse: <a href="https://pipedream.com/apps/stripe/triggers/new-subscription?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">contact every new subscriber</a> with a custom AI-generated message;</li>
<li><a href="https://pipedream.com/apps/stripe/triggers/canceled-subscription?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Connect with the user whenever a subscription is cancelled</a> offering a deal for them to come back;</li>
<li>If the user phone number is present in the Stripe payment form, <a href="https://pipedream.com/apps/twilio/actions/send-sms?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">send a SMS message using Twilio</a>.</li>
</ul>]]></content:encoded>
</item>
<item>
<title><![CDATA[Creating an out-of-office reminder system]]></title>
<description><![CDATA[Setup a Google Calendar + Slack workflow that notifies your team whenever someone is out-of-office.]]></description>
<link>https://rafaelquintanilha.com/creating-an-out-of-office-reminder-system/</link>
<guid isPermaLink="false">670e7cbad8bba20001d2b66f</guid>
<category><![CDATA[Pipedream]]></category><category><![CDATA[Automation]]></category><category><![CDATA[Python]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Tue, 21 May 2024 14:33:00 GMT</pubDate>

<content:encoded><![CDATA[<p>There are several ways to manage a team. In the modern start-up era, it is not uncommon to see HR departments replacing the old, stricter model, with a "responsible freedom" approach. Netflix popularized the principle of <a href="https://hbr.org/2014/01/how-netflix-reinvented-hr" rel="noopener noreferrer" target="_blank">treating employees as fully-formed adults</a>.</p>
<p>In order to have such autonomy in place, automations can be implemented, ensuring that your team is able to run independently without concealing relevant information from each other.</p>
<p>Consider an out-of-office system where each employee is responsible for picking their days off. Based on Netflix's principles, there is no need to strictly oversee such task, especially if some basic rules are respected (say, you should book your day off at least one week in advance, no more than X people from the team can be off at the same time, etc).</p>
<p>A simple system can be easily implemented with a shared Google Calendar, Slack notifications, and Pipedream as the automation engine. Today, I'll show how you can:</p>
<ol>
<li>Notify your team whenever someone book some time off;</li>
<li>Notify who is out for the day.</li>
</ol>
<p>Let's get started!</p>
<h2 id="notifying-new-entries-in-the-calendar">Notifying new entries in the calendar</h2>
<p>Start by creating a new workflow and searching for <em>Google Calendar</em> as trigger. A few options will show up, but for now let's select <strong>New Event Created.</strong></p>
<p><img alt="" loading="lazy" decoding="async" width="1906" height="1008" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-16.16.08@2x.D2j4gfGu_Z2tcRYx.webp"></p>
<p>You will need to connect your Google Calendar account (select the account which has access to the shared calendar).</p>
<p>Next, choose the frequency Pipedream will check if a new event has been created. Pick what works best for you, but as we are not aiming for real-time here, 15 minutes should be more than enough.</p>
<p>Finally, in <strong>Calendar ID</strong> you will be presented with a dropdown to select which calendar will be monitored. Pick the shared calendar and you are good to go!</p>
<p>After creating the source, you will be prompted to select a listened event in order to test the automation. Go ahead and create a new event in the calendar. Give it a few moments and the event should pop out! Select it and you will be able to inspect all the details.</p>
<p><img alt="" loading="lazy" decoding="async" width="1486" height="1738" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-16.23.42@2x.DCwSUo8u_2hPLsv.webp"></p>
<h3 id="generating-a-slack-message">Generating a Slack message</h3>
<p>The data from the trigger step is all we need to build the notification. In particular, we want to know <em>who</em> is out, <em>when</em> they will be out, and <em>how long</em> until they are out.</p>
<p>Let your creativity guide you through this step. All three values can be generated with a simple Python script – hence connect a new Python step to the trigger and add the following code:</p>
<figure class="code"><figcaption>python</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="python"><code><span class="line"><span style="color:#A1C1E4">from</span><span style="color:#ECEBE8"> datetime </span><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> datetime, timedelta, timezone</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> parse_datetime</span><span style="color:#ECEBE8">(date_str):</span></span>
<span class="line"><span style="color:#A1C1E4">    try</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        dt </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> datetime.</span><span style="color:#EDCC95">fromisoformat(date_str)</span></span>
<span class="line"><span style="color:#A1C1E4">    except</span><span style="color:#A1C1E4"> ValueError</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        dt </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> datetime.</span><span style="color:#EDCC95">fromisoformat(date_str </span><span style="color:#A1C1E4">+</span><span style="color:#97CCAE"> "T00:00:00+00:00"</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> dt.</span><span style="color:#EDCC95">astimezone(timezone.utc)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> count_weekdays</span><span style="color:#ECEBE8">(start_date, end_date):</span></span>
<span class="line"><span style="color:#ECEBE8">    days </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> (end_date </span><span style="color:#A1C1E4">-</span><span style="color:#ECEBE8"> start_date).days</span></span>
<span class="line"><span style="color:#ECEBE8">    weekdays </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 0</span></span>
<span class="line"><span style="color:#ECEBE8">    last_weekday </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> start_date</span></span>
<span class="line"><span style="color:#A1C1E4">    for</span><span style="color:#ECEBE8"> i </span><span style="color:#A1C1E4">in</span><span style="color:#EDCC95"> range(days </span><span style="color:#A1C1E4">+</span><span style="color:#97CCAE"> 1</span><span style="color:#EDCC95">)</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        day </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> start_date </span><span style="color:#A1C1E4">+</span><span style="color:#EDCC95"> timedelta(days</span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95">i)</span></span>
<span class="line"><span style="color:#A1C1E4">        if</span><span style="color:#ECEBE8"> day.</span><span style="color:#EDCC95">weekday()</span><span style="color:#A1C1E4"> &#x3C;</span><span style="color:#97CCAE"> 5</span><span style="color:#ECEBE8">:  </span><span style="color:#A7A49E;font-style:italic"># Monday = 0, Friday = 4</span></span>
<span class="line"><span style="color:#ECEBE8">            weekdays </span><span style="color:#A1C1E4">+=</span><span style="color:#97CCAE"> 1</span></span>
<span class="line"><span style="color:#ECEBE8">            last_weekday </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> day</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> weekdays, last_weekday</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> handler</span><span style="color:#ECEBE8">(pd: </span><span style="color:#97CCAE">"pipedream"</span><span style="color:#ECEBE8">):</span></span>
<span class="line"><span style="color:#ECEBE8">    event </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> pd.steps[</span><span style="color:#97CCAE">"trigger"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"event"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"><span style="color:#ECEBE8">    creator </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> event[</span><span style="color:#97CCAE">"creator"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"email"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">    start </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> event[</span><span style="color:#97CCAE">"start"</span><span style="color:#ECEBE8">].</span><span style="color:#EDCC95">get(</span><span style="color:#97CCAE">"dateTime"</span><span style="color:#EDCC95">, event[</span><span style="color:#97CCAE">"start"</span><span style="color:#EDCC95">].get(</span><span style="color:#97CCAE">"date"</span><span style="color:#EDCC95">))</span></span>
<span class="line"><span style="color:#ECEBE8">    end </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> event[</span><span style="color:#97CCAE">"end"</span><span style="color:#ECEBE8">].</span><span style="color:#EDCC95">get(</span><span style="color:#97CCAE">"dateTime"</span><span style="color:#EDCC95">, event[</span><span style="color:#97CCAE">"end"</span><span style="color:#EDCC95">].get(</span><span style="color:#97CCAE">"date"</span><span style="color:#EDCC95">))</span></span>
<span class="line"><span style="color:#ECEBE8">    start_dt </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> parse_datetime(start)</span></span>
<span class="line"><span style="color:#ECEBE8">    end_dt </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> parse_datetime(end)</span></span>
<span class="line"><span style="color:#ECEBE8">    now </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> datetime.</span><span style="color:#EDCC95">now(timezone.utc)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">    duration_days, last_weekday </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> count_weekdays(start_dt.date(), end_dt.date() </span><span style="color:#A1C1E4">-</span><span style="color:#EDCC95"> timedelta(days</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">1</span><span style="color:#EDCC95">))</span></span>
<span class="line"><span style="color:#ECEBE8">    days_until </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> (start_dt.</span><span style="color:#EDCC95">date()</span><span style="color:#A1C1E4"> -</span><span style="color:#ECEBE8"> now.</span><span style="color:#EDCC95">date()</span><span style="color:#ECEBE8">).days</span></span>
<span class="line"><span style="color:#ECEBE8">    start_date_formatted </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> start_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%A, %B %d'</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#ECEBE8">    last_weekday_formatted </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> last_weekday.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%A, %B %d'</span><span style="color:#EDCC95">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> days_until </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> 0</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        time_phrase </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "Today"</span></span>
<span class="line"><span style="color:#A1C1E4">    elif</span><span style="color:#ECEBE8"> days_until </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> 1</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        time_phrase </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "Tomorrow"</span></span>
<span class="line"><span style="color:#A1C1E4">    else</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        time_phrase </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"In </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">days_until</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> days"</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#97CCAE"> "dateTime"</span><span style="color:#A1C1E4"> in</span><span style="color:#ECEBE8"> event[</span><span style="color:#97CCAE">"start"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">and</span><span style="color:#ECEBE8"> start_dt.</span><span style="color:#EDCC95">date()</span><span style="color:#A1C1E4"> ==</span><span style="color:#ECEBE8"> end_dt.</span><span style="color:#EDCC95">date()</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">        # Case 1: The creator is out only for some hours within the same day</span></span>
<span class="line"><span style="color:#A1C1E4">        if</span><span style="color:#ECEBE8"> days_until </span><span style="color:#A1C1E4">&#x3C;=</span><span style="color:#97CCAE"> 1</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">            slack_message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">time_phrase</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">, </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">creator</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> will be out of the office from </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">start_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%H:%M'</span><span style="color:#EDCC95">)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> UTC to </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">end_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%H:%M'</span><span style="color:#EDCC95">)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> UTC."</span></span>
<span class="line"><span style="color:#A1C1E4">        else</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">            slack_message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">time_phrase</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">, </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">creator</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> will be out of the office on </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">start_date_formatted</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> from </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">start_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%H:%M'</span><span style="color:#EDCC95">)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> UTC to </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">end_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%H:%M'</span><span style="color:#EDCC95">)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> UTC."</span></span>
<span class="line"><span style="color:#ECEBE8">        event_type </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "only during the day"</span></span>
<span class="line"><span style="color:#ECEBE8">        duration </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 1</span></span>
<span class="line"><span style="color:#A1C1E4">    elif</span><span style="color:#97CCAE"> "dateTime"</span><span style="color:#A1C1E4"> not</span><span style="color:#A1C1E4"> in</span><span style="color:#ECEBE8"> event[</span><span style="color:#97CCAE">"start"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">and</span><span style="color:#ECEBE8"> start_dt.</span><span style="color:#EDCC95">date()</span><span style="color:#A1C1E4"> ==</span><span style="color:#ECEBE8"> end_dt.</span><span style="color:#EDCC95">date()</span><span style="color:#A1C1E4"> -</span><span style="color:#EDCC95"> timedelta(days</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">1</span><span style="color:#EDCC95">)</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">        # Case 2: The creator is out for a single full day</span></span>
<span class="line"><span style="color:#ECEBE8">        slack_message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">time_phrase</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">, </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">creator</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> will be out of the office."</span></span>
<span class="line"><span style="color:#ECEBE8">        event_type </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "only during the day"</span></span>
<span class="line"><span style="color:#ECEBE8">        duration </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 1</span></span>
<span class="line"><span style="color:#A1C1E4">    else</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">        # Case 3: The creator is out for more than one day</span></span>
<span class="line"><span style="color:#A1C1E4">        if</span><span style="color:#97CCAE"> "dateTime"</span><span style="color:#A1C1E4"> in</span><span style="color:#ECEBE8"> event[</span><span style="color:#97CCAE">"start"</span><span style="color:#ECEBE8">]:</span></span>
<span class="line"><span style="color:#ECEBE8">            slack_message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">time_phrase</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">, </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">creator</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> will be out of the office from </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">start_date_formatted</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> at </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">start_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%H:%M'</span><span style="color:#EDCC95">)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> UTC to </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">last_weekday_formatted</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> at </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">end_dt.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">'%H:%M'</span><span style="color:#EDCC95">)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> UTC (</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">duration_days</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> days)."</span></span>
<span class="line"><span style="color:#A1C1E4">        else</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">            slack_message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">time_phrase</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">, </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">creator</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> will be out of the office from </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">start_date_formatted</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> to </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">last_weekday_formatted</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> (</span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">duration_days</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> days)."</span></span>
<span class="line"><span style="color:#ECEBE8">        event_type </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "more than one day"</span></span>
<span class="line"><span style="color:#ECEBE8">        duration </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> duration_days</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">    output </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#97CCAE">        "creator"</span><span style="color:#ECEBE8">: creator,</span></span>
<span class="line"><span style="color:#97CCAE">        "start"</span><span style="color:#ECEBE8">: start,</span></span>
<span class="line"><span style="color:#97CCAE">        "end"</span><span style="color:#ECEBE8">: end,</span></span>
<span class="line"><span style="color:#97CCAE">        "duration"</span><span style="color:#ECEBE8">: duration,</span></span>
<span class="line"><span style="color:#97CCAE">        "days_until"</span><span style="color:#ECEBE8">: days_until,</span></span>
<span class="line"><span style="color:#97CCAE">        "event_type"</span><span style="color:#ECEBE8">: event_type,</span></span>
<span class="line"><span style="color:#97CCAE">        "slack_message"</span><span style="color:#ECEBE8">: slack_message</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> output</span></span></code></pre></figure>
<p>Although the code is slightly big, there is nothing complicated going on. We are basically just formatting the message in a friendly manner so we highlight if the event is near. For example, we say <em>"Today, <a href="mailto:john@company.com">john@company.com</a> is out of the office"</em>, or <em>"Tomorrow, <a href="mailto:jane@company.com">jane@company.com</a> is out of the office"</em>. If the event is farther away, the output is <em>"In X days, <a href="mailto:mary@company.com">mary@company.com</a> will be out of the office"</em>.</p>
<p>The script also handles the cases when the person will be out for only part of the day, and when they will be out for many days in a row. Take some time to read through the code and make sure to adjust the wording to your needs!</p>
<h3 id="sending-the-slack-message">Sending the Slack message</h3>
<p>The Python step conveniently returns a dictionary with relevant values allowing for a finer control of the next steps. For now, let's simply add a new step, search for <em>Slack</em>, click on <strong>Send Message to a Public Channel,</strong> connect your Slack Account, select the Channel ID and add the message generated in the previous step.</p>
<p><img alt="" loading="lazy" decoding="async" width="1862" height="1040" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-17.43.27@2x.BMRNLB-t_1E3mjv.webp"></p>
<p>And that's it! Publish your workflow, create a new event in the shared calendar and in up to 15 minutes you will see the notification in Slack.</p>
<p>There are many enhancements to be made. For example, the <code>days_until</code> variable returned by the Python step can be used to conditionally trigger a new workflow. Suppose you have a hard rule that no time off can be booked with less than 5 days in advance. Then you can leverage the <strong>Continue based on condition</strong> step to send a warning, or even to delete the event from the calendar.</p>
<h2 id="listing-everyone-out-for-the-day">Listing everyone out for the day</h2>
<p>Notifying when someone book time off is progress, but it's not uncommon that a long-planned trip will be forgotten by the time it takes place (suppose you book a week off with two months in advance. When it's finally time, nobody will remember you are out).</p>
<p>Let's build another workflow, this time triggered at a fixed time on workdays. It will list all events in the calendar for that day and send a Slack message informing who is out. You can set it to run at the beginning of the day, so by the time your team show up to work there is a message letting them know who is unavailable.</p>
<h3 id="triggering-the-workflow">Triggering the workflow</h3>
<p>Start by creating a new workflow and selecting <strong>Custom Interval</strong> as trigger. Next, select the time that better suits your team schedule.</p>
<p><img alt="" loading="lazy" decoding="async" width="1852" height="788" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-17.58.05@2x.jxxNn9w__1UEqdt.webp"></p>
<p>In <em>Results</em> you can see the output, in particular the exact timestamp of when the workflow was triggered – this will be useful to restrict the search within Google Calendar's API.</p>
<h3 id="generating-the-boundaries">Generating the boundaries</h3>
<p>We don't want to list <em>all</em> events in the calendar, just the ones for that day. For example, if the event triggered on 2024-04-26T09:00:00+00, we want to list entries between 2024-04-26 and 2024-04-27 (we'll talk about timezones in a moment).</p>
<p>Let's use a Python script to get those values. Hook up a new step to the trigger and add the following code:</p>
<figure class="code"><figcaption>python</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="python"><code><span class="line"><span style="color:#A1C1E4">from</span><span style="color:#ECEBE8"> datetime </span><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> datetime, timedelta, timezone</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> handler</span><span style="color:#ECEBE8">(pd: </span><span style="color:#97CCAE">"pipedream"</span><span style="color:#ECEBE8">):</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Get the timestamp from the trigger event</span></span>
<span class="line"><span style="color:#ECEBE8">    timestamp </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> pd.steps[</span><span style="color:#97CCAE">"trigger"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"event"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"timezone_configured"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"iso8601"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"timestamp"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Parse the timestamp into a datetime object</span></span>
<span class="line"><span style="color:#ECEBE8">    dt </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> datetime.</span><span style="color:#EDCC95">fromisoformat(timestamp)</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Convert the datetime to GMT (UTC)</span></span>
<span class="line"><span style="color:#ECEBE8">    dt_gmt </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> dt.</span><span style="color:#EDCC95">astimezone(timezone.utc)</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Get the current day at midnight GMT</span></span>
<span class="line"><span style="color:#ECEBE8">    min_time </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> dt_gmt.</span><span style="color:#EDCC95">replace(hour</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">0</span><span style="color:#EDCC95">, minute</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">0</span><span style="color:#EDCC95">, second</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">0</span><span style="color:#EDCC95">, microsecond</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">0</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Get the next day at midnight GMT</span></span>
<span class="line"><span style="color:#ECEBE8">    max_time </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> min_time </span><span style="color:#A1C1E4">+</span><span style="color:#EDCC95"> timedelta(days</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">1</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Format the min_time and max_time as ISO 8601 strings</span></span>
<span class="line"><span style="color:#ECEBE8">    min_time_str </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> min_time.</span><span style="color:#EDCC95">isoformat()</span></span>
<span class="line"><span style="color:#ECEBE8">    max_time_str </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> max_time.</span><span style="color:#EDCC95">isoformat()</span></span>
<span class="line"><span style="color:#ECEBE8">    </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Return the dictionary with min_time and max_time</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#97CCAE">        "min_time"</span><span style="color:#ECEBE8">: min_time_str,</span></span>
<span class="line"><span style="color:#97CCAE">        "max_time"</span><span style="color:#ECEBE8">: max_time_str</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span></code></pre></figure>
<p>The code is simply getting the timestamp of the triggered event, converting it to UTC, setting it to midnight (lower boundary) and then adding 1 day to it (upper boundary).</p>
<h3 id="listing-all-events">Listing all events</h3>
<p>Add a new step and, as before, search for <em>Google Calendar.</em> This time, however, select <strong>List events</strong>.</p>
<p><img alt="" loading="lazy" decoding="async" width="1850" height="1424" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-18.07.16@2x.DPCWlPwS_Z1N4ftP.webp"></p>
<p>Note that the values returned in the previous step are used as <strong>Min time</strong> and <strong>Max time</strong>, and that the <strong>Time Zone</strong> matches the one used during the data transformation.</p>
<p>Click to test and, if there is any event for the current day in the calendar, you will be able to see it.</p>
<p><img alt="" loading="lazy" decoding="async" width="1852" height="1214" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-18.12.27@2x.D88d58Bj_2qgJDC.webp"></p>
<h3 id="generating-the-slack-message">Generating the Slack message</h3>
<p>Let's use the same principle of the first example and use another Python script to generate a Slack message. Add a new step, select <strong>Python</strong> and add the following code:</p>
<figure class="code"><figcaption>python</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="python"><code><span class="line"><span style="color:#A1C1E4">def</span><span style="color:#EDCC95"> handler</span><span style="color:#ECEBE8">(pd: </span><span style="color:#97CCAE">"pipedream"</span><span style="color:#ECEBE8">):</span></span>
<span class="line"><span style="color:#ECEBE8">    events </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> pd.steps[</span><span style="color:#97CCAE">"list_events"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"$return_value"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"items"</span><span style="color:#ECEBE8">]</span></span>
<span class="line"><span style="color:#ECEBE8">    people_off </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> [event[</span><span style="color:#97CCAE">"creator"</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">"email"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">for</span><span style="color:#ECEBE8"> event </span><span style="color:#A1C1E4">in</span><span style="color:#ECEBE8"> events]</span></span>
<span class="line"><span style="color:#ECEBE8">    num_people_off </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> len(people_off)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> num_people_off </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> 0</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        message </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "Good morning! No one is out today."</span></span>
<span class="line"><span style="color:#A1C1E4">    elif</span><span style="color:#ECEBE8"> num_people_off </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> 1</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"Good morning! Today </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">people_off[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">]</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> is out."</span></span>
<span class="line"><span style="color:#A1C1E4">    elif</span><span style="color:#ECEBE8"> num_people_off </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> 2</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"Good morning! Today </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">people_off[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">]</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> and </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">people_off[</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">]</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> are out."</span></span>
<span class="line"><span style="color:#A1C1E4">    else</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">        message </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> f</span><span style="color:#97CCAE">"Good morning! Today </span><span style="color:#97CCAE">{</span><span style="color:#97CCAE">', '</span><span style="color:#ECEBE8">.</span><span style="color:#EDCC95">join(people_off[:</span><span style="color:#A1C1E4">-</span><span style="color:#97CCAE">1</span><span style="color:#EDCC95">])</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">, and </span><span style="color:#97CCAE">{</span><span style="color:#ECEBE8">people_off[</span><span style="color:#A1C1E4">-</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">]</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE"> are out."</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> {</span><span style="color:#97CCAE">"num_people_off"</span><span style="color:#ECEBE8">: num_people_off, </span><span style="color:#97CCAE">"message"</span><span style="color:#ECEBE8">: message}</span></span></code></pre></figure>
<p>This short script is all you need to generate a helpful message to your teammates!</p>
<h3 id="conditionally-sending-a-slack-notification">Conditionally sending a Slack notification</h3>
<p>Finally, let's notify the team, but only if there is people off. Fortunately, the <code>num_people_off</code> return value can be used for it.</p>
<p>Select the option <strong>Continue based on condition</strong> for the next step and configure it like this:</p>
<p><img alt="" loading="lazy" decoding="async" width="1864" height="908" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-18.16.35@2x.D7WNJsIO_GuQ8v.webp"></p>
<p>Now, any subsequent step will <em>only</em> run if the condition is met. That's exactly what we need, and the final act is to send another message to a public channel.</p>
<p><img alt="" loading="lazy" decoding="async" width="1858" height="956" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-18.17.41@2x.TDT88Ese_Z1nicMx.webp"></p>
<p>And that's it! Test the workflow and you should receive a message like this:</p>
<p><img alt="" loading="lazy" decoding="async" width="1188" height="668" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-04-26-at-18.21.18@2x.QgZNXHgc_27AXru.webp"></p>
<p>There are <a href="https://pipedream.com/apps?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">several other calendar apps</a> that can be integrated using Pipedream. They are just a few clicks away from powering your automated workflows.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Classifying bug reports with ChatGPT]]></title>
<description><![CDATA[Integrate Airtable + ChatGPT + Slack using the power of Pipedream.]]></description>
<link>https://rafaelquintanilha.com/classifying-bug-reports-with-chatgpt/</link>
<guid isPermaLink="false">670e7b27d8bba20001d2b65b</guid>
<category><![CDATA[ChatGPT]]></category><category><![CDATA[Automation]]></category><category><![CDATA[Pipedream]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Thu, 28 Mar 2024 14:26:00 GMT</pubDate>

<content:encoded><![CDATA[<p>There is nothing dreaded more by programmers than bugs. Well, actually it's probably either <a href="https://martinfowler.com/bliki/TwoHardThings.html" rel="noopener noreferrer" target="_blank">naming things or cache invalidation</a>, but you see my point. Bugs show up at unwelcome times, perhaps when you are deep on a totally different problem.</p>
<p>If not properly handled, bugs can slow down an engineering team considerably. Context switching is expensive for any cognitive task. If you code, you know what I'm talking about. And if you haven't, then listen to Elon Musk.</p>
<figure class="embed embed-twitter" data-url="https://platform.twitter.com/embed/Tweet.html?creatorScreenName=webquintanilha&#x26;dnt=false&#x26;embedId=twitter-widget-0&#x26;features=eyJ0ZndfdGltZWxpbmVfbGlzdCI6eyJidWNrZXQiOltdLCJ2ZXJzaW9uIjpudWxsfSwidGZ3X2ZvbGxvd2VyX2NvdW50X3N1bnNldCI6eyJidWNrZXQiOnRydWUsInZlcnNpb24iOm51bGx9LCJ0ZndfdHdlZXRfZWRpdF9iYWNrZW5kIjp7ImJ1Y2tldCI6Im9uIiwidmVyc2lvbiI6bnVsbH0sInRmd19yZWZzcmNfc2Vzc2lvbiI6eyJidWNrZXQiOiJvbiIsInZlcnNpb24iOm51bGx9LCJ0ZndfZm9zbnJfc29mdF9pbnRlcnZlbnRpb25zX2VuYWJsZWQiOnsiYnVja2V0Ijoib24iLCJ2ZXJzaW9uIjpudWxsfSwidGZ3X21peGVkX21lZGlhXzE1ODk3Ijp7ImJ1Y2tldCI6InRyZWF0bWVudCIsInZlcnNpb24iOm51bGx9LCJ0ZndfZXhwZXJpbWVudHNfY29va2llX2V4cGlyYXRpb24iOnsiYnVja2V0IjoxMjA5NjAwLCJ2ZXJzaW9uIjpudWxsfSwidGZ3X3Nob3dfYmlyZHdhdGNoX3Bpdm90c19lbmFibGVkIjp7ImJ1Y2tldCI6Im9uIiwidmVyc2lvbiI6bnVsbH0sInRmd19kdXBsaWNhdGVfc2NyaWJlc190b19zZXR0aW5ncyI6eyJidWNrZXQiOiJvbiIsInZlcnNpb24iOm51bGx9LCJ0ZndfdXNlX3Byb2ZpbGVfaW1hZ2Vfc2hhcGVfZW5hYmxlZCI6eyJidWNrZXQiOiJvbiIsInZlcnNpb24iOm51bGx9LCJ0ZndfdmlkZW9faGxzX2R5bmFtaWNfbWFuaWZlc3RzXzE1MDgyIjp7ImJ1Y2tldCI6InRydWVfYml0cmF0ZSIsInZlcnNpb24iOm51bGx9LCJ0ZndfbGVnYWN5X3RpbWVsaW5lX3N1bnNldCI6eyJidWNrZXQiOnRydWUsInZlcnNpb24iOm51bGx9LCJ0ZndfdHdlZXRfZWRpdF9mcm9udGVuZCI6eyJidWNrZXQiOiJvbiIsInZlcnNpb24iOm51bGx9fQ%3D%3D&#x26;frame=false&#x26;hideCard=false&#x26;hideThread=false&#x26;id=1728213431201792492&#x26;lang=en&#x26;origin=https%3A%2F%2Fpipedream.com%2Fblog%2Fclassifying-bug-reports-with-chatgpt%2F&#x26;sessionId=d1d5a63c61277d4529493336dc9b58cbee19c41c&#x26;siteScreenName=pipedream&#x26;theme=light&#x26;widgetsVersion=2615f7e52b7e0%3A1702314776716&#x26;width=550px">
<blockquote class="twitter-tweet"><a href="https://twitter.com/i/status/1728213431201792492" rel="noopener noreferrer" target="_blank">https://twitter.com/i/status/1728213431201792492</a></blockquote>
</figure>
<p>So there are two problems to reconcile: 1) context switching kills developer productivity, but 2) bugs happen. How can we deal with this reality?</p>
<p>One way to tackle this is by enforcing proper prioritization. This is certainly easier said than done, but modern tooling and Pipedream can help.</p>
<p>In this post, we'll create an automated workflow that will:</p>
<ol>
<li>Trigger on new bug reports</li>
<li>Use ChatGPT to classify the report based on the user description</li>
<li>Update the priority accordingly</li>
<li>Send a Slack notification <em>if and only if</em> the bug is deemed as <strong>Urgent</strong>.</li>
</ol>
<p>That's a lot of unpack, so let's get started!</p>
<h3 id="configuring-airtable">Configuring Airtable</h3>
<p>For this example we'll use Airtable as our database. Airtable lets us create public forms, shareable with anyone on the Internet. It also provides its own automation framework, which we'll use to trigger the <a href="https://pipedream.com/new?h=tch_1AfMbY&#x26;via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Pipedream workflow</a>.</p>
<p>Start by creating a new base and a table inside it. I chose the fields <em>Title, Description, Name, Email</em> and <em>Priority</em>. <em>Priority</em> will be a <a href="https://support.airtable.com/docs/single-select-field" rel="noopener noreferrer" target="_blank">Single Select</a> field, holding a set of values that we'll pass to ChatGPT as the options for the classification.</p>
<p><img alt="" loading="lazy" decoding="async" width="3024" height="1868" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-23-at-15.17.38@2x-2.Be2tRW58_Z89MsU.webp"></p>
<p>Now, there are two possible approaches for adding new records.</p>
<p>First, you can add a custom <a href="https://support.airtable.com/docs/button-field" rel="noopener noreferrer" target="_blank">Button</a> to the table (see our post on how to <a href="https://pipedream.com/blog/sharp-js-compatibility/?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Slice and dice images with Sharp.js</a>). Here, Airtable sends an HTTP <code>GET</code> request to a Pipedream-generated URL, passing the record ID as query parameter. While it works beautifully, this means the workflow can be triggered only from <em>within</em> Airtable. In this post, we want to allow <em>anyone</em> to submit a report, e.g. a user affected by the bug.</p>
<p>You can also create a <a href="https://support.airtable.com/docs/building-and-sharing-forms-in-airtable" rel="noopener noreferrer" target="_blank">Form</a>. This can be shared publicly, sending an event when any user submits a bug.</p>
<p><a href="https://support.airtable.com/docs/building-and-sharing-forms-in-airtable" rel="noopener noreferrer" target="_blank">Create a form in Airtable</a> and adjust it to your use case. Don't forget to hide the <em>Priority</em> field, as it will be filled by the AI. You should end up with something like this:</p>
<p><img alt="" loading="lazy" decoding="async" width="2000" height="1204" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-23-at-18.04.30@2x.HKqJzxxK_Z1ujQF8.webp"></p>
<p>Great, now we have a working form storing bug reports. Now, let's configure our trigger.</p>
<h3 id="triggering-the-workflow">Triggering the workflow</h3>
<p>We want form submissions to trigger our workflow. To do that, we need to configure a <em>webhook</em>.</p>
<p>In Pipedream, create a new workflow and select <strong>HTTP / Webhook > HTTP Requests with a Body</strong>. Data from the form sent by Airtable will be available in the body of the HTTP request in Pipedream. You don't need to change anything in the configuration — clicking <strong>Save and continue</strong> and you'll receive a URL like <a href="https://eoqb6ojri6uulck.m.pipedream.net/" rel="noopener noreferrer" target="_blank">https://eoabc123def456.m.pipedream.net</a>.</p>
<p>Head back to Airtable and create a new automation. Similar to Pipedream, Airtable also requires a trigger, which here will be <strong>When a form is submitted</strong>. Next, select the table and the recently-created form.</p>
<p>The next step is the only coding necessary in this tutorial. Click on <strong>Add advanced logic or action > Run script</strong>. On the panel on the left, click on <strong>Add input variable</strong> and name and select all fields submitted via the form. Don't forget to also add the <em>Airtable record ID</em>, once it will be needed later.</p>
<p>Add the following in the code editor, replacing the content of <code>WEBHOOK_URL</code> with the URL provided before:</p>
<figure class="code"><figcaption>javascript</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="javascript"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> WEBHOOK_URL </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 'https://your-endpoint.m.pipedream.net'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">fetch</span><span style="color:#ECEBE8">(WEBHOOK_URL, {</span></span>
<span class="line"><span style="color:#ECEBE8">  method: </span><span style="color:#97CCAE">'POST'</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">  headers: {</span></span>
<span class="line"><span style="color:#97CCAE">    'Content-Type'</span><span style="color:#ECEBE8">: </span><span style="color:#97CCAE">'application/json'</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">  },</span></span>
<span class="line"><span style="color:#ECEBE8">  body: </span><span style="color:#EDCC95">JSON.stringify</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">input.config</span><span style="color:#ECEBE8">()),</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>Great! You can click on <strong>Test action</strong>, and, if a record has been previously selected, you'll receive its content in Pipedream.</p>
<p><img alt="" loading="lazy" decoding="async" width="1864" height="1366" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-23-at-18.23.32@2x.DNh_RTXA_Z1LQtK4.webp"></p>
<p>Let's recap what we did so far.</p>
<ol>
<li>We created a Pipedream workflow whose trigger is a webhook which provides a unique URL;</li>
<li>We created a form in Airtable that inserts records into a table called <em>Bug Reports;</em></li>
<li>We added an <em>Airtable automation</em> triggered on form submissions;</li>
<li>This automation runs a script that sends a <code>POST</code> request along with the submitted data to the webhook URL generated in step 1.</li>
</ol>
<p><img alt="" loading="lazy" decoding="async" width="1548" height="1055" src="https://rafaelquintanilha.com/_astro/image-1.C5PNpbn4_20D17T.webp"></p>
<h3 id="classifying-the-priority-of-the-bug">Classifying the priority of the bug</h3>
<p>Now we're ready to classify the priority of the bug. Let's remember the goal: we want to classify the content of the bug report and notify the developers only when OpenAI detects urgency.</p>
<p>Back in Pipedream, create a new step in your workflow and select the <strong>OpenAI (ChatGPT)</strong> app. Conveniently, Pipedream has an action to <strong>Classify Items into Categories</strong>, which will work for simple classification use cases. Here, we'll use the <strong>Chat</strong> action instead; this gives us more control over the API request, which is key here.</p>
<p>If you don't have one, you'll need an <a href="https://platform.openai.com/api-keys" rel="noopener noreferrer" target="_blank">OpenAI API key</a>. In Pipedream, click the button to add a new <strong>OpenAI (ChatGPT)</strong> account and add the API key there.</p>
<p>Next, select the <em>Model</em> you want to use for classifications. If bug reports are not <em>so</em> frequent in your application, then we recommend choosing <code>gpt-4-turbo-preview</code>, the most-accurate model for classifications as of this post.</p>
<p>In the <em>User Message</em> field, pick the <code>description</code> sent in the body of the request.</p>
<p>Finally, we'll set the <em>System Instructions</em>. System instructions guide how the AI answers prompts. Add the following:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>Your tasks is to receive a bug report from a user and classify into ONE of the following categories:</span></span>
<span class="line"><span></span></span>
<span class="line"><span>Urgent</span></span>
<span class="line"><span>High</span></span>
<span class="line"><span>Medium</span></span>
<span class="line"><span>Low</span></span>
<span class="line"><span></span></span>
<span class="line"><span>You should ONLY output the chosen category, and nothing else.</span></span>
<span class="line"><span></span></span>
<span class="line"><span>Notice that an "Urgent" report is anything that prevents users from:</span></span>
<span class="line"><span>- Accessing their account;</span></span>
<span class="line"><span>- Paying, subscribing, or generally taking revenue-impacting actions.</span></span>
<span class="line"><span></span></span>
<span class="line"><span>This is the description of the bug reported by the user:</span></span></code></pre></figure>
<p>Notice that the categories provided match the priorities expected in Airtable. The instruction explicitly asks the model to return the category and <em>only</em> the category. We also give examples of urgent requests in order to nudge the AI to our specific use-case. Feel free to adjust the instructions with examples pertinent to your application.</p>
<p><em>Note: the pre-made Classify Items into Categories will instruct the LLM to output a JSON, which is very convenient when parsing the output in a code context, but not necessary here.</em></p>
<p>Because of the stochastic character of any AI, we cannot guarantee it will always return one of the 4 categories, though more powerful models are significantly better at adhering to the prompt. There's an extra trick we can do, too. The <a href="https://platform.openai.com/tokenizer" rel="noopener noreferrer" target="_blank">Tokenizer</a> app allows us to simulate how many tokens a given text is expected to yield. It happens that <em>Urgent</em> takes 3 tokens, while all other categories are successfully encoded with a single one. Hence, we can <em>limit</em> the maximum number of tokens allowed in the completion.</p>
<p>Finally, adjust <strong>Temperature</strong> to 0 (we want as little randomness as possible in the outcome) and <strong>N</strong> to 1, and the step is complete.</p>
<p><img alt="" loading="lazy" decoding="async" width="1264" height="1636" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-23-at-19.20.28@2x.BzPjv24S_1cW1yD.webp"></p>
<p>Click on <strong>Test</strong> to run the step, and if all is well, you should see the category selected by the LLM.</p>
<p><img alt="" loading="lazy" decoding="async" width="1776" height="1412" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-23-at-19.24.35@2x.DLF9S18j_ZXONXA.webp"></p>
<h3 id="updating-the-airtable-record">Updating the Airtable record</h3>
<p>Now that the classifier works, let's update the record in Airtable.</p>
<p>Add a new step to the workflow, search for "<em>airtable</em>", and select the <strong>Airtable (OAuth)</strong> app. Click the <strong>Update Record</strong> action. The configuration is straightforward – connect your account and select your <em>Base</em> and <em>Table</em>.</p>
<p>For <em>Record ID</em>, we will need the <code>id</code> from the trigger step. The field we want to update is <em>Priority,</em> and the content is the generated message from the previous step.</p>
<p>The <em>update_record</em> step should look like this:</p>
<p><img alt="" loading="lazy" decoding="async" width="1868" height="1392" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-25-at-09.00.05@2x.DawIrEZa_1K6d6J.webp"></p>
<h3 id="conditionally-send-slack-message">Conditionally send Slack message</h3>
<p>Finally, we'll send a message to Slack. Recall that we want to send notifications <em>only if</em> on <em>Urgent</em> issues. Luckily, Pipedream makes this process a breeze by providing a <strong>Continue based on condition</strong> step: the workflow will only continue if the configured condition is met, else it ends.</p>
<p>You'll need to configure three fields: <em>Initial value, Condition,</em> and <em>Second value.</em></p>
<p>For <em>Initial value</em>, select the same output used when updating Airtable – this will be the category. The <em>Second value</em> is the target priority, i.e., <em>Urgent</em>. Finally, select <em>TEXT_EQUALS</em> as the condition. In order to prevent unnecessary misclassifications, make sure <em>Case sensitive</em> is False as well.</p>
<p><img alt="" loading="lazy" decoding="async" width="1864" height="1140" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-25-at-09.13.21@2x.2xVJJon4_1CXYCh.webp"></p>
<p>Now the workflow will only continue if the AI classifies the report exactly as <em>Urgent</em> (case insensitive). Let's wrap this tutorial up by creating the final step: <strong>Slack > Send Message to a Public Channel</strong>. Connect your account, select the <em>Channel ID</em> from the list, and use the data sent from Airtable to craft a message to your beloved developers.</p>
<p><img alt="" loading="lazy" decoding="async" width="1396" height="698" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-25-at-09.17.50@2x.DDhnoAFz_9wdME.webp"></p>
<p>And that's it! Deploy the Pipedream workflow and don't forget to turn on the Airtable automation. Open the publicly-shareable Airtable form and submit a desperate request in order to receive the notification.</p>
<h3 id="next-steps">Next steps</h3>
<p>A great enhancement to this workflow is to send an automatic email to the user, letting them know that the report has been received.</p>
<p>Pipedream has a convenient <a href="https://pipedream.com/apps/gmail?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Gmail integration</a> that can be used for this purpose. For a more custom experience, you can leverage the <a href="https://pipedream.com/apps/postmark/actions/send-email-with-template?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Postmark</a> integration (my go-to platform for sending templated emails).</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to Scrape Twitter with Puppeteer]]></title>
<description><![CDATA[Learn how to use Puppeteer to crawl tweets without using the official API.]]></description>
<link>https://rafaelquintanilha.com/counting-presidential-tweets/</link>
<guid isPermaLink="false">6370409a42a473003d9dc97c</guid>
<category><![CDATA[Data Science]]></category><category><![CDATA[Web Scraping]]></category><category><![CDATA[Automation]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Tue, 07 May 2019 03:00:00 GMT</pubDate>

<content:encoded><![CDATA[<p>Brazilian president Jair Bolsonaro is very active on social media, specifically, <a href="https://twitter.com/jairbolsonaro" rel="noopener noreferrer" target="_blank">Twitter</a>. This behavior, which has been disrupting "traditional media", is controversial at least. It is also debatable if the president himself is the owner of the account or if <a href="https://twitter.com/carlosbolsonaro" rel="noopener noreferrer" target="_blank">his son</a>, who adopts a more aggressive style, has been tweeting.</p>
<p>This big dilemma (contains irony) caught the attention of a <a href="https://veja.abril.com.br/blog/radar/mais-de-90-dos-tweets-de-bolsonaro-vieram-de-celular-igual-o-de-carlos/" rel="noopener noreferrer" target="_blank">college professor who allegedly counted 6.452 tweets</a>, discovered that most of them were from an iPhone and Sherlock Holmes-style declared that Bolsonaro's son (who apparently owns an iPhone) must be the one piloting the account (it is said that the president owns a Samsumg, even though he has been seen with an Apple device several times).</p>
<p>This big puzzle (contains irony) sparked an idea -- can one count tweets in an efficient manner? It is unclear how the professor did it (most likely a poor undergrad was given this noble task), but I like to think that I am saving humans' time (computers serve this purpose, after all).</p>
<p>In my Twitter account I gave a sneak peek of what we are going to see in this post:</p>
<figure class="embed embed-twitter" data-url="https://twitter.com/webquintanilha/status/1125404654647631873">
<blockquote class="twitter-tweet"><p lang="en" dir="ltr">COUNTING PRESIDENTIAL TWEETS 🤖<br><br>A college professor decided to analyze which medium the Brazilian president <a href="https://twitter.com/jairbolsonaro" rel="noopener noreferrer" target="_blank">@jairbolsonaro</a> (who happens to be very active) tweets. How he did that is unclear, but made me think -- can we automate that? <br><br>Thread 👇<a href="https://twitter.com/hashtag/puppeteer?src=hash&#x26;ref_src=twsrc%5Etfw" rel="noopener noreferrer" target="_blank">#puppeteer</a> <a href="https://twitter.com/nodejs" rel="noopener noreferrer" target="_blank">@nodejs</a></p>— Rafael Quintanilha (@webquintanilha) <a href="https://twitter.com/webquintanilha/status/1125404654647631873" rel="noopener noreferrer" target="_blank">May 6, 2019</a></blockquote>
</figure>
<p>So now it is time to elaborate.</p>
<h2 id="opening-the-toolbox">Opening the Toolbox</h2>
<p>In order to scrape the tweets, I used <a href="https://github.com/GoogleChrome/puppeteer" rel="noopener noreferrer" target="_blank">puppeteer</a>, which is an awesome headless solution powered by the Google Chrome folks.</p>
<p>Puppeteer is a Node library, so make sure you have Node installed on your machine. Also notice that all code related to this tutorial is <a href="https://github.com/rafaelquintanilha/automation/blob/master/tweetCounter.js" rel="noopener noreferrer" target="_blank">available on GitHub</a>.</p>
<h2 id="the-plan">The Plan</h2>
<p>Before starting to get technical, let us establish a baseline plan for our end goal. We want to:</p>
<ol>
<li>Navigate to the target account (in our case, <a href="https://twitter.com" rel="noopener noreferrer" target="_blank">@jairbolsonaro</a>).</li>
<li>Open the most recent tweet.</li>
<li>Scrape the medium used to tweet (e.g. <em>Twitter for iPhone</em>, <em>Twitter for Android</em>, etc).</li>
<li>Go back and open the next tweet.</li>
<li>Repeat 3 and 4 until we analyze all tweets.</li>
</ol>
<p>It is simple but has some gotchas. As we are going to see, Twitter does its best to prevent us to spam its server (and you can get rate-limited) and also try to efficiently load tweets, so only a handful of tweets are "visible" at a single time (i.e. in order to prevent overloading your browser, if you keep scrolling down the top tweets are replaced).</p>
<p>Finished with the preamble, let's finally get our hands around some code.</p>
<h2 id="first-steps">First Steps</h2>
<p>Setup puppeteer is as easy as:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>(async () => {</span></span>
<span class="line"><span>  const browser = await puppeteer.launch({ headless: false });</span></span>
<span class="line"><span>  const page = await browser.newPage();</span></span>
<span class="line"><span>  page.on('console', consoleObj => console.log(consoleObj.text()));</span></span>
<span class="line"><span>  await page.setViewport({ width: 1280, height: 800 });</span></span>
<span class="line"><span>});</span></span></code></pre></figure>
<p>I like to launch puppeteer with the <code>headless: false</code> option when I'm actively developing so I can see it visually working, but feel free to omit the config if you want.</p>
<p>The highlighted line is a cool trick where you can check the outputs of <code>console.log</code> right into the terminal. It will be useful during the development phase.</p>
<p>Next, we need to login into Twitter. There is an <a href="#extra-asking-user-credentials">extra at the end of the article</a> to make this process interactive, i.e., to ask for the username, password, and target account.</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">async</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  ...</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  // Make sure you change to your credentials</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> username </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "webquintanilha"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> pwd </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "mysecretpwd"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  // Login</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.goto</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'https://twitter.com/'</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.waitForSelector</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'.StaticLoggedOutHomePage-cell > .StaticLoggedOutHomePage-login > .LoginForm > .LoginForm-username > .text-input'</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.type</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'.StaticLoggedOutHomePage-cell > .StaticLoggedOutHomePage-login > .LoginForm > .LoginForm-username > .text-input'</span><span style="color:#ECEBE8">, username);</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.type</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'.StaticLoggedOutHomePage-cell > .StaticLoggedOutHomePage-login > .LoginForm > .LoginForm-password > .text-input'</span><span style="color:#ECEBE8">, pwd);</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.click</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'.StaticLoggedOutHomePage-content > .StaticLoggedOutHomePage-cell > .StaticLoggedOutHomePage-login > .LoginForm > .EdgeButton'</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.waitForNavigation</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">});</span></span></code></pre></figure>
<p>Once you are logged in, it is important to switch to the new version of Twitter, once the medium used to tweet is only available there. Realize that this might change in the future (and become the default). In any case, the solution here is to click on settings and select the <em>Try the new Twitter</em> option.</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A7A49E;font-style:italic">// Open new Twitter</span></span>
<span class="line"><span style="color:#A1C1E4">await</span><span style="color:#EDCC95"> page.waitForSelector</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'#timeline'</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">await</span><span style="color:#EDCC95"> page.click</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'#user-dropdown-toggle'</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">await</span><span style="color:#EDCC95"> page.waitForSelector</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'.enable-rweb-link'</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">await</span><span style="color:#EDCC95"> page.click</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'.enable-rweb-link'</span><span style="color:#ECEBE8">);</span></span></code></pre></figure>
<p>To finish the first step all you need to do is go to your target account. Make sure you go to their profile with replies, so you don't miss anything.</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>const target = "jairbolsonaro";</span></span>
<span class="line"><span>await page.waitForNavigation({ waitUntil: 'networkidle2' });</span></span>
<span class="line"><span>await page.goto(</span></span>
<span class="line"><span>  `https://twitter.com/${target}/with_replies`, </span></span>
<span class="line"><span>  { waitUntil: 'networkidle2' }</span></span>
<span class="line"><span>);</span></span></code></pre></figure>
<p>The <code>waitUntil</code> option basically determines when to consider the navigation succeeded. <code>networkidle2</code> means <em>consider navigation to be finished when there are no more than 2 network connections for at least 500 ms.</em> All that can be checked in the <a href="https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md" rel="noopener noreferrer" target="_blank">API docs</a>.</p>
<p>Save and run your code and see if you are in the right territory! Now things will get more interesting.</p>
<h2 id="fetching-tweets">Fetching Tweets</h2>
<p>Let us now fetch and analyze every tweet. Notice that the new version of Twitter has a unique URL for each tweet, which makes our life way easier. All we need to do is do tweet by tweet, click on it, wait for the new URL to open, get the relevant data, rinse and repeat.</p>
<p>But first, let's define some control variables:</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> data </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> [];</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> urls </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> [];</span></span>
<span class="line"><span style="color:#A1C1E4">await</span><span style="color:#EDCC95"> page.evaluate</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  window.i </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 0</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">});</span></span></code></pre></figure>
<p>The <code>data</code> array will hold our values and <code>urls</code> will hold every inspected tweet, once we will need to avoid counting the same tweet twice.</p>
<p>The different thing here, <code>page.evaluate</code>, basically gives us access to the regular DOM (like you are writing JavaScript in the console). We will define an iterator which we will use to go over the list of tweets. Now, <code>window.i</code> will be available in the browser context.</p>
<p>We need the iterator because Twitter only shows a subset of the tweets. As you scroll down, this list changes and we will need to re-assess them all again. The bad news is that there will be <strong>a lot of overlap</strong>.</p>
<p>Suppose that the following is your visible timeline, i.e., the tweets loaded from the server.</p>
<ol start="0">
<li>Tweet A</li>
<li>Tweet B</li>
<li>Tweet C</li>
</ol>
<p>We can get the total visible tweets with a selector like:</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">await</span><span style="color:#EDCC95"> page.evaluate</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> visibleTweets </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> document.querySelectorAll</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"div[data-testid=tweet]"</span><span style="color:#ECEBE8">).length;</span></span>
<span class="line"><span style="color:#EDCC95">  console.log</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"Total visible tweets"</span><span style="color:#ECEBE8">, visibleTweets);</span></span>
<span class="line"><span style="color:#ECEBE8">});</span></span></code></pre></figure>
<p>And in our example <code>visibleTweets</code> is <code>3</code>. Using our iterator, we can do something like:</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">while</span><span style="color:#ECEBE8"> ( </span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8"> ) {</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.evaluate</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    ...</span></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#ECEBE8"> tweet </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> document.querySelectorAll</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"div[data-testid=tweet]"</span><span style="color:#ECEBE8">)[window.i];</span></span>
<span class="line"><span style="color:#EDCC95">    tweet.click</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">    window.i</span><span style="color:#A1C1E4">++</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">  });</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  /* DO SOMETHING IN THE PAGE */</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.goBack</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>This will work for the first 3 posts, but after that <code>window.i</code> will overflow the array and our code will crash (<code>tweet</code> will be <code>undefined</code>). So we need to handle the case where we need to fetch more tweets.</p>
<p>We can do this by scrolling down a bit and waiting for a while (to make sure the tweets are loaded). This will also be handy to avoid being throttled by Twitter.</p>
<p>Here's a complete version:</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">while</span><span style="color:#ECEBE8"> ( </span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8"> ) {</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.evaluate</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">async</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    ...</span></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#ECEBE8"> tweet </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> document.querySelectorAll</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"div[data-testid=tweet]"</span><span style="color:#ECEBE8">)[window.i];</span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> ( </span><span style="color:#A1C1E4">typeof</span><span style="color:#ECEBE8"> tweet </span><span style="color:#A1C1E4">===</span><span style="color:#97CCAE"> "undefined"</span><span style="color:#ECEBE8"> ) {</span></span>
<span class="line"><span style="color:#ECEBE8">      window.i </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> 0</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#EDCC95">      window.scrollBy</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">1500</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">      const</span><span style="color:#EDCC95"> sleep</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ms </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> { </span><span style="color:#A1C1E4">return</span><span style="color:#A1C1E4"> new</span><span style="color:#EDCC95"> Promise</span><span style="color:#ECEBE8">(resolve </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setTimeout</span><span style="color:#ECEBE8">(resolve, ms)); }</span></span>
<span class="line"><span style="color:#A1C1E4">      await</span><span style="color:#EDCC95"> sleep</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">5000</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#EDCC95">      document.querySelectorAll</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"div[data-testid=tweet]"</span><span style="color:#ECEBE8">)[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">]</span><span style="color:#EDCC95">.click</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">    } </span><span style="color:#A1C1E4">else</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">      tweet.click</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#ECEBE8">    window.i</span><span style="color:#A1C1E4">++</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#ECEBE8">  });</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  /* DO SOMETHING IN THE PAGE */</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.goBack</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Couple important things going on here:</p>
<ul>
<li>First notice that <code>page.evaluate</code> now receives an <code>async</code> function, which is necessary in order to <code>sleep</code> 5s.</li>
<li>When we extrapolate the visible tweets, we reset our count.</li>
<li>We scroll an arbitrary number of pixels. By trial and error, I found that 1500px gave me the best results (you don't want to scroll too little and fetch few posts nor scroll too much and lose tweets in the way).</li>
<li>We sleep 5 seconds, which I consider safe by trial and error. You can experiment smaller delays such as 4 seconds, but 1-2s definitely will get the Twitter police after you.</li>
</ul>
<p>Now one important caveat of this approach: when we fetch new posts, remember that <em>some</em> of the previously visible ones will remain visible. So now we get a situation like:</p>
<ol start="0">
<li>Tweet B</li>
<li>Tweet C</li>
<li><strong>Tweet D</strong></li>
<li><strong>Tweet E</strong></li>
<li><strong>Tweet F</strong></li>
</ol>
<p>While the bottom 3 tweets are new, B and C will overlap and be evaluated again. We will need to account for that in the next section.</p>
<h2 id="scraping-the-data">Scraping the Data</h2>
<p>Recall that we are in a <code>while</code> loop which redirects us to a specific URL.</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">while</span><span style="color:#ECEBE8"> ( </span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8"> ) {</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.evaluate</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">async</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    ...</span></span>
<span class="line"><span style="color:#ECEBE8">  });</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  /* </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    WE ARE IN THE TWEET PAGE</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    DO SOMETHING AND RETURN </span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  */</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.goBack</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>The first thing is to check which URL we are in. We can use <code>page.url()</code> for that.</p>
<p>There are 3 possible outcomes for a URL:</p>
<ol>
<li>The URL was already evaluated;</li>
<li>The URL does not belong to the target (i.e. current tweet is a retweet of another user);</li>
<li>The URL is a new tweet yet to be scrapped.</li>
</ol>
<p>Here's how we can summarize it:</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">while</span><span style="color:#ECEBE8"> ( </span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8"> ) {</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.evaluate</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">async</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    ...</span></span>
<span class="line"><span style="color:#ECEBE8">  });</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> url </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> page.url</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#A1C1E4">  if</span><span style="color:#ECEBE8"> ( </span><span style="color:#EDCC95">urls.indexOf</span><span style="color:#ECEBE8">(url) </span><span style="color:#A1C1E4">></span><span style="color:#A1C1E4"> -</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8"> ) {</span></span>
<span class="line"><span style="color:#EDCC95">    console.log</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"Ooops, repeated URL"</span><span style="color:#ECEBE8">, url);</span></span>
<span class="line"><span style="color:#ECEBE8">  } </span><span style="color:#A1C1E4">else</span><span style="color:#A1C1E4"> if</span><span style="color:#ECEBE8"> ( </span><span style="color:#EDCC95">url.indexOf</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`https://twitter.com/${</span><span style="color:#97CCAE">target</span><span style="color:#97CCAE">}/`</span><span style="color:#ECEBE8">) </span><span style="color:#A1C1E4">===</span><span style="color:#A1C1E4"> -</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8"> ) {</span></span>
<span class="line"><span style="color:#EDCC95">    console.log</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"Ooops, this does not belong to the target"</span><span style="color:#ECEBE8">, url);</span></span>
<span class="line"><span style="color:#ECEBE8">  } </span><span style="color:#A1C1E4">else</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    /* SCRAPE RELEVANT INFO HERE */</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.goBack</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Let's fill the <code>else</code> clause. All you need to do is to make sure you add the current URL to our <code>urls</code> array and use CSS selectors to get the relevant information. I suggest you inspect the element you want to scrape directly in the browser and use <code>document.querySelector</code> and <code>document.querySelectorAll</code> to make sure your selector works.</p>
<p>The red box is what we want to select:</p>
<figure class="image"><img alt="Example with the medium used to tweet highlighted." loading="lazy" decoding="async" width="745" height="551" src="https://rafaelquintanilha.com/_astro/tweet.B91H6Q3W_ZWAiVy.webp"><figcaption>Example with the medium used to tweet highlighted.</figcaption></figure>
<p>At the time of this writing, one can do:</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> selector </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "a[href='https://help.twitter.com/using-twitter/how-to-tweet#source-labels'] > span"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> medium </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> document.querySelector</span><span style="color:#ECEBE8">(selector).textContent;</span></span></code></pre></figure>
<p>And <code>medium</code> will be whatever medium the user has used to tweet (e.g. <em>Twitter Web App</em>).</p>
<p>We can do it with puppeteer by using <a href="https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pageevalselector-pagefunction-args" rel="noopener noreferrer" target="_blank">page.$eval</a>, which mimics <code>document.querySelector</code> (or <a href="https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pageevalselector-pagefunction-args" rel="noopener noreferrer" target="_blank">page.$$eval</a>, which mimics its cousin <code>querySelectorAll</code>).</p>
<p>Here's how the <code>else</code> looks like:</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#ECEBE8">} </span><span style="color:#A1C1E4">else</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">  urls.push</span><span style="color:#ECEBE8">(url);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> selector </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "a[href='https://help.twitter.com/using-twitter/how-to-tweet#source-labels'] > span"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.waitForSelector</span><span style="color:#ECEBE8">(selector);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> medium </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> page.$eval</span><span style="color:#ECEBE8">(</span></span>
<span class="line"><span style="color:#ECEBE8">    selector, </span></span>
<span class="line"><span style="color:#ECEBE8">    node </span><span style="color:#A1C1E4">=></span><span style="color:#97CCAE"> `${</span><span style="color:#97CCAE">node.textContent</span><span style="color:#97CCAE">}`</span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#EDCC95">  data.push</span><span style="color:#ECEBE8">(medium);</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<p>Once you have <code>data</code> populated you can check how many tweets were posted via iPhone (if that matters to you):</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> TARGET_MEDIUM </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "Twitter for iPhone"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> count </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> data.filter</span><span style="color:#ECEBE8">(medium </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> medium </span><span style="color:#A1C1E4">===</span><span style="color:#ECEBE8"> TARGET_MEDIUM).length;</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> percentage </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> ((count </span><span style="color:#A1C1E4">/</span><span style="color:#ECEBE8"> total.length) </span><span style="color:#A1C1E4">*</span><span style="color:#97CCAE"> 100</span><span style="color:#ECEBE8">)</span><span style="color:#EDCC95">.toFixed</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">2</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#EDCC95">console.log</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`Total tweets with ${</span><span style="color:#97CCAE">TARGET_MEDIUM</span><span style="color:#97CCAE">}: ${</span><span style="color:#97CCAE">percentage</span><span style="color:#97CCAE">}%`</span><span style="color:#ECEBE8">);</span></span></code></pre></figure>
<p>To finalize, I suggest you <code>sleep</code> a little before opening a new tweet. After that, you are safe to <code>goBack</code> and continue:</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">while</span><span style="color:#ECEBE8"> ( </span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8"> ) {</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.evaluate</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">async</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    ...</span></span>
<span class="line"><span style="color:#ECEBE8">  });</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  ...</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  // Wait to prevent API throttle</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> sleep</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> ms </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> { </span><span style="color:#A1C1E4">return</span><span style="color:#A1C1E4"> new</span><span style="color:#EDCC95"> Promise</span><span style="color:#ECEBE8">(resolve </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setTimeout</span><span style="color:#ECEBE8">(resolve, ms)); }</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> sleep</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">5000</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">  await</span><span style="color:#EDCC95"> page.goBack</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span></code></pre></figure>
<h2 id="final-thoughts">Final Thoughts</h2>
<p>The above isn't, by all means, a final guide or the best practices for web automation. In fact, I'm pretty new to puppeteer and automation in general. This post was a fun exercise on how technology (and specifically puppeteer) can save us time with a minimum knowledge of JavaScript and a lot of trial and error.</p>
<p>I haven't spent much time trying to optimize the code, so feel free to drop me a message on <a href="https://twitter.com/webquintanilha" rel="noopener noreferrer" target="_blank">Twitter</a> if you have suggestions. In my tests, I was able to scrape around 10 tweets per minute using a delay of 4 seconds. This isn't super fast but safe and fun (I admit I love watching robots operating). Additional considerations:</p>
<ul>
<li>We are using selectors that are subject to change (as the Twitter devs might rearrange their DOM elements), so this is work that might need adjustments from time to time.</li>
<li>The <code>while</code> loop runs forever. If we reach the bottom of the target timeline, the code will keep going and open repeated URLs. I leave the fix as an exercise for the reader.</li>
</ul>
<p>Don't forget to check the complete code in <a href="https://github.com/rafaelquintanilha/automation/blob/master/tweetCounter.js" rel="noopener noreferrer" target="_blank">GitHub</a>.</p>
<p>More automation articles coming soon!</p>
<h2 id="extra-asking-user-credentials">Extra (Asking User Credentials)</h2>
<p>I don't like having my password hardcoded in the file and passing it via env variables is not safe (once our bash history gets stored). So an alternative is to prompt the user to input the credentials of the account that will be used to scrape and the target account.</p>
<p>There is a very easy-to-use library called <a href="https://www.npmjs.com/package/readline-sync" rel="noopener noreferrer" target="_blank">readline-sync</a> that allows exactly that.</p>
<p>Add that before setting up puppeteer, at the very top of the code:</p>
<figure class="code"><figcaption>js</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> readlineSync </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> require</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'readline-sync'</span><span style="color:#ECEBE8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">// Wait for user's response.</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> username </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> readlineSync.question</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Your twitter username: '</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> pwd </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> readlineSync.question</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Password: '</span><span style="color:#ECEBE8">, {</span></span>
<span class="line"><span style="color:#ECEBE8">  hideEchoBack: </span><span style="color:#A1C1E4">true</span></span>
<span class="line"><span style="color:#ECEBE8">});</span></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> target </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> readlineSync.question</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'User you want to analyze: '</span><span style="color:#ECEBE8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">async</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  // Setup puppeteer</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> browser </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> puppeteer.launch</span><span style="color:#ECEBE8">({ headless: </span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8"> });</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> page </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> browser.newPage</span><span style="color:#ECEBE8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  ...</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">});</span></span></code></pre></figure>
<p>In order to hide the password the <code>hideEchoBack</code> option comes really handy. Make sure your credentials are read from those variables and that you go to the right URL given your target.</p>]]></content:encoded>
</item>
</channel>
</rss>
