How to display message payload data in template - django

I'm getting the messages from Gmail I am unable to display the message body in a template.
I got encoded data from payload after I decoded it using base64, after I stored this in the dictionary in python after I am displaying in template it is displaying the payload data as a string data.
msg = service.users().messages().get(userId='me', id=message['id']).execute()
msg_str = base64.urlsafe_b64decode(msg['payload']['body']['data'].encode('UTF8'))
return render(request,'emailapp/index.html',{'msgdecddata':msg_str})
Need to execute payload data in template.

Related

How to add JSON from "Body" in the query parameter?

I'm trying to send a message to an SQS queue. I have everything setup correctly.
I'm using a fifo queue, so my post string looks like this:
https://queuename?Action=SendMessage&MessageBody=TEST&MessageGroupId=6&MessageDeduplicationId=6
The above works and the body of the message is TEST, However, I'd like to send data in JSON format
In the body tab, I have my payload formatted in JSON. How do I get that JSON value into the MessageBody field as a variable?
Step 1. Save json in a variable
const body = {
"key": "value"
}
//encoded the special character to make it valid in URL
const payload = encodeURIComponent(JSON.stringify(body))
//Put it in an environment variable
pm.environment.set("payload", payload)
Step 2: Use this var in URL
https://queuename?Action=SendMessage&MessageBody={{payload}}&MessageGroupId=6&MessageDeduplicationId=6

Converting string literal to JSON Array and sending using HTTP Post Request

I'm trying to send a post request over an ESP32 WiFi module using an Arduino IDE. Although the response received is 200, I receive a formatting error with the JSON body object. How should I format the JSON object?
Here is what the original JSON object looks like that I need to send:
{
"method":"passthrough",
"params":{
"deviceId":"9006765C87CD29BC37447E490C4C91F819143376",
"requestData":"{\"system\":{\"set_relay_state\":{\"state\":1}}}"
}
}
And here is what I've tried in the Post Request:
HTTPClient http;
http.begin(serverName);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST("{\"deviceId\":\"9006765C87CD29BC37447E490C4C91F819143376\",\"requestData\":\"{\"system\":{\"set_relay_state\":{\"state\":0}}}\"}");
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
Serial.print(http.getString());
http.end();
Here is the response:
{"error_code":-10100,"msg":"JSON format error"}HTTP Response code: 200
UPDATE
I originally thought I would only need to pass the params but here is a version I have tried passing the method and params. I still get the same results, however.
String json =
"({"
"\"method\":\"passthrough\","
"\"params\":{"
"\"deviceId\":\"9006765C87CD29BC37447E490C4C91F819143376\","
"\"requestData\":\"{\"system\":{\"set_relay_state\":{\"state\":1}}}\""
"}"
"})";
Using this json string - I have tried passing int httpResponseCode = http.POST(json); but that doesn't work either and I get the same error. I'm assuming I need to convert this string to a Json array before passing to htt.Post?
The value of requestData needs to escape the quotes within the string. Otherwise the payload that is sent is malformed JSON with the value of requestData terminated too early.
This can be done with:
http.POST("{\"method\":\"passthrough\",\"params\":{\"deviceId\":\"9006765C87CD29BC37447E490C4C91F819143376\",\"requestData\":\"{\\\"system\\\":{\\\"set_relay_state\\\":{\\\"state\\\":0}}}\"}}";);
Or alternatively using a raw string literal:
http.POST(R"({"method":"passthrough","params":{"deviceId":"9006765C87CD29BC37447E490C4C91F819143376","requestData":"{\\"system\\":{\\"set_relay_state\\":{\\"state\\":0}}}"}})");

How to post a message with an image using Postman

