I want to use this cURL command in (python with pycurl):
curl -X POST --header "Authorization: key=AAAAWuduLSU:APA91bEStixxx" --header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d '{"to" : "fC6xEWZwcu0:APA91xxx", "priority" : "high", "notification" : { "body" : "Background Message", "title" : "BG Title", "sound" : "default"}, "data" : { "title" : "FG Title", "message" : "Foreground Message" }}'
My source code is like this
import pycurl
import re
import io
import json
import requests
data = {"to" : "fC6xEWZwcu0:APA91xxx", "priority" : "high", "notification" : { "body" : "Background Message", "title" : "BG Title", "sound" : "sound.mp3"}, "data" : { "title" : "FG Title", "message" : "Foreground Message" }}
buffer = io.BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://fcm.googleapis.com/fcm/send')
c.setopt(c.POST, True)
c.setopt(c.SSL_VERIFYPEER, False)
c.setopt(pycurl.HTTPHEADER, [
'Content-type:application/json charset=utf-8',
'Content-Length:0'
'Authorization: Basic key=AAAAWuduLSU:APA91bEStixxx'
])
c.setopt(c.WRITEDATA, buffer)
'''
c.setopt(pycurl.HTTPBODY, [
'test:test'
])
'''
print(buffer)
# c.setopt(c.HEADERFUNCTION, header_function)
c.perform()
print('\n\nStatus: %d' % c.getinfo(c.RESPONSE_CODE))
print('TOTAL_TIME: %f' % c.getinfo(c.TOTAL_TIME))
c.close()
body = buffer.getvalue()
print(body)
No need to use curl in Python when you have requests!
import requests
import json
post_data = {"to" : "fC6xEWZwcu0:APA91xxx",
"priority" : "high",
"notification": {"body": "Background Message",
"title": "BG Title",
"sound": "sound.mp3"},
"data": {"title": "FG Title",
"message": "Foreground Message"}}
header_data = {'Authorization': 'key=AAAAWuduLSU:APA91bEStixxx',
'Content-Length': '0',
'Content-type': 'application/json'}
r = requests.post('https://fcm.googleapis.com/fcm/send',
data = json.dumps(post_data),
headers=header_data)
print('\n\nStatus: %d'.format(r.status_code))
print('TOTAL_TIME: %f'.format(r.elapsed.total_seconds()))
print(r.text)
Haven't tested this, but it should set you on the right track.
I'd also recommend checking out the Requests module docs for more information :-)
Related
background: I am trying to make a fastapi and wordpress plugin which will use api in localhost (both sits on the same server), i have developed the api and its working perfectly fine through swagger ui and python request library however can't use it in the plugin through wp_remote_post
code for the api:
from fastapi import FastAPI
from pydantic import BaseModel
from api.article import add_article, html_format_data
app = FastAPI()
class PostData(BaseModel):
links: list
title: str
#app.post('/create_post/')
def create_post(post_data: PostData):
html_format = html_format_data(post_data.links, post_data.title) # list of dicts
if add_article(post_data.title, html_format):
return {"status": 201, "success": True}
else:
return {"error"}
python request code:
import requests
data = {
"title": "gaming",
"links": [
{
"id": "video id 1",
"thumbnail": "url of thumbnail 1,
"title": "title of video 1"
},
{
"id": "video id 2",
"thumbnail": "url of thumbnail 2 ,
"title": "title of video 2"
}
]
}
res = requests.post('http://127.0.0.1:5000/create_post/', json=data)
print(res.content)
same success through swagger ui:
curl -X 'POST' \
'http://127.0.0.1:5000/create_post/' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"links": [
{
"id": "shortand",
"thumbnail": "shortand",
"title": "shortand"
},
{
"id": "shortand",
"thumbnail": "shortand",
"title": "shortand"
}
],
"title": "gaming"
}'
but when i do it through wordpress plugin which code is below:
function create_post( $data, $query ) {
$url = 'http://127.0.0.1:5000/create_post/';
$arguments = array(
'method' => 'POST',
'body' => json_encode(array(
"links" => $data,
"title" => $query
)),
'header' => array(
'Content-Type' => 'application/json',
'accept' => 'application/json'
)
);
$response = wp_remote_post( $url, $arguments );
// echo '<script>console.log(`data: ' . $arguments["body"] . '`)</script>';
echo '<script>console.log(`' . json_encode($response) . '`)</script>';
}
i get this error in the console:
{"headers":{},"body":"{"detail":[{"loc":["body"],"msg":"value is not a valid dict","type":"type_error.dict"}]}","response":{"code":422,"message":"Unprocessable Entity"},"cookies":[],"filename":null,"http_response":{"data":null,"headers":null,"status":null}}
i am new to wordpress and php.
i did consult these solutions but nothing seem to work as i am doing in from php.
POST request response 422 error {'detail': [{'loc': ['body'], 'msg': 'value is not a valid dict', 'type': 'type_error.dict'}]}
FastAPI - "msg": "value is not a valid dict" in schema request
EDIT
i did the below as suggested BUT still getting the same error, heres the php code:
function create_post( $data, $query ) {
$url = 'http://127.0.0.1:5000/create_post/';
$data_arr = array("links" => $data,"title" => $query);
$data_obj = (object) $data_arr;
$body = json_encode( $data_obj );
$arguments = array(
'method' => 'POST',
'body' => $body,
'header' => array(
'Content-Type' => 'application/json',
'accept' => 'application/json'
)
);
$response = wp_remote_post( $url, $arguments );
echo '<script>console.log(`' . $body . '`)</script>';
echo '<script>console.log(`' . json_encode($response) . '`)</script>';
}
SOLVED
lol my issue was a idiotic, i missed the "s" in headers so it want any json anymore because it cant see headers so it couldnt find it json thats why it was giving the error not a valid dict.
When handling JSON from php, we sometimes run into problems with the distinction between objects and associative arrays.
Try casting your body array as an object before giving it to json_encode(), something like this:
$body = json_encode( (object)
array(
"links" => $data,
"title" => $query
));
print_r ($body); //debugging: examine JSON to pass to web service
$arguments = array(
'method' => 'POST',
'body' => $body,
'header' => array(
'Content-Type' => 'application/json',
'accept' => 'application/json'
)
);
$response = wp_remote_post( $url, $arguments );
json = {"chat_id":chat_id, "media":[{"type" : "photo", "media" : "attach://photo1.jpg"}, {"type" : "photo", "media" : "attach://photo2.jpg"}]}
files = {"photo1.jpg" : open(r"../photo1.jpg", 'rb'), "photo2.jpg" : open(r"../photo2.jpg", 'rb')}
temp = r.post("https://api.telegram.org/bot<TOKEN>/sendMediaGroup", json=json, files=files)
print(temp.json())
I keep getting this response: {'ok': False, 'error_code': 400, 'description': 'Bad Request: parameter "media" is required'}
How can I send photo.jpg with sendMediaGroup using multipart/form-data?
I'd recommend using data with a custom dict.
Then the only thing you should note is the media array inside data, should be JSON encoded using json.dumps
So the code becomes:
import json
import requests as r
#####
chat_id = 1010011
TOKEN = 'ABCDEF....'
#####
data = {
"chat_id": chat_id,
"media": json.dumps([
{"type": "photo", "media": "attach://photo1.png"},
{"type": "photo", "media": "attach://photo2.png"}
])
}
files = {
"photo1.png" : open("./photo1.png", 'rb'),
"photo2.png" : open("./photo2.png", 'rb')
}
temp = r.post("https://api.telegram.org/bot" + TOKEN + "/sendMediaGroup", data=data, files=files)
print(temp.json())
Result in Telegram desktop:
Autentique API is Graphql. Documentation: https://docs.autentique.com.br/api/integracao/criando-um-documento
You must create an account on Autentique and an API key first.
Uploading the file in sandbox and sending it to an email for signing. It returns document's id and name.
Using curl
curl -H "Authorization: Bearer <TOKEN>" https://api.autentique.com.br/v2/graphql \
-F operations='{"query": "mutation CreateDocumentMutation($document: DocumentInput! $signers: [SignerInput!]! $file: Upload!) {createDocument(sandbox: true, document: $document, signers: $signers, file: $file) {id name }}", "variables": { "document": {"name": "<DOCUMENT_NAME>"}, "signers": [{"email": "<FROM_EMAIL>","action": "SIGN"}], "file": null } }' \
-F map='{ "0": ["variables.file"] }' \
-F 0=#<FULL_PATH_FILE>
Using aiogqlc
https://github.com/DoctorJohn/aiogqlc
import asyncio
from aiogqlc import GraphQLClient
endpoint = "https://api.autentique.com.br/v2/graphql"
headers = {
"Authorization": "Bearer <TOKEN>"
}
client = GraphQLClient(endpoint, headers=headers)
async def create_document():
query = """
mutation CreateDocumentMutation(
$document: DocumentInput!
$signers: [SignerInput!]!
$file: Upload!
) {
createDocument(
sandbox: true,
document: $document,
signers: $signers,
file: $file)
{
id
name
}
}"""
variables = {
"document": {
"name": "<DOCUMENT_NAME>"
},
"signers": [{
"email": "<FROM_EMAIL>",
"action": "SIGN"
}],
"file": open('<FULL_PATH_FILE>', 'rb'),
}
response = await client.execute(query, variables=variables)
print(await response.json())
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(create_document())
For more languages implementations: https://github.com/jaydenseric/graphql-multipart-request-spec#implementations
I have a file that is connected to another one of my programs, and upon being run, it sends an embed to Discord using the following code:
payload = {"embeds": [
{
"author": {
"name": "EAS Software",
"icon_url": "https://www.fema.gov/sites/default/files/styles/unicorn_rotator/public/uni-rotator-imgs/eas_logo_rev1_3.png?itok=56iK9r2a"
},
"title": lines,
"description": "Issued "+datetime.now().strftime('%m/%d/%Y %H:%M:%S') + " " + TMZ,
"color": 0xff9900,
"fields": [
{
"name": "Text Data:",
"value": args.text
},
{
"name": "EAS Protocol Data:",
"value": "ZCZC-"+args.org+"-"+args.event+"-"+args.fips+"+"+args.time+"-"+ts_val+"-"+args.calls+"-"
},
],
"timestamp" : datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.000Z'),
"footer": {
"text": "Nerp EAS Logger System"
}
}
]
}
header_data = {'content-type': 'application/json'}
requests.post(webhook1, json.dumps(payload), headers=header_data)
print("Succesfully posted.")
And this works, I get an embed to post to Discord. The issue I am having is that another program generates a file, combined.wav, and I would like to send it to the same webhook. I have settled on splitting the File-sending process and the Embed process for ease of debugging, but the issue is that the code that sends the file sends it, but it has no data.
Here's the code I use to send the file:
dataList = []
boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T'
dataList.append('--' + boundary)
dataList.append('Content-Disposition: form-data; name=file; filename={0}'.format('C:\Users\Brigan\Desktop\EAS-APPS\Encoder\combined.wav'))
fileType = mimetypes.guess_type('C:\Users\Brigan\Desktop\EAS-APPS\Encoder\combined.wav')[0] or 'application/octet-stream'
dataList.append('Content-Type: {}'.format(fileType))
dataList.append('')
with open('C:\Users\Brigan\Desktop\EAS-APPS\Encoder\combined.wav') as f:
dataList.append(f.read())
dataList.append('--'+boundary+'--')
dataList.append('')
body = '\r\n'.join(dataList)
payload = body
headers = {
'Content-Type': 'multipart/form-data; boundary=--------------------------248330258300818905783969',
'Content-type': 'multipart/form-data; boundary={}'.format(boundary)
}
conn.request("POST", "/api/webhooks/688944637209083926/vAv6UScav_j1AUun8GZ1RnYlYd2JvcvGvR1Wv5Db7_av3NhrBTsLWLlxH5PT8b0yQlpy", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
Does anyone know how to send a .WAV file to Discord in Python, or am I just outta luck?
**EDIT
I found out that the system named discord-webhooks is cross platform, so I jsut used that using the following code:
#Post Json Embed to Discord!
webhook = DiscordWebhook(url='webhook1')
embed = DiscordEmbed(title=lines, description="Issued "+datetime.now().strftime('%m/%d/%Y %H:%M:%S') + " " + TMZ, color=0xff9900)
embed.set_author(name='EAS Software', icon_url='https://www.fema.gov/sites/default/files/styles/unicorn_rotator/public/uni-rotator-imgs/eas_logo_rev1_3.png?itok=56iK9r2a')
embed.set_footer(text='NERP EAS Logger System')
embed.set_timestamp()
embed.add_embed_field(name='EAS Text Data:', value=args.text, inline=False)
embed.add_embed_field(name='EAS Protocol Data:', value="ZCZC-"+args.org+"-"+args.event+"-"+args.fips+"+"+args.time+"-"+ts_val+"-"+args.calls+"-", inline=False)
webhook.add_embed(embed)
response = webhook.execute()
webhook = DiscordWebhook(url='webhook1')
with open("Output/FULL-ALERT-DATA.wav", "rb") as f:
webhook.add_file(file=f.read(), filename='Alert-Audio.wav')
response = webhook.execute()
print("Succesfully posted.")
Thanks for the help!
I have this curl that works, it returns this
curl -X POST \
https://login.smoobu.com/booking/checkApartmentAvailability \
-H 'Api-Key: xxxxx' \
-H 'cache-control: no-cache' \
-d '{
"arrivalDate" : "2018-04-01",
"departureDate": "2019-12-03",
"apartments": [126936, 127858, 126937],
"customerId": 38484
}'
it returns this
{
"availableApartments": [
127858
],
"prices": [],
"errorMessages": {
"126936": {
"errorCode": 405,
"message": "The chosen day of departure is not available.",
"departureDays": [
"Sa"
]
},
"126937": {
"errorCode": 405,
"message": "The chosen day of departure is not available.",
"departureDays": [
"Sa"
]
}
}
}
I rewrote it in python like so
In [1]: import requests
In [2]: headers = {'Api-Key': 'xxxx', 'cache-control': 'no-cache'}
In [8]: payload = {
...: "arrivalDate" : "2018-04-01",
...: "departureDate": "2019-12-03",
...: "apartments": [126936, 127858, 126937],
...: "customerId": 38484
...: }
In [4]: r = requests.post("https://login.smoobu.com/booking/checkApartmentAvailability", data=payload, headers=headers)
In [5]: r
Out[5]: <Response [400]>
In [13]: r.content
Out[13]: b'{"title":"Error occurred","detail":"json is invalid"}'
I got back a response of invalid json, I'm not sure why though since the way I know it works is it takes a dict and turns it into a json request.
For sending JSON, you should use the json parameter:
r = requests.post("https://login.smoobu.com/booking/checkApartmentAvailability", json=payload, headers=headers)
As explained in the docs:
r = requests.post(url, data=json.dumps(payload))
r = requests.post(url, json=payload)
Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically