Build a WhatsApp Chatbot With Python

building chatbot it’s very easy with Ultramsg API, you can build a customer service chatbot and best ai chatbot Through simple steps using the Python language.

Chatbot Opportunities and tasks of the WhatsApp bot

  • The output of the command list .
  • The output of the server time of the bot running on .
  • Sending image to phone number or group .
  • Sending audio file .
  • Sending ppt audio recording .
  • Sending Video File.
  • Sending contact .

Step 1 : install flask

we need to deploy the server using the FLASK framework.
The FLASK allows to conveniently respond to incoming requests and process them.

pip install flask

Step 2 : install ngrok

for local development purposes, a tunneling service is required. This example uses ngrok , You can download ngrok from here.

Step 3 : Create new flask app

We will create the file: app.py And we write the following code inside it

from flask import Flask, request, jsonify
from ultrabot import ultraChatBot
import json

app = Flask(__name__)

@app.route('/', methods=['POST'])
def home():
    if request.method == 'POST':
        bot = ultraChatBot(request.json)
        return bot.Processingـincomingـmessages()

if(__name__) == '__main__':
    app.run()

Step 4 : Incoming message processing

We will create the file: ultrabot.py And we write the following code inside it

import json
import requests
import datetime

class ultraChatBot():    
    def __init__(self, json):
        self.json = json
        self.dict_messages = json['data']
        self.ultraAPIUrl = 'https://api.ultramsg.com/{{instance_id}}/'
        self.token = '{{token}}'

   
    def send_requests(self, type, data):
        url = f"{self.ultraAPIUrl}{type}?token={self.token}"
        headers = {'Content-type': 'application/json'}
        answer = requests.post(url, data=json.dumps(data), headers=headers)
        return answer.json()

    def send_message(self, chatID, text):
        data = {"to" : chatID,
                "body" : text}  
        answer = self.send_requests('messages/chat', data)
        return answer

    def send_image(self, chatID):
        data = {"to" : chatID,
                "image" : "https://file-example.s3-accelerate.amazonaws.com/images/test.jpeg"}  
        answer = self.send_requests('messages/image', data)
        return answer

    def send_video(self, chatID):
        data = {"to" : chatID,
                "video" : "https://file-example.s3-accelerate.amazonaws.com/video/test.mp4"}  
        answer = self.send_requests('messages/video', data)
        return answer

    def send_audio(self, chatID):
        data = {"to" : chatID,
                "audio" : "https://file-example.s3-accelerate.amazonaws.com/audio/2.mp3"}  
        answer = self.send_requests('messages/audio', data)
        return answer


    def send_voice(self, chatID):
        data = {"to" : chatID,
                "audio" : "https://file-example.s3-accelerate.amazonaws.com/voice/oog_example.ogg"}  
        answer = self.send_requests('messages/voice', data)
        return answer

    def send_contact(self, chatID):
        data = {"to" : chatID,
                "contact" : "[email protected]"}  
        answer = self.send_requests('messages/contact', data)
        return answer


    def time(self, chatID):
        t = datetime.datetime.now()
        time = t.strftime('%Y-%m-%d %H:%M:%S')
        return self.send_message(chatID, time)


    def welcome(self,chatID, noWelcome = False):
        welcome_string = ''
        if (noWelcome == False):
            welcome_string = "Hi , welcome to WhatsApp chatbot using Python\n"
        else:
            welcome_string = """wrong command
Please type one of these commands:
*hi* : Saluting
*time* : show server time
*image* : I will send you a picture
*video* : I will send you a Video
*audio* : I will send you a audio file
*voice* : I will send you a ppt audio recording
*contact* : I will send you a contact
"""
        return self.send_message(chatID, welcome_string)


    def Processingـincomingـmessages(self):
        if self.dict_messages != []:
            message =self.dict_messages
            text = message['body'].split()
            if not message['fromMe']:
                chatID  = message['from'] 
                if text[0].lower() == 'hi':
                    return self.welcome(chatID)
                elif text[0].lower() == 'time':
                    return self.time(chatID)
                elif text[0].lower() == 'image':
                    return self.send_image(chatID)
                elif text[0].lower() == 'video':
                    return self.send_video(chatID)
                elif text[0].lower() == 'audio':
                    return self.send_audio(chatID)
                elif text[0].lower() == 'voice':
                    return self.send_voice(chatID)
                elif text[0].lower() == 'contact':
                    return self.send_contact(chatID)
                else:
                    return self.welcome(chatID, True)
            else: return 'NoCommand'

Step 5 : start WhatsApp Chatbot project

Run FLASK server

flask run

Run ngrok

Run ngrok For Windows :

ngrok http 5000

Run ngrok For Mac :

./ngrok http 5000

Step 6 : Set URL Webhook in Instance settings

After run ngrok , you should see a for example :

https://7647-115-83-121-164.ngrok.io

paste your URL in Instance settings ، As the following picture :

Receive WhatsApp messages using python and webhook-ultramsg

Chatbot Functions used in the code

send_message

Used to send WhatsApp text messages

def send_message(self, chatID, text):
    data = {"to" : chatID,
        "body" : text}  
    answer = self.send_requests('messages/chat', data)
    return answer
  • ChatID – ID of the chat where the message should be sent for him, e.g [email protected] .
  • Text – Text of the message .

time

Sends the current server time.

def time(self, chatID):
    t = datetime.datetime.now()
    time = t.strftime('%Y-%m-%d %H:%M:%S')
    return self.send_message(chatID, time)
  • ChatID – ID of the chat where the message should be sent for him, e.g [email protected] .

send_image

Send an image to phone number or group

def send_image(self, chatID):
    data = {"to" : chatID,
        "image" : "https://file-example.s3-accelerate.amazonaws.com/images/test.jpeg"}  
    answer = self.send_requests('messages/image', data)
    return answer

send_video

Send a Video to phone number or group

def send_video(self, chatID):
    data = {"to" : chatID,
        "video" : "https://file-example.s3-accelerate.amazonaws.com/video/test.mp4"}  
    answer = self.send_requests('messages/video', data)
    return answer

send_audio

Send an audio file to the phone number or group

def send_audio(self, chatID):
    data = {"to" : chatID,
        "audio" : "https://file-example.s3-accelerate.amazonaws.com/audio/2.mp3"}  
    answer = self.send_requests('messages/audio', data)
    return answer

send_voice

Send a ppt audio recording to the phone number or group

def send_voice(self, chatID):
    data = {"to" : chatID,
        "audio" : "https://file-example.s3-accelerate.amazonaws.com/voice/oog_example.ogg"}  
    answer = self.send_requests('messages/voice', data)
    return answer

send_contact

Sending one contact or contact list to phone number or group

def send_contact(self, chatID):
    data = {"to" : chatID,
        "contact" : "[email protected]"}  
    answer = self.send_requests('messages/contact', data)
    return answer

Processingـincomingـmessages

def Processingـincomingـmessages(self):
    if self.dict_messages != []:
        message =self.dict_messages
        text = message['body'].split()
        if not message['fromMe']:
        chatID  = message['from'] 
        if text[0].lower() == 'hi':
            return self.welcome(chatID)
        elif text[0].lower() == 'time':
            return self.time(chatID)
        elif text[0].lower() == 'image':
            return self.send_image(chatID)
        elif text[0].lower() == 'video':
            return self.send_video(chatID)
        elif text[0].lower() == 'audio':
            return self.send_audio(chatID)
        elif text[0].lower() == 'voice':
            return self.send_voice(chatID)
        elif text[0].lower() == 'contact':
            return self.send_contact(chatID)
        else:
            return self.welcome(chatID, True)
        else: return 'NoCommand'

You can see the previous steps in this video :

Useful Links