I am trying to send a variable value pulled from a spreadsheet in a webhook, my issue is that i am not being able to pass the variable value in the "data variable", when i only send pure text, everything works fine but the variable value is not arriving, as it simple as it may sound, can anyone guide me on this matter? Thanks in advance.
function message (){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getSheetByName("Backlog Report");
var backlogValue = ws.getRange("U7").getValue();
var totalCases = ws.getRange("Z7").getValue();
console.log(backlogValue);
var data = {
text: "Backlog: " + backlogValue
};
var payload = JSON.stringify(data);
var options = {
method: "POST",
contentType: "application/json; charset=UTF-8",
payload: payload,
muteHttpExceptions: true
};
var webhook = 'https://chat.googleapis.com/v1/spaces/XXXX/messages?key=XXX';
var response = UrlFetchApp.fetch(webhook, options);
Logger.log(response.getContentText());
}
I was stuck with webhooks as well... i can't tell you exactly why the following works for me, but if it helps you solve your problem, then here you go with my function. I've used it to send google sheets data to one of my Discord Channels with a embed format.
I think the relevant part of this is, to get the value of a field
var docName = sheets.getRange('B2').getValue();
Full Function:
//Discord webhook Aktiv-Recruitment
function postMessageToDiscord() {
var sheets = SpreadsheetApp.getActiveSpreadsheet();
var docName = sheets.getRange('B2').getValue();
var docRealm = sheets.getRange('C2').getValue();
var docClass = sheets.getRange('D2').getValue();
var docBtag = sheets.getRange('J2').getValue();
var docProg = sheets.getRange('I2').getValue();
var docDate = sheets.getRange('K2').getValue();
var discordUrl = "YOUR_WEBHOOK_URL";
`changed to var payload = {content:message} and received the new error`
var payload = JSON.stringify({
"embeds": [{
"author":{
"name": docClass + " hinzugefügt!",
},
"title": docBtag,
"color": 15374745,
"url" : "SOME_LINK",
"fields": [
{
"name": "Name",
"value": docName,
"inline": true
},
{
"name": "Realm",
"value": docRealm,
"inline": true
},
{
"name": "Progress",
"value": docProg
}
],
"footer": {
"text": docDate
}
}]
});
var params = {
method: "POST",
payload: payload,
muteHttpExceptions : true,
contentType: "application/json"
};
var response = UrlFetchApp.fetch(discordUrl, params);
Logger.log(response.getContentText());
}
Related
I'm trying to use the new Google Forms API to add an image to an existing Google form. At the moment I'm just trying to change the image Alt Text. I haven't been able to get it to work. I keep getting a 400 error. I'm hooping someone can point out what I'm doing wrong.
TIA for any help
This is the code:
function callFormsAPI() {
Logger.log('Calling the Forms API!');
var formId = "1oxBZrRG6UEcrLSXrT9P9hcqgkvE12UQDYUOAYyg3eeA"
// Get OAuth Token
var OAuthToken = ScriptApp.getOAuthToken();
Logger.log('OAuth token is: ' + OAuthToken);
var path = "https://forms.googleapis.com/v1beta/forms/"
var formsAPIUrl = path+formId+':batchUpdate'
Logger.log('formsAPIUrl is: ' + formsAPIUrl);
var body = tempAPI()
var options = {
'headers': {
Authorization: 'Bearer ' + OAuthToken,
Accept: 'application/json'
},
muteHttpExceptions: true,
'method': 'post',
'payload' : JSON.stringify(body)
// 'payload' : body
};
var response = UrlFetchApp.fetch(formsAPIUrl, options);
Logger.log('Response from forms.responses was: ' + response);
var text = response.getContentText()
console.log(text)
}
function tempAPI(){
var itemId = "2005660890"
var imageString = 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d';
var request = {
"requests": [
{
"updateItem": {
"item": {
"itemId": itemId,
"questionItem": {
"image": {
"altText": 'this is a car',
// "sourceUri": imageString
}
}
},
"updateMask": "altText"
// "updateMask": "item/questionItem/image/sourceUri"
} //end of update item
}
]
}
return request
}
This is the response I'm getting
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"{\"requests\":[{\"updateItem\":{\"item\":{\"itemId\":\"2005660890\",\"questionItem\":{\"image\":{\"altText\":\"this is a car\"}}},\"updateMask\":\"altText\"}}]}\": Cannot bind query parameter. Field '{\"requests\":[{\"updateItem\":{\"item\":{\"itemId\":\"2005660890\",\"questionItem\":{\"image\":{\"altText\":\"this is a car\"}}},\"updateMask\":\"altText\"}}]}' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"{\"requests\":[{\"updateItem\":{\"item\":{\"itemId\":\"2005660890\",\"questionItem\":{\"image\":{\"altText\":\"this is a car\"}}},\"updateMask\":\"altText\"}}]}\": Cannot bind query parameter. Field '{\"requests\":[{\"updateItem\":{\"item\":{\"itemId\":\"2005660890\",\"questionItem\":{\"image\":{\"altText\":\"this is a car\"}}},\"updateMask\":\"altText\"}}]}' could not be found in request message."
}
]
}
]
}
}
the webhook only runs when im the one posting to it, the permissions are set to anyone but that has not helped, it worked just fine not 2 months ago then google and discord changed some things and now its broken.
var POST_URL = "https://discord.com/api/webhooks/sI9VjZ_v0TsMNA5yBWmkopvFX";
function onSubmit(e) {
var form = FormApp.getActiveForm();
var allResponses = form.getResponses();
var latestResponse = allResponses[allResponses.length - 1];
var response = latestResponse.getItemResponses();
var items = [];
for (var i = 0; i < response.length; i++) {
var question = response[i].getItem().getTitle();
var answer = response[i].getResponse();
try {
var parts = answer.match(/[\s\S]{1,1024}/g) || [];
} catch (e) {
var parts = answer;
}
if (answer == "") {
continue;
}
for (var j = 0; j < parts.length; j++) {
if (j == 0) {
items.push({
"name": question,
"value": parts[j],
"inline": false
});
} else {
items.push({
"name": question.concat(" (cont.)"),
"value": parts[j],
"inline": false
});
}
}
}
var options = {
"method": "post",
"headers": {
"Content-Type": "application/json",
},
"payload": JSON.stringify({
"content": "", // This is not an empty string
"embeds": [{
"title": "Pirate Hunting",
"fields": items,
"footer": {
"text": "Happy Hunting"
}
}]
})
};
UrlFetchApp.fetch(POST_URL, options);
};
is there something wrong with the code or is this a permissions problem
The notification script give title and value, and I am trying to get value only without title
Google Form script
Method1
var POST_URL = "hidden url";
function onSubmit(e) {
var response = e.response.getItemResponses();
var items = [];
for (var i = 0; i < response.length ; i++) {
var question = response[i].getItem().getTitle();
var answer = response[i].getResponse();
var parts = answer.match(/[\s\S]{1,1024}/g) || [];
if (answer == "") {continue;}
for (var j = 0; j< parts.length; j++) {
if (j == 0) {
items.push({"name": question, "value": parts[j], "inline": true});
} else {
items.push({"name": question.concat(" (cont.)"), "value": parts[j], "inline": true});
}
}
}
var options = {
"method" : "post",
"payload": JSON.stringify({
"embeds": [
{
"title":"New request",
"fields":items,
}
]
}
)
};
UrlFetchApp.fetch(POST_URL, options);
};
Method2 added
function onFormSubmit(e) {
var fields = [];
for (i = 0; i < e.response.getItemResponses().length; i++) {
var response = e.response.getItemResponses()[i];
fields.push({
"name": response.getItem().getTitle(),
"value": JSON.stringify(response.getResponse()),
"inline": false
});
}
var data = {
"embeds": [{
"title": "**Test Rep** — " + (e.source.getTitle() != null && e.source.getTitle().length > 0 ? e.source.getTitle() : "Untitled Form"),
"type": "rich",
"fields": fields,
}]
};
var options = {
method: "post",
payload: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
muteHttpExceptions: true,
};
Logger.log("Attempting to send:");
Logger.log(JSON.stringify(data));
var response = UrlFetchApp.fetch("Hidden URL", options);
Logger.log(response.getContentText());
};
The method2 do same job as method1 but i hope someone can help to workaround
I expected to get notification with form title + the value of two fields without question title.
The problem
A form has the title "New request" and has two questions.
The notification should have the form title "New request" and the answers to the questions but not the questions themselves.
A solution
Try these steps:
(1) Remove or comment out
var question = response[i].getItem().getTitle();
(2) Change this
items.push({"name": question, "value": parts[j], "inline": true});
to
items.push({"value": parts[j], "inline": true});
(3) Change this
items.push({"name": question.concat(" (cont.)"), "value": parts[j], "inline": true});
to
items.push({"value": parts[j], "inline": true});
This here is my function that hears for anything incoming from Telegram. It does work well with any message and files or whatever but it doesn't work when i press a but of an inline_keyboard, Why?
How can i create a function that hears for a inline_keyboard button pressed?
function doPost(e) {
var data = JSON.parse(e.postData.contents);
sendText('personal_chat_id', JSON.stringify(data));
}
In case you need it here under is my function that can send a message with an inline_keyboard.
function lol(){
var keyboard ={
inline_keyboard: [
[
{
text: "A",
callback_data: 123
},
{
text: "B",
callback_data: 234
}
],
[
{
text: "C",
callback_data: 345
},
{
text: "D",
callback_data: 456
}
]
]
}
sendText('personal_chat_id', "lol", keyboard)
}
function sendText(chatId,text,keyBoard){
keyBoard = keyBoard || 0;
if(keyBoard.inline_keyboard || keyBoard.keyboard){
var data = {
method: "post",
payload: {
method: "sendMessage",
chat_id: String(chatId),
text: text,
parse_mode: "HTML",
reply_markup: JSON.stringify(keyBoard)
}
}
}
var response = UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);
return response.getContentText()
}
You need to do it inside the doPost(e) function. Take the "e" parameter and verify what kind of type it is. If it is "contents.callback_query" is coming from the inline keyboard response and if it is "contents.message" it's text typed by the user.
And dont forget declare sendText() and sendKeyboard() functions.
function doPost(e) {
var contents = JSON.parse(e.postData.contents);
var keyboard = {
"inline_keyboard": [
[{
"text": "Players",
"callback_data": "player"
}],
[{
"text": "Match",
"callback_data": "match"
}],
[{
"text": "Results",
"callback_data": "result"
}]
]}
if (contents.callback_query) {
var id = contents.callback_query.message.chat.id;
var text = contents.callback_query.data;
switch (text) {
case 'Player':
var answer = 'Ingresa tu nombre y apellido';
sendText(id, answer);
break;
case 'match':
var answer = 'Ingresá tu nombre y apellido';
sendText(id, answer);
break;
case 'result':
var keyboard = {
'inline_keyboard': [
[{
'text': 'Youtube',
'url': 'https://youtube.com'
},{
'text': 'Google',
'url': 'https://google.com'
}]
]
};
sendTextWithButtons(id, 'Algunos enlaces', JSON.stringify(keyboard));
break;
default:
var answer = 'Default answer';
sendText(id, answer);
break;
}
var chat_id = contents.callback_query.from.id;
var user = contents.callback_query.message.chat.first_name;
var cb_data = contents.callback_query.data;
sendText(chat_id, CariDataDariIDSheet(cb_data));
}else if (contents.message) {
var chat_id = contents.message.from.id;
var user = contents.message.chat.first_name;
var answer = "your answer";
sendKeyboard(chat_id, answer, keyboard);
}
}
I am creating a googlesheet addon to send mails.And for sending mails I am using sendgrid.
I cannot find any documentation or example code for sending mails with Google Appscript. This is the code I am using, but it is no good.
var data = {
"api_user":"username",
"api_key":"ioioi",
"to":[],
"tonnage":[],
"cc":[],
"ccname":[],
"bcc":[],
"subject":sub,
"from":from,
"html":htmlBody
}
var headers = { "Accept":"application/json",
"Content-Type":"application/json"
};
data = JSON.stringify(data);
var options = {
"method": "POST",
"payload": data,
"headers": headers,
"muteHttpExceptions": true
};
var res = UrlFetchApp.fetch("https://api.sendgrid.com/api/mail.send.json", options);
Does anyone have any idea or code to send emails with sendgrid using googl appscript?
Try the below code. It worked for me
var SENDGRID_KEY ='Your API KEY';
var headers = {
"Authorization" : "Bearer "+SENDGRID_KEY,
"Content-Type": "application/json"
}
var body =
{
"personalizations": [
{
"to": [
{
"email": "email id of the sender"
}
],
"subject": "Hello, World!"
}
],
"from": {
"email": "From email id"
},
"content": [
{
"type": "text",
"value": "Hello, World!"
}
]
}
var options = {
'method':'post',
'headers':headers,
'payload':JSON.stringify(body)
}
var response = UrlFetchApp.fetch("https://api.sendgrid.com/v3/mail/send",options);
Logger.log(response);
Also ensure that the API key you created in SendGrid has the all the credentials it needs to send the email
For anyone who has this issue in the future with Transactional Email Template:
https://sendgrid.com/docs/ui/sending-email/how-to-send-an-email-with-dynamic-transactional-templates/
This is the function to send (similar to the answer of Nikil Mathew, but for transactional email template with dynamic data):
export const sendBySendGrid = (toEmail, templateId, dynamicTemplateData) => {
const headers = {
Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
'Content-Type': 'application/json',
}
const body = {
from: {
email: process.env.SENDGRID_FROM_EMAIL,
name: process.env.SENDGRID_FROM_NAME,
},
personalizations: [
{
to: [
{
email: toEmail,
},
],
dynamic_template_data: dynamicTemplateData,
},
],
template_id: templateId,
}
const options = {
method: 'POST',
headers,
payload: JSON.stringify(body),
}
const response = UrlFetchApp.fetch('https://api.sendgrid.com/v3/mail/send', options)
Logger.log(response)
}
You can update process.env.SENDGRID_API_KEY, process.env.SENDGRID_FROM_EMAIL, process.env.SENDGRID_FROM_NAME with your SendGrid credentials
Here's what's working for me right now in Google Apps Script, including using a dynamic template and insertion of dynamic data for the "handlebars" in my SendGrid template:
var SENDGRID_KEY ='API_KEY';
var headers = {
"Authorization" : "Bearer "+SENDGRID_KEY,
"Content-Type": "application/json"
}
function sendEmail_1() {
var body = {
"personalizations": [
{
"to": [
{
"email": "test#test.com",
"name": "Test Name"
}
],
"bcc": [
{
"email": "test#test.com"
}
],
"dynamic_template_data":
{
"firstName": "Marco Polo"
}
}
],
"from":
{
"email": "test#test.com",
"name": "Test Name"
},
"reply_to": {
"email": "test#test.com"
},
"template_id":"TEMPLATE_ID"
}
var options = {
'method':'post',
'headers':headers,
'payload':JSON.stringify(body)
}
var response = UrlFetchApp.fetch("https://api.sendgrid.com/v3/mail/send",options);
}