Package: whatsapp-chatbot-python
whatsapp-chatbot-pythonДокументация на русском языке.whatsapp-chatbot-python is a library for integration with WhatsApp messenger using the API
servicegreen-api.com. You should get a registration token and an account ID in
yourpersonal cabinetto use the library. There is a free developer account tariff.APIThe documentation for the REST API can be found at thelink. The library is a wrapper
for the REST API, so the documentation at the link above also applies.AuthorizationTo 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 yourcabinetand scan the QR code using the WhatsApp app.InstallationInstallation:python-mpipinstallwhatsapp-chatbot-pythonImportfrom whatsapp_chatbot_python import GreenAPIBot, NotificationExamplesHow to initialize an objectbot = GreenAPIBot(
    "1101000001", "d75b3a66374942c5b3c019c698abc2067e151558acbd412345"
)How to enable debug modebot = GreenAPIBot(
    "1101000001", "d75b3a66374942c5b3c019c698abc2067e151558acbd412345",
    bot_debug_mode=True
)You can also enable API debug mode:bot = GreenAPIBot(
    "1101000001", "d75b3a66374942c5b3c019c698abc2067e151558acbd412345",
    debug_mode=True, bot_debug_mode=True
)How to set up an instanceTo start receiving incoming notifications, you need to set up an instance. Open the personal cabinet page at
thelink. Select an instance from the list and click on it. ClickChange. In theNotificationscategory, enable all notifications that you want to receive.How to start receiving and answering messagesTo start receiving messages, you must create a handler function with one parameter (notification). Thenotificationparameter 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 thenotification.answerfunction and pass there
the text of the message. You don't need to pass thechatIdparameter 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 thebot.router.messagedecorator as in the example or with thebot.router.message.add_handlerfunction. The decorator must be called with
brackets.To start the bot, call thebot.run_foreverfunction. You can stop the bot with the key combination Ctrl + C.In this example, the bot will only answer themessagemessage.Link to example:base.py.@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 bodyYou 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 thebot.router.outgoing_messageobject;To receive outgoing API messages, you need to use thebot.router.outgoing_api_messageobject;To receive the status of sent messages, you need to use thebot.router.outgoing_message_statusobject.The body of the notification is innotification.event. In this example, we get the message type from the notification
body.In this example, the bot receives all incoming messages.Link to example:event.py.@bot.router.message()
def message_handler(notification: Notification) -> None:
    print(notification.event)


