<?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 Mehdi Chekori on Medium]]></title>
        <description><![CDATA[Stories by Mehdi Chekori on Medium]]></description>
        <link>https://medium.com/@mehdichekori?source=rss-80f030daff43------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*P9ZyLM0OZTgZLFdCtyXLTA.jpeg</url>
            <title>Stories by Mehdi Chekori on Medium</title>
            <link>https://medium.com/@mehdichekori?source=rss-80f030daff43------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 22:26:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mehdichekori/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[How to build a Twitter weather bot with Node.js Part III: Hosting on the cloud]]></title>
            <link>https://medium.com/@mehdichekori/how-to-build-a-twitter-weather-bot-with-node-js-part-iii-hosting-on-the-cloud-d704c88145c0?source=rss-80f030daff43------2</link>
            <guid isPermaLink="false">https://medium.com/p/d704c88145c0</guid>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mehdi Chekori]]></dc:creator>
            <pubDate>Sat, 30 Nov 2019 21:07:51 GMT</pubDate>
            <atom:updated>2019-11-30T21:07:51.657Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*JY7v83OLTe5BjLFdoAolNg.png" /></figure><p>Welcome to the final part of “How to build a Twitter weather bot with Node.js” series. In this tutorial, we will be hosting the bot on the cloud to make it run 24/7.</p><p>If you haven’t read part I and II you can check them out here:</p><p><a href="https://medium.com/@mehdichekori/how-to-build-a-twitter-weather-bot-with-node-js-4560eca55538">How to build a Twitter weather bot with Node.js Part I: Getting started!</a></p><p><a href="https://medium.com/@mehdichekori/how-to-build-a-twitter-weather-bot-with-node-js-part-ii-responding-to-tweets-15dc935c3194">How to build a Twitter weather bot with Node.js Part II: Responding to Tweets</a></p><p>Let’s deploy our bot to the Cloud!</p><p>To do so, we will be using the free services offered by <a href="https://www.heroku.com/pricing">Heroku</a>.</p><p>First, we want to modify the package.json file to add a start section under scripts.</p><p>This will allow Heroku to start the bot by running the npm start command.</p><pre>{<br>  &quot;name&quot;: &quot;twitter-weather-bot&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;A node.js bot that tweets your city&#39;s weather&quot;,<br>  &quot;main&quot;: &quot;weatherbot.js&quot;,<br>  &quot;scripts&quot;: {<br>    <strong>&quot;start&quot;: &quot;node weatherbot.js&quot;,</strong><br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;author&quot;: &quot;Mehdi Chekori&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;request&quot;: &quot;^2.88.0&quot;,<br>    &quot;twit&quot;: &quot;^2.2.11&quot;<br>  }<br>}</pre><p>Commit and push your changes to your GitHub repo.</p><pre>git add package.json<br>git commit -m &quot;added the npm start command to package.json&quot;<br>git push -u origin master</pre><p>Sign up to <a href="https://signup.heroku.com/login">Heroku</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1ooNnK9m3it9DOXz.png" /></figure><p>Once your account is created you will be redirected to your dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fqt20XOieLnx5DU7.png" /></figure><p>Click on the new button (top right), fill in your app’s name and select a region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FCCopfhHHdHRAOez.png" /></figure><p>Then you will need to select a deployment method. In this case, since the repo is already on GitHub (from the previous 2 tutorials) we will be selecting the GitHub option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/30/0*SIp95vp-_HrD9Stc" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L-_uWHauWsDZ1Z8s.png" /></figure><p>You will be asked to log in to your GitHub account then you will need to search for your repository name. Once you see your repository click on the connect button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WhY6ilLG0nf54dog.png" /></figure><p>Now that Heroku has access to your code you need to deploy it to Heroku. Select the master branch and click on the Deploy branch button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yJ3xUsOlBatw6J94.png" /></figure><p>You will see Heroku fetching your code and a confirmation message will be displayed once it’s done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gyX124ZAWMYYL5Db.png" /></figure><p>You can check if your dyno is running by navigating to the overview tab and verifying if the web npm start command is set to ON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*rUwPO12fiRDEfwQo.png" /></figure><p>Congratulations your Twitter bot is now online!</p><p>You can see it in action by asking it for a city’s weather on Twitter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*M6xtdGhbES7UJY43.png" /></figure><p>Thank you for reading! Consider following me if you found these tutorials helpful :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d704c88145c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a Twitter weather bot with Node.js Part II: Responding to Tweets]]></title>
            <link>https://medium.com/@mehdichekori/how-to-build-a-twitter-weather-bot-with-node-js-part-ii-responding-to-tweets-15dc935c3194?source=rss-80f030daff43------2</link>
            <guid isPermaLink="false">https://medium.com/p/15dc935c3194</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Mehdi Chekori]]></dc:creator>
            <pubDate>Sun, 24 Nov 2019 21:37:25 GMT</pubDate>
            <atom:updated>2019-11-24T21:37:25.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2lDTCMlybZsfCnzQ9SY9g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@freestocks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">freestocks.org</a> on <a href="https://unsplash.com/s/photos/twitter?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Hey everyone, welcome to part II of III of my how to build a Twitter Bot Series. If you haven’t read part I <a href="https://medium.com/@mehdichekori/how-to-build-a-twitter-weather-bot-with-node-js-4560eca55538">Click Here</a>.</p><p>Today we are going to add a new feature where our bot will be able to read inputs from users and respond with the corresponding weather data.</p><p>As always you can find the source code in the <a href="https://github.com/mehdichekori/twitter-weather-bot">Github repo.</a></p><p>Let’s get started!</p><p>This is how it will look like by the end of this tutorial :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*Os5g8jihopQ8fvJkRX4aTg.png" /></figure><p>As you can see I am Tweeting @ MtlWeatherBot followed by my city (Montreal), then I’m specifying the country code.</p><p>The bot then proceeds to respond with the current weather.</p><p>The Twit library offers the ability to listen to a stream. We can specify that we want to listen to the status stream and filter them by those who contain our username to get the tweets that are directed at us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*CF-0ejeJkOnpVY4a_VIg3g.png" /></figure><p>configs.username is our Twitter handle:’@mtlweatherbot’</p><p>Now that we are listening to the stream, every time that there is a tweet that contains @mtlweatherbot the TweetEvent Function will be called.</p><p>Let’s define that function.</p><p>The Tweet Event function will need to read that tweet, parse it to get the city &amp; country code get their weather data and then reply.</p><p>The function will receive a tweet object that contains quite a lot of information. You can see an example <a href="https://developer.twitter.com/en/docs/tweets/sample-realtime/api-reference/get-statuses-sample">here</a>.</p><p>We will need :</p><ul><li>the username of who tweeted at us (tweet.user.screen_name)</li><li>the reply identifier (tweet.id_str)</li><li>and the text (tweet.text)</li></ul><p>The text will need to be parsed to make sure it follows our specified format.</p><p>Let’s create a new function called ParsedTweet(tweet.text) and we will pass it the text content of our tweet.</p><p>The reason we want the tweets to follow a specific pattern is to make it easier for us to find and reply with the right data. In the previous tutorial, we were accepting any tweet that had our username and a word that came after it. That can lead to errors from the API, or us returning the wrong data if for example the city that they are looking for exists in multiple states or countries.</p><p>An easy way to do so is to use a regex expression.</p><blockquote>A regular expression, regex or regexp is a sequence of <a href="https://en.wikipedia.org/wiki/Character_(computing)">characters</a> that define a search <a href="https://en.wikipedia.org/wiki/Pattern_matching">pattern</a>. Usually such patterns are used by <a href="https://en.wikipedia.org/wiki/String_searching_algorithm">string searching algorithms</a> for “find” or “find and replace” operations on <a href="https://en.wikipedia.org/wiki/String_(computer_science)">strings</a>, or for input validation. It is a technique developed in <a href="https://en.wikipedia.org/wiki/Theoretical_computer_science">theoretical computer science</a> and <a href="https://en.wikipedia.org/wiki/Formal_language">formal language</a> theory.</blockquote><p>We want all the tweets to follow this pattern @TheBotUsername ,The city, The country code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*JfXeYo-I92jyVFeaNwyiSA.png" /></figure><p>At first glance, this looks complicated but we can break it down in sections.</p><pre><strong>@MtlWeatherBot </strong>: Matches “@Mtlweatherbot “ (with a space after the username)</pre><blockquote><strong><em>@MtlWeatherBot </em></strong>,Montreal,ca</blockquote><pre><strong>(([a-z]*)|([a-z]* [a-z]*)) </strong>: Matches any 1 word composted with characters from a to z or any 2 words with a space in between</pre><blockquote>@MtlWeatherBot <strong><em>,Montreal</em></strong>,ca</blockquote><pre><strong>,[a-z]{2} </strong>: Matches any 2 character country code preceded by a comma</pre><blockquote>@MtlWeatherBot ,Montreal<strong><em>,ca</em></strong></blockquote><pre><strong>$</strong> : Matches the end of a string</pre><blockquote><strong><em>@MtlWeatherBot ,Montreal,ca</em></strong></blockquote><p>Finally, the second parameter (“i”) is to specify that we want to ignore the case.</p><p>If you would like to learn more while playing with regular expressions I recommend the website <a href="https://regexr.com/">https://regexr.com/</a></p><p>To test if the tweet fits our regular expression we can use the test function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*j_XZ4-pmQN53kJY_MV3zXQ.png" /></figure><p>If the tweet matches our pattern we want to extract the city and the country code from it.</p><p>To do so we will use the substring function and the split function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*kaeAx9gMHrAilzaoY3gdsA.png" /></figure><blockquote><strong>The substring() method extracts the characters from a string, between two specified indices, and returns the new substring.</strong></blockquote><p>Since we only specified 15, that’s where the substring will start. 15 is the index where the city’s name starts.</p><p>This index depends on the length of your bot’s username.</p><blockquote><strong>The split() method is used to split a string into an array of substrings, and returns the new array.</strong></blockquote><p>The function also takes a separator parameter, in our case, it will be the comma.</p><p>Now that we can read a tweet, see if it matches the correct pattern and extract the city and the country code from it we want to throw an error if it doesn’t match our pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*jzkXkKlnQrYZ3r0GfpX7eg.png" /></figure><p>The full function looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_mcJ7q9FQa5J-UJRVlVcw.png" /></figure><p>Back to the TweetEvent function!</p><p>So far the function looked like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*DVulIZWFeoDlHGgq87Hxtw.png" /></figure><p>Let’s call the ParseTweet function we created with the text from the tweet as a parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*f1VEyDnU-ge6ido2J7T_Uw.png" /></figure><p>Then we assign the results to two variables city and country. We then need to call the GetData function. But since in the first part of this tutorial we were always gathering the data for Montreal that function didn’t take a city and a country as a parameter.</p><p>We then need to refactor the GetData() to make it more flexible.</p><p>We start by making the function asynchronous and adding two parameters city and country.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*5TZ2Fy1B-dBezcfhOruG9w.png" /></figure><p>and this function will return a new promise.</p><blockquote>A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action&#39;s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*SCU9yHsrZwmLdw8uvTefCw.png" /></figure><p>We don’t want this change to break the functions that were calling GetData from the previous tutorial, so we will add a condition that checks if we are specifying a city and a country and if we are we will change the URL we use to call the Open Weather Map API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*LyopfnKd0ZTTRv-Kw9exdw.png" /></figure><p>If the parameters are undefined we will be calling the default URL which is set to Montreal.</p><p>The request stays the same for one change which is that we need to call the resolve() function when we are done with our call. It will set the state of the promise to resolved.</p><p>Then in the else part of the code, we added a New Error. The error will be replied to the user later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AcnjI9ZgUNP0HIf1weUOdA.png" /></figure><p>Back to TweetEvent.</p><p>We want to call GetData() with the city and country extracted and once we get the result from the API, we want to construct our tweet.</p><p>You can easily do so by using the function ‘then’. It allows us to execute code once a promise is resolved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*Tx1VPsoLcIVewZvlkACpgQ.png" /></figure><p>Once we have the results from the API we then call CleanData() and we want to set the status for the reply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*Dg_jIgyCa3puzEx2v09jKQ.png" /></figure><p>If we pass a tweeter username as a parameter that means we are construction a tweet for a reply, if not it means we are constructing a tweet for a general broadcast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*NbxyRaIzLRRnjn5OMUTRag.png" /></figure><p>Then we assign the status and the reply id to the params object to be used for the TwitterApi Post and you tweet your reply!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*l_P0OU3PNUUWuoqZWGXXnQ.png" /></figure><p>If anything went wrong during the process we want the bot to reply to let the user know.</p><p>In the catch, we reconstruct the params but this time we will use the content of the error as a status reply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*Fe0LdK2wCbxnVdbqhEVcQQ.png" /></figure><p>Finally, the full function should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*-e9HlSmazQE2cpWE440NMA.png" /></figure><p>Finally, let’s refactor the old Tweet() function to use the same logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*NVdDrkl-RJ3X8w_IaVWe4w.png" /></figure><p>We still want to broadcast Montreal’s weather once per hour as in the previous tutorial, so we call the function inside of setInterval().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*RdlbtDU-TRKi-mGv76U-4w.png" /></figure><p>🎉🥳 There you go! 🎉🥳</p><p>Our bot is now able to tweet Montreal’s weather every hour and reply to anyone that wants to know the weather for their own city!</p><p>You can see the results by Tweeting at <a href="https://twitter.com/MtlWeatherBot">@MtlWeatherBot</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*rFvGKl7kaqAmHG7uqq6aTw.png" /></figure><p>Don’t you wish you were at Cancun? Because I sure do!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4Bhol3cOYG_0WLkkDCeMw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nextvoyage_pl?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Andreas NextVoyagePL</a> on <a href="https://unsplash.com/s/photos/cancun?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Thank you for reading this article. In the next tutorial, we will be hosting our project on the cloud and getting it to run automatically 24/7.</p><p>Stay tuned!</p><p>As always you can find the source code in the <a href="https://github.com/mehdichekori/twitter-weather-bot">Github repo.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15dc935c3194" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a twitter weather bot with Node.js]]></title>
            <link>https://medium.com/@mehdichekori/how-to-build-a-twitter-weather-bot-with-node-js-4560eca55538?source=rss-80f030daff43------2</link>
            <guid isPermaLink="false">https://medium.com/p/4560eca55538</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Mehdi Chekori]]></dc:creator>
            <pubDate>Tue, 19 Nov 2019 03:31:14 GMT</pubDate>
            <atom:updated>2019-11-24T18:26:44.607Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to build a Twitter weather bot with Node.js Part I: Getting started!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*ZDhDbcXoc8qpHhV20I__bw.png" /></figure><p>Hey everyone, this is my first post in a multi-part bot building series. For this first part, we will be building a weather bot that broadcasts your city’s weather to the Twittersphere.</p><p>You can find the code for this tutorial in my GitHub Repository: <a href="https://github.com/mehdichekori/twitter-weather-bot">twitter-weather-bot</a>.</p><p>Here is what we need:</p><ul><li><a href="https://git-scm.com/">Git</a></li><li><a href="https://nodejs.org/en/">Node</a></li><li><a href="https://www.npmjs.com/get-npm">Npm</a></li><li>A text editor (I prefer to use Visual Studio Code)</li><li>A command-line interface (I prefer to use PowerShell)</li></ul><h3>Step 1: Set up a new twitter account</h3><p>This is where your bot will communicate with the world its passion for the weather. Once your account is created you should check out Twitter’s rules for automated accounts. There are few rules to protect against spam that you want to follow. The rules can be found <a href="https://help.twitter.com/en/rules-and-policies/twitter-automation">here.</a></p><h3>Step 2: Create a new Twitter App</h3><p>Now that you have an account, your bot needs credentials to be able to communicate with the Twitter API. In order to get them, you need to create a new Twitter App.</p><p>Go to <a href="https://developer.twitter.com/en/apps">https://developer.twitter.com/en/apps</a> and click on Create an App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INNZLhmgLTUEWVjo4de7ug.png" /><figcaption>Twitter Apps screen</figcaption></figure><p>Fill in your app’s details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPrQtl-GNS7GE7riyo__fQ.png" /></figure><p>Make sure to follow the Developer Agreement and Policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*HqjOvz00JUtuaSc3fYcALw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*5xu_cP_bFQJ6NhtGQ-mMkg.png" /></figure><p>Good job! Your app is created! You should see a summary of your app’s information.</p><h3>Step 3: Keys and Tokens</h3><blockquote>An <strong>application programming interface key</strong> (<strong>API key</strong>) is a unique identifier used to authenticate a user, developer, or calling program to an <a href="https://en.wikipedia.org/wiki/Application_programming_interface">API</a>. However, they are typically used to authenticate a <em>project</em> with the API rather than a human user.</blockquote><p>Navigate to the “Keys and tokens” tab of your application and generate access tokens. Our bot needs these keys and tokens in order to authenticate and send tweets to twitter.</p><p>You should always keep these 4 strings hidden because anyone could use your app if they can get a hold of them. You can see mine in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KloQ8H8lqoL4atHmL1FMrw.png" /></figure><p>Don’t get tempted to use them because they will be regenerated when this article goes live ;)</p><p>Moving on!</p><p>Now that you have a Twitter account and a Twitter app you need the weather data that you will be broadcasting!</p><h3>Step 3: Set up a new Open weather map account</h3><p><a href="https://openweathermap.org/api">Openweathermap.org</a> offers a great API that has all the weather data we need for this tutorial. Go on and create an account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nXXzhCOMqyYaHvIrX_dXRw.png" /></figure><p>They will send you your API Keys by email.</p><p>While you’re there you should take a look at their <a href="https://openweathermap.org/current">current weather data section API documentation</a> which we will be using for this tutorial.</p><h3>Step 4: Create the project</h3><p>Open up a new command prompt window and enter the following commands</p><pre><strong>Git init</strong></pre><p><strong>Git init</strong> will initialize an empty Git repository.</p><pre><strong>Npm init</strong></pre><p><strong>Npm init</strong> will ask you to enter a few details about your new repository and it will create a package.json file for you.</p><p>This is the content of my package.json file.</p><pre>{<br>  &quot;name&quot;: &quot;montreal-weather-bot&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;A node.js bot that broadcasts weather data about Montreal on Twitter.&quot;,<br>  &quot;main&quot;: &quot;weatherBot.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;author&quot;: &quot;Mehdi Chekori&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hHHLRjgkzyONo_3oMxK-bg.png" /></figure><p>Install the 2 packages we will need.</p><p><strong>Request:</strong> Request is designed to be the simplest way possible to make HTTP calls. It supports HTTPS and follows redirects by default.</p><p><strong>Twit:</strong> Twitter API Client for node.</p><pre>Npm install request</pre><pre>Npm install twit</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*6w2r2Bm673gFiQGzOAhfDg.png" /></figure><p>You can see your freshly installed packages in the “dependencies” section of your package.json file.</p><pre>{<br>  &quot;name&quot;: &quot;montreal-weather-bot&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;A node.js bot that broadcasts weather data about Montreal on Twitter.&quot;,<br>  &quot;main&quot;: &quot;weatherBot.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;author&quot;: &quot;Mehdi Chekori&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br><strong>  &quot;dependencies&quot;: {<br>    &quot;request&quot;: &quot;^2.88.0&quot;,<br>    &quot;twit&quot;: &quot;^2.2.11&quot;<br>  }</strong><br>}</pre><p>Create a configs.js file that will store the Twitter &amp; OpenWeaterMap API keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*LCaTR7zcN6Z3ABetE1JE0g.png" /></figure><p>Create a weatherBot.js file that will contain the logic for our Twitter bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*CvrWufVyhJGr25-azBkIlw.png" /></figure><h3>Step 5: Start Coding!</h3><p>Open up the configs.js file and paste the snippet below in it.</p><pre>module.exports = {<br>  // twitter api configs<br>  consumer_key: ‘GrQ1ZUtFMRhYsoIYnZvUmHpBy’,<br>  consumer_secret:<br>  ‘NShduET9yIovcMM2HAwOrsH3HCFg9HudjZp3ecPgGfigDq6UJH’,<br>  access_token: <br>  ‘809949568586620928-9EtkVZucCkr3eUucusiCZktpZeV3NjU’,<br>  access_token_secret:<br>  ‘RE3lSZ5RrFzRSxwy4wIH7CDnb7XfdlcGs3aTPDafgPRnR’,</pre><pre>// open weather map api configs<br>  apiLink: ‘http://api.openweathermap.org/data/2.5/weather?q=&#39;,<br>  city: ‘Montreal’,<br>  appID: [‘&amp;appid=’,’b6907d289e10d714a6e88b30761fae22&#39;],<br>  units: [‘&amp;units=’,’metric’]<br>}</pre><p>You need to replace the values by your own in order to access your Twitter App.</p><p>Now that you have your keys configured let’s build a bot!</p><p>Open up weatherBot.js file and import our dependencies.</p><pre>var request = require(&#39;request&#39;);</pre><pre>var Twit = require(&#39;twit&#39;)</pre><pre>var configs = require(&#39;./configs&#39;);</pre><p>Then we declare the variables we will be using.</p><pre>var TwitterApi = new Twit(configs);</pre><pre>var currentTemp;</pre><pre>var minimumTemp;</pre><pre>var maximumTemp;</pre><pre>var weatherDescription;</pre><pre>var windSpeed;</pre><pre>var url = configs.apiLink + configs.city + configs.appID[0] + configs.appID[1] + configs.units[0] + configs.units[1];</pre><p>Don’t get scared by the URL. What we are doing is pretty simple, we are building a dynamic URL based on the values from our configs. This way we don’t have any hardcoded configuration values inside of our weatherBot file.</p><p>Let’s build a function that will grab the data from the OpenWeatherMap API. We will call it GetData.</p><pre>function GetData(){</pre><pre>request({ url:url, json:true }, function (error, response, body){</pre><pre>if(!error &amp;&amp; response.statusCode === 200){</pre><pre>currentTemp = body.main.temp;<br>    minimumTemp = body.main.temp_min;<br>    maximumTemp = body.main.temp_max;<br>    humidity = body.main.humidity;<br>    windSpeed = body.wind.speed;<br>    weatherDescription = body.weather[0].description;</pre><pre>} else {</pre><pre>console.log(&quot;Error triggered inside of the GetData function.&quot;);<br>    console.log(error);<br>  }</pre><pre>})</pre><pre>}</pre><p>Inside of this function we use the request package to make a call to the URL we passed in parameters and specify that we want a JSON response.</p><p>If there are no errors and we get a response with a status code of 200 (OK) we proceed to assign weather data to our variables. If we get an error we log it in the console.</p><p>Now that we have this data we need to parse it in a way that it’s readable and tweet it!</p><p>To clean up, create a new function called CleanData and a function called ConvertMetersPerSecondToKmPerHour.</p><p>We want our temperatures to be whole integers and the wind to be in Km/h</p><pre>function CleanData(){</pre><pre>currentTemp = currentTemp.toFixed(0);<br>minimumTemp = minimumTemp.toFixed(0);<br>maximumTemp = maximumTemp.toFixed(0);<br>windSpeed   = ConvertMetersPerSecondToKmPerHour(windSpeed);</pre><pre>}</pre><p>To convert from meters per second we can multiple the speed by 3.6</p><pre>function ConvertMetersPerSecondToKmPerHour(speed){</pre><pre>return (speed * 3.6).toFixed(0);</pre><pre>}</pre><p>Now that your data is looking neat let’s tweet it!</p><p>Create a function called Tweet()</p><pre>function Tweet(){</pre><pre>var weatherUpdate = &quot;Currently &quot;+ configs.city +&quot; is experiencing &quot; + weatherDescription + &quot; at &quot; + currentTemp + &quot;°C.&quot; + &quot;\n&quot; +&quot;Daily forecast: min of &quot; + minimumTemp + &quot;°C &quot; + &quot;&amp; a max of &quot; + maximumTemp + &quot;°C with &quot; + humidity + &quot;% Humidity&quot; + &quot; &amp; &quot; + ConvertMetersPerSecondToKmPerHour(windSpeed) + &quot;Km/h Wind. \n#montreal #montrealweather&quot;</pre><pre>var tweet = {<br>    status: weatherUpdate<br>  }</pre><pre>TwitterApi.post(&#39;statuses/update&#39;,tweet, callback);</pre><pre>function callback(error){<br>    if(error){<br>      console.log(error);<br>    } else {<br>      console.log(&quot;Tweeted successfully: \n&quot; + weatherUpdate);<br>    }<br>  }<br>}</pre><p>We start by constructing a string (weatherUpdate) with the values we gathered.</p><pre>“Currently “+ configs.city +</pre><pre>” is experiencing “ + weatherDescription +</pre><pre>“ at “ + currentTemp + “°C.”</pre><pre>“\n” +”Daily forecast: min of “ + minimumTemp +</pre><pre>“°C “ + “&amp; a max of “ + maximumTemp +</pre><pre>“°C with “ + humidity + “% Humidity” +</pre><pre>“ &amp; “ + windSpeed +</pre><pre>“Km/h Wind. \n#montreal #montrealweather”</pre><p>This will output the following sentence:</p><pre>Currently Montreal is experiencing few clouds at -8°C. Daily forecast: min of -12°C &amp; a max of -4°C with 62% Humidity &amp; 61Km/h Wind. #montreal #montrealweather</pre><p>You can switch what the bot will broadcast as you like.</p><p>In order to use our functions, we need to be call them.</p><p>We need to start with GetData() which will call CleanData() once it has the response from the weather API and once the data is cleaned we need to Tweet() it.</p><p>It should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*PXCy0u_49NnH3kIUh99n6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*m1SZBcm0HRZVfgiBSUmIMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*4qM7TWUCyIW_a_sYIImcfg.png" /></figure><p>Finally, we don’t want to be running this app every time we want the bot to tweet. So let’s put in on a recurring schedule.</p><pre>setInterval(GetData,1000*60*60);</pre><p>The set interval function calls the function it has as a first parameter at the interval specified by the second one in milliseconds (1000ms = 1 second).</p><p>This will trigger our bot to tweet every hour.</p><p>To run our bot run the following command :</p><pre>node weatherbot.js</pre><h3>Step 6: Get your weather forecast on Twitter!</h3><p>Navigate to your account’s page and you should have your first tweet!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*9ZqaDMrOf_0Qj4JOOWbn_A.png" /></figure><p>You can see the bot in action on <a href="https://twitter.com/mtlweatherbot">https://twitter.com/mtlweatherbot</a></p><h3>Step 7: Push your code (optional)</h3><p>You can do so by running the following commands :</p><p>We want to git ignore the Node_Modules folder.</p><pre>Set-Content Path\twitter-weather-bot\.gitignore &#39;/node_modules&#39;</pre><p>Git Add the files you created.</p><pre>git add -A</pre><p>Git Commit them.</p><pre>git commit -m &quot;first commit&quot;</pre><p>Add the remote origin.</p><pre>git remote add origin <a href="https://github.com/YourUser/twitter-weather-bot.git">https://github.com/YourUser/twitter-weather-bot.git</a></pre><p>And finally, push the code.</p><pre>git push -u origin master</pre><p>Remark: if your repository is public, you don’t want to push your config file since it contains your API keys.</p><p>Thank you for following along. In the next article, we will be adding an auto-respond feature and hosting our Twitter bot on the cloud so that it can run 24/7.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4560eca55538" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>