How to filter the Google Api inbox to read only the main messages? - gmail-api

I made a script to check if there are new emails in my inbox, but it returns the emails (Gmail) from the Main, Social and Promotions box, but I just want to read the one from the Main box.
Its an script for my IA
# Call the Gmail API to fetch INBOX
results = service.users().messages().list(userId='me',labelIds = ['INBOX', 'UNREAD']).execute()
messages = results.get('messages', [])
if not messages:
frase = 'Sem novas mensagens na caixa de email'
a = Pesquise(frase)
a.fala(frase)
else:
for message in messages:
msg = service.users().messages().get(userId='me', id=message['id']).execute()
payld = msg['payload'] # get payload of the message
headr = payld['headers'] # get header of the payload
for one in headr: # getting the Subject
if one['name'] == 'Subject':
msg_subject = remover_acentos(one['value'])
else:
pass
frase = 'Hugo, novo email na caixa de entrada, ' + msg_subject
a = Pesquise(frase)
a.fala(frase)
sleep(600)
except Exception as err:
print err
I just want the script to read the Main box, not the Main, Social, and Promotions.

Based from SGC's answer, you can add the following q parameter on your Users.messages: list :
in:inbox is:unread -category:(promotions OR social)
The result will be something like:
{
"messages": [
{
"id": "169f891015afd26b",
"threadId": "169f891015afd26b"
},
{
"id": "169f67bfu70eed28",
"threadId": "169f67bf5d0eed28"
},
{
"id": "169f65c4bea507b9",
"threadId": "169f27c4bea507b9"
},
{
"id": "169ef58fd53f6c1d",
"threadId": "169ef58fd53f6c1d"
},
{
"id": "169eecy7846c17ca",
"threadId": "169eecy7846c17ca"
},
{
"id": "169ea5df63c40128",
"threadId": "169ea5df63c40128"
}
],
"resultSizeEstimate": 6
}
You can try this here.

Related

Problem with left join with contition typeorm

This is my code:
const query = this.requestRepository
.createQueryBuilder('request')
.leftJoinAndMapMany(
'request.approvers',
RequestApprover,
'approvers',
'request.id = approvers.requestId',
);
And this is data I got from query:
"requests":
[
{
"id": "8ceee413-521c-4e21-a75b-27048d184804",
"status": "waiting",
"reason": "1",
"approvers": [
{
"id": "04946109-ba35-4c08-a469-761023f33b3c",
"employeeCode": "EMP001",
"status": "waiting",
},
{
"id": "a9dec055-e237-434c-897e-d877f64df4af",
"employeeCode": "EMP002",
"status": "approved",
}
]
}
]
The problem is that when I add contidion to get all request which have been approve by employee EMP002
query.andWhere(`approvers.employeeCode = 'EMP002'`)
The approvers[0] is missing. I know that's correct but I wonder if there is a way to get full approvers but still get requests which have EMP002 is a approver. Thank you for your attention.
You can do this using two queries. First, get all the ids of the request where approvers.employeeCode = 'EMP002'. Then get all the requests where id of request equals the requestIds fetched above.
const results = await this.requestRepository
.createQueryBuilder('request')
.leftJoinAndMapMany(
'request.approvers',
RequestApprover,
'approvers',
'request.id = approvers.requestId',
)
.select('request.id', 'id')
.where('approvers.employeeCode = :empCode', { empCode: 'EMP002' })
.getRawMany();
const requestIds = results.map(e => e.id);
const requests = await this.requestRepository
.createQueryBuilder('request')
.leftJoinAndMapMany(
'request.approvers',
RequestApprover,
'approvers',
'request.id = approvers.requestId',
)
.where('request.id IN (:...requestIds)', { requestIds: requestIds });
requests would now contain the desired result.

Karate: Can I iterate on a Json array response and do some conditional statements