bot.run_forever()How to filter incoming messagesMessages 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 nameDescriptionPossible valuesfrom_chatChats or chats from which you want to receive messages"11001234567@c.us"or["11001234567@c.us", "11002345678@c.us"]from_senderThe sender or senders from whom you want to receive messages"11001234567@c.us"or["11001234567@c.us", "11002345678@c.us"]type_messageThe type or types of message to be handled"textMessage"or["textMessage", "extendedTextMessage"]text_messageYour function will be executed if the text fully matches the text"message"or["message", "MESSAGE"]regexpYour function will be executed if the text matches the regular expression patternr"message"or(r"message", re.IGNORECASE)commandYour 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 functionbot.router.message.add_handler(handler, command="command")How to filter messages by chat, sender, or message typeTo 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 expressionsYou 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 commandAdd 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/.command = "help"command = ("help", "!/")ExampleIn this example, the bot will send a photo in response to theratescommand.Link to example:filters.py.@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 buttonsTo be notified when a button is pressed, you must use thebot.router.buttonsobject.Link to example:buttons.py.@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 stateAs an example, a bot was created for user registration.To manage user states, we need to create states. Import theBaseStatesclass and inherit from it. To manage the state
we need to usenotification.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 methodDescriptionget_stateReturns a state class with state name and user dataset_stateSets the state for the user. If the state exists then the data will be deletedupdate_stateIf a state exists, it changes it. If not, it creates a new statedelete_stateDeletes the user's state. Remember to get the data before deletingget_state_dataIf the state exists, it returns the data in the form of a dictionary (dict)set_state_dataIf the state exists, it changes the data to the new dataupdate_state_dataIf the state exists, it updates the data. If no data exists, the data will be createddelete_state_dataIf the state exists, it deletes the dataThe first argument is the sender ID. It can be found by callingnotification.sender.Link to example:states.py.fromwhatsapp_chatbot_pythonimportBaseStates,GreenAPIBot,Notificationbot=GreenAPIBot("1101000001","d75b3a66374942c5b3c019c698abc2067e151558acbd412345")classStates(BaseStates):USERNAME="username"PASSWORD="password"@bot.router.message(state=None)defmessage_handler(notification:Notification)->None:sender=notification.sendernotification.state_manager.set_state(sender,States.USERNAME.value)notification.answer("Hello. Tell me your username.")@bot.router.message(command="cancel")defcancel_handler(notification:Notification)->None:sender=notification.senderstate=notification.state_manager.get_state(sender)ifnotstate:returnNoneelse:notification.state_manager.delete_state(sender)notification.answer("Bye")@bot.router.message(state=States.USERNAME.value)defusername_handler(notification:Notification)->None:sender=notification.senderusername=notification.message_textifnot5<=len(username)<=20:notification.answer("Invalid username.")else:notification.state_manager.update_state(sender,States.PASSWORD.value)notification.state_manager.set_state_data(sender,{"username":username})notification.answer("Tell me your password.")@bot.router.message(state=States.PASSWORD.value)defpassword_handler(notification:Notification)->None:sender=notification.senderpassword=notification.message_textifnot8<=len(password)<=20:notification.answer("Invalid password.")else:data=notification.state_manager.get_state_data(sender)username=data["username"]notification.answer(("Successful account creation.\n\n"f"Your username:{username}.\n"f"Your password:{password}."))notification.state_manager.delete_state(sender)bot.run_forever()FAQHow to call API methods?bot.api.account.getSettings()Ornotification.api.account.getSettings()How do I disable error raising?bot = GreenAPIBot(
    "1101000001", "d75b3a66374942c5b3c019c698abc2067e151558acbd412345",
    raise_errors=False
)How do I subscribe only to text messages?You need to import the required constants first:from whatsapp_chatbot_python.filters import TEXT_TYPESThen add this filter:type_message=TEXT_TYPES.How do I get the message text and sender ID?This data is in the notification object (notification):@bot.router.message()
def message_handler(notification: Notification) -> None:
    print(notification.sender)
    print(notification.message_text)Example of a botAs 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 thenotification.answermethod.
To send a location, you have to use thesending.sendLocationmethod fromnotification.api.
To send a message with a file, you have to use thenotification.answer_with_filemethod.In this example, the bot only responds to commands from the list above.Link to example:full.py.fromwhatsapp_chatbot_pythonimportGreenAPIBot,Notificationbot=GreenAPIBot("1101000001","d75b3a66374942c5b3c019c698abc2067e151558acbd412345")@bot.router.message(command="start")defmessage_handler(notification:Notification)->None:sender_data=notification.event["senderData"]sender_name=sender_data["senderName"]notification.answer((f"Hello,{sender_name}. Here's what I can do:\n\n""1. Report a problem\n""2. Show office address\n""3. Show available rates\n""4. Call a support operator\n\n""Choose a number and send to me."))@bot.router.message(text_message=["1","Report a problem"])defreport_problem_handler(notification:Notification)->None:notification.answer("https://github.com/green-api/issues/issues/new",link_preview=False)@bot.router.message(text_message=["2","Show office address"])defshow_office_address_handler(notification:Notification)->None:chat=notification.chatnotification.api.sending.sendLocation(chatId=chat,latitude=55.7522200,longitude=37.6155600)@bot.router.message(text_message=["3","Show available rates"])defshow_available_rates_handler(notification:Notification)->None:notification.answer_with_file("data/rates.png")@bot.router.message(text_message=["4","Call a support operator"])defcall_support_operator_handler(notification:Notification)->None:notification.answer("Good. A tech support operator will contact you soon.")bot.run_forever()Service methods documentationService methods documentationLicenseLicensed underCreative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0)terms. Please see fileLICENSE.