Code Monkey home page Code Monkey logo

whatsapp-api-client-python's Introduction

whatsapp-api-client-python

Support links

Support Support Support

Guides & News

Guides News News

whatsapp-api-client-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.

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-api-client-python

Import

from whatsapp_api_client_python import API

Examples

How to initialize an object

greenAPI = API.GreenAPI(
    "1101000001", "d75b3a66374942c5b3c019c698abc2067e151558acbd412345"
)

Sending a text message to a WhatsApp number

Link to example: sendTextMessage.py.

response = greenAPI.sending.sendMessage("[email protected]", "Message text")

print(response.data)

Sending an image via URL

Link to example: sendPictureByLink.py.

response = greenAPI.sending.sendFileByUrl(
    "[email protected]",
    "https://download.samplelib.com/png/sample-clouds2-400x300.png",
    "sample-clouds2-400x300.png",
    "Sample PNG"
)

print(response.data)

Sending an image by uploading from the disk

Link to example: sendPictureByUpload.py.

response = greenAPI.sending.sendFileByUpload(
    "[email protected]",
    "data/rates.png",
    "rates.png",
    "Available rates"
)

print(response.data)

Group creation and sending a message to the group

Attention. If one tries to create a group with a non-existent number, WhatsApp may block the sender's number. The number in the example is non-existent.

Link to example: createGroupAndSendMessage.py.

create_group_response = greenAPI.groups.createGroup(
    "Group Name", ["[email protected]"]
)
if create_group_response.code == 200:
    send_message_response = greenAPI.sending.sendMessage(
        create_group_response.data["chatId"], "Message text"
    )

Receive incoming messages by HTTP API

Link to example: receiveNotification.py.

The general concept of receiving data in the GREEN API is described here. To start receiving notifications by the HTTP API you need to execute the library method:

greenAPI.webhooks.startReceivingNotifications(onEvent)

onEvent - your function which should contain parameters:

Parameter Description
typeWebhook received notification type (str)
body notification body (dict)

Notification body types and formats can be found here.

This method will be called when an incoming notification is received. Next, process notifications according to the business logic of your system.

Sending a polling message

Link to example: sendPoll.py.

response = greenAPI.sending.sendPoll(
    "[email protected]",
    "Please choose a color:",
    [
        {"optionName": "Red"},
        {"optionName": "Green"},
        {"optionName": "Blue"}
    ]
)

print(response.data)

Examples list

Description Module
Example of sending text sendTextMessage.py
Example of sending a picture by URL sendPictureByLink.py
Example of sending a picture by uploading from the disk sendPictureByUpload.py
Example of a group creation and sending a message to the group createGroupAndSendMessage.py
Example of incoming webhooks receiving receiveNotification.py
Example of sending a polling message sendPoll.py

The full list of the library methods

API method Description Documentation link
account.getSettings The method is designed to get the current settings of the account GetSettings
account.getWaSettings The method is designed to get information about the WhatsApp account GetWaSettings
account.setSettings The method is designed to set the account settings SetSettings
account.getStateInstance The method is designed to get the state of the account GetStateInstance
account.getStatusInstance The method is designed to get the socket connection state of the account instance with WhatsApp GetStatusInstance
account.reboot The method is designed to restart the account Reboot
account.logout The method is designed to unlogin the account Logout
account.qr The method is designed to get a QR code QR
account.setProfilePicture The method is designed to set the avatar of the account SetProfilePicture
account.getAuthorizationCode The method is designed to authorize an instance by phone number GetAuthorizationCode
device.getDeviceInfo The method is designed to get information about the device (phone) on which the WhatsApp Business application is running GetDeviceInfo
groups.createGroup The method is designed to create a group chat CreateGroup
groups.updateGroupName The method changes the name of the group chat UpdateGroupName
groups.getGroupData The method gets group chat data GetGroupData
groups.addGroupParticipant The method adds a participant to the group chat AddGroupParticipant
groups.removeGroupParticipant The method removes the participant from the group chat RemoveGroupParticipant
groups.setGroupAdmin The method designates a member of a group chat as an administrator SetGroupAdmin
groups.removeAdmin The method deprives the participant of group chat administration rights RemoveAdmin
groups.setGroupPicture The method sets the avatar of the group SetGroupPicture
groups.leaveGroup The method logs the user of the current account out of the group chat LeaveGroup
journals.getChatHistory The method returns the chat message history GetChatHistory
journals.getMessage The method returns a chat message GetMessage
journals.lastIncomingMessages The method returns the most recent incoming messages of the account LastIncomingMessages
journals.lastOutgoingMessages The method returns the last sent messages of the account LastOutgoingMessages
queues.showMessagesQueue The method is designed to get the list of messages that are in the queue to be sent ShowMessagesQueue
queues.clearMessagesQueue The method is designed to clear the queue of messages to be sent ClearMessagesQueue
marking.readChat The method is designed to mark chat messages as read ReadChat
receiving.receiveNotification The method is designed to receive a single incoming notification from the notification queue ReceiveNotification
receiving.deleteNotification The method is designed to remove an incoming notification from the notification queue DeleteNotification
receiving.downloadFile The method is for downloading received and sent files DownloadFile
sending.sendMessage The method is designed to send a text message to a personal or group chat SendMessage
sending.sendButtons The method is designed to send a message with buttons to a personal or group chat SendButtons
sending.sendTemplateButtons The method is designed to send a message with interactive buttons from the list of templates in a personal or group chat SendTemplateButtons
sending.sendListMessage The method is designed to send a message with a selection button from a list of values to a personal or group chat SendListMessage
sending.sendFileByUpload The method is designed to send a file loaded through a form (form-data) SendFileByUpload
sending.sendFileByUrl The method is designed to send a file downloaded via a link SendFileByUrl
sending.uploadFile The method is designed to upload a file to the cloud storage, which can be sent using the sendFileByUrl method UploadFile
sending.sendLocation The method is designed to send a geolocation message SendLocation
sending.sendContact The method is for sending a message with a contact SendContact
sending.sendLink The method is designed to send a message with a link that will add an image preview, title and description SendLink
sending.forwardMessages The method is designed for forwarding messages to a personal or group chat ForwardMessages
sending.sendPoll The method is designed for sending messages with a poll to a private or group chat SendPoll
serviceMethods.checkWhatsapp The method checks if there is a WhatsApp account on the phone number CheckWhatsapp
serviceMethods.getAvatar The method returns the avatar of the correspondent or group chat GetAvatar
serviceMethods.getContacts The method is designed to get a list of contacts of the current account GetContacts
serviceMethods.getContactInfo The method is designed to obtain information about the contact GetContactInfo
serviceMethods.deleteMessage The method deletes the message from chat DeleteMessage
serviceMethods.archiveChat The method archives the chat ArchiveChat
serviceMethods.unarchiveChat The method unarchives the chat UnarchiveChat
serviceMethods.setDisappearingChat The method is designed to change the settings of disappearing messages in chats SetDisappearingChat
webhooks.startReceivingNotifications The method is designed to start receiving new notifications
webhooks.stopReceivingNotifications The method is designed to stop receiving new notifications

Service methods documentation

https://green-api.com/en/docs/api/.

External products

License

Licensed under Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0) terms. Please see file LICENSE.

whatsapp-api-client-python's People

Contributors

amele9 avatar andreymalyshkin avatar dependabot[bot] avatar eschelpnew avatar injitools avatar jibek100 avatar mrslain avatar olegius88 avatar ripreal avatar sadiv avatar slikman1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

whatsapp-api-client-python's Issues

issues on sending message through API

I'm having problems on using this simple example:
https://github.com/green-api/whatsapp-api-client-python/blob/master/examples/sendTextMessage.py

