<?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[Pipedream - 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/pipedream/</link>
<image><url>https://rafaelquintanilha.com/content/images/2022/12/Logo-Design--2-.png</url><title>Pipedream - Rafael Quintanilha</title><link>https://rafaelquintanilha.com/topic/pipedream/</link></image>
<lastBuildDate>Tue, 15 Oct 2024 14:39:33 GMT</lastBuildDate>
<atom:link href="https://rafaelquintanilha.com/topic/pipedream/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[Scraping market data with Python]]></title>
<description><![CDATA[Web scraping with the BeautifulSoup Python library.]]></description>
<link>https://rafaelquintanilha.com/scraping-market-data-with-python/</link>
<guid isPermaLink="false">670e78a1d8bba20001d2b645</guid>
<category><![CDATA[Web Scraping]]></category><category><![CDATA[Python]]></category><category><![CDATA[Pipedream]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Tue, 19 Mar 2024 14:17:00 GMT</pubDate>

<content:encoded><![CDATA[<p>For many investors, <em>timing</em> is extremely important. We've seen the market be irrational (despite some arguing that it is <a href="https://www.investopedia.com/terms/e/efficientmarkethypothesis.asp" rel="noopener noreferrer" target="_blank">efficient</a>) countless times, which often translates into great investment opportunities.</p>
<p>The combination of <em>quantitative analysis</em> and <em>software engineering</em> can be extremely useful for exploiting such moments. Having access to real-time data, executing some computation, and plugging it into a decision-making algorithm is a workflow that you can start benefitting today. And the good news – it's never been easier to start.</p>
<p>There is a problem, though. While there are plenty of data sources available, they are usually restricted to specific markets, rate-limited, throttled, or flat out expensive. Outside of the American market and crypto assets, chances are you won't have access to good, reliable APIs.</p>
<p>Thankfully, Pipedream allows you to run JavaScript or Python code as part of your workflows. This unlocks every website as a data source for your project — that's what we'll explore today.</p>
<p>We'll build a workflow that:</p>
<ol>
<li>Runs at fixed intervals</li>
<li>Launches a Python code to scrape data from a website containing market data of unusual assets.</li>
<li>Sends the <a href="https://en.wikipedia.org/wiki/Open-high-low-close_chart" rel="noopener noreferrer" target="_blank">OHLC</a> values to Slack</li>
</ol>
<p>You can copy the <a href="https://pipedream.com/new?h=tch_ovfybN&#x26;via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">final workflow</a> at any time and use it in your own Pipedream account.</p>
<p>With that all said, let's get started!</p>
<h3 id="create-the-workflow">Create the workflow</h3>
<p>When you create a workflow, you'll be presented with a list of settings. Depending on what you're scraping, it's important to pay attention to the workflow's <strong>Timeout</strong>.</p>
<p>By default, Pipedream will set a 30-second timeout on workflow executions, which should be enough for our example. You may need to raise it or <a href="https://pipedream.com/docs/workflows/settings?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">take advantage of other settings</a> for more complex workflows.</p>
<p><img alt="" loading="lazy" decoding="async" width="1306" height="1396" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-14-at-08.37.02@2x.BNFlZSDv_Z1FtVSJ.webp"></p>
<h3 id="add-a-custom-interval-trigger">Add a Custom Interval trigger</h3>
<p>We need a <a href="https://pipedream.com/docs/workflows/triggers?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">trigger</a> to launch our web scraper. As we want to constantly monitor the security we're interested on, a <strong>Custom Interval</strong> is the best choice. Select it from the list of triggers.</p>
<p>You'll be asked to set a <em>Schedule</em>, i.e., when the action will be triggered. Typically, a fixed interval like "once every hour" is enough. But for this example I'll be scraping IBOV data, the Brazilian benchmark index. The Brazilian market opens from Monday to Friday, during working hours. Fortunately, Pipedream supports custom <a href="https://en.wikipedia.org/wiki/Cron" rel="noopener noreferrer" target="_blank">cron expressions</a>, which we can leverage in order to avoid triggering the action unnecessarily.</p>
<p>I never remember the cron syntax, so that's a great use-case for your LLM of choice to help you (I'm using <a href="https://www.raycast.com/" rel="noopener noreferrer" target="_blank">Raycast</a>'s built-in <strong>Ask AI</strong> feature to get quick answers like that).</p>
<p><img alt="" loading="lazy" decoding="async" width="1204" height="668" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-14-at-08.48.07@2x.COKxE9MX_1LHs1b.webp"></p>
<p>Great! We can then set that schedule and get a human-friendly description that confirms it's what we wanted:</p>
<p><img alt="" loading="lazy" decoding="async" width="1860" height="884" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-14-at-08.49.45@2x.BZEKK6gP_Z1jTw7m.webp"></p>
<h3 id="configure-the-scraper">Configure the scraper</h3>
<p>Now that the trigger is configured, we're ready to build the scraper. Pipedream will prompt you to connect a <a href="https://pipedream.com/docs/workflows/steps?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">step</a>, i.e., an action to be performed after the workflow triggers.</p>
<p>Select <strong>Python > Run Python code</strong> to open the editor.</p>
<p>You'll be greeted with a functional editor where you can start running Python code or add third-party dependencies without the fuss of dealing with package managers like <code>pip</code> or <code>poetry</code>. Pretty neat.</p>
<p>We'll scrape the Polish website <a href="https://stooq.com/q/g/?s=%5Ebvp" rel="noopener noreferrer" target="_blank">Stooq.com</a>, passing the Brazilian index ticker as the query parameter (try adjusting it to use your ticker of choice).</p>
<p>Replace the content of the editor with the following:</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"> requests</span></span>
<span class="line"><span style="color:#A1C1E4">from</span><span style="color:#ECEBE8"> bs4 </span><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> BeautifulSoup</span></span>
<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</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:#A1C1E4">  try</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # The base URL</span></span>
<span class="line"><span style="color:#ECEBE8">    url </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "https://stooq.com/q/g/?s=^bvp"</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # Sending a GET request</span></span>
<span class="line"><span style="color:#ECEBE8">    response </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> requests.</span><span style="color:#EDCC95">get(url)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    # If the GET request is successful, the status code will be 200</span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> response.status_code </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> 200</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Get the content of the response</span></span>
<span class="line"><span style="color:#ECEBE8">      page_content </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> response.content</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Create a BeautifulSoup object and specify the parser</span></span>
<span class="line"><span style="color:#ECEBE8">      soup </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> BeautifulSoup(page_content, </span><span style="color:#97CCAE">"html.parser"</span><span style="color:#EDCC95">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Find the tables</span></span>
<span class="line"><span style="color:#ECEBE8">      tables </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> soup.</span><span style="color:#EDCC95">find_all(</span><span style="color:#97CCAE">"table"</span><span style="color:#EDCC95">, {</span><span style="color:#97CCAE">"id"</span><span style="color:#EDCC95">: </span><span style="color:#97CCAE">"t1"</span><span style="color:#EDCC95">})</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Initialize a dictionary to hold the data</span></span>
<span class="line"><span style="color:#ECEBE8">      data </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> {}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Iterate through the rows in the first table</span></span>
<span class="line"><span style="color:#A1C1E4">      for</span><span style="color:#ECEBE8"> row </span><span style="color:#A1C1E4">in</span><span style="color:#ECEBE8"> tables[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">].</span><span style="color:#EDCC95">find_all(</span><span style="color:#97CCAE">"tr"</span><span style="color:#EDCC95">)</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">          cells </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> row.</span><span style="color:#EDCC95">find_all(</span><span style="color:#97CCAE">"td"</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#A1C1E4">          if</span><span style="color:#ECEBE8"> cells[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">].text </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> "Otwarcie"</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"open"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> float</span><span style="color:#EDCC95">(cells[</span><span style="color:#97CCAE">1</span><span style="color:#EDCC95">].text.replace(</span><span style="color:#97CCAE">","</span><span style="color:#EDCC95">, </span><span style="color:#97CCAE">""</span><span style="color:#EDCC95">))</span></span>
<span class="line"><span style="color:#A1C1E4">          elif</span><span style="color:#ECEBE8"> cells[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">].text </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> "Kurs"</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"close"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> float</span><span style="color:#EDCC95">(cells[</span><span style="color:#97CCAE">1</span><span style="color:#EDCC95">].text.replace(</span><span style="color:#97CCAE">","</span><span style="color:#EDCC95">, </span><span style="color:#97CCAE">""</span><span style="color:#EDCC95">))</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Iterate through the rows in the second table</span></span>
<span class="line"><span style="color:#A1C1E4">      for</span><span style="color:#ECEBE8"> row </span><span style="color:#A1C1E4">in</span><span style="color:#ECEBE8"> tables[</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">].</span><span style="color:#EDCC95">find_all(</span><span style="color:#97CCAE">"tr"</span><span style="color:#EDCC95">)</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">          cells </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> row.</span><span style="color:#EDCC95">find_all(</span><span style="color:#97CCAE">"td"</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#A1C1E4">          if</span><span style="color:#ECEBE8"> cells[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">].text </span><span style="color:#A1C1E4">==</span><span style="color:#97CCAE"> "Max/min"</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#ECEBE8">              high, low </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> cells[</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">].text.</span><span style="color:#EDCC95">split(</span><span style="color:#97CCAE">" / "</span><span style="color:#EDCC95">)</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"high"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> float</span><span style="color:#EDCC95">(high.replace(</span><span style="color:#97CCAE">","</span><span style="color:#EDCC95">, </span><span style="color:#97CCAE">""</span><span style="color:#EDCC95">))</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"low"</span><span style="color:#ECEBE8">] </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> float</span><span style="color:#EDCC95">(low.replace(</span><span style="color:#97CCAE">","</span><span style="color:#EDCC95">, </span><span style="color:#97CCAE">""</span><span style="color:#EDCC95">))</span></span>
<span class="line"></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">now()</span><span style="color:#ECEBE8">.</span><span style="color:#EDCC95">strftime(</span><span style="color:#97CCAE">"%Y-%m-%d"</span><span style="color:#EDCC95">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#ECEBE8">      data </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 style="color:#ECEBE8">              dt,</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"open"</span><span style="color:#ECEBE8">],</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"high"</span><span style="color:#ECEBE8">],</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"low"</span><span style="color:#ECEBE8">],</span></span>
<span class="line"><span style="color:#ECEBE8">              data[</span><span style="color:#97CCAE">"close"</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>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">      return</span><span style="color:#ECEBE8"> data</span></span>
<span class="line"><span style="color:#A1C1E4">    else</span><span style="color:#ECEBE8">:</span></span>
<span class="line"><span style="color:#EDCC95">      print(</span><span style="color:#97CCAE">"Error fetching data!"</span><span style="color:#EDCC95">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">      # Raise a network error so we can retry the task again</span></span>
<span class="line"><span style="color:#A1C1E4">      raise</span><span style="color:#ECEBE8"> requests.exceptions.RequestException</span></span>
<span class="line"><span style="color:#A1C1E4">  except</span><span style="color:#A1C1E4"> Exception</span><span style="color:#A1C1E4"> as</span><span style="color:#ECEBE8"> e:</span></span>
<span class="line"><span style="color:#EDCC95">    print(</span><span style="color:#A1C1E4">f</span><span style="color:#97CCAE">"Error scraping data: </span><span style="color:#97CCAE">{</span><span style="color:#EDCC95">repr(e)</span><span style="color:#97CCAE">}</span><span style="color:#97CCAE">"</span><span style="color:#EDCC95">)</span></span></code></pre></figure>
<p>The code should be pretty straightforward (though admittedly easier if you happen to know Polish), and the only thing you need to change in order to scrape other assets is the URL:</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:#ECEBE8">url </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "https://stooq.com/q/g/?s=^bvp"</span></span></code></pre></figure>
<p>Go ahead and test the code. If successful, you'll see something like this:</p>
<p><img alt="" loading="lazy" decoding="async" width="1874" height="1384" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-16-at-10.38.36@2x.BU7kbxbd_1frGPK.webp"></p>
<p><em>Note: If you run into timeout issues, consider increasing the Timeout value in Settings (shortcut: press M then S).</em></p>
<p>Great! The <em>Exports</em> tab exposes all data that will be available in future steps. Let's take advantage of it next.</p>
<h3 id="connect-to-slack">Connect to Slack</h3>
<p>The last step of this proof-of-concept is to send the results of the scraper to Slack.</p>
<p>Click on the plus button to add a new step and select <strong>Slack > Send Message to a Public Channel</strong>.</p>
<p>The wizard is also straightforward. Click on <strong>Slack Account</strong> and allow Pipedream to connect to your workspace. Next select the <strong>Channel ID</strong> you want the messages to be sent. Finally, format the <strong>Text</strong> as you like, using the floating dropdown menu to help you integrate variables returned from prior steps.</p>
<p><img alt="" loading="lazy" decoding="async" width="1880" height="1302" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-16-at-10.58.39@2x.C_EIGJ6-_2tIewx.webp"></p>
<p>Notice how I plugged data from the previous two steps:</p>
<ol>
<li>A nicely-formatted timestamp pulled from the trigger step</li>
<li>The actual return of the Python function pulled from the scraping step.</li>
</ol>
<p>Now, we are able to test our integration! Click on <strong>Test</strong> and within a moment you shall receive a message in the selected channel:</p>
<p><img alt="" loading="lazy" decoding="async" width="1416" height="914" src="https://rafaelquintanilha.com/_astro/CleanShot-2024-03-16-at-10.57.53@2x.C73l0YZ9_20zjgI.webp"></p>
<p>That's it! You successfully hooked an end-to-end automation capable to power your quantitative analysis!</p>
<h3 id="next-steps">Next steps</h3>
<p>Hopefully this article serves as a base for further exploration. Here are some follow-up suggestions:</p>
<ul>
<li>Notify how much the asset price has <em>changed.</em> It's usually useful to know the variation in percentage points. Sharpen your Python (and Polish) skills to scrape this information from <a href="https://pipedream.com/blog/scraping-market-data-with-python/stooq.com" rel="noopener noreferrer" target="_blank">Stooq.com</a>, or store previously scraped data elsewhere (can be as simple as a <a href="https://pipedream.com/apps/pipedream/integrations/google-sheets" rel="noopener noreferrer" target="_blank">Google Sheet</a>).</li>
<li>Go to the next level by storing the data in a <strong>database</strong> (e.g. <a href="https://pipedream.com/apps/pipedream/integrations/supabase?via=rafael-quintanilha-blog" rel="noopener noreferrer" target="_blank">Supabase</a>). This will unlock a world of automated possibilities, including running your own data analysis, allowing you to generate real-time notifications based on historical data.</li>
</ul>]]></content:encoded>
</item>
</channel>
</rss>
