Чат бот ватсап python

python-whatsapp-bot

A whatsapp client library for python utilizing the WhatsApp Business Cloud API.

Features supported

Getting started

To start, install with pip:

pip3 install --upgrade python-whatsapp-bot

Setting up

To get started using this library, you have to obtain a TOKEN and PHONE NUMBER ID from Facebook Developer Portal. You get these after setting up a developer account and setting up an app.

If you followed the tutorial, you should now have a TOKEN and TEST WHATSAPP NUMBER and its phone_number_id.activeYou might have even already sent your first message on the platform using the provided curl request.

Now you have all you need to start using this library. Note: The given token is temporary. This tutorial on the platform guides you to create a permanent token. This guide shows how to register an authentic phone number.

Initialization

To initialize the app instance, you need to specify the TOKEN and phone_number_id you obtained from the steps above. Note that phone number id is not phone number.

Once initialized, you can start using some of the bot's features right away.

Sending Messages

For buttons and lists, use the same send_message endpoint but with a reply_markup parameter. e.g

Читайте также:  Обозначение тегов html документ

For buttons

To send a pre-approved template message:

A short note about Webhooks

For every message sent to your bot business account, whatsapp sends an object containing the message as a post request to a url which you have to provide beforehand. The url you provide should be able to process simple get and post requests. This url is the webhook url, and the object whatsapp sends to your url is the webhook.

Now, you can write a small server with the Python Flask library to handle the webhook requests, but another problem arises if you’re developing on a local server; whatsapp will not be able to send requests to your localhost url, so a quick fix would be to deploy your project to an online server each time you make a change to be able to test it. Once deployed, you can proceed to register the url of your deployed app using this tutorial from the platform.

If you’re like me however, you wouldn’t want to always deploy before you test, you want to run everything on local first. In this case, you might decide to use Ngrok to tunnel a live url to your local server, but another issue arises; Since Ngrok generates a new url each time it is restarted, you’d have to constantly log in to facebook servers to register the newly generated url. I presume you don’t want that hassle either. In this situation, a webhook forwarder can be deployed to a virtual server like Heroku, and it doesn’t get modified. You register the deployed forwarder’s url on Whatsapp servers, it receives all the webhook requests and forwards them to your local machine using ngrok.

Читайте также:  Установка curl php ubuntu

To continue with this fowarding process, open this repository https://github.com/Radi-dev/webhook-forwarder and follow the readme instructions to deploy it and setup a client for it on your device, then register the url following this guide.

Issues

Please open an issue to draw my attention to mistake or suggestion

Contributing

This is an opensource project under MIT License so anyone is welcome to contribute from typo, to source code to documentation, JUST FORK IT .

References

All the credit

Источник

Создайте чат-бота WhatsApp с помощью Python

Создание чат-бота очень просто с Ultramsg API, вы можете создать чат-бота для обслуживания клиентов и лучшего чат-бота с искусственным интеллектом. Выполнив простые шаги, используя язык Python.

Чат-бот Возможности и задачи бота WhatsApp

  • Вывод списка команд.
  • Вывод серверного времени бота, работающего на .
  • Отправка изображения на номер телефона или в группу.
  • Отправка аудиофайла.
  • Отправка аудиозаписи ppt.
  • Отправка видеофайла.
  • Отправка контакта.

Шаг 1: установить колбу

нам нужно развернуть сервер с помощью фреймворка FLASK.
FLASK позволяет удобно отвечать на входящие запросы и обрабатывать их.

Шаг 2: установите ngrok

для целей локальной разработки требуется служба туннелирования. В этом примере используется ngrok. Вы можете скачать ngrok отсюда .

Шаг 3: Создайте новое фляжное приложение

Мы создадим файл: app.py и пишем в нем следующий код

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

Шаг 4: Обработка входящего сообщения

Мы создадим файл: ultrabot.py и пропишем внутри него следующий код

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/>/' self.token = '>' def send_requests(self, type, data): url = f"?token=" headers = answer = requests.post(url, data=json.dumps(data), headers=headers) return answer.json() def send_message(self, chatID, text): data = answer = self.send_requests('messages/chat', data) return answer def send_image(self, chatID): data = answer = self.send_requests('messages/image', data) return answer def send_video(self, chatID): data = answer = self.send_requests('messages/video', data) return answer def send_audio(self, chatID): data = answer = self.send_requests('messages/audio', data) return answer def send_voice(self, chatID): data = answer = self.send_requests('messages/voice', data) return answer def send_contact(self, chatID): data = [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'

Шаг 5: запустите проект WhatsApp Chatbot

Запустить FLASK-сервер

Запустить нгрок

Запустите ngrok для Windows:

Читайте также:  String to function name in javascript

Источник

Оцените статью