My json array response is something like below:
response = [
{
"ID": "123",
"Name":"Test1",
"Data":{
"Status":"Red",
"Message":"user not valid",
"Code": "ERROR-P1"
}
},
{
"ID": "143",
"Name":"Test2",
"Data":{
"Status":"Amber",
"Message":"user data missing",
"Code": "ERROR-P2"
}
},
{
"ID": "133",
"Name":"Test3",
"Data":{
"Status":"Green",
"Message":"",
"Code": ""
}
}
There could be more entries in the json array with same data and status.
My use case is to check, based on a condition that if my json array has Status as Red or Amber, then message and code is not empty and similarly if my status is Green then message and code is empty.
I need to iterate to the entire array and validate this scenario.
And also need to get a count of Status: Red, Amber and Greens from the Array Json response.
What could be the best possible solution with karate?
Any help would be appreciated.
Thank you
Here you go:
* def red = []
* def amber = []
* def green = []
* def fun =
"""
function(x){
if (x.Data.Status == 'Red') karate.appendTo(red, x);
if (x.Data.Status == 'Amber') karate.appendTo(amber, x);
if (x.Data.Status == 'Green') karate.appendTo(green, x);
}
"""
* karate.forEach(response, fun)
* assert red.length == 1
* match each red..Message == 'user not valid'
* match each amber contains { Data: { Status: 'Amber', Message: 'user data missing', Code: 'ERROR-P2' } }

Convert raw string to JSON format

Hi I just have a question on how can I convert this API response into json data. I tried using explode but the response seems like separated into array.
StatCode: 11
StatName: cancelled
OrderID: OP_AFIFAH_6889
Amount: 1.10
TranID: 143519171
Domain: test
BillingDate: 2019-11-26 16:58:49
BillingName: test
VrfKey: test
Channel: credit
Currency: MYR
ErrorCode: CC_000
ErrorDesc: Successful Payment :
Maybe something like this
{
"StatCode": 11,
"StatName": "cancelled",
"OrderID": "OP_AFIFAH_6889",
"Amount": 1.10,
"TranID": 143519171
etc..
}
Thanks
The best way is changing the API to return the JSON object. If you don't have access to the API, I wrote a simple javascript for you which can convert it to the JSON object:
function toJSON(input) {
const lines = input.split('\n')
const result = []
for (let i = 1; i < lines.length; i++) {
if (!lines[i])
continue;
const obj = {}
const currentline = lines[i].split(':')
obj[currentline[0]] = currentline[1]
result.push(obj)
}
return JSON.stringify(result)
}
console.log(toJSON(`StatName: cancelled
OrderID: OP_AFIFAH_6889
Amount: 1.10
TranID: 143519171
Domain: test
BillingDate: 2019-11-26 16:58:49
BillingName: test
VrfKey: test
Channel: credit
Currency: MYR
ErrorCode: CC_000
ErrorDesc: Successful Payment :`)
);
[
{
"StatName": "cancelled",
"OrderID": "OP_AFIFAH_6889",
"Amount": 1.10,
"TranID": 143519171,
"Domain": "test",
"BillingDate": "2019-11-26 16:58:49",
"BillingName": "test",
"VrfKey": "test",
"Channel": "credit",
"Currency": "MYR",
"ErrorCode": "CC_000",
"ErrorDesc": "Successful Payment"
}
]
Note: Amount and TranID values are both numbers ,if you want them to be a type of string kindly add double quotes to them.
Thanks

How to read objects and store into array

I made an http request and got back e.g the below json. I want to read the cars and the shoes objects into separate arrays at the time of the http request.
json
{
"id": 9,
"name": "Zlatan",
"cars": [
{
"type": "ford",
"year": "2019"
},
{
"type": "audi",
"year": "2017"
}
]
"shoes": [
{
"brand": "adidas",
"status": "old"
},
{
"brand": "timberland",
"status": "new"
}
]
}
comp.ts
cars = [];
shoes = [];
//......
getZlatan() {
return this.httpService.getInfo()
.subscribe( data => {
this.objZlatan = data; //this part holds the json obj above
this.cars ....//what to add here
this.shoes ....// here too.
} );
}
Or is there a cleaner way to load the arrays at http request?
Access the cars and shoes properties of the data with simple dot-notation. It might be ideal to check if the data returned is not null with if(condition here) and then perform your logic. If you have more objects and want to bring all cars and shoes under one array then you have to loop through.
getZlatan() {
return this.httpService.getInfo()
.subscribe(data => {
this.objZlatan = data;
this.cars = this.objZlatan.cars;
this.shoes = this.objZlatan.shoes;
});
}
Just use . and type names to access cars and shoes. Let me show an example:
return this.httpService.getInfo()
.subscribe( data => {
this.objZlatan = data; //this part holds the json obj above
this.cars = data.cars;
this.shoes =data.shoes;
} );

how to read stanza message of xmpp in nodejs

i wan to send message using xmpp+nodejs
For this i send like this ..
var mess_set = {
"messageId": 1,
"isHTML": false,
"serverMsgts": 1482308138,
"msgts": 1482308138,
"rid": send_id,
"sname": "Sender me..",
"text": text,
"sid": me_chat_id,
"type": "0",
"rname": "Developer recive..",
"imgName": "64A419D8BAF811E6BFD706E21CB7534C---1480948613315cropped_image.jpg",
"class": 'text-area'
}
var stanza = new xmpp.Element('message', {to: send_id + '#testing.twodegrees.io', type: 'chat', id: send_id}).
c('body').t(mess_set)
connection.send(stanza);
var test = {'text': text, "class": 'text-area'}
this message sent and on the reciver side i got this message in this format
Incoming_message..: <message to="586f2fc0ba5d09594e0ef5bf#testing.twodegrees.io" type="chat" id="586f2fc0
ba5d09594e0ef5bf" xmlns:stream="http://etherx.jabber.org/streams" from="586f3b52ba5d09594b4d6e22#testing.
twodegrees.io/74ab3f34a0d5a2885768d29426c39ef6" xmlns="jabber:client"><body>[object Object]</body></messa
ge>
So when i try to get text message and all other detail that is sent from sender
Using this code
var body = stanza.getChild('body');
var message = body.getText();
var body = stanza.getChild('body');
this give me [objec objet]
I get this through
So My question is :
1-How i get original message with all other detail like image,id etc
Thanks

Resources