DEV Community

Cover image for Send and Receive message in WhatsApp using twilio & python
Raunak Tamang
Raunak Tamang

Posted on

2

Send and Receive message in WhatsApp using twilio & python

Previously, i made WhatsApp automation using python selenium, this time i thought to do more with it and used twilio to send and receive messages from WhatsApp using twilio and flask

prerequisite:

$ pip install flask
$ pip install twilio
install ngrok
make twilio trial account
Enter fullscreen mode Exit fullscreen mode

first for most integrate your number with twilio sandbox

app.py

packagae to import :

from flask import Flask, request ,render_template
from twilio.twiml.messaging_response import MessagingResponse 

from twilio.rest import Client 

Enter fullscreen mode Exit fullscreen mode

For sending message

app.py

@app.route("/" , methods = ['GET' , 'POST'])

def index():

    if request.method == "POST":
        fname = request.form['fname']
        lname = request.form['lname']
        pname = request.form['pname']


        sid = 'account_sid'
        auth = 'auth_token'

        client = Client(sid,auth)

        message = client.messages.create(
             from_='whatsapp:+14155238886',  
             body='hello ' +  str(fname) + " " +  str(lname) +  ' welcome to Tanzible',   
             to='whatsapp:+91'+str(pname)
        )

        return 'registration successfully'

    return render_template('index.html')
Enter fullscreen mode Exit fullscreen mode

for receiving message

first we have to configure ngrok to put localhost to on public address

so download ngrok and install it via command line where is you ngrok file

./ngrok http 5000 
Enter fullscreen mode Exit fullscreen mode

5000 is by default port given by flask

def msg(request):
    if request.method == 'POST':
        resp = MessagingResponse()
        resp.message("Thank you for contacting us! Our team will shortly in touch with you ")
        print(resp)
        return str(resp)


Enter fullscreen mode Exit fullscreen mode

That's all folk !

check code in my GitHub https://github.com/cyber-hoax/WhatsApp_twilio

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay