Bina Chatbot WhatsApp Dengan Python

membina chatbot sangat mudah dengan Ultramsg API, anda boleh membina chatbot perkhidmatan pelanggan dan ai chatbot terbaik Melalui langkah mudah menggunakan bahasa Python.

Chatbot Peluang dan tugas bot WhatsApp

  • Keluaran senarai arahan .
  • Output masa pelayan bot berjalan pada .
  • Menghantar imej ke nombor telefon atau kumpulan .
  • Menghantar fail audio.
  • Menghantar rakaman audio ppt.
  • Menghantar Fail Video.
  • Menghantar kenalan.

Langkah 1: pasang kelalang

kita perlu menggunakan pelayan menggunakan rangka kerja FLASK.
FLASK membolehkan anda bertindak balas dengan mudah kepada permintaan masuk dan memprosesnya.

pip install flask

Langkah 2: pasang ngrok

untuk tujuan pembangunan tempatan, perkhidmatan terowong diperlukan. Contoh ini menggunakan ngrok , Anda boleh memuat turun ngrok dari sini .

Langkah 3 : Cipta apl kelalang baharu

Kami akan mencipta fail: app.py Dan kami menulis kod berikut di dalamnya

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()

Langkah 4 : Pemprosesan mesej masuk

Kami akan mencipta fail: ultrabot.py Dan kami menulis kod berikut di dalamnya

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'

Langkah 5 : mulakan projek WhatsApp Chatbot

Jalankan pelayan FLASK

flask run

Lari ngrok

Jalankan ngrok Untuk Windows :

ngrok http 5000

Jalankan ngrok Untuk Mac :

./ngrok http 5000

Langkah 6 : Tetapkan URL Webhook dalam tetapan Instance

Selepas menjalankan ngrok , anda harus melihat contohnya:

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

tampal URL anda dalam tetapan Instance ، Seperti gambar berikut :

Terima mesej WhatsApp menggunakan python dan webhook-ultramsg

Fungsi Chatbot yang digunakan dalam kod

menghantar mesej

Digunakan untuk menghantar mesej teks WhatsApp

def send_message(self, chatID, text):
    data = {"to" : chatID,
        "body" : text}  
    answer = self.send_requests('messages/chat', data)
    return answer
  • ChatID – ID sembang tempat mesej harus dihantar untuknya, cth [email protected] .
  • Teks – Teks mesej .

masa

Menghantar masa pelayan semasa.

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

hantar_imej

Hantar imej ke nombor telefon atau kumpulan

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

hantar_video

Hantar Video ke nombor telefon atau kumpulan

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

hantar_audio

Hantar fail audio ke nombor telefon atau kumpulan

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

hantar_suara

Hantar rakaman audio ppt ke nombor telefon atau kumpulan

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

hantar_hubungi

Menghantar satu kenalan atau senarai kenalan ke nombor telefon atau kumpulan

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

Memproses mesej masuk

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'

Anda boleh lihat langkah sebelumnya dalam video ini:

Pautan Berguna