Send a WhatsApp message with Python
By the end, you will have a Python script that sends a text message through the Nigora Zap API and prints the response. It uses only the standard library, so there is nothing to install.
Prerequisites
Section titled “Prerequisites”- A connected instance. If you have not connected one yet, see Connection.
- The instance ID and token, as in Getting started.
- Python 3.9 or newer. Check with
python3 --version.
1. Keep the credentials in the environment
Section titled “1. Keep the credentials in the environment”Do not write the token in the code. Read it from environment variables:
export NIGORA_INSTANCIA_ID="cole-aqui-o-id-da-instancia"export NIGORA_TOKEN="cole-aqui-o-token"2. Create the script
Section titled “2. Create the script”Save it as enviar.py:
import jsonimport osimport sysimport urllib.errorimport urllib.request
instancia_id = os.environ.get("NIGORA_INSTANCIA_ID")token = os.environ.get("NIGORA_TOKEN")if not instancia_id or not token: sys.exit("Defina NIGORA_INSTANCIA_ID e NIGORA_TOKEN.")
requisicao = urllib.request.Request( f"https://api.zap.nigora.com.br/v1/instances/{instancia_id}/messages/text", data=json.dumps({ "to": "5511999999999", "text": "Olá! Esta mensagem saiu pela API.", }).encode("utf-8"), headers={ "Authorization": f"Bearer {token}", "Content-Type": "application/json", }, method="POST",)
try: with urllib.request.urlopen(requisicao, timeout=15) as resposta: status, corpo = resposta.status, resposta.read().decode("utf-8")except urllib.error.HTTPError as erro: # The API answered with an error: the body explains why. status, corpo = erro.code, erro.read().decode("utf-8")
print("Status HTTP:", status)print(corpo)sys.exit(0 if status < 300 else 1)Replace 5511999999999 with the phone of the person who will receive the message, with country and area codes. The API ignores everything that is not a digit and adds the 55 when the number has 10 or 11 digits.
3. Run it
Section titled “3. Run it”python3 enviar.pyExpected result:
Status HTTP: 202{"id":"…","status":"queued"}The 202 means the message entered the queue. It has not been delivered yet. Keep the id: it is how you match the response to the message.sent and message.status events, which arrive by webhook.
If something goes wrong
Section titled “If something goes wrong”| Status | Code | What to do |
|---|---|---|
400 |
invalid_phone |
Fix the phone: it must have 12 or 13 digits including the 55 |
401 |
invalid_token |
Check the token and the instance ID |
402 |
instance_suspended |
The instance is suspended or has a pending payment |
422 |
contact_opted_out |
The contact asked not to receive messages |
If the network is down, urlopen raises URLError and Python prints the error in the terminal.
Next steps
Section titled “Next steps”- Sending messages: replies, queue and tracking the result.
- Receive messages by webhook: see the replies arrive in your system.
- Sending media: image, video, audio and document.