How to retrieve the ID of the sent e-mail via GmailApp? - javascript

Here is a sample code
GmailApp.sendEmail("email#example.com", "mail subject", "mail body");
after the call I can see a sent message in my gmail account and that has a ID like this 147f7e77a4efed11 I want to retrieve this ID for the sent mail via the above code
sendEmail method returns an instance of GmailApp which is useful for chaining actions but no way to get the ID of the sent email.
what I am doing now is to perform a search and take the first message. But I am sure that is not a reliable way.
example
var message = GmailApp.search("to:email#example.com", 0, 1)[0].getMessages()[0];
now I can get the ID of the message and perform the desired actions.
Is it possible to retrieve the message or the ID of the message without an unreliable search?

After building your service, you can use the messages.list and then filter them like you would when searching in GMail, you can also use labels to get only sent mails etc.
messages = gmail_service.users().messages().list(userId='me', q="subject:mail subject deliveredto:email#example.com", maxResults=1).execute()
if messages['messages']:
for message in messages['messages']:
print 'message ID: %s' % (message['id'])
If you pass through the email you're searching for and other "unique" references as arguments in a Python function it makes it a lot more versatile too.
Edit: After talking with you I think that creating your own personal ID/reference for each email sent would be the most prudent method of retrieval. I recommend using faker, they have a javascript version and I use faker for all of my data needs. There's plenty of documentation for it and then you can filter your list according to how you set your ID.

you can use the new gmail api directly. you will need a manual oauth flow to get the token, then use urlFetch to make the call. https://developers.google.com/gmail/api/v1/reference/users/messages/send
it returns a message resource with its id. might also be possible to do this with advanced services but i havent tried. i have done it with urlfetch and worked ok.

Can you set the Message-Id header on the email? (Not sure if the apps scripts allows that or overwrites it or not.) If so, I'd generate a unique Id that way and you can look it up using a search "rfc822msgid:".

create a draft first, then send it
function sendEmail(opts) {
let draft = GmailApp.createDraft(recipient=opts.recipient, subject=opts.title, {
htmlBody: opts.msg,
});
draft.send()
let ret = {
id: draft.getId(),
messageId: draft.getMessageId(),
}
console.log('sendEmail results: ', ret )
return ret
}

2022 Update
GmailDraft.send() returns a GmailMessage you can use that to label the sent message.
Example:
const draft = GmailApp.createDraft('Foo <foo#bar.com>','Lorem Ipsum','Dolor Sit Amet');
const label = GmailApp.getUserLabelByName('Test');
const msg = draft.send();
const thrd = msg.getThread();
label.addToThread(thrd);

google-apps-script solution working for sent messages with methods: GmailApp, MailApp
enable Gmail service
use the code:
var messages = Gmail.Users.Messages.list(
"me", {q: "subject:Test Me", maxResults: 1}
).messages;
console.log(messages[0].id)

Related

How to get total number of users from a Telegram group and display those stats in simple html text?