I am trying send an image from POSTMAN. I am able to send a message but image is not getting posted.
https://slack.com/api/chat.postMessage
Used POST type headers i am passing token, channel and i have an Image URL but not sure how to send that. Can anyone please help me on this.
There are two alternative approaches on how to send your message to the API endpoint chat.postMessage:
Body as form-urlencoded
Here is how to include an image in a message send as x-www-form-urlencoded:
The image has to be send as part of an attachment by setting the property called image_url.
The attachments are set with the attachments key in the API call, which requires you define your attachments as array of attachment object in JSON.
In addition to the image_url your attachment needs to contain a fallback property, which is used to display a text to the user in case the image can not be displayed.
Your attachments object then looks like this in JSON:
{
"fallback": "this did not work",
"image_url": "https://secure.gravatar.com/avatar/d6ada88a40de8504c6b6068db88266ad.jpg?s=512&d=https%3A%2F%2Fa.slack-edge.com%2F27b6e%2Fimg%2Favatars%2Fsmiley_blobs%2Fava_0016-512.png"
}
Now you have to put that into an array (by adding [] around it) and this is what you get as value for your attachments key:
[{"fallback":"did not work","image_url":"https://secure.gravatar.com/avatar/d6ada88a40de8504c6b6068db88266ad.jpg?s=512&d=https%3A%2F%2Fa.slack-edge.com%2F27b6e%2Fimg%2Favatars%2Fsmiley_blobs%2Fava_0016-512.png"}]
In addition you need to add the keys token, channel, text key to your message. Voila.
Body as JSON
An alternative and probably easier approach is to send your data as JSON instead of x-www-form-urlencoded to the API.
This requires you to send the token in the Auth header and switch to JSON for the body.
To do that in Postman put your token as "Bearer Token" under "Authorization".
In "Body" switch to "raw" and select "JSON".
Then you can define the whole message as follows:
{
"channel": "test",
"text": "Hi there!",
"attachments":
[
{
"fallback": "this did not work",
"image_url": "https://secure.gravatar.com/avatar/d6ada88a40de8504c6b6068db88266ad.jpg?s=512&d=https%3A%2F%2Fa.slack-edge.com%2F27b6e%2Fimg%2Favatars%2Fsmiley_blobs%2Fava_0016-512.png"
}
]
}
Of course you can do the same in your code. Since your are working in JavaScript using JSON would be the natural approach.
Note that not all API methods support sending the body in JSON. Check out this documentation for more info.

Sending message to server using python SocketIO

I have a situation where I have a python client try to send a message to a server using SocketIO. I'm using sock.emit to send a json message as shown below
sock = SocketIO(url, None, ...)
message = {'ob': 'house',
'ids': ['54fjadb70f9756','39f1ax451f6567']}
self.sock.emit(message)
server expects the follow:
{"ob":"house","ids":['54fjadb70f9756','39f1ax451f6567']}
the server is current receive the following message:
{"args": [], "name": "{\"ids\": [\"54fjadb70f9756\", \"39f1ax451f6567\"], \"ob\": \"house\"}"}
then complains about an invalid message.
How would I send the message so that the server receives it as expected i.e which the original message structure I specified? it seems emit is changing the structure of the message when I send it, is it possible to override and change emit to that it retain the original message structure? is so how would I do that?
Socket.io .emit() takes two arguments. The first argument is a message name which should be a plain string. The second argument is optional and can be data which will be JSON encoded data.
So, you are trying to send your data as the message name. That will not work. You need to create a message name and send the data as the argument for that message name.
sock = SocketIO(url, None, ...)
message = {'ob': 'house',
'ids': ['54fjadb70f9756','39f1ax451f6567']}
sock.emit("someMessageName", message)
Then, on the server, you need to have a listener for that specific message name and then you can receive the data when that message listener is invoked.

Is there any nicer way to get the full message from gmail with google-api

I'm working on a project where I, among other things, need to read the message in e-mails from my google account. I came up with a solution that works but wonder if there are any simpler ways?
The first part of the code is pretty standard to get access to the mailbox. But I post it so you can see what I did to get it to work.
SCOPES = 'https://www.googleapis.com/auth/gmail.modify'
CLIENT_SECRET ='A.json'
store =file.Storage('storage.json')
credz=store.get()
flags = tools.argparser.parse_args(args=[])
if not credz or credz.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET,SCOPES)
if flags:
credz = tools.run_flow(flow, store, flags)
GMAIL = build('gmail','v1',http=credz.authorize(Http()))
response = GMAIL.users().messages().list(userId='me',q='').execute()
messages = []
if 'messages' in response:
messages.extend(response['messages'])
print len(messages)
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = service.users().messages().list(userId='me', q=query,pageToken=page_token).execute()
messages.extend(response['messages'])
FromMeInd=0
for message in messages:
ReadMessage(GMAIL,'me',message['id'])
It is this part that I'm more interested to imporve. Is there any other way to more directly get the message with python and the gmail-api. I've looked through the api documentation but could not get any more efficient way to read it.
def ReadMessage(service,userID,messID):
message = service.users().messages().get(userId=userID, id=messID,format='full').execute()
decoded=base64.urlsafe_b64decode(message['payload']['body']['data'].encode('ASCII'))
print decoded
You can get the body as raw and then parse it using the standard Python email module
According to the official API: https://developers.google.com/gmail/api/v1/reference/users/messages/get:
import email
message = service.users().messages().get(userId='me', id=msg_id,
format='raw').execute()
print 'Message snippet: %s' % message['snippet']
msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
mime_msg = email.message_from_string(msg_str)
You'll get a mime message with a payload containing mime parts, e.g. plain text, HTML, quoted printable, attachments, etc.