Open In App

Sending SMS from Python with Google Cloud Functions

Last Updated : 25 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to talk about how we are going to send SMS (Short Message Services) with the addition of the Powers of Google Cloud Functions. Combining it with Twilio which is a cloud communications platform that provides APIs for sending and receiving SMS messages, as well as other communication channels like voice calls and video will help us to create a “serverless” solution for sending SMS messages.

Setting up your Google Cloud Project

Step 1: Sign in with your Google Account in Google Cloud (Type Google Cloud and then search for Console, NOT the topmost link)Or you can skip the account creation as It requires Card information and tax details some of you might not have them

Step 2: Create a new Project, If you are a new user it should create a default project by itself, if not. Creating project It will look Something like this

Image-3-

Output of Cloud page

Step 3: Now you will be welcomed to the console of the Google Cloud with your project name. Now select the 3 dots (Navigation Menu) which will have all the necessary APIs.

Image-4

Step 4: Now In the Navigation menu select the API & Services and then select Libary in the drop-down menu.

image-5

Step 5: Now Search for “Cloud Pub/Sub” API not to be confused with Pub/Sub lite API, click on it and press activate

Step 6: Now you might see this after activating the “Cloud Pub/Sub” API.

Image-6

Don’t Panic No money is required (Thnx!)

Step 7: Now you just need to fill up your credentials, for our project we need to select these options

Image-7

Step 8: Click Next and Create your Service Account Name, Service ID will be automatically generated. Now grant the Service Account Cloud Pub/Sub Service Agent to your service account as his role.Now Grant admin access to your Gmail account, this makes it so that in the future you can access this service account. Your Policy will be updated. Now go and search for “Cloud Functions API” Activate it and you are golden!

Step 9: From Nevagation Menu select “IAM & Admin” and click on “Service Accounts” Find the service account for which you want to generate the JSON key file and click on it. In the service account details page, click on the “Manage Keys” tab from Action (three dots thingy) “Click” on Add key and select “Create new key“. JSON file will have been downloaded in your system. It contains many sensitive informations.

Step 10: Now we will be requiring to create Topic for your project, you will be required to go to Pub/Sub in Analytic section, nevigate to “Topics” and there you will find this option

Image-10

Create Topic

After creating your “Topic” Click on the newly created Topic ID it will redirect you to “Topic name“, now copy that “Topic name

Image-9

After Setting up your Google Cloud Project, You set up your Twilio account with thee help os given instructions.

Setting Up your Twilio Account

  1. Go to Twilio and Sign in after which you will find fue important Informations.
  2. After Signing in select “Get your number” to get your new Twilio number and also copy your “Account SID” and “Auth Token“and then we will move on to the coding.

Python code for sending messages

Step 1: First we need to install the necessary packages.

Python3




pip install twilio
pip install google-cloud-pubsub


Step 2: Next we need to write the following code. Remember that JSON file that we just downloaded!, now copy and locate your JSON file and then type in the following code along with your other credentials

Python3




from twilio.rest import Client
from google.cloud import pubsub_v1
import os
 
# Your JSON file location
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] =
'/path/to/your/credentials/filename.json'
 
# Twilio account credentials
account_sid = 'YOUR TWILIO ACCOUNT SID'
auth_token = 'YOUR TWILIO AUTH TOKEN'
 
# Twilio phone number and target phone number
twilio_number = 'YOUR TWILIO NUMBER'
# Give full phone number without spacking and also specify your country code
target_number = 'YOUR REGISTERED PHONE NUMBER WITH TWILIO'
 
# Create a Twilio client
client = Client(account_sid, auth_token)
 
# Create a Pub/Sub publisher client
publisher = pubsub_v1.PublisherClient()
 
# Define the Pub/Sub topic name
topic_name = 'projects/your-project-id/topics/your-topic-name'
 
 
def send_sms(sender, recipient, message):
    # Send the SMS using Twilio
    client.messages.create(
        body=message,
        from_=sender,
        to=recipient
    )
    print("SMS sent successfully.")
 
 
def publish_message(message):
    # Publish a message to the Pub/Sub topic
    message_data = message.encode()
    future = publisher.publish(topic_name, data=message_data)
    print("Message published to Pub/Sub. Message ID:", future.result())
 
 
if __name__ == "__main__":
    # Send the SMS using Twilio
    send_sms(twilio_number, target_number,
             'Thank you for using geeksforgeeks!')
 
    # Publish a message to the Pub/Sub topic
    publish_message('Thank you for using geeksforgeeks!')


Output:

output

SMS you will receive in your phone

This Python code will deliver a Message to your Target Phone number and then it will also Publish a message to the Pub/Sub topic, you can always change your message replace it with a link . Now If we look into the Topic in the Google Cloud services we can find this,

Image-2

Output in Google Cloud Service

Python code which can send SMS which can be monitered using Google cloud and it can pull messages in Google Cloud By going in Pub/Sub, By Creating Subscription( Good to know that all the published message are stored in the topic until a subscriber subscribes to the topic and acknowledges receipt of the message.Or the message will die after 7 days).

Image-11

Visualizing the data

Conclusion

We can deploy our code using Cloud Function using the Inline editor Once your function is deployed, you can test it by sending it an HTTP request. The URL for your function is in the output of the deployment command, you could use this approach to send marketing messages, to send notifications, or to integrate with other applications. One another mportant thing to remember is that Google Cloud Pub/Sub is commonly used in app or web applications where there is a need for a messaging pipeline or event-driven architecture, It is useful when we have to perform and keep records of multiple functions or works.



Similar Reads

Google Cloud Platform - Running Different Versions of Python on Google Cloud Run
Problem Statement: Rinki works for StoreCraft(Say) as a site reliability engineer, where she's on-call maintaining their custom storefront. StoreCraft's systems are developed in-house in Python and have been running on virtual machines for years, a set up that evolved as StoreCraft's businesses did. These virtual machines use slightly different ver
3 min read
Send SMS updates to mobile phone using python
If you are running any python script and want to send regular updates from your script to your mobile phone through SMS, you can use SinchSMS API to send SMS.Approach : Create an app on Sinch and get the key and secret of the app and use these credentials in the following script to send SMS to your mobile.Limitation of Sinch : If you don't have any
2 min read
Python | SMS Bomber using Selenium
Here, we are going to learn a simple SMS bomber trick (for fun and educational purpose). Selenium is a free tool for automated testing across different browsers. In this tutorial, we will learn to send automatically number of spam SMS for given number of frequency and interval.Requirement: You need to install chromedriver and set path. Click here t
2 min read
Python | Send SMS using Twilio
As we know Python is a cool scripting language and can be used to write scripts to easify day-to-day task. Also, since python has large community support and lots of module/API available, it makes Python more versatile and popular among users. In this article, we will see how to use Twilio API to send SMS using Python. It will be a very quick and e
2 min read
How to send SMS alert using Python and MSG91 API
In our college days we most often forget our daily classes, right? To keep track of classes every day, we can send a Notification (i.e, ) SMS Alert regards their classes to their mobile phones using Python. We need to use two functionalities: http module and MSG91 API for sending SMS. import http.client as ht conn = ht.HTTPSConnection("api.msg
3 min read
Send SMS with REST Using Python
In this article, we are going to see how we can send SMS with REST using Python. The requests library can be used to make REST requests using Python to send SMS. Approach:You need to first create a REST API KEY for sending SMS using Python Script. We have used Fast2SMS for creating API KEY.You can go on the website and create an account after which
2 min read
Send an SMS Message with Python
In today's fastest-growing world, SMS is still a powerful tool by which we can reach billions of users and one can establish a connection globally. In this new world when instant messaging and social media are dominating you can feel our humble SMS outdated but you don't underestimate its power, it will remain an omnipresent tool for communication
4 min read
SMS Spam Detection using TensorFlow in Python
In today's society, practically everyone has a mobile phone, and they all get communications (SMS/ email) on their phone regularly. But the essential point is that majority of the messages received will be spam, with only a few being ham or necessary communications. Scammers create fraudulent text messages to deceive you into giving them your perso
7 min read
Automatic Birthday mail sending with Python
Are you bored with sending birthday wishes to your friends or do you forget to send wishes to your friends or do you want to wish them at 12 AM but you always fall asleep? Why not automate this simple task by writing a Python script. The first thing we do is import six libraries: pandasdatetimesmtplibtimerequestswin10toast Apart from this, Also cre
3 min read
Sending Email using FastAPI Framework in Python
Before jumping into the topic directly, let's have a small intro about the technologies we are going to use. As the name suggests, we will be using FastAPI, a Python language framework. FastAPI: FastAPI is a python framework to develop REST Apis. It is very easy to build, high performance, easy to learn, and ready to deploy code. Though we are usin
3 min read
Article Tags :
Practice Tags :