Help with WhatsApp Cloud API in Python

6 views
Skip to first unread message

Trevor Hughes

unread,
Apr 5, 2023, 3:20:05 AM4/5/23
to ct...@googlegroups.com
Greetings

I have cobbeled this code together to send whatsapp messages from the cloudAPI which I just set up

I can send freely to my own number but as soon as I put in any other number I get a failure - I believe this is nothing worng with my code but my understanding of the API - apparently you have to have permission to send messages? But how do you get that

Then the second question once I get thi workin is dealing with replies - eems I have to set up webhooks - I just want to be able to see replies on my phone or pc and respond to them manually - my initial use case is to automatically send messages to individuals on my staff - like info, shift lists etc and would like to be able to see if they respond (just on my phone where I can carry on the conversation)

Here is the code and outputs

import requests
import sys
from trevsecrets import access_token, phone_id

if len(sys.argv) > 1:
num = sys.argv[1]
else:
num = '+27724386800'


url = f'https://graph.facebook.com/v16.0/{phone_id}/messages'


headers = {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/json',
}

body = '''Greetings Earthling\n
WhatsApp has given me the powers to
send WhatsApps automatically from the
commandline using Python and an API\n
How magicis this??\n\n Trvr Out!'''

data = {
'messaging_product': 'WHATSAPP',
'recipient_type': 'individual',
'to': num,
'type': 'text',
'text': {
'preview_url': False,
'body': body
}
}

response = requests.post(url, headers=headers, json=data)

print(response.ok)
print(response.text)

(dev_env) trev@ramapoesa:~/Dropbox/programming/python/whatsapp$ python whatsapp3.py +27724386800
True
{"messaging_product":"whatsapp","contacts":[{"input":"+27724386800","wa_id":"27724386800"}],"messages":[{"id":"wamid.HBgLMjc3MjQzODY4MDAVAgARGBI0NDgxRkQwQkNDRUM2M0M0RUYA"}]}
(dev_env) trev@ramapoesa:~/Dropbox/programming/python/whatsapp$ python whatsapp3.py +27214480508
False
{"error":{"message":"(#100) Invalid parameter","type":"OAuthException","code":100,"error_data":{"messaging_product":"whatsapp","details":"Invalid parameter"},"fbtrace_id":"APS5j_Mj6VienScWfzjiTxY"}}
(dev_env) trev@ramapoesa:~/Dropbox/programming/python/whatsapp$

Francois Loubser

unread,
Apr 6, 2023, 4:13:04 AM4/6/23
to ct...@googlegroups.com
Hi

Haven't tried whatsapp api, but probably better to use a python module that does the hard work for you, maybe try this:


Francois

--
You received this message because you are subscribed to the Google Groups "Cape Town Python Users Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ctpug+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ctpug/CAKaKKL-cL2BQctY_UHECKO3O-b1k%3D0wh%3DYtk%3Dbk2rZAYpbVL-g%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages