DEV Community

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

Posted on

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

Top comments (0)