This is what I've done:

  • created a developer account on green api
  • created an instance
  • activated the instance through quare code
  • installed libreries on my venv
  • changed the code of the ,py file as following:

greenAPI = API.GreenApi("IdInstance", "ApiTokenInstance")

  • changed the phone number as following:

response = greenAPI.sending.sendMessage("[email protected]", "my_message")

  • I tryed the following 3 phone number:
  1. 392xxxxxx26 (without prefix)
  2. 0039392xxxxxx26 (0039 prefix)
  3. +39392xxxxxx26 (+39 prefix)

This is the respective output.

  1. It send my message to +39 2xxxxxx26
  2. it returns me this error

"message": "Validation failed. Details: 'chatId' must be one of the next formats: '[email protected]' or '[email protected]'"

  1. it returns me this error

"message": "Validation failed. Details: 'chatId' must be one of the next formats: '[email protected]' or '[email protected]'"`

it should send it to:
+39392xxxxxx26

let me know

Question | Find group's id by group name

I did a pretty thorough search on the API docs, but maybe I missed something.
I wanted to know if there is a way to return all the groups I am in? (to work with a specific group that I want, but I don't have its ID)

Anyway, looking forward to any reply(:

Q | Create a WhatsApp bot

Hey there, I was wondering if there is an option to create a WhatsApp bot like a Discord bot by any chance?
~ In simple terms, to control an account who isn't yours, but is defined as an official WhatsApp bot.


My goal in the purpose of the program is to send (not through my account. maybe, from a bot/webhook) all the messages I receive from group x to group y.

Anyways, thanks for any incoming reply(:

Cant register account

I cant register account in your website. I am using selenium and trying to use a whatsapp api to remind my colleagues of all the pending assignments and due dates.

I want to run it in a runner in github so I cant use pywhatkit. Using selenium headless I cant save cookies for whatsapp as well.

https://github.com/sakmalh/APIITReminder
You can check my current progress here

Getting JSONDecodeError on invalid response from API

Traceback (most recent call last):
File "/workspaces/whatsapp-api-client-python/main.py", line 15, in
main()
File "/workspaces/whatsapp-api-client-python/main.py", line 9, in main
response = greenAPI.sending.sendMessage("[email protected]", "Message text")
File "/workspaces/whatsapp-api-client-python/whatsapp_api_client_python/tools/sending.py", line 32, in sendMessage
return self.api.request(
File "/workspaces/whatsapp-api-client-python/whatsapp_api_client_python/API.py", line 93, in request
self.__handle_response(response)
File "/workspaces/whatsapp-api-client-python/whatsapp_api_client_python/API.py", line 117, in __handle_response
json.loads(response.text), ensure_ascii=False, indent=4
File "/home/codespace/.python/current/lib/python3.10/json/init.py", line 346, in loads
return _default_decoder.decode(s)
File "/home/codespace/.python/current/lib/python3.10/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/home/codespace/.python/current/lib/python3.10/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Предложение по улучшению

Добавьте dev-ветку.

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

add member to group issues

can't add members not registered on what's app phone to group ?
after run code below only numbers registered on phone added successfully
tdf = pd.read_excel('Book.xlsx') phones = tdf.Phones.tolist() for c in phones: c = '964'+str(c)+'@c.us' print('Start Processing : '+c) r = wclient.groups.addGroupParticipant(group_id,c) time.sleep(2) if r.data['addParticipant']: print('Phone added successfully ✅') s.append(c) else: print('Phone added Failed ❌') f.append(c)

Требуется передавать хосты по параметру для класса GreenApi / Required to pass hosts as parameters in GreenApi class

Ошибка
Требуется передавать хосты по параметру для класса GreenApi, так как на данный момент они захардкодены внутри класса (см. скриншот)

Уровень
SDK


Error
It is required to pass hosts as parameters in the GreenApi class, currently hosts are hardcoded inside the class (see the screenshot)

Level
SDK

ImportError

image

Код копировал из примеров.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.