Gmail API get messages where there are contacts included in the CC - gmail

I'm trying to get all the messages where:
I cced someone
Someone has cced somebody to a message inbound to me.
I looked in the advanced search operators for some guides, but all I can see is specifying a contact to a cc: search operator, reference.
There's really no docs for searching all messages where there are someone who's being cced to a message. Be it SENT or INBOX
It would be good if someone can provide an answer to this.

Issue:
You want to list all messages where there Cc header is populated.
There's no way to directly filter out by whether any cc is present, just for a certain email address (i.e. cc:my_user#my_domain.com). That's the case for the API as well as the UI.
Solution:
In that case, I'd suggest the following worflow:
Call users.messages.list to list all messages in your mailbox. You'll have to handle pagination at this point, if you want to retrieve all messages, using pageToken and nextPageToken.
For each message id, call users.messages.get to get the corresponding message (only id and threadId are returned from list).
Filter out messages that don't have the Cc header.
Code sample:
For example, in Apps Script you could do something like this (pagination is not implemented in this sample):
function getCcMessages() {
const userId = "me";
const { messages } = Gmail.Users.Messages.list(userId);
const messageIds = messages.map(m => m["id"]);
const optionalArgs = {
format: "METADATA",
metadataHeaders: "Cc"
}
const ccMessages = messageIds.map(id => {
const message = Gmail.Users.Messages.get(userId, id, optionalArgs);
return message;
}).filter(m => {
const headers = m["payload"]["headers"];
return headers;
});
return ccMessages;
}

Related

XERO-NODE SDK => How to choose a specific email template

I am using the Xero-node SDK to automatically create client invoices which works well.
At the end of the process, I would like to automatically email the client the invoice.
In the documentation it has the following example:
const xeroTenantId = 'YOUR_XERO_TENANT_ID';
const invoiceID = '00000000-0000-0000-0000-000000000000';
const requestEmpty: RequestEmpty = { };
try {
const response = await xero.accountingApi.emailInvoice(xeroTenantId, invoiceID, requestEmpty);
console.log(response.body || response.response.statusCode)
} catch (err) {
const error = JSON.stringify(err.response.body, null, 2)
console.log(`Status Code: ${err.response.statusCode} => ${error}`);
}
I have 2 questions:
The requestEmpty method does not work in javascript. Does anyone know the correct structure of requestEmpty?
I have used requestEmpty = { } but this throws an error => even though the system does actually send an email (probably a bug)
AND....
Is there a way for me to specify the email template that I would like the invoice to use (if I have specific templates setup in the web version)? Currently it seems to use the default Xero email template.
If you don't get an answer to your first query here, please can you raise it on the SDK page in Github and the Xero SDK team will look into this for you.
With regards to point 2, it is not possible to choose the email template when sending through the API, a basic template is used.

How change friendly name notify twilio sms

I am having some problems, I want to change the name of the sender. I mean, it is possible to assign an Alphanumeric Sender ID, I reviewed the documentation and followed the guidelines, in the response of the twilio api the name goes but when in the messages I receive it sends them to the same number. I know that it is not something due to the regulations of the country because according to the twilio documentation, it is possible. (https://support.twilio.com/hc/en-us/articles/223133767-International-support-for-Alphanumeric-Sender-ID) What is happening? How can I fix? Do I have to do any configuration?
How I want the sender ID to be seen
As I receive the sender ID
UPDATING QUESTION
Ok, the way I have structured the code is as follows:
I am working on a nodejs project, I need to send a message to multiple phone numbers so in order to do it I used the SMS notification service offered by Twilio, this is the method that was created:
async sendSMSAsNotify(req: Request, res: Response) {
try {
console.log("req.body:", req.body);
let messageBody = req.body.body;
console.log(messageBody);
let numberList = req.body.toBinding;
let extractBody = messageBody.replace(/<[^>]+>/g, '');
console.log(extractBody);
var decodedStripedHtml = he.decode(extractBody);
//console.log(decodedStripedHtml);
//console.log(`Body: ${messageBody}`);
var numbers = [];
for (let i = 0; i < numberList.length; i++) {
numbers.push(
JSON.stringify({
binding_type: "sms",
address: numberList[i],
})
);
}
const notificationOpts = {
toBinding: numbers,
body: decodedStripedHtml,
title: 'MyCompany'
};
// console.log("numbers:", notificationOpts.toBinding);
// console.log("body", notificationOpts.body);
const response = await this.client.notify
.services(process.env.SERVICE_SID_NTF)
.notifications.create(notificationOpts);
console.log('response', response);
res.json({
msg: `Message sent successfully! ${response}`,
});
} catch (e) {
throw new HttpException(HttpErrors.NOT_FOUND_ERROR, HttpStatus.NOT_FOUND);
}
}
The sendSMSAsNotify() method works great, I can send the same SMS to multiple numbers. But now what I want to achieve is that every message I send shows the sender id. I didn't find how to do it in the documentation of the SMS notification service, so I tried to change it and use a very simple method to send SMS via twilio to a single number just for testing.
async sendSMS(sms: SMSDto) {
try {
return await this.client.messages.create({
body: sms.message,
from: 'MyCompany',
to: sms.number,
});
} catch (e) {
return e
}
}
But in neither of the two methods in which I tried to change the sender identification it did not allow me and that is what brings me here, I really need help, it is a requirement that I need to fulfill and I cannot find a way to help me.
First up, while the list of countries that support alphanumeric sender IDs does contain Honduras there are further guidelines for SMS in Honduras that say:
Dynamic Alphanumeric Sender IDs are not fully supported for Honduras mobile operators. Sender IDs may be overwritten with a local long code or short code outside the Twilio platform.
So, even if you set everything up as I am about to explain, it is still possible that your sender ID may be overwritten with a local long code or short code and that Twilio is unable to do anything about that.
That being said, here's how to set up for alphanumeric sender IDs.
Since you are using Notify to send the messages, you will have set up a Messaging Service to use with Notify.
The Messaging Service controls how the SMS messages are sent out from Notify, from a pool of numbers. That pool can also contain your alphanumeric sender ID
So, to send from an alphanumeric sender ID you need to go to your Sender Pool within your Messaging Service and add an alpha sender.
Once you have the alpha sender set in your Messaging Service's pool, it will be used to send your messages out. You can even remove any long code numbers you have in the pool, if you do not plan to use them, though they are useful to fallback to if you do send to a country that doesn't support alphanumeric sender IDs.
Is it possible that you are in a country that does not support alphanumeric sender IDs and that Twilio falls back on a short code then?
PS: It would be helpful if you could add a code snippet, that shows the code you run, to your question.

Is there a way to obtain Discord message ID upon posting msg to channel from node server?

Using Discord.js in an Express/Node.js app, I'm trying to build a bot that grabs external data periodically and updates Discord with an embed msg containing some elements of that data. I'm trying to add a feature that will check if that data was deleted from the external source(no longer existing upon the next grab), then delete the specific msg in Discord that contains that data that was sent.
Some of the msgs posted in Discord may have duplicate data items, so I want to delete by specific msg ID, but it seems that msg ID is assigned when posted to Discord.
Is there a way to programmatically grab or return this msg ID when sending from Discord.js, rather than manually copy/pasting the msg ID from the Discord GUI? In other words, I need my bot to know which message to delete if it sees that msg's source data is no longer being grabbed.
// FOR-LOOP TO POST DATA TO DISCORD
// see if those IDs are found in persistent array
for (var i = 0; i < newIDs.length; i++) {
if (currentIDs.indexOf(newIDs[i]) == -1) {
currentIDs.push(newIDs[i]); // add to persistent array
TD.getTicket(33, newIDs[i]) // get ticket object
.then(ticket => { postDiscord(ticket); }) // post to DISCORD!
}
}
// if an ID in the persistent array is not in temp array,
// delete from persistent array & existing DISCORD msg.
// message.delete() - need message ID to get msg object...
// var msg = channel.fetchMessage(messageID) ?
Let me refer you to:
https://discord.js.org/#/docs/main/stable/class/Message
Assuming you are using async/await, you would have something like:
async () => {
let message = await channel.send(some message);
//now you can grab the ID from it like
console.log(message.id)
}
If you are going to use .then for promises, it is the same idea:
channel.send(some message)
.then(message => {
console.log(message.id)
});
ID is a property of messages, and you will only get the ID after you receive a response from the Discord API. This means you have to handle them asynchronously.

Get user join / leave events retroactively from Channels

I'm trying to do some analytics on average response time from some of our users on Twilio Chat.
I'm iterating through my channels, and I'm able to pull the info about messages, so I can compare times a message went un-responded to. However, I can't determine which users were in the channel at that time.
Is there anything on the channel that would give me historic member data? Who was in the channel? The channel.messages().list() method is only giving me the text of the messages sent to the channel and who it was by, but the user who may have been in a channel to respond changes throughout a channel's life time.
This is on the backend using the node.js SDK. note: This isn't a complete implementation for what I'm trying to do, but taking it in steps to get access to the information I'd need to do this. Once I have these messages and know which users are supposed to be in a channel at a given time, I can do the analytics to see how long it took for the users I am looking for to respond.
var fs = require('fs');
const Twilio = require('twilio');
const client = new Twilio(env.TWILIO_ACCOUNT_SID, env.TWILIO_AUTH);
const service = client.chat.services(env.TWILIO_IPM_SERVICE_SID);
async function getChatMessages() {
const fileName = 'fileName.csv';
const getLine = message => {
return `${message.channelSid},${message.sid},${message.dateCreated},${message.from},${message.type},${message.body}\n`;
}
const writeToFile = message => { fs.appendFileSync(fileName, getLine(message)); };
const headerLine = `channelSid,messageSid,dateCreated,author,type,body`;
fs.writeFileSync(fileName, headerLine);
await service.channels.each(
async (channel, done) => {
i++;
let channelSid = channel.sid;
if( channel.messagesCount == 0 ) return;
try {
await channel.messages().list({limit:1000, order:"asc"}).then(
messages => {
messages.forEach( writeToFile );
}
);
} catch(e) {
console.log(`There was an error getting messages for ${channelSid}: ${e.toString()}`);
}
if( i >= max ) done();
}
);
}
I'm beginning to be resigned to the fact that maybe this would only have been possible to track had I set up the proper event listeners / webhooks to begin with. If that's the case, I'd like to know so I can get that set up. But, if there's any endpoint I can reach out to and see who was joining / leaving a channel, that would be ideal for now.
The answer is that unfortunately you can not get this data retroactively. Twilio offers a webhooks API for chat which you can use to track this data yourself as it happens, but if you don't capture the events, you do not get access to them again.

Twilio Functions - SMS masking

Hello I am quite new to Twilio, but I have tried to look up how to answer this question. I would like to use Twilio Functions to solve my problem. I was wondering if it is possible for two people to send SMS messages to each other without revealing either of their numbers.
I was hoping to do this with only one new number per pair.
I imagined it would be through a conditional statement, where person X sends a message to the twilio number and person Y receives it, and vice versa. I assume this cannot be done with the twiML bins because of this conditional statement.
Thanks for your attention.
Twilio developer evangelist here.
You could absolutely do this with Twilio Functions. Here's a simple example of using a number to mask SMS messages between two callers.
class NumberMapping {
constructor() {
this.mapping = {};
}
addMaskedPair(numberA, numberB, twilioNumber) {
if (!this.mapping[twilioNumber]) {
this.mapping[twilioNumber] = {};
}
this.mapping[twilioNumber][numberA] = numberB;
this.mapping[twilioNumber][numberB] = numberA;
}
findNumber(from, to) {
const numberPairs = this.mapping[to];
if (!numberPairs) { return undefined; }
return numberPairs[from];
}
}
const numberMapping = new NumberMapping();
numberMapping.addMaskedPair('+1234567890', '+1098765432', '+1203948576');
exports.handler = function(context, event, callback) {
const to = numberMapping.findNumber(event.From, event.To);
if (typeof to !== 'undefined') {
const response = new Twilio.twiml.MessagingResponse();
response.message({ from: event.To, to: to }, event.Body);
callback(null, response);
} else {
callback(new Error(`Number mapping couldn't be found for sender ${event.From} and Twilio number ${event.To}.`));
}
};
The idea is that you create a NumberMapping object that maps between the two external numbers and your Twilio number. You add your mappings using:
numberMapping.addMaskedPair(firstNumber, secondNumber, twilioNumber);
and then when you need to retrieve the other number in a pair you can call
numberMapping.findNumber(number, twilioNumber);
The rest is just the function to return TwiML.
Note, you will only need as many Twilio numbers as there are relationships of the number that has the maximum set of relationships.
Let me know if that helps at all.
You need to purchase a number from twilio, then use node JS code to send and receive sms with it. You can also send voice messages too. The thing with twilio is that when you receive messages, twilio saves it to its website so you have to go to website and check it explicitly with your account.
You can create account and receive messages with this link
Here is some tutorial on how to send messages, you have to choose node.JS option.

Resources