avatarKartik Nighania

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3987

Abstract

icity, I saved it as <i>Twilio Sandbox</i>, then sent it a message from my dad’s phone, as seen above. This has to be done once and only once.</p><p id="17f2">Now go to <a href="https://www.twilio.com/console?source=post_page---------------------------">Twilio Console</a> and get your account SSID and authentication token. This will help Twilio know it’s you when the code is executed.</p><h1 id="58ff">Step 2: Understanding and Modifying the Code</h1><p id="b49b"><a href="https://github.com/kartik-nighania/whatsapp_with_aws_lambda">Download the GitHub repository</a> and extract it.</p><figure id="e76a"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*18uT8WsHFEjzbRyB.png"><figcaption>inside the zip file</figcaption></figure><p id="2c91">Inside this, you’ll find our code file and deployment package.</p><ul><li><code>whatsapp_messaging.py</code></li><li><code>aws_lambda_deploy.zip</code></li></ul><figure id="ac55"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*WN20eV2n9fRF3t9B.png"><figcaption>whatsapp_messaging code file</figcaption></figure><ul><li><b>line 1 </b>imports the Twilio package and uses its <code>REST</code> client to hit the Twilio API.</li><li><b>line 3: </b>We<b> </b>create a function, <code>msg_mom_and_dad</code>, which will be given to AWS to run every day at a certain time.</li><li><b>line 6–7: </b>Replace the <code>sid</code> and <code>auth_token</code> of your account as discussed in step 1.</li><li><b>line 9: </b>Twilio client object is created with our credentials.</li><li><b>line 13: </b>A Python dictionary is created with name as <code>key</code> and mobile number as <code>value</code>. You can keep adding to this Python dictionary to send messages to more people as well.</li><li><b>line 15</b>: A <code>for</code> loop that runs through all the <code>key</code> and <code>value</code> pairs (currently we just have one). In <code>body</code>,<b> </b>mention your message. I have created a simple one, which says good morning, followed by the <code>key</code> value. In the above code, it is “good morning daddy!”<i> </i>We then mention the <code>from</code><b> </b>number, which is the Twilio WhatsApp number you got earlier, and the <code>to</code><b> </b>number, from which you previously sent the WhatsApp sandbox confirmation.</li><li><b>line 23: </b>A line to check message status by printing the SID. We won’t use this anyway.</li></ul><p id="4ee7">We have five things to change:</p><ul><li><code>twilio_sid</code></li><li><code>auth_token</code></li><li><code>contact_directory</code></li><li><code>from_</code></li><li><code>body (optional)</code></li></ul><p id="09f8">After you have changed these, save it. Then extract the <code>aws_lambda_deploy.zip</code><b> </b>and replace the <code>whatsapp_messaging.py</code><b> </b>inside it with your newly created one. Zip the package again. We just wanted to change the code with your credentials and contact details. Your deployment package is now ready.</p><h1 id="c95a">Step 3: Put Our Package on AWS Lambda With Triggers</h1><p id="4ae6">Our code is ready to run and send WhatsApp messages. If you’re wondering what the other files in our deployment package are, they’re the Twilio package and all its other dependencies. This is because we’ll use an AWS Lambda function in a Python environment that doesn’t have the Twilio package. But why not just run <code>pip install twilio</code> to install it? This is because we don’t have a server here.</p><figure id="3bfc"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*fEAzzAGatzVMD46r.png"><figcaption></figcaption></figure><p id="5fce"><b>AWS Lambda </b>is a serverless computing service where you have a piece of code that you want to run based on different AWS events and triggers, according to the users’ needs. Therefore, it’s a waste of computing resources and money to run a server (EC2 instance in AWS) 24/7 to do our small cute task. Here our Lambda function will on

Options

