Slack API conversations.replies internal_error - python

I'm trying to get thread replies when somebody posts a message to a private slack channel using the python slack api, but I keep getting the following error:
{"ok":false,"error":"internal_error","warning":"missing_charset",
"response_metadata":{"warnings":["missing_charset"]}}
The scopes for my user token are: channels:history, groups:history, and chat:write.
Here's my code:
slack_client = WebClient(token='xoxp-xxxx-xxxx-xxxx-xxxx')
resp = slack_client.api_call(api_method="conversations.replies",
json={"channel": 'xxxx',
"ts": received_data['event']['thread_ts'],
"token": 'xoxp-xxxx-xxxx-xxxx-xxxx'})
I get the same error using curl:
curl -X POST -H 'Authorization: Bearer xoxp-xxxx-xxxx-xxxx' -H "Content-type: application/json"
--data '{"token": "xoxp-xxxx-xxxx-xxxx-xxxx","ts":"1595895414.009700", "channel": "xxxx"}'
https://slack.com/api/conversations.replies

I think you have to use GET method
you can add http_verb="GET" in parameter to api_call method
There is also a conversations_replies method that wraps this call

Thanks! Here's what my code ended up looking like:
slack_client = WebClient(token='xoxp-xxxx-xxxx-xxxx-xxxx')
resp = slack_client.api_call(api_method="conversations.replies",
params={"channel": 'xxxx',
"ts": received_data['event']['thread_ts'],
"token": 'xoxp-xxxx-xxxx-xxxx-xxxx'},
http_verb="GET")

Related

How to send a text message with Whatsapp Cloud API

I'm having troubles using Whatsapp Cloud API (which was released to the public on May 22). I did everything in the getting started in "Set up Developer Assets and Platform Access" section, that way I was able to send the template hello world in Ubuntu 20.04.4 LTS with:
curl -i -X POST \
https://graph.facebook.com/v14.0/my_number/messages \
-H 'Authorization: Bearer my_token' \
-H 'Content-Type: application/json' \
-d '{ "messaging_product": "whatsapp",
"to": "my_reciever",
"type": "template",
"template": { "name": "hello_world", "language": { "code": "en_US" } }
}'
or with Python 3.10 and requests 2.27.1 with:
from requests import Session
import json
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
BASE_URL = "https://graph.facebook.com/"
API_VERSION = "v13.0/"
SENDER = "my_number/"
ENDPOINT = "messages"
URL = BASE_URL + API_VERSION + SENDER + ENDPOINT
API_TOKEN = "my_token"
TO = "my_reciever"
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
parameters = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": TO,
"type": "template",
"template": {"name": "hello_world", "language": {"code": "en_US"}}
}
session = Session()
session.headers.update(headers)
try:
response = session.post(URL, json=parameters)
data = json.loads(response.text)
print(f"data: {data}")
except (ConnectionError, Timeout, TooManyRedirects) as e:
print(e)
Then, I tried to send a text message with this:
from requests import Session
import json
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
BASE_URL = "https://graph.facebook.com/"
API_VERSION = "v13.0/"
SENDER = "my_number/"
ENDPOINT = "messages"
URL = BASE_URL + API_VERSION + SENDER + ENDPOINT
API_TOKEN = "my_token"
TO = "my_reciever"
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
parameters = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": TO,
"type": "text",
"text": {
"preview_url": "false",
"body": "MESSAGE_CONTENT"
}
}
session = Session()
session.headers.update(headers)
try:
response = session.post(URL, json=parameters)
data = json.loads(response.text)
print(f"data: {data}")
except (ConnectionError, Timeout, TooManyRedirects) as e:
print(e)
And, even though the response is correct, something like this:
{'messaging_product': 'whatsapp', 'contacts': [{'input': 'my_reciever', 'wa_id': 'my_reciever'}], 'messages': [{'id': 'wamid.HBgMNTchangingMDYyM0I2AA=='}]}
I don't recieve any message in my_reciver. I don't know what I'm doing wrong, I might have to configure the webhook for this to work? Do I need to opt-in before recieve the message (this can be read in get-started page)?
I even tried using some unofficial wrappers in python like heyoo, but I got the same result.
Hope someone can help me with this, thanks.
Note: this is a similar post, but that one is with node, not Python or Curl, so I guess this does not count as repost.
I have written a brief article on WhatsApp Cloud API like how to send and receive WhatsApp messages and also set up a never expiry access token. Please have a look WhatsApp Cloud API
You need to send the WhatsApp message from your personal number to your WhatsApp business number after that you can send the message from your business number to your personal number. Basically, WhatsApp has a template message concept within 24h session and according to your question, I think you are trying to send a normal unsession message from a business number to your personal number. So, to avoid this case you need to first message from your personal to your business number then you can receive the message to your personal number. Full details in the article regarding template message.
Here is the CURL request for normal message
curl --location --request POST 'https://graph.facebook.com/v13.0/<Your Phone number ID>/messages' \
--header 'Authorization: Bearer <Your Temporary access token>' \
--header 'Content-Type: application/json' \
--data-raw '{"messaging_product":"whatsapp","recipient_type":"individual",
"to":"918587808915","type":"text","text": {"body":"Hello Rishabh!"}
}'
The official META-whatsapp documentation indicates that in order to send such messages, the conversation must be initiated by the user. https://developers.facebook.com/docs/whatsapp/conversation-types

