membangun chatbot sangat mudah dengan Ultramsg API, Anda dapat membangun chatbot layanan pelanggan dan chatbot ai terbaik Melalui langkah-langkah sederhana menggunakan bahasa Python.
Chatbot Peluang dan tugas bot WhatsApp
- Output dari daftar perintah.
- Output dari waktu server bot berjalan di .
- Mengirim gambar ke nomor telepon atau grup.
- Mengirim file audio.
- Mengirim rekaman audio ppt.
- Mengirim File Video.
- Mengirim kontak.
Langkah 1: instal termos
kita perlu menggunakan server menggunakan kerangka FLASK.
FLASK memungkinkan untuk dengan mudah menanggapi permintaan yang masuk dan memprosesnya.
pip install flask
Langkah 2: instal ngrok
untuk tujuan pembangunan lokal, layanan tunneling diperlukan. Contoh ini menggunakan ngrok , Anda dapat mengunduh ngrok dari sini .
Langkah 3: Buat aplikasi labu baru
Kami akan membuat file: app.py Dan kami menulis kode 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: Pemrosesan pesan masuk
Kami akan membuat file: ultrabot.py Dan kami menulis kode 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: mulai proyek WhatsApp Chatbot
Jalankan server FLASK
flask run
Jalankan ngrok
Jalankan ngrok Untuk Windows:
ngrok http 5000
Jalankan ngrok Untuk Mac:
./ngrok http 5000
Langkah 6: Setel Webhook URL di pengaturan Instance
Setelah menjalankan ngrok , Anda akan melihat contoh:
https://7647-115-83-121-164.ngrok.io
paste URL anda di Instance setting Seperti gambar berikut :
Fungsi Chatbot yang digunakan dalam kode
mengirim pesan
Digunakan untuk mengirim pesan teks WhatsApp
def send_message(self, chatID, text):
data = {"to" : chatID,
"body" : text}
answer = self.send_requests('messages/chat', data)
return answer
- ChatID – ID obrolan tempat pesan harus dikirim untuknya, misalnya [email protected] .
- Teks – Teks pesan .
waktu
Mengirim waktu server saat ini.
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 obrolan tempat pesan harus dikirim untuknya, misalnya [email protected] .
kirim_gambar
Kirim gambar ke nomor telepon atau grup
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
mengirim video
Kirim Video ke nomor telepon atau grup
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
kirim_audio
Kirim file audio ke nomor telepon atau grup
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
kirim_suara
Kirim rekaman audio ppt ke nomor telepon atau grup
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
kirim_kontak
Mengirim satu kontak atau daftar kontak ke nomor telepon atau grup
def send_contact(self, chatID):
data = {"to" : chatID,
"contact" : "[email protected]"}
answer = self.send_requests('messages/contact', data)
return answer
Memproses masuk pesan
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 dapat melihat langkah-langkah sebelumnya di video ini:
Tautan Berguna
- Semua kode tersedia di GitHub .
- kirim pesan API WhatsApp menggunakan Python.
- cara menyetel WebHook menggunakan Platform Ultramsg
- cara menerima pesan whatsapp menggunakan python dan webhook.