ly run for a very short time every day on our mentioned time trigger.</p><p id="3863">The Lambda service is very cheap and gives you a million requests per month for free.</p><figure id="93de"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*HGJzJL6xYBOykofm.png"><figcaption></figcaption></figure><p id="5bbf">Log in to <a href="https://aws.amazon.com/?source=post_page---------------------------">https://aws.amazon.com</a>. Then click on Services -> Compute -> Lambda -> create a function</p><figure id="1b72"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*iWIJ3d3KAA3NjeiU.png"><figcaption></figcaption></figure><p id="3e94">Give your function a name.</p><p id="a73e">We selected Python 3.6 as our environment of choice.</p><p id="d64c">As we don’t need to connect to other services in AWS, the option of basic permission is fine.</p><p id="1576">Click on <i>create function</i> and you’ll be taken to the main dashboard.</p><figure id="9d8e"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*F-OBEyjZaEroKAytiWLN7A.png"><figcaption></figcaption></figure><p id="0458">In the function code block, specify to the Lambda Function Handler that we want to run our <code>whatsapp_messaging</code> Python file and the <code>msg_mom_and_dad</code><b> </b>function inside it each time the Lambda function is called. Change the handler value as above.</p><p id="ea4f">At the code entry point, select <i>upload a .zip file</i>, upload the deployment package you created in step 2, and save<b> </b>it.</p><p id="68e2">Our code is ready to run. You can click on <b>test </b>and check that the function successfully sends a message to the specified WhatsApp number.</p><p id="89e0">Our last step is to trigger it every day at a given time. For this, click <b>add trigger -> CloudWatch Events </b>in the designer box.</p><figure id="ee4d"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*iVW3YNmCTFi946yG.png"><figcaption></figcaption></figure><p id="5ffd">We’ll have to create a new rule. You can give it any name and description if you want.</p><p id="3d53">Set the rule type as <i>schedule expression</i>.</p><p id="b1ca">We specified the time using <code>cron()</code><i>. </i><code>30 1</code> refers to 1:30 am, UTC (equivalent to my 7 AM, IST time).</p><p id="3054">The next two,<code>* *</code>, are for the day of the month and the month.</p><p id="e2d7">The next two, <code>? </code>,<b> </b>are for the day of the week and year. We set <code></code> and <code>?</code> to specify every day, month, and year. You can refer to the example below to create your own <code>cron</code> parameters. Otherwise, you can refer to the <code>cron</code> guide on <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html?source=post_page---------------------------#CronExpressions">aws_cron_docs</a> to learn it in depth.</p><figure id="3fcf"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*dUTWSEgGn6jMJd0h.png"><figcaption></figcaption></figure><p id="3275">After you’re done, make sure the <b>Enable trigger</b> checkbox is checked. Finally, click the add button.</p><figure id="8f50"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*lfTTomYB-WvJfIBavz6mKw.png"><figcaption></figcaption></figure><figure id="cf8f"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*Wi_egEWINElZtGZ2uzC4eQ.png"><figcaption></figcaption></figure><p id="b884">On the Lambda function dashboard, you can now see your CloudWatch Event attached to your Lambda function. Upon scrolling down, you can see the CloudWatch event enabled to trigger your function.</p><p id="5894">That’s it! You can change the Twilio Sandbox name to your name and can even respond to replies from the Twilio dashboard.</p><figure id="208d"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*KeTft1r6hsaFjXP2.jpeg"><figcaption></figcaption></figure></article></body>

I Wrote a Script to WhatsApp My Parents Every Morning in Just 20 Lines of Python Code

A step-by-step guide with walkthrough code

Photo by Brittany Simuangco on Unsplash

In our busy work lives, we often forget to WhatsApp our loved ones. Looking at how regular my parents are in messaging me with inspirational quotes and health tips first thing in the morning, it was time to reciprocate.

In this tutorial, we will write a simple Python script to send a WhatsApp message. Twilio is the Python package we will use. To run it every day at a certain time, we will put our code on the AWS (Amazon Web Services) cloud.

So let’s get started!

One solution is to use Python’s Selenium package and go to WhatsApp web rather than using Twilio, which is subscription-based after the free tier is over. But as WhatsApp requires QR-code scanning through mobile from time to time, automation wasn’t possible.

We will do it in a three-step process:

Step 1: Twilio Initial Setup

Create a free Twilio account and confirm your email and mobile number.

Also, a free tier Twilio account requires using Twilio Sandbox for WhatsApp, which means you can’t use your number and have to go through one-time permission to receive WhatsApp messages.

Both can be solved when you get your own number, which is done after WhatsApp approves Twilio to use your number. There is a form to fill out and a wait time too.

All of this is discouraging, but our free tier solution does the job fine. Also, for now, this is the only available way.

Now you have to connect the receiver’s phone to the WhatsApp Sandbox to start receiving messages.

Go to WhatsApp beta in the learn section of the console.

Save the WhatsApp number assigned to you in your contacts. You can give it any name you want. For simplicity, I saved it as Twilio Sandbox, then sent it a message from my dad’s phone, as seen above. This has to be done once and only once.

Now go to Twilio Console and get your account SSID and authentication token. This will help Twilio know it’s you when the code is executed.

Step 2: Understanding and Modifying the Code

Download the GitHub repository and extract it.

inside the zip file

Inside this, you’ll find our code file and deployment package.

  • whatsapp_messaging.py
  • aws_lambda_deploy.zip
whatsapp_messaging code file
  • line 1 imports the Twilio package and uses its REST client to hit the Twilio API.
  • line 3: We create a function, msg_mom_and_dad, which will be given to AWS to run every day at a certain time.
  • line 6–7: Replace the sid and auth_token of your account as discussed in step 1.
  • line 9: Twilio client object is created with our credentials.
  • line 13: A Python dictionary is created with name as key and mobile number as value. You can keep adding to this Python dictionary to send messages to more people as well.
  • line 15: A for loop that runs through all the key and value pairs (currently we just have one). In body, mention your message. I have created a simple one, which says good morning, followed by the key value. In the above code, it is “good morning daddy!” We then mention the from number, which is the Twilio WhatsApp number you got earlier, and the to number, from which you previously sent the WhatsApp sandbox confirmation.
  • line 23: A line to check message status by printing the SID. We won’t use this anyway.

We have five things to change:

  • twilio_sid
  • auth_token
  • contact_directory
  • from_
  • body (optional)

After you have changed these, save it. Then extract the aws_lambda_deploy.zip and replace the whatsapp_messaging.py inside it with your newly created one. Zip the package again. We just wanted to change the code with your credentials and contact details. Your deployment package is now ready.

Step 3: Put Our Package on AWS Lambda With Triggers

Our code is ready to run and send WhatsApp messages. If you’re wondering what the other files in our deployment package are, they’re the Twilio package and all its other dependencies. This is because we’ll use an AWS Lambda function in a Python environment that doesn’t have the Twilio package. But why not just run pip install twilio to install it? This is because we don’t have a server here.

AWS Lambda is a serverless computing service where you have a piece of code that you want to run based on different AWS events and triggers, according to the users’ needs. Therefore, it’s a waste of computing resources and money to run a server (EC2 instance in AWS) 24/7 to do our small cute task. Here our Lambda function will only run for a very short time every day on our mentioned time trigger.

The Lambda service is very cheap and gives you a million requests per month for free.

Log in to https://aws.amazon.com. Then click on Services -> Compute -> Lambda -> create a function

Give your function a name.

We selected Python 3.6 as our environment of choice.

As we don’t need to connect to other services in AWS, the option of basic permission is fine.

Click on create function and you’ll be taken to the main dashboard.

In the function code block, specify to the Lambda Function Handler that we want to run our whatsapp_messaging Python file and the msg_mom_and_dad function inside it each time the Lambda function is called. Change the handler value as above.

At the code entry point, select upload a .zip file, upload the deployment package you created in step 2, and save it.

Our code is ready to run. You can click on test and check that the function successfully sends a message to the specified WhatsApp number.

Our last step is to trigger it every day at a given time. For this, click add trigger -> CloudWatch Events in the designer box.

We’ll have to create a new rule. You can give it any name and description if you want.

Set the rule type as schedule expression.

We specified the time using cron(). 30 1 refers to 1:30 am, UTC (equivalent to my 7 AM, IST time).

The next two,* *, are for the day of the month and the month.

The next two, ? *, are for the day of the week and year. We set * and ? to specify every day, month, and year. You can refer to the example below to create your own cron parameters. Otherwise, you can refer to the cron guide on aws_cron_docs to learn it in depth.

After you’re done, make sure the Enable trigger checkbox is checked. Finally, click the add button.

On the Lambda function dashboard, you can now see your CloudWatch Event attached to your Lambda function. Upon scrolling down, you can see the CloudWatch event enabled to trigger your function.

That’s it! You can change the Twilio Sandbox name to your name and can even respond to replies from the Twilio dashboard.

AWS
Python
Social Media
Coding
Programming
Recommended from ReadMedium