I am trying to find the API endpoint for telegram... a public one that does not require any login or API keys...
I found this: https://core.telegram.org/schema/json which includes a long JSON list of functions. Not sure if there are other API endpoints that can be used to query just a group and show stats for that group or how exactly to go about it.
I have seen other users suggest creating a telegram bot and then pull this data from the bot however not sure exactly how to do this effectively.
The main goal is to simply display the total users of a group via javascript and add the number via <span id="telegram-users">1</span>
I have seen this being done on coingecko's coins and token listings under social however can not figure out how to simply show the total number of a telegram group in simple HTML format from JSON data for API..
UPDATE:
I did some research and freshened up on my coding skills.
There is this website: https://tgstat.com/ that pulls data for telegram channels. I am trying to use a simple javascript function to fetch this url and then use jsoup to get the data by using the element identifier which is .columns.large-2.medium-4.small-6.margin-bottom15 > div > .align-center > #text
Then use document.getElementById("telegram-members").innerHTML = ()
to display this data in html.
I understand the cosp and will use https://api.allorigins.win/raw?url= to bypass this.
Alright, if I understand your question well. You're trying to get the total number of users from a telegram group, channel, or chat.
The premise is, you want to avoid using Telegram API which will require auth token.
However, since your main goal is just basically the same. I'll leave this method here, so you'll have a "backup plan" later.
Requirement & Notes:
Create a bot on Telegram app, and get the bot token.
For tracking channels, you just need to find the #channel name.
However for group chats, you need to find the chat_id for it. As explained below!
Only vanilla Javascript is needed
A bit of patience
At most usage, you just need to send a HTTP request to the Telegram API.
API Example: https://api.telegram.org/bot<token-here>?<api-method-here>
You can learn more about other API method Here.
Hold Up!
Firstly, what do you want to track? Is it a group? Is it a channel?
Both have different method, please check out the example below!.
To track the number of members that are following a channel
This is fairly easy. Just send a HTTP request to:
https://api.telegram.org/bot<token-here>/getChatMembersCount?chat_id=<channel-name>
For example: the name of the official telegram channel is #telegram.
Sooo, send a request to:
https://api.telegram.org/bot<token-here>/getChatMembersCount?chat_id=#telegram
You'll get a response like:
{ ok: true, result: 5605541 }
The total number of followers is shown in the result key.
To track the number of members in a group chat
Before we can get the number of members in a group. You need to find the <chat_id> for your group chat.
Note: Your bot must join the group before you can do anything like tracking, send message etc.
To do that, send a HTTP request to https://api.telegram.org/bot<token-here>/getUpdates.
Look closely into the response. You need to find the chat object, like this.
<...>
​​
0: Object { update_id: 122334455, my_chat_member: {…} }
​​​
my_chat_member: Object { chat: {…}, from: {…}, date: 1622275487, … }
​​​​
chat: Object { id: -1234567890, title: "Group-Name", type: "group", … }
<...>
You just need the id from the chat object. Which is -1234567890 in this case.
After you got the chat_id number.
Just send a HTTP request to:
https://api.telegram.org/bot<token-here>/getChatMembersCount?chat_id=<id-number>
You'll also get the response as:
{ ok: true, result: 3 }
The number of members is stored in the result key. Just parse it out and boom!
Full Example
hello.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<span id="telegram-users">null</span>
</head>
<body></body>
<script src="hello.js"></script>
</html>
hello.js
// Set Your Bot Token Here
var Token = "insert_your_bot_token";
/*
chat_id for the group or channel you want to track,
For channels, they are usually like #telegram, #Bitcoin_News_Crypto, #TelegramTips,
For group chats, they are numbers alike. Just like "-1234567890",
Modify and set your chat_id here if you found it,
It should look like var group_chat_id = "-1234567890".
*/
var chat_id = "#telegram";
// HTTP Request Function
function httpRequest(URL, Method)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open(Method, URL, false);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(null);
return JSON.parse(xmlHttp.responseText);
}
// Send a request to Telegram API to get number of members in a particular group or channel
function getMemberCount()
{
return httpRequest(`https://api.telegram.org/bot${Token}/getChatMembersCount?chat_id=${chat_id}`, "GET");
}
// Run function and parse only the number of members
var result = getMemberCount()["result"];
console.log(result);
// Write the numbers of member back to HTML
document.getElementById("telegram-users").innerText = `The group or channel currently has ${result} members.`;
// Use this to find the *chat_id* for your group chat
//console.log(httpRequest(`https://api.telegram.org/bot${Token}/getUpdates`, "GET"));
This question has been moved here for easier understanding of the issue. How to pull data from another website using Javascript or jQuery (cross-domain) CORS (no api)

How can I make Dialogflow agent greet user if they have used the action before?

I'm using Actions On Google / Dialogflow, and I'm trying to make a function that will greet a user by their name if they've used the action before, and if not, will ask for their name. I have tried to map this to the "Welcome intent" through fulfillment, but whenever I try to run the action on the simulator, I get this error:
Error 206: Webhook Error
Which Initially would make sense if this was mapped to another intent, but I'm wondering if I'm getting this error because you can't have a fulfillment with the welcome intent?
Here's the code I'm using in the inline editor which may be the problem:
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request,response) => {
const agent = new WebhookClient({ request, response });
function welcome(conv) {
if (conv.user.last.seen) {
conv.ask(`Welcome back ${name}!`);
} else {
conv.ask('Welcome to The app! My name is Atlas, could I get your name?');
}}
let intentMap = new Map();
intentMap.set('Welcome Intent', welcome);
agent.handleRequest(intentMap);
How come this isn't working? Do I need to implement user login? Do I need to use a function that would write to a firestore databbase?
Thanks for the help or suggestions!
Let's clear a few things up to start:
You can have fulfillment with your welcome intent.
You do not need user login. Although using Google Sign In for Assistant can certainly be used, it doesn't fundamentally change your problem here.
You do not need to use a function that writes to the firestore database. Again, you could use it, but this doesn't change your problems.
The specific reason this isn't working is because the conv parameter in this case contains a Dialogflow WebhookClient rather than an actions-on-google Conversation object.
To get the Conversation object with the parameter you have, you can call conv.getConv(), which will give you an object that has a user parameter. So this may look something like
function welcome(conv) {
let aog = conv.getConv();
if (aog.user.last.seen) {
conv.ask(`Welcome back ${name}!`);
} else {
conv.ask('Welcome to The app! My name is Atlas, could I get your name?');
}}
There are, however, still some issues with this. Most notably, it isn't clear where name will come from. I assume you will get it out of the user store object, but you don't seem to have done this.
For anyone who comes across this question in the future and just wants a straight forward answer without having to search through ambiguous answers / documentation, here is what to do step by step:
note: I ended up using the Google Sign in method, but even if this isn't your goal, i'll post the link to the alternative method.
1) Import the actions on google module. What people / tutorials don't to show is you have to import the library like this (for user login):
const {
dialogflow,
Permission,
SignIn
} = require('actions-on-google')
instead of
const dialogflow = require('actions-on-google')
2) Use this code:
const app = dialogflow({
clientId: '<YOUR CLIENT ID from Actions on Google>',
});
app.intent('Start Signin', conv => {
conv.ask(new SignIn('To get your account details'));
});
app.intent('Get Signin', (conv, params, signin) => {
if (signin.status === 'OK') {
const payload = conv.user.profile.payload;
conv.ask(`Welcome back ${payload.name}. What do you want to do next?`);
} else {
conv.ask(`I won't be able to save your data, but what do you want to do next?`);
}
});
This function will ask the user for a login, and next time you invoke the intent, it will say "Welcome back name", because google automatically saves it.
Here's the link to the alternative method:

