Copying, modifying and sending request POST Fiddler - fiddler

sorry for my English)))
I have been trying to solve my problem for a long time, but unfortunately so far without success ((((
I have a POST request of a certain type, I need to change it and send it to another address, and the original request should go further to its address. I'm trying to work with the exchange. More to the point, I have a request like this :
https://api.binance.com/api/v3/order?symbol=CELRBTC&orderId=73902412&recvWindow=55000&timestamp=1635266807744&signature=556b9c4121eb819d96a440b54661181e75ab2324a9d3b5fe0a73dd793626cb96
I need to send this request after the original one
https://fapi/binance.com/fapi/v1/order?symbol=KEEPUSDT&side=BUY&type=MARKET&quantity=100&timeInForce=GTC&recvWindow=5000&timestamp=1591702613943&signature= 3c661234138461fcc7a7d8746c6558c9842d4e10870d2ecbedf7777cad694af
In addition, the public API is passed in the header
Connection: Keep-Alive
Content-Type: application/x-www-form-urlencoded
Accept: application/json, text/plain; q=0.9, text/html;q=0.8,
Accept-Charset: UTF-8, *;q=0.8
Accept-Encoding: gzip, deflate
X-MBX-APIKEY: YIGXAtXbQg0790CnIvKzo3oIQPmEPwiySjdQj28h0H3g87D2rwcun0kRWvh4m9J6
Host: api.binance.com
I tried to do all this work in the onBeforeRequest method
static function OnBeforeRequest(oSession: Session) {
if (oSession.RequestMethod == "POST" && oSession.uriContains("order") ) {
oSession.utilDecodeResponse()
var strBody=oSession.GetRequestBodyAsString();
// timestamp, time ms
var timestampSTART= oSession.url.IndexOf("timestamp=") + 10;
var timestampEND= oSession.url.IndexOf("&", timestampSTART);
var timestamp = oSession.url.Substring(timestampSTART, 13);
// SYMBOL
var symbolStart = oSession.url.IndexOf("symbol=")+7;
var symbolend = oSession.url.IndexOf("BTC", symbolStart)+3;
var symbol = oSession.url.Substring(symbolStart, symbolend-symbolStart);
// Signature (timestamp+SecretAPIKey=Hmac Sha256) theoretically, it can be taken from the original request, but it is more reliable to make your own
var signStart = oSession.url.IndexOf("signature=")+10;
var sign = oSession.url.Substring(signStart);
//PRICE
var PriceStart = oSession.url.IndexOf("price=")+6;
var PriceEND = oSession.url.IndexOf("&", PriceStart);
var priceStr = oSession.url.Substring(PriceStart, PriceEND-PriceStart);
var price = parseFloat(priceStr);
// Quantity
var quantity = 50/ price*63000;
var apiBIN = "https://fapi.binance.com/fapi/v1/order?" ;
// var result = apiBIN+"symbol="+symbol+"&side=BUY&type=MARKET&quantity="+ quantity+"&timeInForce=GTC&recvWindow=5000&timestamp="+timestamp+"&signature="+sign;
// oSession.utilSetRequestBody(result)
// FiddlerApplication.oProxy.SendRequest(oSession.RequestHeaders, oSession.requestBodyBytes, null);
have selected the necessary parameters from the request, but I do not understand how to send it in any way, and I also lose the header with the API key.
Separately, I want to note the "Signature" parameter, which is created using the Hmac Sha256 algorithm from the secret API key and time, which I also can't figure out how to describe it in the code.
I would be very grateful for any help, with the possibility of some payment for substantial help.

I used C# to solve the problem. I didn't know Fiddler could choose the language. Technically, I have achieved my goal, but currently finance is writing an incorrect request. I will deal with this separately. Special thanks to Robert for his help.
public static void OnBeforeResponse(Session oSession)
{
if (oSession.HTTPMethodIs("POST") && oSession.uriContains("order"))
{
String strBody = oSession.GetRequestBodyAsString();
//Price
int PriceStart = strBody.IndexOf("price=")+6;
int PriceEND = strBody.IndexOf("&", PriceStart);
string priceStr = strBody.Substring(PriceStart, PriceEND-PriceStart);
float priceF = float.Parse(priceStr, System.Globalization.CultureInfo.InvariantCulture);
// SYMBOL
int symbolStart = strBody.IndexOf("symbol=")+7;
int symbolend = strBody.IndexOf("BTC", symbolStart);
string symbol = strBody.Substring(symbolStart, symbolend-symbolStart);
// Quantity
int quantStart = strBody.IndexOf("quantity=")+9;
int quantend = strBody.IndexOf("&price", quantStart);
string quant = strBody.Substring(quantStart, quantend-quantStart);
float quantity = float.Parse(quant, System.Globalization.CultureInfo.InvariantCulture)*2;
// timestamp
decimal timestamp = Math.Round(Convert.ToDecimal(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds), 0);
//Sign
Encoding ascii = Encoding.ASCII;
string secretKey = "lfaeGkjitNwvyG2lqDueMhSAOzRFlzL73w5pKRCAvSy7YrxyTkvwKCcHBHj...";
HMACSHA256 hmac = new HMACSHA256(ascii.GetBytes(secretKey));
// string query_string_LIMIT = "symbol="+symbol+"USDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity="+quantity+"&price="+priceF+"&recvWindow=5000&timestamp="+timestamp+"&signature=";
string result = "symbol="+symbol+"USDT&side=BUY&type=MARKET&quantity="+ quantity+"&recvWindow=5000&timestamp="+timestamp+"&signature=";
String signature = BitConverter.ToString(hmac.ComputeHash(ascii.GetBytes(result))).Replace("-","");
oSession.host="fapi.binance.com";
string resultRequest = "symbol="+symbol+"USDT&side=BUY&type=MARKET&quantity="+ quantity+"&recvWindow=5000&timestamp="+timestamp+"&signature="+signature;
byte[] resulByte = System.Text.Encoding.ASCII.GetBytes(resultRequest);
//oSession.utilReplaceInRequest("api/v3/order","fapi/v1/order?"+resultFin);
oSession.url = oSession.url.Replace("api/v3/order", "fapi/v1/order?"+resultRequest);
FiddlerApplication.oProxy.SendRequest (oSession.RequestHeaders, resulByte, null);
}

Related

How to send emails based on data filled in a form?

function ifstatement() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Product Form");
const ws2 = ss.getSheetByName("Email details");
var Avals = ws.getRange("c1:c").getValues();
var lr = Avals.filter(String).length;
Logger.log(lr);
var recipient = ws.getRange(lr,2).getValue();
var sub = ws.getRange(lr,4).getValue();
var mailTemp = ws.getRange(lr,5).getValue();
var impfield1 = ws.getRange(lr,6).getValue();
var impfield2 = ws.getRange(lr,8).getValue();
var impfield3 = ws.getRange(lr,10).getValue();
var fieldvalue1 = ws.getRange(lr,7).getValue();
var fieldvalue2 = ws.getRange(lr,9).getValue();
var fieldvalue3 = ws.getRange(lr,11).getValue();
var heading = ws.getRange(lr,12).getValue();
var subheading = ws.getRange(lr,13).getValue();
var body = ws.getRange(lr,14).getValue();
var footer = ws.getRange(lr,15).getValue();
var attach = ws.getRange(lr,17).getValue();
var tomail = ws.getRange(lr,16).getValue();
var file1 = attach.split(",").map(url => DriveApp.getFileById(url.trim().split("=")[1]).getBlob());
var AvalsWealth = ws2.getRange("b1:b").getValues();
var AvalsInsurance = ws2.getRange("c1:c").getValues();
var AvalsTeam = ws2.getRange("e1:e").getValues();
var lrWealth = AvalsWealth.filter(String).length;
var lrInsurance = AvalsInsurance.filter(String).length;
var lrTeam = AvalsTeam.filter(String).length;
Logger.log(mailTemp);
Logger.log(heading);
if(tomail=="Wealth RMs"){
var bccmail = ws2.getRange(2,2,lrWealth).getValues().toString();
} else if(tomail=="Self"){
var bccmail = recipient;
} else if(tomail=="Insurance RMs"){
var bccmail = ws2.getRange(2,3,lrInsurance).getValues().toString();
} else if(tomail=="All India"){
var bccmail = ws2.getRange(2,4,lrTeam).getValues().toString();
}
Logger.log(bccmail)
if(mailTemp=="HTML1"){
const htmlTemplate = HtmlService.createTemplateFromFile("HTML1");
htmlTemplate.heading = heading;
htmlTemplate.subheading = subheading;
htmlTemplate.body = body;
htmlTemplate.footer = footer;
htmlTemplate.impfield1 = impfield1;
htmlTemplate.impfield2 = impfield2;
htmlTemplate.impfield3 = impfield3;
htmlTemplate.fieldvalue1 = fieldvalue1;
htmlTemplate.fieldvalue2 = fieldvalue2;
htmlTemplate.fieldvalue3 = fieldvalue3;
const htmlforemail = htmlTemplate.evaluate().getContent();
GmailApp.sendEmail('',
""+ sub + "",
'',
{htmlBody: htmlforemail,
bcc: bccmail,
attachments: file1}
) } else if(mailTemp=="HTML2"){
const htmlTemplate = HtmlService.createTemplateFromFile("HTML2");
htmlTemplate.heading = heading;
htmlTemplate.subheading = subheading;
htmlTemplate.body = body;
htmlTemplate.footer = footer;
htmlTemplate.impfield1 = impfield1;
htmlTemplate.impfield2 = impfield2;
htmlTemplate.impfield3 = impfield3;
htmlTemplate.fieldvalue1 = fieldvalue1;
htmlTemplate.fieldvalue2 = fieldvalue2;
htmlTemplate.fieldvalue3 = fieldvalue3;
const htmlforemail = htmlTemplate.evaluate().getContent();
GmailApp.sendEmail('',
""+ sub + "",
'',
{htmlBody: htmlforemail,
bcc: bccmail,
attachments: file1}
) } else if(mailTemp=="HTML3"){
const htmlTemplate = HtmlService.createTemplateFromFile("AUM Annual awards");
htmlTemplate.heading = heading;
htmlTemplate.subheading = subheading;
htmlTemplate.body = body;
htmlTemplate.footer = footer;
htmlTemplate.impfield1 = impfield1;
htmlTemplate.impfield2 = impfield2;
htmlTemplate.impfield3 = impfield3;
htmlTemplate.fieldvalue1 = fieldvalue1;
htmlTemplate.fieldvalue2 = fieldvalue2;
htmlTemplate.fieldvalue3 = fieldvalue3;
const htmlforemail = htmlTemplate.evaluate().getContent();
GmailApp.sendEmail('',
""+ sub + "",
'',
{htmlBody: htmlforemail,
bcc: bccmail}
) } else if(mailTemp=="HTML4"){
const htmlTemplate = HtmlService.createTemplateFromFile("HTML4");
htmlTemplate.heading = heading;
htmlTemplate.subheading = subheading;
htmlTemplate.body = body;
htmlTemplate.footer = footer;
htmlTemplate.impfield1 = impfield1;
htmlTemplate.impfield2 = impfield2;
htmlTemplate.impfield3 = impfield3;
htmlTemplate.fieldvalue1 = fieldvalue1;
htmlTemplate.fieldvalue2 = fieldvalue2;
htmlTemplate.fieldvalue3 = fieldvalue3;
const htmlforemail = htmlTemplate.evaluate().getContent();
GmailApp.sendEmail('mayank.agarwal#aumcap.com',
""+ sub + "",
'',
{htmlBody: htmlforemail,
bcc: bccmail,
attachments: file1}
) }
}
I have this small setup where I have a Google Sheet, Google Appscript and Google form.
The user needs to input data in a Google Form - and once the sheet (linked with Form response) receives the updated row - a script is triggered which takes the data from the row and feeds it into the sheet and sends mail to the selected set of users.
Now the problem I am facing is that I need to send this mail to approx 100-150 people, however Googel appscript does not allow me to send mail to more than 30 participants at a time.
I understand that I need an Email service for this, however, I am unable to find any good solution wherein I can store my templates and the user just fills up data fields and shoots the mail.
Maybe because I am very new to this tech field so thats why.
Can anyone please guide me as to what is the setup I need to use for my purpose?
Thanks!
The first thing you need to do is to keep the BCC list as an array until it's necessary. This will allow us to make chunks out of it. This means removing the .toString() at the end of assigning bccmail.
Then, we need a custom function to send the email in batches of emails. I'm calling that function sendMassEmail.
function sendMassEmail(bccList, subject, plainBody, htmlBody, attachments) {
for (let bcc of chunks(bccList, 30)) {
GmailApp.sendEmail(
'',
subject,
plainBody,
{
htmlBody,
bcc: bcc.join(','),
attachments,
},
)
}
}
Chunks is a function that does exactly that, gets the elements of an array in chunks. My favorite implementation for this case is by using a generator.
I've kept the plain text body as it's important to generate it if you are sending it, as it is shown in most clients on the Inbox. Also, some of them can only read this ones (think smart watch).
The last argument (attachments) is optional.
Here is an example on how you would use it:
sendMassEmail(
bccmail,
sub.toString(),
'', // Should probably change it
htmlforemail,
file1,
)
Note that it's better to use toString() than concatenating into an empty string.
References
GmailApp.sendEmail(recipient, subject, body, options) (Apps Script reference)
for..of (MDN JavaScript reference)
Functions (MDN JavaScript guide)
Split array into chunks (StackOverflow question)

Unable to add inline image to email in google apps script

I'm new to Google Apps script and am trying to add an image inline to an automated response email.
The auto reply works perfectly, the main text of the email formats well in plain text and html.
the problem i'm facing is that the image does not appear.
my code:
// This constant is written in column Y for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'EMAIL_SENT';
/**
* Sends non-duplicate emails with data from the current spreadsheet.
*/
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Data'))
var startRow = 2; // First row of data to process
// Fetch the range
var dataRange = sheet.getRange("L2:L1000")
var dataRange2 = sheet.getRange("K2:K1000")
var dataRange3 = sheet.getRange("O2:O1000")
var dataRange4 = sheet.getRange("Y2:Y1000")
var dataRange5 = sheet.getRange("B2:B1000")
// Fetch values for each row in the Range.
var data = dataRange.getValues();
var data2 = dataRange2.getValues();
var data3 = dataRange3.getValues();
var data4 = dataRange4.getValues();
var data5 = dataRange5.getValues();
for (var i = 0; i < data.length; ++i) {
var yesno = data2[i]
if(yesno == "Yes"){
var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = UrlFetchApp
.fetch(TFlogoUrl)
.getBlob()
.setName("TFlogoBlob");
var emailAddress = data[i];
var ShipID = data3[i];
var cmdrID = data5[i];
var TFmsg = "Hi " + cmdrID + ",/n /nThank you for signing up to The Fatherhoods Lost Souls Expedition./n /nYour unique Ship ID is: " + ShipID + "/n /nWe look forward to seeing you on the expedition CMDR!/n /nFly Safe,/nThe Lost Souls Expedition team.";
var htmlTFmsg = "Hi " + cmdrID + ",<br> <br>Thank you for signing up to The Fatherhoods Lost Souls Expedition.<br> <br>Your unique Ship ID is: " + ShipID + "<br> <br>We look forward to seeing you on the expedition CMDR!<br> <br>Fly Safe,<br>The Lost Souls Expedition team.<br><img src='cid:TFlogo'>";
emailSent = data4[i]; // email sent (column Y)
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = "Lost Souls Expedition Sign up confirmation";
MailApp.sendEmail(emailAddress,subject,TFmsg,{
htmlBody: htmlTFmsg,
inlineImage:
{
TFlogo:TFlogoBlob
}
});
sheet.getRange("Y" + (startRow + i)).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
}
How about this modification?
Modification points:
You cannot retrieve the file blob from this URL var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";. If you want to retrieve the file blob from URL, please use var TFlogoUrl = "http://drive.google.com/uc?export=view&id=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";. 1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287 is the file ID.
As an another method, from the file ID, it is found that the values of getSharingAccess() and getSharingPermission() are ANYONE_WITH_LINK and VIEW, respectively. So you can also retrieve the blob using var TFlogoBlob = DriveApp.getFileById("1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287").getBlob().setName("TFlogoBlob");. I recommend this.
When you want to use the inline image to email, please modify from inlineImage to inlineImages.
The script which reflected above points is as follows.
Modified script:
Please modify your script as follows.
From:
var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = UrlFetchApp.fetch(TFlogoUrl).getBlob().setName("TFlogoBlob");
To:
var id = "1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = DriveApp.getFileById(id).getBlob().setName("TFlogoBlob");
And
From:
inlineImage: {TFlogo:TFlogoBlob}
To:
inlineImages: {TFlogo:TFlogoBlob}
References:
sendEmail(recipient, subject, body, options)
If I misunderstand your question, please tell me. I would like to modify it.

Populating RITM Variables from a REST Call

I'm in the process of learning scripted REST API's. I have one that creates a REQ and RITM when the user does a POST. I'm having trouble populating variables from the rest post to the RITM. Below is my current code. Response is the RITM, Requester, and short description. I'm open to all suggestions, like I said I'm learning this on the fly, so if there is any glaring problems, I'm all ears. Thanks!
(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
var cartId = GlideGuid.generate(null);
var cart = new Cart(cartId);
var item = cart.addItem('25409830135aa20099fc7e776144b0a0');
var rc = cart.placeOrder();
var req = request.getHeader('ContactEmployeeId');
var sdesc = request.getHeader('ShortDescription');
//return rc.number;
//gs.addInfoMessage(rc.number);
var num = rc.sys_id; //get sys ID of newly created request
var rnum = 0;
//using the request number, query the RITM table for related RITM
var u = new GlideRecord('sc_req_item');
u.addEncodedQuery('request='+num);
u.query();
while ( u.next() )
{
rnum = u.number;
}
response.setBody({
Requested_Item: rnum,
u_requester: req,
short_description: sdesc
});
response.setContentType('application/json');
})(request, response);
You can use the setVariable(ritm, variableName, value) method such as this.
var cartId = GlideGuid.generate(null);
var cart = new Cart(cartId);
var item = cart.addItem('25409830135aa20099fc7e776144b0a0');
// add your variables here to the item variable in your cart object
cart.setVariable(item, "comments", message);
cart.setVariable(item, "my_var_1", value1);
cart.setVariable(item, "my_var_2", value2);
// submit order
var rc = cart.placeOrder();

Reapeat/replay a session x times with a different request header

is it possible to reapeat/replay a session x times with a different reaquest header.
I was thinking of a for loop inside OnBeforeRequest which will iterate over the same request from the session, but with a different parameter for the request header ...
But I am kind of lost, can you help me?
for (var i=0; i< 50; i++)
{
var oSD = new System.Collections.Specialized.StringDictionary();
oSD.Add("x-Builder-MaxRedir", "10");
var oRH: Fiddler.HTTPRequestHeaders = new Fiddler.HTTPRequestHeaders();
var oURI: System.Uri = new Uri("https://whatever.com/" + i.ToString());
var sHeaders: String = String.Format("GET {0} HTTP/1.1\r\nHost: {1}\r\n\r\n", oURI.PathAndQuery, oURI.Host);
// ^^^ Add any header you like here, then...
oRH.AssignFromString(sHeaders);
var newSession = FiddlerApplication.oProxy.SendRequest(oRH, null, oSD);
}

Extract unread emails (in Plain Text) and store in a Google Doc

Problem: Daily we get a dozen of mails. We need to print all of them in regular basis. Is it possible for a Google Apps Script to read only the unread mails and to store them in a Google Doc? No HTML nothing, I just need the plain text in the following format.
​From: S. Banerjee Date: 3 January
2017 at 02:40 Subject: Re: Happy New Year To: "Br. Sayan"
...... ...... Message ..... ......
I was searching for a solution, but only managed to get something like the following here. Now we need to get the msgIDs of the unread mail pass them on to the function. Rest of the formatting can be solved later on piecemeal basis I think.
function saveGmail(msgID) {
// Based on Drive Scoop
// Available at https://github.com/google/gfw-deployments
var message = GmailApp.getMessageById(msgID);
// Grab the message's headers.
var from = message.getFrom();
var subject = message.getSubject();
var to = message.getTo();
var cc = message.getCc();
var date = message.getDate();
var body = message.getBody();
// Begin creating a doc.
var document = DocumentApp.create(subject);
var document_title = document.appendParagraph(subject);
document_title.setHeading(DocumentApp.ParagraphHeading.HEADING1);
var style = {};
style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = (DocumentApp.HorizontalAlignment.CENTER);
document_title.setAttributes(style);
var headers_heading = (document.appendParagraph("Gmail Message Headers"));
headers_heading.setHeading(DocumentApp.ParagraphHeading.HEADING2);
AddGmailHeaderToDoc(document, "From", from);
AddGmailHeaderToDoc(document, "To", to);
AddGmailHeaderToDoc(document, "Cc", cc);
AddGmailHeaderToDoc(document, "Date", date);
AddGmailHeaderToDoc(document, "Subject", subject);
var body_heading = (
document.appendParagraph("Body (without Markup)"));
body_heading.setHeading(DocumentApp.ParagraphHeading.HEADING2);
var sanitized_body = body.replace(/<\/div>/, "\r\r");
sanitized_body = sanitized_body.replace(/<br.*?>/g, "\r");
sanitized_body = sanitized_body.replace(/<\/p>/g, "\r\r");
sanitized_body = sanitized_body.replace(/<.*?>/g, "");
sanitized_body = sanitized_body.replace(/'/g, "'");
sanitized_body = sanitized_body.replace(/"/g, '"');
sanitized_body = sanitized_body.replace(/&/g, "&");
sanitized_body = sanitized_body.replace(/\r\r\r/g, "\r\r");
var paragraph = document.appendParagraph(sanitized_body);
document.saveAndClose();
return document.getUrl();
}
function AddGmailHeaderToDoc(document, header_name, header_value) {
if (header_value === "") return;
var paragraph = document.appendParagraph("");
paragraph.setIndentStart(72.0);
paragraph.setIndentFirstLine(36.0);
paragraph.setSpacingBefore(0.0);
paragraph.setSpacingAfter(0.0);
var name = paragraph.appendText(header_name + ": ");
name.setBold(false);
var value = paragraph.appendText(header_value);
value.setBold(true);
}
Your help will be very much appreciated!!
An easier way might be to use 'is:unread' search
var threads = GmailApp.search('is:unread');
var messages = threads[0].getMessages();
for (var i = 0; i < messages.length; i++) {
Logger.log(messages[i].getId());
}
This will log the Id's but you can return them as well. Also note that threads and messages are different. The above will get the first unread thread and all the messages in this thread (even if the messages are read).