GMail API & C#: not receiving any messsage counts - gmail-api

I'm trying to get the message count of my Gmail Inbox from C#, but it turns out that the message counts are not returned for ANY of my labels.
The following returns my label names (both personal and system created) just fine, but the the respective message counts are always null. I've tried all of the message counts: MessagesUnread, MessagesTotal, ThreadsUnread, ThreadsTotal, and always get "No" below.
ListLabelsResponse response = service.Users.Labels.List("me").Execute();
foreach (Label label in response.Labels)
{
Console.Write("{0}, has messages? ", label.Name);
if (label.MessagesUnread.HasValue)
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
What am I doing wrong?

Apparently the Google API is too lazy to fill in the count details on the List method. Instead I tried the Get...
Label rsp = service.Users.Labels.Get("me", "INBOX").Execute();
..and everything shows up nicely in the Label object. Problem solved.

Related

Discord.js V13 -- Store persisting hidden data on the message object

I have coded a bot to send a message response to a given command, !a. I want to store additional data on the message object, so that if the user reacts to that message the bot can read the hidden data property and know the original message resulted from !a.
Ideas I had:
Create a custom property on the message object: Message.Custom_Prop
Hijack an unused property: Maybe Message.webhookId?
Store hidden text in the form of an embed or message content.
I haven't been able to get any of these to work though.
The best way that I can think of is to store an array of message IDs that were triggered by !a. Something like this:
// At the start of your script
const commandResponses = [];
// Logic for sending the command response
message.channel.send("response here").then(msg => commandResponses.push(msg.id));
// Checking whether the message was a response
if (commandResponses.includes(reaction.message.id)) {
// It's a response so do stuff here
}
(Not tested so it's possible that this won't work)

Get the previous message to a discord channel

Given a discord message id and a channel id, is there a way of finding the previous message to the same discord channel?
Message ids are intigers, and my impression is that the are monotonously increasing. So if there was a way of looking up all the message ids that a channel has recieved, i think it would be as simple as finding the highest that is less than the id you are interested in.
Im not sure if u meant to find the content of the message itself or the previous message before it but you can read more on txt_channel.history here:
What history does is enabling you to see the message history of a text channel.
So if you want to find the contents of a specific message using it's id you can do:
(of course you need to fetch the text channel, you can look at here)
async for msg in txt_ch.history(limit=[how many messages back you want the loop to go]):
if msg.id == ID_OF_MSG: # you found the message
print("the message with the id has been found")
now this code ^^ is pointing you to the message you gave with the current id but if you want to get the message previous to it you just add this:
async for msg in txt_ch.history(limit=[how many messages back you want the loop to go]):
found_message = False
if msg.id == ID_OF_MSG: # you found the message
found_message =True
elif found_message:
found_message = False
print("previous message")
Of course you can change the last line on the print to something like:
print(msg.content)
to see it's content, or you can send it back to the channel, it is up to you.
side not:
I tried to test it and it doesn't seem that the ids of the messages are one after another so you can't do id-1 to get the previous message id.

Gmail API: messages.list suddenly there's a messages error key despite there's a nextPageToken in the prior iteration

I used to interact with the Gmail API since past year using these tests https://developers.google.com/gmail/api/v1/reference/users/messages/list#try-it but now this examples are failing because seems there are more messages but the next iteration is coming empty.
Problem is in this part of the code:
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = service.users().messages().list(userId=user_id, q=query,
pageToken=page_token).execute()
messages.extend(response['messages'])
The error is raised when trying to access the response['messages'] as the unique key in the reponse is 'resultSizeEstimate' and is 0. Sounds like the page_token is pointing to a next empty page.
Is someone experiencing this issue as well?
If your last page perfectly contains the last email with that particular query, you will get a nextPageToken to a page with a response like this:
{
"resultSizeEstimate": 0
}
The easiest way around this is to just add a check if messages is part of the response:
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = service.users().messages().list(userId=user_id, q=query, pageToken=page_token).execute()
if 'messages' in response:
messages.extend(response['messages'])

GMail API: Not Found (404) errors when calling retrieving drafts with drafts.get from ids supplied by drafts.list

In the Gmail API quite frequently drafts.list will return a draft id
but when I pass it to drafts.get it returns a 404 error. This is
repeatable for certain draft ids, I can call drafts.list again and
they're still there and I can then call drafts.get and get the same
error again. I can also call messages.get with the given message id
and get a response as expected and I can see the draft in the gmail client.
Seems to be a bug in the GMail API. Any ideas for workarounds? And does anyone know the right way to report bugs to Google?
I'm getting the same issue, here is how to reproduce:
1) Start writing a new message in the Gmail web client. Don't add anything in the To field or the Body. Then close the message to save it as a Draft.
2) Retrieve a list of threads with the following code:
threads = gmail_client.users().threads().list(userId='me', maxResults=15, pageToken=pageToken, q='-in:(chats OR draft) in:all').execute()
4) Then retrieve each of these threads in a batch request:
batch.add(gmail_client.users().threads().get(userId='me', id=thread['id'], format='metadata', metadataHeaders=['subject','date','to','from']), callback=threadCallback)
The error that gets returned is:
https://www.googleapis.com/gmail/v1/users/me/threads/154e44a4c80ec7e4?format=metadata&metadataHeaders=subject&metadataHeaders=date&metadataHeaders=to&metadataHeaders=from&alt=json returned "Not Found">
In order to use drafts.get, you should use immutable id of the draft, not the message id of the draft which will change after each update in draft. Drafts.list supplies both immutable id and the message id of the messages in the draft.

Getting more data from messages.get in C#

I'm having trouble getting more than just the snippet for text data for the message I am trying to retrieve using the Gmail API. Here is the piece of test code I am working with:
public string GetMail()
{
GmailService service = (GmailService)HttpContext.Current.Session["service"];
Message messageFeed = service.Users.Messages.List("me").Execute().Messages.First();
UsersResource.MessagesResource.GetRequest getReq = new UsersResource.MessagesResource.GetRequest(service, "me", messageFeed.Id);
getReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full;
Message message = getReq.Execute();
return message.Raw;
}
For some reason, when I call message.Raw, it is returning null. I am able to retrieve other properties as what the format=minimal setting would based off of the API playground example I was playing with.
However in my code, I am setting the format enum to "full", yet I am still unable to retrieve the full data of the message.
Am I completely missing something here?
Seems like you're mixing up formats and response types. If you want the raw message as a string in Message.raw then you need to set:
getReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;
If you want the parsed message back (in the "payload" field) then you can use getReq.Format of Full like you have.
Acceptable values are:
"full": Returns the parsed email message content in the payload field and the raw field is not used. (default)
"minimal": Only returns email message metadata such as identifiers and labels, it does not return the email headers, body, or payload.
"raw": Returns the entire email message content in the raw field as a string and the payload field is not used. This includes the identifiers, labels, metadata, MIME structure, and small body parts (typically less than 2KB).
from: https://developers.google.com/gmail/api/v1/reference/users/messages/get

Resources