Sending a canned response with Gmail Apps Script

I'm writing an auto-replying tool for gmail using Google Apps Script (http://script.google.com).
In the docs, I don't find any function to send a Gmail canned response. Is there no such feature?
If not, how would you handle this? I thought about sending an email to myself in gmail:
To:example#gmail.com
From:example#gmail.com
Subject:This is a canned response ID1847
Hi
This is a test
adding the label mycannedresponse to it, and then loading in Apps Script this mail from code:
var threads = GmailApp.search("label:mycannedresponse ID1847");
if (threads.length != 1) {
// error: the canned response ID... is not unique
} else {
threads[0].getBody(...)
threads[0].getPlainBody(...)
}
Is there a more-documented way to do it?
Have you seen the sendEmail method for GAS? You can create a trigger to fire off this email.
// The code below will send an email with the current date and time.
var now = new Date();
GmailApp.sendEmail("mike#example.com", "current time", "The time is: " + now.toString());
https://developers.google.com/apps-script/reference/gmail/gmail-app#sendemailrecipient-subject-body

How to send message to specific selector using ActiveMQ ajax

Is there any possibility to send an ActiveMQ message from a browser using amq ajax, including a topic and a specific selector?
I have an app in 2 parts:
PART 1 --> Web client is listening on a topic:
var myHandler = function(message) {console.log(message);}
amq.addListener('amqlistener', 'topic://mytopic', myHandler);
PART 2 --> Web app sends different orders to this topic:
amq.sendMessage('topic://mytopic', myData);
Very simple and all works OK.
Now, I need to filter some messages, so I have put a selector in the PART 1 like this:
amq.addListener('amqlistener', 'topic://mytopic', myHandler, {selector:"dev='xxxxx'"} );
and here is (in PART 2) where I don't get the way to send a message including this specific selector.
Any help is well welcome :)
You don't send with selectors, you send with headers/properties that the selector can use to filter out messages.
amq has a function that looks like this:
var sendJmsMessage = function(destination, message, type, headers)
It accepts headers. I would supply your header 'dev' with value 'xxxxx' there.

How to pass object argument to PlusDomains.Circles.list in Apps Script

Recently was enabled Google + Domains API For Apps Script, I have explored some options and it seems is going to work, but in the specific case of PlusdDomains.Circles.list I don't know how to pass the second argument what is an object, I can not obtain several fields in the response, this is my code.
function getProfile() {
var userId = 'me';
var post = { maxResults: 2, fields:"title"};
var profile = PlusDomains.Circles.list(userId, post);
Logger.log('all: %s', JSON.stringify(profile));
}
this is the output,all: {"title":"Google+ List of Circles"}
if I try to get another field I don't know if this is correct, I put this:
var post = { maxResults: 2, fields:["title", "items"]};
but I get the same result:all: {"title":"Google+ List of Circles"}
If I try to get the result value for items, I get undefined. I don't how to pass the object correctly or if this is a bug in the Apps Script, somebody has idea??
I'm trying to get this working too. From the public google+ domain api docs it looks that the fields property expects a string with field names comma separated, i.e.
var post = { maxResults: 2, fields:"title,items"};
I don't seem to get the items populated (all the properties are undefined) in my google apps script. But when I use the API explorer "try it" console with OAuth2 enabled for scopes https://developers.google.com/+/domains/api/circles/list and https://developers.google.com/+/domains/api/circles/list I do see the items populated, so I'm thinking there may be an issue with my scripts authorization scopes or a bug in the google apps google+ domain service.

Categories

Resources