Forming a request.post from a curl on python

I have a small project i need a tempmail for, so i found this site https://mail.tm/en, so i was trying to acess the post via the api and instructions given here https://api.mail.tm/.
As I am new at working with curl and so on I have a lot of problems authorizing into an account there.
First of all i got an CURL link on site like this one:
curl -X POST "https://api.mail.tm/accounts" -H "accept: application/ld+json" -H "Authorization: testing" -H "Content-Type: application/ld+json" -d "{\"address\":\"test\",\"password\":\"stackoverflow\"}"
I tried to form it all in a post request, so i did this
headers = {"accept": "application/ld+json", "Authorization": "header", "Content-Type": "application/ld+json"}
data = "{\"address\":\"zashyganii\",\"password\":\"chertila\"}"
mail = requests.post("https://api.mail.tm/accounts", data = data, headers = headers)
print(mail.status_code)
the error code is 400, noted on the api site like this.
400 Error:
Response body
Download
{
"#context": "/contexts/ConstraintViolationList",
"#type": "ConstraintViolationList",
"hydra:title": "An error occurred",
"hydra:description": "address: This value is not a valid email address.\naddress: The domain \"\" is not valid.",
"violations": [
{
"propertyPath": "address",
"message": "This value is not a valid email address."
},
{
"propertyPath": "address",
"message": "The domain \"\" is not valid."
}
]
}
Could you please turn this curl in to a request.post on python so it will work for this api
Seems like there are not any problem with the request. It's a validation fail.

How to execute the following command using Python?

It would be a great help if somebody helps me to understand how the following command can be executed using python:
curl -X POST https://insights-collector.newrelic.com/v1/accounts/YOUR_ACCOUNT_ID/events -H "Content-Type: application/json" -H "X-Insert-Key: YOUR_KEY_HERE" -d '{"eventType":"Custom Event Name", "attribute1": "value"}'
SQL query results need to be converted to JSON format and need to be pushed to new relic using the above command.
try doing this
import requests
headers = {
'Content-Type': 'application/json',
'X-Insert-Key': 'YOUR_KEY_HERE',
}
data = '{"eventType":"Custom Event Name", "attribute1": "value"}'
response = requests.post('https://insights-collector.newrelic.com/v1/accounts/YOUR_ACCOUNT_ID/events', headers=headers, data=data)

How to Translate CURL to Python Requests

I am currently trying to integrate Stripe Connect and have come across the flowing CURl POST request:
curl https://connect.stripe.com/oauth/token \
-d client_secret=SECRET_CODE \
-d code="{AUTHORIZATION_CODE}" \
-d grant_type=authorization_code
However I am very new to CURL and have been doing some research and trying to use the requests package to do it. This is what my current code looks like:
data = '{"client_secret": "%s", "code": "%s", "grant_type": "authorization_code"}' % (SECRET_KEY, AUTHORIZATION_CODE)
response = requests.post('https://connect.stripe.com/oauth/token', json=data)
However this always returns a response code 400. I have no idea where I am going wrong and any guidance would be thoroughly appreciated.
The error is because you are passing your data as string, instead json param of requests.post call expects it to be dict. Your code should be:
import requests
data = {
"client_secret": SECRET_KEY,
"code": AUTHORIZATION_CODE,
"grant_type": "authorization_code"
}
response = requests.post('https://connect.stripe.com/oauth/token', json=data)
Take a look at request library's More complicated POST requests document.

What is the python requests equivalent of the following curl command

On ably.io they have an example where one can use the following curl request to publish a message to a channel:
curl -X POST https://rest.ably.io/channels/channelname/messages \
-u "some_AP.aYYMcQ:VmGHauKOqo-35Zxo" \
-H "Content-Type: application/json" \
--data '{ "name": "greeting", "data": "example" }'
The value passed to -u is an API key that has publish privileges. How does one make the same post request using Python requests library? I searched the documentation but could not find it. Note there is no password here, only the api key.
Thanks in advance.
You could use this:
requests.post("https://rest.ably.io/channels/channelname/messages",
auth=('some_AP.aYYMcQ', 'VmGHauKOqo-35Zxo'), # Equivalent of -u
json={ "name": "greeting", "data": "example" }) # Equivalent of --data
When you use the json option, -H is automatically set to Content-Type: application/json.

Categories