<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Girish Ramloul on Medium]]></title>
        <description><![CDATA[Stories by Girish Ramloul on Medium]]></description>
        <link>https://medium.com/@ramloul24?source=rss-9d828152ef88------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*yJPsAfMm7RAKv6Wu0Q3cnA.jpeg</url>
            <title>Stories by Girish Ramloul on Medium</title>
            <link>https://medium.com/@ramloul24?source=rss-9d828152ef88------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 21:32:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ramloul24/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Missing water-cooler chats? Automate a flow on Slack!]]></title>
            <link>https://medium.com/make-it-heady/automating-a-flow-on-slack-cbaf2b887c20?source=rss-9d828152ef88------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbaf2b887c20</guid>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Girish Ramloul]]></dc:creator>
            <pubDate>Fri, 15 May 2020 14:47:38 GMT</pubDate>
            <atom:updated>2020-05-21T21:24:43.007Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*zwP77OudeN8T-vCJ3ZFXYg.png" /></figure><p>As our teams work remotely to protect ourselves and others, we’ve found ourselves missing one element of in-office culture in particular. Namely, the serendipitous meetups that take place in office hallways, kitchens, and corners—and the lighthearted sharing of ideas and plans that takes place therein. But wait, we thought! There’s an app for that.</p><p>Recreating water-cooler chats through an automated flow on Slack: a comprehensive guide, from ideation to development to deployment.</p><h3><strong>Proof of Concept</strong></h3><p>So, you want to build an app on Slack to request that your workspace’s members share their plans for the day (show-and-tell style). After gathering requirements and exploring the Slack APIs, you plan your app around your favorite tech stack.</p><ol><li>The app will <strong>randomly select</strong> a user from the workspace to share their plan for the day at a <strong>specified time</strong> of the day.</li><li>A <strong>bot</strong> packaged as a Slack app prompts the selected user to share.</li><li>The selected user has <strong>two options</strong>: share their plan or kindly decline.</li><li>If the user declines, select another user to volunteer and repeat steps 1–4.</li><li>If the user accepts, they are prompted to enter their plan for the day.</li><li>The app posts the plan to a private channel.</li><li>The app posts a summary on Friday at the end of the day.</li></ol><pre>+--------------+----------------------------------------------+<br>| Requirements |                 Action Plan                  |<br>+--------------+----------------------------------------------+<br>|            1 | - Method to randomly select User Ids         |<br>|              | - Set up a Task Scheduler                    |<br>|            2 | - Bot with access to User Ids                |<br>|              | - Slack Chat API Post Message                |<br>|            3 | - Slack Interactive Components               |<br>|            4 | - Queue up randomly selected user ids (FIFO) |<br>|            5 | - Slack Modal                                |<br>|            6 | - Slack API and Webhook                      |<br>|            7 | - Database to save weekly plans              |<br>+--------------+----------------------------------------------+</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*Q3Kn4_Av8dUSkfcOd9Z02g.png" /><figcaption>Sequence Diagram for our app</figcaption></figure><h3><strong>Initial Setup (Development Environment)</strong></h3><ul><li><em>Create a Slack App.</em></li></ul><ol><li>Head to your <a href="https://api.slack.com/apps">Slack’s workspace</a>. Create an app. Enable the <strong>Bot</strong> and <strong>Interactive Components</strong> features. Add the following Bot Token Scopes: channels:join, channels:read, chat:write and incoming-webhook.</li><li>Create a private channel and add a <strong>webhook URL</strong> to dispatch messages to the channel. Invite your team to the channel.</li><li>Install the app (in our example, we’ll call it show_tell) to your workspace. A <strong>Bot User OAuth Access Token </strong>will be generated upon successful completion.</li></ol><ul><li><a href="https://nodejs.org/en/download/package-manager/"><em>Install Node</em></a><em> using a package installer and, if not installed with Node, Node Package Manager (npm).</em></li><li><em>Create a Node project in your working directory.</em></li></ul><pre>$ npm init</pre><p>A package.json file will be created by default. Add the node modules (express, axios, body-parser, forever, node-cron and firebase-admin) by using the <em>npm install -- save </em>command, which will automatically add the dependencies.</p><ul><li><em>Create an</em><a href="https://expressjs.com/en/starter/hello-world.html"><em> Express server</em></a><em> in an index.js file. Mount the body-parser middleware via the app.use() function.</em></li></ul><pre>const express = require(&#39;express&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);<br>const app = express();</pre><pre>app.use(bodyParser.urlencoded({ extended: false }));<br>app.use(bodyParser.json());</pre><pre>const PORT = 9647;<br>app.listen(PORT, () =&gt; {<br> console.log(`Slack bot server has started on port ${PORT}`);<br>});</pre><ul><li><em>Install </em><a href="https://ngrok.com/download"><em>ngrok</em></a><em> (Use it to establish a secure tunnel from a publicly accessible URL to your local machine).</em></li></ul><p>The public URL will be used as the request URL for interactivity between the app and Slack. Start a HTTP tunnel on the same port using your CLI.</p><pre>$ ./ngrok http 9647</pre><p>Copy the public URL and paste it in the Request URL field box. Slack will send an HTTP POST request to this URL when your users interact with the Interactive Components and Modal.</p><ul><li><em>Set up Firebase</em></li></ul><p>Login to <a href="https://firebase.google.com/">Firebase</a> with your Google account. Create a new project (we’ll name ours showtellplans). You’ll need to set up the Firebase Admin SDK to use the Realtime Database service. (We’ll cover how to do this later in the tutorial, in the database section.)</p><ul><li><em>Set up a config.js file.</em></li></ul><p>Store the bot auth token, webhook URL, Firebase private key and an array of User Ids in this file, and export those values.</p><pre>module.exports = {<br>   botToken: &#39;xoxb-&#39;,<br>   webhookURL: &#39;https://hooks.slack.com/services/&#39;,<br>   userIds: [],<br>   firebasePrivateKey: &#39;&#39;<br>}</pre><p>Wondering where to find the User Ids? <br>Go to the private channel on the Slack App. Click on the Channel Details button and select Members. Under the View Full Profile, the user Id of that user will be displayed as member ID. You’ll need the user Ids to post messages to each and every member of the channel.</p><ul><li><em>Set up version control on GitHub</em></li></ul><p>Make sure you have <a href="https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup">Git</a> on your system. Create a new repo on Github with a README.md file. Initialize a Git repository in your Node project, git clone your fresh repo, git add, make a first commit and git push your changes after adding the index.js and config.js files. Add a .gitignore file and add config.js and node_modules to that file (you don’t want to push these files to a public repo).</p><pre>$ git init<br>$ git clone &lt;urlToGitHubRepo&gt;<br>$ git add .<br>$ git commit -m &quot;commit-message&quot;<br>$ git push</pre><h3><strong>Requirement 1(a): <em>Randomly pick Users Ids</em></strong></h3><p>You need to define a method to achieve the following:</p><ul><li>Randomly pick a user id from your array of user Ids.</li><li>Keep track of user Ids already selected: you want to pick a new user Id every day.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f370db2e456179c80a0477e1ede1e8eb/href">https://medium.com/media/f370db2e456179c80a0477e1ede1e8eb/href</a></iframe><p>Watch the method unfold in this <a href="https://repl.it/@ramloul24/randomselector">Repl</a>. The array listOfIds will be the const array we defined in our config.js file and the selectedIds array will be a global array we’ll add to the root folder (index.js).</p><p>Then, add this function to a utilities.js file.</p><h3>Requirement 2: Post Message function</h3><p>Next, you’ll need to set up your file directory. Here’s our example:</p><pre>|<br>+-- index.js<br>+-- api.js<br>+-- routes.js<br>+-- utilities.js<br>+-- config.js<br>+-- payloads.js<br>+-- .gitignore<br>+-- package.json<br>|</pre><p>Use Slack’s <a href="https://api.slack.com/methods/chat.postMessage">chat.postMessage</a> method to send a message to the selected user. The method has a method URL to which you’ll have to make a HTTP POST request. The required arguments are the authentication token, channel (the selected user ID represents the IM channel we want to send to) and a text. You can also make use of the optional attachments argument.<br>Use the <a href="https://www.npmjs.com/package/axios">Axios</a> node module to perform the HTTP requests in the api.js file.</p><pre>const axios = require(&#39;axios&#39;);<br>const config = require(&#39;./config&#39;);<br>const payloads = require(&#39;./payloads&#39;);</pre><pre>const sendDM = async (userId, payload) =&gt; {<br>  try {<br>    const postResponse = await axios.post(<br>      &#39;https://slack.com/api/chat.postMessage&#39;,<br>      {<br>        channel: `${userId}`,<br>        text: payload.message,<br>        attachments: JSON.stringify(payload.attachments)<br>      },<br>      {<br>        headers: {<br>           Authorization: `Bearer ${config.botToken}`<br>        }<br>      }<br>   );<br>   return postResponse.data;<br> } catch (error) {<br>   throw error;<br> }<br>};<br>module.exports = {<br>   sendDM<br>}</pre><p>In our example, we’ll call this function in the index.js file our Task Scheduler.</p><h3>Requirement 3: Allow interactivity</h3><p>Next, pass the randomly selected user Id and an <a href="https://api.slack.com/messaging/interactivity">Interactive Message</a> to the sendDM function you have built.<br>First, define the payload in your payloads.js file.</p><pre>module.exports = {<br>   request_message: () =&gt; {<br>      return {<br>         message: &#39;Hi there! :waving: We appreciate your work.&#39;,<br>         attachments: [<br>            {<br>              &quot;text&quot;: &quot;Feel like sharing your plan for the day.&quot;,<br>              &quot;callback_id&quot;: &quot;show_tell&quot;,<br>              &quot;color&quot;: &quot;#a157c9&quot;,<br>              &quot;attachment_type&quot;: &quot;default&quot;,<br>              &quot;actions&quot;: [<br>                  {<br>                    &quot;name&quot;: &quot;positive&quot;,<br>                    &quot;text&quot;: &quot;Yes!&quot;,<br>                    &quot;type&quot;: &quot;button&quot;,<br>                    &quot;value&quot;: &quot;postive&quot;<br>                  },<br>                  {<br>                    &quot;name&quot;: &quot;negative&quot;,<br>                    &quot;text&quot;: &quot;Not today&quot;,<br>                    &quot;type&quot;: &quot;button&quot;,<br>                    &quot;value&quot;: &quot;negative&quot;<br>                  }<br>               ]<br>            }]<br>      }<br>}</pre><p>Per the earlier plan, only request a maximum of 3 users to volunteer per day. You’ll use your predefined method to randomly generate 3 Ids, which you’ll add to a queue.</p><p>Next, put everything together in your index.js file.</p><pre>const { userIds } = require(./config);<br>const { sendDM } = require(./api);<br>const { payloads } = require(./payloads);<br>const Deque = require(&#39;double-ended-queue&#39;);</pre><pre>global.selectedIdsSoFar = []; // global array to keep track of <br>                              // selected user Ids so far<br>global.queue = new Deque(); // Set the queue to the global namespace<br>        // to make it globally accessible within the running process</pre><pre>// Call our method to randomly select 3 user Ids and queue them up<br>for (let i=0; i&lt;3; i++) {<br>    let userId = selectId(userIds, selectedIdsSoFar);<br>    global.queue.push(userId);<br>}</pre><pre>let userId = global.queue.shift(); // try with first Id</pre><pre>sendDM(userId, payloads.request_message());</pre><p>Later, you’ll trigger this function using a Task Scheduler. To verify the right message is sent, run this file.</p><pre>node index.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*Nvizf15d23sPAaL6bYRJVA.png" /><figcaption>Expected Output on the Slack App</figcaption></figure><p>Any interaction with the Interactive Components will be sent to the URL you specify in the Slack API page. Copy the public URL from the ngrok tunnel you started and add the extension /action. So, Slack will send an HTTP POST request to this url: https://{publicURL_from_ngrok}/action.</p><p>Let’s look at a typical response when your user interacts with the buttons.</p><pre>{ type: &#39;interactive_message&#39;,<br>  actions: [ { name: &#39;positive&#39;,type: &#39;button&#39;,value:&#39;postive&#39; } ],<br>  callback_id: &#39;show_tell&#39;,<br>  team: { id: &#39;&#39;, domain: &#39;&#39; },<br>  channel: { id: &#39;&#39;, name: &#39;&#39; },<br>  user: { id: &#39;&#39;, name: &#39;&#39; },<br>  action_ts: &#39;&#39;,<br>  message_ts: &#39;&#39;,<br>  attachment_id: &#39;1&#39;,<br>  token: &#39;&#39;,<br>  is_app_unfurl: false,<br>  original_message: {},<br>  response_url:&#39;&#39;,<br>  trigger_id: &#39;&#39; <br>}</pre><p>Pay attention to the type of the payload, the actions section and later the trigger_id (to open the modal). The actions tell you what option the user selected. You’ll handle both options in the next sections: requirements.</p><h3>Requirement 4: Handling negative response</h3><p>Your user can kindly reject to volunteer to share their plan. In that case, you want to modify the original message to confirm you received their response, and give another user the opportunity to share.</p><pre>const { queue } = require(./index);<br>const { sendDM } = require(./api);</pre><pre>app.post(&#39;/action&#39;, (req, res) =&gt; {<br> const interactiveMessage = JSON.parse(req.body.payload);<br> let originalTextMessage;<br> switch (interactiveMessage.type) {<br>   case &#39;interactive_message&#39;:<br>     originalTextMessage = interactiveMessage.original_message.text;<br>     if (interactiveMessage.actions[0].name === &#39;positive&#39;) {<br>        // handle positive case<br>     }<br>     else { // negative case<br>        res.json({<br>            text: originalTextMessage,<br>            attachments: [<br>                  { text: &#39;Have a good day! :smiley:&#39; }<br>            ]<br>        });<br>        if (global.queue.length !== 0) {<br>          let nextId = global.queue.shift(); // get next Id in queue<br>          sendDM(nextId, payloads.request_message());<br>        }<br>)</pre><h3>Requirement 5: Handling positive response — Modal</h3><p>If your user clicks on Yes!, you want to present a <a href="https://api.slack.com/surfaces/modals">Modal</a>. You’ll accomplish that by using Slack’s <a href="https://api.slack.com/methods/views.open">views.open</a> method. This method requires three arguments: the authentication token, a trigger_id (you received from the payload of the interactive message) and a view payload.</p><p>First, add this method to your api.js file.</p><pre>const openModal = async(trigger, payload) =&gt; {<br>    try {<br>      const postModal = await axios.post(<br>           &#39;https://slack.com/api/chat.postMessage&#39;,<br>           {<br>            trigger_id: `${trigger}`,<br>            view: JSON.stringify(payload)<br>           },<br>           {<br>            headers: {<br>               Authorization: `Bearer ${config.botToken}`<br>            }<br>           }<br>      );<br>      return postModal.data;<br>   } catch (error) {<br>       throw error;<br>   }<br>};</pre><p>Next, define the payload.</p><pre>modal: () =&gt; {<br>   return {<br>       type: &#39;modal&#39;,<br>       callback_id: &#39;modal-identifier&#39;,<br>       title: {<br>               &quot;type&quot;: &quot;plain_text&quot;,<br>               &quot;text&quot;: &quot;Show &amp; Tell&quot;<br>              },<br>       submit: {<br>               &quot;type&quot;: &quot;plain_text&quot;,<br>               &quot;text&quot;: &quot;Submit&quot;,<br>               &quot;emoji&quot;: true<br>              },<br>       close: {<br>              &quot;type&quot;: &quot;plain_text&quot;,<br>              &quot;text&quot;: &quot;Cancel&quot;,<br>              &quot;emoji&quot;: true<br>              },<br>       blocks: [{<br>              &quot;type&quot;: &quot;input&quot;,<br>              &quot;block_id&quot;: &quot;multiline&quot;,<br>              &quot;element&quot;: {<br>                         &quot;type&quot;: &quot;plain_text_input&quot;,<br>                         &quot;multiline&quot;: true,<br>                         &quot;action_id&quot;: &quot;mlvalue&quot;, <br>                         &quot;placeholder&quot;: {<br>                             &quot;type&quot;: &quot;plain_text&quot;,<br>                             &quot;text&quot;: &quot;Share your plan for the day.&quot;<br>                         }<br>              },<br>              &quot;label&quot;: {<br>                       &quot;type&quot;: &quot;plain_text&quot;,<br>                       &quot;text&quot;: &quot;Today&#39;s plan&quot;<br>              }<br>              }]<br>    }<br>}</pre><p>Finally, you can complete your app.post() function to handle the positive case.</p><pre>if (interactiveMessage.actions[0].name === &#39;positive&#39;) {<br>   // handle positive case<br>   openModal(interactiveMessage.trigger_id, payloads.modal());<br>   res.json({<br>       text: originalTextMessage,<br>       attachments: [{ text: &#39;Thanks for sharing :smiley:&#39; }]<br>   });<br>   // Remove the rest of ids from our global array<br>   global.selectedIdsSoFar = global.selectedIdsSoFar.filter((el) =&gt; !(global.queue).includes(el));<br>}</pre><p>Now, when the user clicks on Yes, a Modal like this will pop up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGOFYDo8R-3Ajy8NoeeocQ.png" /><figcaption>Modal View of our app</figcaption></figure><p>After your user is done typing in the text box and clicks Submit, Slack will send an HTTP POST request to the same Redirect URL you previously linked. But the type of the payload will be ‘view_submission’. In that case, you want to grab the text and send it to your private channel via the webhook generated during the Initial Setup.</p><h3><strong>Requirement 6: Posting plan to private channel using Webhook URL</strong></h3><p>In your config.js file, you’ve already copied the webhook URL you added for our private channel. To dispatch messages with the URL, you’ll need to send them in JSON as the body of an application/json POST request.</p><p>Add the method to your api.js file.</p><pre>const sendSlackMessage = async(webhookURL, payload) =&gt; {<br>   try {<br>     const postMessage = await axis.post(webhookURl, payload,<br>                   { headers: {&#39;Content-Type&#39;:&#39;application/json&#39;}<br>                          });<br>     return postMesssage;<br>   } catch (error) {<br>       throw error;<br>   }<br>};</pre><p>Now, the payload.</p><pre>post_announcement: (message) =&gt; {<br>  return {<br>     blocks: [<br>          {<br>            &quot;type&quot;: &quot;section&quot;,<br>            &quot;text&quot;: {<br>               &quot;type&quot;: &quot;plain_text&quot;,<br>               &quot;emoji&quot;: true,<br>               &quot;text&quot;: `Hi team! ${message.user} wants to share their plan for the day with us. :clap:`<br>             }<br>          },<br>          { &quot;type&quot;: &quot;divider&quot; },<br>          {<br>            &quot;type&quot;: &quot;section&quot;,<br>            &quot;text&quot;: {<br>               &quot;type&quot;: &quot;mrkdwn&quot;,<br>               &quot;text&quot;: `${message.plan}`<br>            }<br>          }]<br>  }<br>}</pre><p>You can now add the case to handle the ‘view_submission’ case. Your payload for the sendSlackMessage function expects the username and plan submitted by user. You can grab those from the payload received when the view was submitted.</p><pre>app.post(&#39;/action&#39;, (req, res) =&gt; {<br> const interactiveMessage = JSON.parse(req.body.payload);<br> let originalTextMessage;<br> switch (interactiveMessage.type) {<br>   case &#39;interactive_message&#39;:<br>    // We already implemented this<br>   case &#39;view_submission&#39;:</pre><pre>     <strong>// Grab the username and plan from the payload<br>     let message = {<br>  user: interactiveMessage.user.username,<br>  plan: interactiveMessage.view.state.values.multiline.mlvalue.value<br>     }</strong></pre><pre><strong>     let response = sendSlackMessage(config.webhookURL, payloads.post_announcement(message));</strong></pre><pre><strong>     res.send(response.state); /* Slack expects a 200 response to <br>                                  close the view */      </strong>   <br>)</pre><p>By the end of this section, you will be able to request a random user to share their plan for the day, which they’ll input in a modal. Your app will post that plan to the private channel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJlrhqrXAT26KROpyhMjRQ.jpeg" /></figure><h3>Requirement 7: Store plans in Firebase</h3><p>Your app will post a summary of all the weekly plans. So, you’ll need to store them in a database. <br>Define the database functionality in a new file, i.e. <em>database.js</em>. But first, finish <a href="https://firebase.google.com/docs/admin/setup">setting up the Firebase Admin SDK</a> to authenticate your real time database.</p><ol><li>Head to the project in Firebase, then the Service Account page under the Settings tab. Generate a new private key. Save the json file in your app’s directory in a new folder, Keys. Add this folder to your .gitignore file.</li><li>Copy the configuration snippet from Firebase into your database.js file.</li><li>It’s probably not a good idea to hardcode the path to your service account key JSON file. Instead add the path to your config.js file and call it an extension of the relative path .</li></ol><pre>const admin = require(&#39;firebase-admin&#39;);<br>const config = require(&#39;../config&#39;);</pre><pre>const serviceAccount = require(`../keys/${config.firebasePrivateKey}`);<br><br>admin.initializeApp({<br>  credential: admin.credential.cert(serviceAccount),<br>  databaseURL: &quot;https://showtellplans.firebaseio.com&quot;<br>});</pre><p>First, you need to set a database reference at which your data will be stored.</p><pre>const db = admin.database();<br>const ref = db.ref(&#39;/&#39;);</pre><p>Use the push() method to <a href="https://firebase.google.com/docs/database/admin/save-data">write data</a> to the Firebase Real Time Database. This function allows you to save the plans without worrying about write conflicts since it generates a unique key for each new child. To <a href="https://firebase.google.com/docs/database/admin/retrieve-data">retrieve the data</a>, attach an asynchronous listener to our database reference. You need to call the callback only once, so use the “once” helper function.</p><pre>const savePlan = (userName, plan) =&gt; {<br>  const response = ref.push({ userName, plan });<br>  return response.key;<br>}<br>const readPlans = async key =&gt; {<br>  const snapshot = await ref.child(key).once(&#39;value&#39;);<br>  return snapshot.val();<br>}<br>module.exports = {<br>  savePlan, readPlans<br>}</pre><p>Call the savePlan function inside our ‘view_submission’ block. Only grab the first sentence of the user’s plan by splitting the string by the newline character using regex.</p><pre>app.post(&#39;/action&#39;, (req, res) =&gt; {<br> const interactiveMessage = JSON.parse(req.body.payload);<br> let originalTextMessage;<br> switch (interactiveMessage.type) {<br>   case &#39;interactive_message&#39;:<br>    // We already implemented this<br>   case &#39;view_submission&#39;:</pre><pre>// Grab the username and plan from the payload<br>     <strong>let user = interactiveMessage.user.username;<br>     let plan = interactiveMessage.view.state.values.multiline.mlvalue.value;</strong></pre><pre>     let message = {<br>                     user: user,<br>                     plan: plan <br>     }<br>     <br>     <strong>await savePlan(user, plan.split(/\r?\n/)[0]);</strong></pre><pre>     let response = sendSlackMessage(config.webhookURL, payloads.post_announcement(message));</pre><pre>     res.send(response.state); /* Slack expects a 200 response to <br>                                  close the view */         <br>)</pre><p>Finally, you’ll need to read the data at a scheduled time, which brings us back to the first requirement: setting up a task scheduler.</p><h3>Requirement 1(b): Setting up the Cron Jobs</h3><p>You need to set up two cron jobs: one that will run daily at 10 am to request the selected user to share their plan, and the other on Fridays only at 5 pm.</p><p>The illustration below represents the typical format of a cron job.</p><pre> # ┌────────────── second (optional)<br> # │ ┌──────────── minute<br> # │ │ ┌────────── hour<br> # │ │ │ ┌──────── day of month<br> # │ │ │ │ ┌────── month<br> # │ │ │ │ │ ┌──── day of week<br> # │ │ │ │ │ │<br> # │ │ │ │ │ │<br> # * * * * * *</pre><p>Call your predefined functions in the jobs.</p><ul><li>At 10 am on weekdays only, dispatch the sendDM function to request input from the selected user. The rest of flow will work as we defined in the previous sections.</li></ul><pre><strong>cron.schedule(&#39;00 10 * * 1-5&#39;, () =&gt; { // Run at 10 00 on weekdays<br>                                       // only </strong>       <br>  var queue = new Deque();<br>  for (let i=0; i&lt;2; i++) {      <br>    let [userId, selectedIds] = selectId(userIds, selectedIdsSoFar);<br>    queue.push(userId);  <br>  }  <br>  let userId = queue.unshift();  <br>  sendDM(userId, payloads.request_message());<br><strong>});</strong></pre><ul><li>At 5 pm on Fridays, use the readPlans() function you implemented in your database.js file to get every plan shared by your users and post the summary to the private channel using your predefined sendSlackMessage function but with a different payload.<br>First, build the new payload.</li></ul><pre>post_summary: (message) =&gt; {<br>  return {<br>     blocks: [<br>          {<br>            &quot;type&quot;: &quot;section&quot;,<br>            &quot;text&quot;: {<br>               &quot;type&quot;: &quot;plain_text&quot;,<br>               &quot;emoji&quot;: true,<br>               &quot;text&quot;: `It&#39;s a wrap for this week. :tada:\nThank you to ${message.users} for keeping us in the loop. Here are a few things they&#39;ve accomplished:`<br>             }<br>          },<br>          { &quot;type&quot;: &quot;divider&quot; },<br>          {<br>            &quot;type&quot;: &quot;section&quot;,<br>            &quot;text&quot;: {<br>               &quot;type&quot;: &quot;mrkdwn&quot;,<br>               &quot;text&quot;: `${message.plans}`<br>            }<br>          },<br>          { &quot;type&quot;: &quot;divider&quot; },<br>          {<br>            &quot;type&quot;: &quot;section&quot;,<br>            &quot;text&quot;: {<br>               &quot;type&quot;: &quot;mrkdwn&quot;,<br>               &quot;text&quot;: `${message.plans}`<br>            }<br>          }]<br>  }<br>}</pre><p>When you query your database, you will get each plan per user. The payload expects a string of all the users and plans. For that, add another function in your utilities.js file. That function will build the strings from an array of user names or plans. Here’s what it will look like (watch it in action in this <a href="https://repl.it/@ramloul24/buildString">Repl</a>.):</p><pre>function buildString(arr, type) {<br>  let finalStr = &#39;&#39;;<br>  if (type === &#39;names&#39;) {<br>    for (let i=0; i&lt;arr.length-1; i++) {<br>      finalStr += arr[i].concat(&#39; &#39;).concat(&#39;,&#39;);<br>    }<br>    return finalStr + &#39;and &#39; + arr[arr.length-1];<br>  }<br>  else if (type === &#39;plans&#39;) {<br>    for (let i=0; i&lt;arr.length-1; i++) {<br>      finalStr += &#39;• &#39; + arr[i] + &#39;\n&#39;;<br>    }<br>    return finalStr;<br>  }<br>}</pre><p>And now the cron job.</p><pre>cron.schedule(&#39;00 17 * * 5&#39;, () =&gt; { // Run at 5 pm on Fridays only<br>  const allPlans = await readPlans();<br>  let usersArr = [];<br>  let plansArr = [];<br>  for (let key of Object.keys(allPlans)) {<br>    const { userName, plan } = allPlans[key];<br>    usersArr.push(userName);<br>    plansArr.push(plan)<br>  }<br>  let usernames = buildString(usersArr, &#39;names&#39;);<br>  let plans = buildString(plansArr, &#39;plans&#39;);<br>  let message = {users:usernames, plans: plans}<br>  sendSlackMessage(config.webhookURL,<br>                   payloads.post_summary(message))<br>});</pre><p>If all goes according to plan, here’s what you can expect to be posted at 5 pm on Fridays to your private channel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klgUjJypiQiRNOEcG65hng.png" /></figure><p>You are done with developing the app. Commit and push your working code to the GitHub repo you set earlier.</p><h3>Deploying our app to production</h3><p>So far, in our example steps above, we used our local machine as a server. But you’ll probably want to move your app to a live server. Here’s a step-by-step guide to one of the many ways you can achieve that:</p><ul><li>Set up a Virtual Private Server.</li></ul><p>For development, we used ngrok’s public URL which tunneled to our local machine to make the HTTP POST requests to our app.</p><p>Let’s say you’ll use the Linux-based VPS, Digital Ocean.</p><ol><li>Create a new Ubuntu server by following the configuration steps in <a href="https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04?utm_source=local&amp;utm_medium=Email_Internal&amp;utm_campaign=Email_UbuntuDistroNginxWelcome&amp;mkt_tok=eyJpIjoiTXpSbVpUQXhNVFUyTWpBeCIsInQiOiI3a3VYMVgzUXZkUlV1YlQ5Q3MrUEVyWU0xQ0VEdnh4WGcwNXpweGppUTJ5VVZ3M0lxTVlydVJYR3dYNWordWhXUmF5d0g1dzZ4OWUzbGZOcFZwVE4rSWJ1anBYemZ3dVZzb3RlNUsxeDkrREZURHdpZXNtRkl4Yk5uenNqaGhPTiJ9">this tutorial</a>.</li><li>Create a droplet on <a href="https://www.digitalocean.com/docs/droplets/how-to/create/">Digital Ocean</a>. The Standard Droplet plan should suffice for your small app. Once fully set up, obtain an IP address which you’ll use to make the requests to your app.</li></ol><ul><li>Set up Reverse Proxy on a Web Server</li></ul><p>Let’s say you’ll use the Nginx web server on Ubuntu.</p><ol><li>Install Nginx by following <a href="https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-18-04?utm_source=local&amp;utm_medium=Email_Internal&amp;utm_campaign=Email_UbuntuDistroNginxWelcome&amp;mkt_tok=eyJpIjoiTXpSbVpUQXhNVFUyTWpBeCIsInQiOiI3a3VYMVgzUXZkUlV1YlQ5Q3MrUEVyWU0xQ0VEdnh4WGcwNXpweGppUTJ5VVZ3M0lxTVlydVJYR3dYNWordWhXUmF5d0g1dzZ4OWUzbGZOcFZwVE4rSWJ1anBYemZ3dVZzb3RlNUsxeDkrREZURHdpZXNtRkl4Yk5uenNqaGhPTiJ9">this tutorial</a>.</li><li>Configure Nginx.<br>SSH into your droplet (replace with the IP of your droplet). Go to the ‘sites-available’ directory directory and create a new virtual host configuration file.</li></ol><pre>$ ssh root@203.0.113.0<br>$ cd /etc/nginx/sites-available<br>$ nano reverse-proxy.conf</pre><p>Paste the following configuration.</p><pre>server {<br>        listen 80;<br>        listen [::]:80;<br><br>        access_log /var/log/nginx/reverse-access.log;<br>        error_log /var/log/nginx/reverse-error.log;<br><br>        location / {<br>                    proxy_pass http://127.0.0.1:8000;<br>  }<br>}</pre><p>Replace the port with 9647 and the IP with the IP of your droplet. Copy the configuration file to the sites-enabled folder.</p><pre>$ ln -s /etc/nginx/sites-available/reverse-proxy.conf /etc/nginx/sites-enabled/reverse-proxy.conf</pre><p>Check for syntax errors.</p><pre>$ nginx -t</pre><p>If the response is ok, start the server.</p><pre>$ sudo systemctl start nginx</pre><p>Paste the IP in your web browser which should display this page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqDvdRNS3P0AafBd5viIhA.png" /></figure><ul><li>Install Node and NPM on your Ubuntu server.</li></ul><pre>$ sudo apt install nodejs<br>$ sudo apt install npm</pre><ul><li>Move your Node app to your live server.</li></ul><pre>$ git clone &lt;urlToGitHubRepo&gt;</pre><p>Remember you added config.js, node modules and the keys folder to your .gitignore file. <em>npm install</em> will create the node modules on your server. To move the config file and keys folder, transfer them from the working directory to the server using the <a href="https://docs.fedoraproject.org/en-US/Fedora/12/html/Deployment_Guide/s2-openssh-using-scp.html">SCP command</a>.</p><pre>$ scp config.js root@...<br>$ scp keys root@...</pre><ul><li>Run your script forever.</li></ul><p>Use <a href="https://www.npmjs.com/package/pm2">PM2</a> to keep your application alive forever. Install it on your server and start the application.</p><pre>$ npm install pm2<br>$ pm2 start index.js</pre><p>If you found this tutorial interesting, consider buying me a coffee. It will keep me awake when I will work on a video tutorial of this article.</p><figure><a href="https://www.buymeacoffee.com/girish"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*Dpw8-hNGI2fDmosV4E8DVQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbaf2b887c20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/make-it-heady/automating-a-flow-on-slack-cbaf2b887c20">Missing water-cooler chats? Automate a flow on Slack!</a> was originally published in <a href="https://medium.com/make-it-heady">make it heady</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node App/ Slack Plugin: Staying up to date with COVID-19 data]]></title>
            <link>https://medium.com/make-it-heady/node-app-slack-plugin-staying-up-to-date-during-corona-732ac1d394f7?source=rss-9d828152ef88------2</link>
            <guid isPermaLink="false">https://medium.com/p/732ac1d394f7</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[coronavirus]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[scheduling]]></category>
            <dc:creator><![CDATA[Girish Ramloul]]></dc:creator>
            <pubDate>Tue, 07 Apr 2020 20:05:20 GMT</pubDate>
            <atom:updated>2020-07-27T15:11:52.480Z</atom:updated>
            <content:encoded><![CDATA[<h3>Node App + Slack Plugin: Staying Up to Date with COVID-19 Data</h3><p>In this article, we’ll look at how to make a simple Node.js app to scrape COVID-19 data from a reliable source, build a Slack message with the data and then send the message at a scheduled time each day using a webhook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IF4IdF18fw6yE97lq7VGVg.jpeg" /><figcaption>The App in action</figcaption></figure><p><strong>Part 1: Data, Data Everywhere</strong></p><p>We’ll obtain the COVID-19 cases data from <a href="https://www.worldometers.info/coronavirus/">WorldOMeter</a> (a well-maintained site, vetted by the American Library Association), because we want reliable numbers, not misinformation. To scrape the web page for the relevant stats, we’ll use the <a href="https://www.npmjs.com/package/cheerio">Cheerio</a> module (assuming we already have node installed). And we’ll store the stats in the reader’s preferred DBMS (I used <a href="https://www.postgresql.org/">Postgres</a> and the <a href="https://sequelize.org/">Sequelize</a> ORM to set up a connection to my local server and model the table).</p><p>We’ll be scraping and storing a few data points: the total number of COVID-19 cases, new cases, total deaths, new deaths and total recovered.</p><p>Let’s set up our table, ‘livestats’, for that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fd6b52d0be59134512cdae74b98f643/href">https://medium.com/media/4fd6b52d0be59134512cdae74b98f643/href</a></iframe><p>The findByCountry function will help us query the table and find the stats by country, while findCasesByCountry will bring up the number of cases. These are class methods we are defining to add functionality to our models for when we need information by country.</p><p>Now that we have our models set up, let’s inspect the HTML elements of the DOM from the website to plan how we’ll scrape the relevant data. We’ll first need a jQuery Selector to fetch each row of the table (one row per country).</p><blockquote>$(‘#main_table_countries_today &gt; tbody:nth-child(2) &gt; tr’)</blockquote><p>The selector will return an object of the selected DOM elements that we can iterate over to get the set of data for each row. We are interested in the children property of the HTML element, and more specifically, the odd children (1 through 11 in terms of indices).</p><p>For example, to get to the first country’s name from the table, the selector will look something like this:</p><blockquote>$(‘#main_table_countries_today &gt; tbody:nth-child(2) &gt; tr:nth-child(2) &gt; td:nth-child(1)’)</blockquote><p>For each row, we’ll store the data in the casesByCountry object, create an instance and add it to our Sequelize model.</p><p>Before loading the HTML page into Cheerio, we’ll need to make an HTTP request to our website URL. We’ll use <a href="https://github.com/axios/axios">Axios</a> to do this. Add in some routine string manipulation to polish the data, and we have our scraping algorithm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad5630c8e6c970f75d8111dfd6867c4d/href">https://medium.com/media/ad5630c8e6c970f75d8111dfd6867c4d/href</a></iframe><p><strong>Part 2: Load up the ship</strong></p><p>The Slack messaging app will serve as our front end.</p><p>To start, we’ll fetch the data stored in our database and build the payload. Then, we’ll send it using <a href="https://api.slack.com/methods/chat.postMessage">Slack’s postMessage API</a>. (There are some prerequisites here: a configured Slack app and a webhook that we’ve generated to a channel in the workspace.)</p><p><em>First, let’s build the graph portion of the message.</em></p><p>If our front end was a plain website, then we’d have the luxury of including a script tag to our HTML to render a chart. But the best we can do with the Slack API is to download a chart, host the image and attach the link to our payload.</p><p>To begin, we’ll fetch the number of cases from our database for the country we’re interested in, using our predefined findCasesByCountry class method. (An array of model instances will be returned, which can be iterated over using the ‘get’ function.)</p><p>Then we’ll feed this data into a dynamic graph generator (I created an HTML Canvas Element using <a href="https://www.chartjs.org/docs/latest/">Chart.js</a> and added the .<a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL">toDataURL()</a> method to export the graph to a PNG file, but I’ll leave this part to the imagination of the reader.) Once we have the image, we’ll host it on <a href="https://postimages.org/">an image hosting website</a>.</p><p>By the end of this step, by whatever means the reader deems most convenient, we’ll have a URL to our graph image.</p><p><em>Now, let’s build the actual payload that we’ll pass to the postMessage API.</em></p><p>We’ll use our predefined findByCountry function to get all the statistics for our country of choice. Then we’ll populate the payload using template literals to enclose dynamic data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e37ab3fdb70dd2e862967cfb666f11b/href">https://medium.com/media/6e37ab3fdb70dd2e862967cfb666f11b/href</a></iframe><p><strong>Part 3: Lift the anchor</strong></p><p>We are almost done. The last task is to set up a job that will periodically scrape the data, sync our model with the database and post our previously built dynamic message using node’s<a href="https://www.npmjs.com/package/http-service"> http-service module</a>. We’ll use <a href="https://www.npmjs.com/package/node-schedule">Node Schedule</a> to schedule the job.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/417c975c96af10837dce0470aa93d4f1/href">https://medium.com/media/417c975c96af10837dce0470aa93d4f1/href</a></iframe><p><strong>Part 4: The ship has sailed</strong></p><p>In this article, we went over how we can scrape the WorldOMeter website to obtain timely data on the COVID-19 pandemic (using Cheerio.js) and set up a database to store that data (Postgres and Sequelize). Then we looked at how to feed that data into a simple line graph and a dynamic payload and send the payload to a Slack channel via a webhook (Slack API and Http-service) at a time scheduled by a scheduler (Node Scheduler).</p><p>We hope this was helpful!</p><p><strong>P.S :</strong> We’re hiring at Heady! 👋 If you would like to come work with us on some really cool apps please check out our <a href="https://www.heady.io/careers">careers</a> page.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=732ac1d394f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/make-it-heady/node-app-slack-plugin-staying-up-to-date-during-corona-732ac1d394f7">Node App/ Slack Plugin: Staying up to date with COVID-19 data</a> was originally published in <a href="https://medium.com/make-it-heady">make it heady</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trie Implemented in JS]]></title>
            <link>https://medium.com/@ramloul24/trie-implemented-in-js-1882954ef0e7?source=rss-9d828152ef88------2</link>
            <guid isPermaLink="false">https://medium.com/p/1882954ef0e7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[trie]]></category>
            <dc:creator><![CDATA[Girish Ramloul]]></dc:creator>
            <pubDate>Tue, 01 Oct 2019 02:35:13 GMT</pubDate>
            <atom:updated>2019-10-04T01:12:50.439Z</atom:updated>
            <content:encoded><![CDATA[<p>How do you even pronounce Trie? Is it the same as tree? If you are seeking the answer to this unsettled debate, then you are in the wrong place. But if you’re looking for a simple implementation of a trie, then read along.</p><p>What is a Trie anyway?</p><p>A Trie is a tree-like data structure whose nodes store a set of strings usually. I came across the concept of a trie the first time when I was struggling to come up with an optimal solution to an interview problem that had to do with substrings. For the scope of this article, I will only consider a trie’s implementation as a prefix tree.</p><p>Take a minute to watch the following video that visually demonstrates a Trie.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-urNrIAQnNo%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-urNrIAQnNo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-urNrIAQnNo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c35dd1edb219fcea2984018e85269272/href">https://medium.com/media/c35dd1edb219fcea2984018e85269272/href</a></iframe><p>Now, without any further ado, let’s get to the fun part, the code. I will be only looking at three of the various methods you might want in a Trie, namely “insert”, “search” (search for a full word) and “isPrefix” (search for substring or prefix).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b48f08ac0096b161f597b1dd441e1557/href">https://medium.com/media/b48f08ac0096b161f597b1dd441e1557/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1882954ef0e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>