greenapi-client-python
Write correct Python code with the official GREEN-API SDK whatsapp-api-client-python (package whatsapp_api_client_python). Use when sending/receiving WhatsApp messages, files, polls, groups, journals, queues, statuses, contacts, partner instances, polling notifications, or configuring a GREEN-API instance in Python. Triggers: GREEN-API, green-api, whatsapp-api-client-python, GreenAPI, GreenApi, sendMessage, receiveNotification.
インストール方法を見る含まれるファイル(14)
- SKILL.md12.9 KB
- references/account.md2.9 KB
- references/contacts.md796 B
- references/device.md346 B
- references/groups.md1.9 KB
- references/inventory.md12.1 KB
- references/journals.md1.1 KB
- references/marking.md436 B
- references/partner.md930 B
- references/queues.md843 B
- references/receiving.md4.1 KB
- references/sending.md3.7 KB
- references/service-methods.md2.0 KB
- references/statuses.md1.3 KB
SKILL.md(原文)
インストールする前に、エージェントに与えられる指示の中身を確認できます。
GREEN-API Python client (whatsapp-api-client-python)
When to apply
Use this skill whenever the task is to call GREEN-API from Python via the official
SDK. Do not invent HTTP paths or method names from memory: only methods listed in
references/inventory.md exist in this SDK. Semantics of
parameters, chatId formats, delays, and notification types come from the official docs
linked in each method section — not from other repos.
For webhook HTTP server libraries in other languages, use a language-specific
webhook skill if present. This SDK receives notifications via polling
(webhooks.startReceivingNotifications / receiving.receiveNotification) or you can
build your own HTTP endpoint for webhook-endpoint technology.
Sources of truth (mandatory)
- Official API docs — https://green-api.com/en/docs/api/
Parameters, response shapes, limits,chatId, delays, notification formats. - This repository / installed package — method names, class attributes, init signatures. Inventory: references/inventory.md.
If a method exists in the docs but not in the inventory → do not use it in code.
Install
python -m pip install whatsapp-api-client-python
Requires Python >= 3.10. Credentials: idInstance and apiTokenInstance from
console.green-api.com.
Client initialization
from whatsapp_api_client_python import API
greenAPI = API.GreenAPI(
"1101000001", # idInstance (string)
"d75b3a66374942c5b3c019c698abc2067e151558acbd412345", # apiTokenInstance
)
Optional constructor kwargs (from GreenApi.__init__ in API.py):
| Kwarg | Default | Meaning |
|---|---|---|
debug_mode | False | Verbose request logging |
raise_errors | False | Raise GreenAPIError on failures |
host | https://api.green-api.com | API host (apiUrl) |
media | https://media.green-api.com | Media host for uploads |
host_timeout | 180 | Seconds per host request retry |
media_timeout | 10800 | Seconds per media request |
Aliases: API.GreenAPI is the same class as API.GreenApi.
Partner API (separate client):
partner = API.GreenApiPartner(partnerToken="PARTNER_TOKEN")
# then: partner.partner.getInstances() / createInstance / deleteInstanceAccount
Response object
Every API method returns whatsapp_api_client_python.response.Response:
| Attribute | When | Content |
|---|---|---|
code | always | HTTP status, or None on transport failure |
data | code == 200 | Parsed JSON (dict / list) |
error | non-200 | Response body text |
Always check response.code == 200 before reading response.data.
Async
Most groups expose *Async twins (sendMessageAsync, receiveNotificationAsync, …).
Call them with await inside asyncio.
chatId and phone format
Docs: https://green-api.com/en/docs/api/chat-id/
| Kind | Format | Example |
|---|---|---|
| Personal chat | <phone>@c.us | 79876543210@c.us |
| Group chat | ...@g.us | 120363043968066561@g.us |
| Lid | ...@lid | returned by API; do not invent |
- Phone: full international number, digits only, no
+, spaces, or leading zeros tricks. - Never hand-craft group IDs — take them from
createGroup, journals, or notifications. - Wrong
chatId→ validation 400: must bephone_number@c.usorgroup_id@g.us.
Instance must be authorized
Docs: https://green-api.com/en/docs/api/account/GetStateInstance/
Before sending, verify:
state = greenAPI.account.getStateInstance()
print(state.data) # expect {"stateInstance": "authorized"}
Important states: authorized, notAuthorized, blocked, starting, suspended.
Authorize via console QR / account.qr() / account.getAuthorizationCode(phoneNumber).
Messages sit in the send queue up to 24 hours until the instance is authorized.
Message sending delay
Docs: https://green-api.com/en/docs/api/send-messages-delay/
Outgoing messages go through a FIFO queue. Delay is controlled by instance setting
delaySendMessagesMilliseconds (min 500 ms, max 600000 ms; recommend ≤ 300000):
greenAPI.account.setSettings({"delaySendMessagesMilliseconds": 5000})
Note: setSettings reboots the instance; settings apply within ~5 minutes.
Typical scenarios
1. Send a text message
Docs: https://green-api.com/en/docs/api/sending/SendMessage/
from whatsapp_api_client_python import API
greenAPI = API.GreenAPI(id_instance, api_token)
response = greenAPI.sending.sendMessage(
"79876543210@c.us",
"Hello from GREEN-API",
typingTime=3000, # optional: 1000–20000 ms typing indicator
)
if response.code == 200:
print(response.data["idMessage"])
else:
print(response.error)
Required: chatId, message (max 20000 chars). Optional in SDK: quotedMessageId,
archiveChat, linkPreview, typingTime, typePreview, customPreview.
Response: { "idMessage": "..." }.
2. Send a file by URL
Docs: https://green-api.com/en/docs/api/sending/SendFileByUrl/
response = greenAPI.sending.sendFileByUrl(
"79876543210@c.us",
"https://download.samplelib.com/png/sample-clouds2-400x300.png",
"sample-clouds2-400x300.png",
"Caption text",
)
Required: chatId, urlFile, fileName (with extension). Max file size 100 MB.
3. Send a file by upload (local path)
Docs: https://green-api.com/en/docs/api/sending/SendFileByUpload/
Uses media host (SDK sets this automatically).
response = greenAPI.sending.sendFileByUpload(
"79876543210@c.us",
"data/logo.jpg",
"logo.jpg",
"Available rates",
)
# response.data: idMessage, urlFile (link valid 15 days)
SDK signature: sendFileByUpload(chatId, path, fileName=None, caption=None, ...).
The local path is the second argument (path), not a raw file object.
4. Receive notifications — polling (built-in)
Docs: https://green-api.com/en/docs/api/receiving/technology-http-api/ReceiveNotification/
Requirement: instance webhookUrl must be empty. If a custom webhook URL is set,
receiveNotification returns an error telling you to clear it.
from whatsapp_api_client_python import API
greenAPI = API.GreenAPI(id_instance, api_token)
def on_event(type_webhook: str, body: dict) -> None:
if type_webhook == "incomingMessageReceived":
chat_id = body["senderData"]["chatId"]
msg = body["messageData"]
if msg.get("typeMessage") == "textMessage":
text = msg["textMessageData"]["textMessage"]
print(chat_id, text)
# Blocks; Ctrl+C to stop. Internally: receiveNotification → handler → deleteNotification
greenAPI.webhooks.startReceivingNotifications(on_event)
Handler signature is fixed: (typeWebhook: str, body: dict).
After handling, the SDK deletes the notification by receiptId (do not skip this
if you poll manually).
Manual poll loop:
resp = greenAPI.receiving.receiveNotification(receiveTimeout=5)
if resp.code == 200 and resp.data:
receipt_id = resp.data["receiptId"]
body = resp.data["body"]
# ... process body["typeWebhook"] ...
greenAPI.receiving.deleteNotification(receipt_id)
receiveTimeout: 5–60 seconds (API default 5). Empty queue → empty body / no data.
Notifications live in the queue 24 hours, FIFO.
5. Receive notifications — webhook endpoint (your HTTP server)
Docs: https://green-api.com/en/docs/api/receiving/technology-webhook-endpoint/
This SDK does not ship a webhook HTTP server. Configure the instance, then run your own endpoint that accepts POST JSON and returns 200:
greenAPI.account.setSettings({
"webhookUrl": "https://your.public.host/webhook",
"webhookUrlToken": "Bearer your-secret", # optional; see docs for Basic/Bearer
"incomingWebhook": "yes",
"outgoingWebhook": "yes",
"outgoingAPIMessageWebhook": "yes",
"stateWebhook": "yes",
})
GREEN-API POSTs notification JSON to webhookUrl. Retries every ~1 minute; guaranteed
within 24 hours. While webhookUrl is set, polling will not receive those notifications.
Common typeWebhook values: incomingMessageReceived, outgoingMessageReceived,
outgoingAPIMessageReceived, outgoingMessageStatus, stateInstanceChanged,
statusInstanceChanged, incomingCall, outgoingCall, quotaExceeded, …
Full list: https://green-api.com/en/docs/api/receiving/notifications-format/type-webhook/
6. Create a group and message it
Docs: https://green-api.com/en/docs/api/groups/CreateGroup/
created = greenAPI.groups.createGroup("Group Name", ["79876543210@c.us"])
if created.code == 200 and created.data.get("created"):
chat_id = created.data["chatId"] # ...@g.us
greenAPI.sending.sendMessage(chat_id, "Hello group")
Do not create groups faster than about 1 per 5 minutes (anti-spam). Invalid numbers can get the sender blocked.
API surface map (SDK attributes)
Access as greenAPI.<group>.<method>(...).
| Attribute | Class | Reference |
|---|---|---|
account | Account | references/account.md |
sending | Sending | references/sending.md |
receiving | Receiving | references/receiving.md |
webhooks | Webhooks | references/receiving.md |
groups | Groups | references/groups.md |
journals | Journals | references/journals.md |
queues | Queues | references/queues.md |
serviceMethods | ServiceMethods | references/service-methods.md |
marking | Marking | references/marking.md |
contacts | Contacts | references/contacts.md |
statuses | Statuses | references/statuses.md |
device | Device | references/device.md |
partner | Partner | only on GreenApiPartner — references/partner.md |
Full method list + signatures: references/inventory.md.
Pitfalls (read before coding)
chatIdformat — personalphone@c.us, groupid@g.us. No+in the phone part.- Authorized instance —
getStateInstancemust beauthorizedfor delivery. - Polling vs webhook — mutually exclusive for the same traffic: clear
webhookUrlfor HTTP API polling; setwebhookUrlfor push. - Always
deleteNotificationafter processing a polled notification, or the same event will be returned forever. - Sending delay — use
delaySendMessagesMilliseconds≥ 500 ms; bulk blasts without delay risk limits / bans. - File size — max 100 MB;
sendFileByUploadgoes tomedia.green-api.com. - Response handling — use
response.dataonly whenresponse.code == 200. - Deprecated sending APIs still in SDK but marked deprecated:
sendButtons,sendTemplateButtons,sendListMessage,sendLink— prefersendInteractiveButtons/sendInteractiveButtonsReply/sendMessage. serviceMethodsattribute name — camelCaseserviceMethods, notservice.- Partner methods require
GreenApiPartner, notGreenAPI. - Groups rate limit — create groups slowly; non-existent numbers are dangerous.
- Hosts — default
api.green-api.com/media.green-api.com; some accounts use instance-specific hosts from console — passhost=/media=if console shows them.
Agent checklist
When writing code for the user:
- Import
from whatsapp_api_client_python import API - Init
API.GreenAPI(idInstance, apiTokenInstance)with real or env credentials - Use only methods from references/inventory.md
- Format
chatIdas@c.us/@g.us - Check
response.codebeforeresponse.data - For receive: either polling (
startReceivingNotifications/ manual receive+delete) or webhook endpoint +setSettings, not a fictional SDK method - Prefer reading the matching
references/*.mdfile for parameters before coding - Prefer official docs URL from the method docstring when unsure about edge cases
レビュー
まだレビューはありません。使ってみた感想をお寄せください。