Чат бот ватсап питон

Содержание
  1. whatsapp-chatbot-python 0.5.3
  2. Навигация
  3. Ссылки проекта
  4. Статистика
  5. Метаданные
  6. Сопровождающие
  7. Классификаторы
  8. Описание проекта
  9. whatsapp-chatbot-python
  10. API
  11. Authorization
  12. Installation
  13. Import
  14. Examples
  15. How to initialize an object
  16. How to start receiving and answering messages
  17. How to receive other notifications and handle the notification body
  18. How to filter incoming messages
  19. How to add filters through the decorator
  20. How to add filters with the function
  21. How to filter messages by chat, sender, or message type
  22. How to filter messages by message text or regular expressions
  23. How to filter messages by command
  24. Example
  25. How to handle buttons
  26. How to manage user state
  27. Создайте чат-бота WhatsApp с помощью Python
  28. Чат-бот Возможности и задачи бота WhatsApp
  29. Шаг 1: установить колбу
  30. Шаг 2: установите ngrok
  31. Шаг 3: Создайте новое фляжное приложение
  32. Шаг 4: Обработка входящего сообщения
  33. Шаг 5: запустите проект WhatsApp Chatbot
  34. Запустить FLASK-сервер
  35. Запустить нгрок
  36. Python chatbot WhatsApp Library#
  37. API#
  38. Авторизация#
  39. Как начать получать сообщения и отвечать на них#
  40. Как получать другие уведомления и обрабатывать тело уведомления#
  41. Как фильтровать входящие сообщения#
  42. Как обрабатывать кнопки#
  43. Пример бота#
  44. Документация по методам сервиса#
  45. Лицензия#

whatsapp-chatbot-python 0.5.3

This library helps you easily create a Python chatbot with WhatsApp API.

Ссылки проекта

Статистика

Метаданные

Лицензия: Other/Proprietary License (Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0))

Требует: Python >=3.7

Сопровождающие

Классификаторы

Описание проекта

whatsapp-chatbot-python

whatsapp-chatbot-python is a library for integration with WhatsApp messenger using the API service green-api.com. You should get a registration token and an account ID in your personal cabinet to use the library. There is a free developer account tariff.

API

The documentation for the REST API can be found at the link. The library is a wrapper for the REST API, so the documentation at the link above also applies.

Читайте также:  Собеседование qa automation java

Authorization

To send a message or perform other Green API methods, the WhatsApp account in the phone app must be authorized. To authorize the account, go to your cabinet and scan the QR code using the WhatsApp app.

Installation

python -m pip install whatsapp-chatbot-python

Import

from whatsapp_chatbot_python import GreenAPIBot, Notification 

Examples

How to initialize an object

bot = GreenAPIBot( "1101000001", "d75b3a66374942c5b3c019c698abc2067e151558acbd412345" ) 

How to start receiving and answering messages

To start receiving messages, you must create a handler function with one parameter ( notification ). The notification parameter is the class where the notification object ( event ) and the functions to answer the message are stored. To send a text message in response to a notification, you need to call the notification.answer function and pass there the text of the message. You don’t need to pass the chatId parameter because it is automatically taken from the notification.

Next, you need to add the handler function to the list of handlers. This can be done with the bot.router.message decorator as in the example or with the bot.router.message.add_handler function. The decorator must be called with brackets.

To start the bot, call the bot.run_forever function. You can stop the bot with the key combination Ctrl + C.

@bot.router.message(text_message="message") def message_handler(notification: Notification) -> None: notification.answer("Hello") bot.run_forever() 

How to receive other notifications and handle the notification body

You can receive not only incoming messages but also outgoing messages. You can also get the status of the sent message.

  • To receive outgoing messages, you need to use the bot.router.outgoing_message object;
  • To receive outgoing API messages, you need to use the bot.router.outgoing_api_message object;
  • To receive the status of sent messages, you need to use the bot.router.outgoing_message_status object.

The body of the notification is in notification.event . In this example, we get the message type from the notification body.

@bot.router.message() def message_handler(notification: Notification) -> None: print(notification.event) bot.run_forever() 

How to filter incoming messages

Messages can be filtered by chat, sender, message type, and text. To filter chat, sender, and message type, you can use a string ( str ) or a list of strings ( list[str] ). The message text can be filtered by text, command, and regular expressions. Below is a table with filter names and possible values.

Filter name Description Possible values
from_chat Chats or chats from which you want to receive messages «11001234567@c.us» or [«11001234567@c.us», «11002345678@c.us»]
from_sender The sender or senders from whom you want to receive messages «11001234567@c.us» or [«11001234567@c.us», «11002345678@c.us»]
type_message The type or types of message to be handled «textMessage» or [«textMessage», «extendedTextMessage»]
text_message Your function will be executed if the text fully matches the text «Hello. I need help.» or [«Hello», «I need help»]
regexp Your function will be executed if the text matches the regular expression pattern r»Hello. I need help.»
command Your function will be executed if the prefix and the command match your values completely «help» or («help», «!/»)

How to add filters through the decorator

@bot.router.message(command="command") 

How to add filters with the function

bot.router.message.add_handler(handler, command="command") 

How to filter messages by chat, sender, or message type

To filter messages by chat, sender, or message type, you must add a string ( str ) or a list of strings ( list[str] ).

from_chat = "11001234567@c.us" 
from_sender = "11001234567@c.us" 
type_message = ["textMessage", "extendedTextMessage"] 

How to filter messages by message text or regular expressions

You must add a string ( str ) to filter messages by text or regular expressions.

text_message = "Hello. I need help." 
regexp = r"Hello. I need help." 

How to filter messages by command

Add a string ( str ) or a tuple ( tuple ) to filter messages by command. You need to specify either a command name or a command name and a prefix string. The default prefix is / .

Example

@bot.router.message(command="rates") def message_handler(notification: Notification) -> None: notification.answer_with_file(file="data/rates.png") bot.run_forever() 

How to handle buttons

To be notified when a button is pressed, you must use the bot.router.buttons object.

@bot.router.buttons() def buttons_handler(notification: Notification) -> None: notification.answer_buttons("Choose a color", [ < "buttonId": 1, "buttonText": "Red" >, < "buttonId": 2, "buttonText": "Green" >, < "buttonId": 3, "buttonText": "Blue" >]) bot.run_forever() 

How to manage user state

As an example, a bot was created for user registration.

To manage user states, we need to create states. Import the BaseStates class and inherit from it. To manage the state we need to use notification.state_manager . The manager has methods for getting, setting, updating and deleting state. You also have the option to save the user’s data in his state.

Manager’s method Description
get_state Returns a state class with state name and user data
set_state Sets the state for the user. If the state exists then the data will be deleted
update_state If a state exists, it changes it. If not, it creates a new state
delete_state Deletes the user’s state. Remember to get the data before deleting
get_state_data If the state exists, it returns the data in the form of a dictionary (dict)
set_state_data If the state exists, it changes the data to the new data
update_state_data If the state exists, it updates the data. If no data exists, the data will be created
delete_state_data If the state exists, it deletes the data

The first argument is the sender ID. It can be found by calling notification.sender .

As an example, a bot was created to support the GREEN API. Command list:

  • start (the bot says hello and sends a list of commands)
  • 1 or Report a problem (the bot will send a link to GitHub to create the bug)
  • 2 or Show office address (the bot will send the office address as a map)
  • 3 or Show available rates (the bot will send a picture of the rates)
  • 4 or Call a support operator (the bot will send a text message)

To send a text message, you have to use the notification.answer method. To send a location, you have to use the sending.sendLocation method from notification.api . To send a message with a file, you have to use the notification.answer_with_file method.

Источник

Создайте чат-бота 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:

Источник

Python chatbot WhatsApp Library#

Python библиотека — библиотека для интеграции с мессенджером WhatsApp через API сервиса green-api.com. Чтобы воспользоваться библиотекой, нужно получить регистрационный токен и ID аккаунта в личном кабинете. Есть бесплатный тариф аккаунта разработчика.

API#

Документация к REST API находится по ссылке. Библиотека является обёрткой к REST API, поэтому документация по ссылке выше применима и к самой библиотеке.

Авторизация#

Чтобы отправить сообщение или выполнить другие методы GREEN API, аккаунт WhatsApp в приложении телефона должен быть в авторизованном состоянии. Для авторизации аккаунта перейдите в личный кабинет и сканируйте QR-код с использованием приложения WhatsApp.

Как начать получать сообщения и отвечать на них#

Как получать другие уведомления и обрабатывать тело уведомления#

Как фильтровать входящие сообщения#

Как обрабатывать кнопки#

Пример бота#

Документация по методам сервиса#

Лицензия#

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. —>

Источник

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