how to send photo from telegram bot api (javascript) - javascript

I have a problem with sending the api via telegram text messages that arrive but the pictures are not arriving and I don't understand where the problem is
Is it possible to modify this code and make it send images?
var telegram_bot_id = "api";
var chat_id = "id";
var img;
var ready = function () {
img = document.getElementById("photo").value;
message = "photo: " + img ;
};
var sender = function () {
ready();
var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.telegram.org/bot" + telegram_bot_id + "/sendPhoto",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"cache-control": "no-cache"
},
"data": JSON.stringify({
"chat_id": chat_id,
"text": message
})
};
$.ajax(settings).done(function (response) {
console.log(response);
window.location.href = "index.html";
});
document.getElementById("photo").value = "";
return false;
};

In order to be able to send a photo via sendPhoto method, you have to send a proper picture file or a string represent a valid URL.
According to code you posted, you're sending into the HTTP request as body parameters the chat_id, the text message itself and that's it.
The sendPhoto method does not expect a text field, that's used in sendMessage method.
In your case, since you're trying to send via Telegram chatbot a picture taken from the HTML entity, which in this case is not the picture itself but its path on your webserver, you have to change the POST request body and to set the picture URL as parameter of the request itself.
To conclude, if you want to add the text message, the sendPhoto method allows you to add it but as caption.
For instance:
var telegram_bot_id = "api";
var chat_id = "id";
var img;
var ready = function () {
img = "http://your-website.com/imagepath/imagename.png";
};
var sender = function () {
ready();
var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.telegram.org/bot" + telegram_bot_id + "/sendPhoto",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"cache-control": "no-cache"
},
"data": JSON.stringify({
"chat_id": chat_id,
"photo": img,
"caption": message
})
};
$.ajax(settings).done(function (response) {
console.log(response);
window.location.href = "index.html";
});
return false;
};

Related

Possible to create an account system with restdb.io? AJAX jQquery method

I'm fairly new to APIs in general, I managed to post data into restdb but how can i go about creating a system to log in based on the user/account data that i posted previously? what i'm thinking is using get and checking if any email and password matches but that does not sound efficient to code or im not sure if its possible to. could someone point me in the right direction
This is how my post function looks
$(document).ready(function () {
const APIKEY = ".";
$("#account-submit").on("click", function (e) {
//prevent default action of the button
e.preventDefault();
let name = $("#name").val();
let contactEmail = $("#contact-email").val();
let studentID = $("#student-id").val();
let password = $("#password").val();
var jsondata = {
"name": name,
"email": contactEmail,
"studentid": studentID,
"password": password,
};
var settings = {
"async": true,
"crossDomain": true,
"url": "https://nerdge-d48f.restdb.io/rest/account",
"method": "POST",
"headers": {
"content-type": "application/json",
"x-apikey": ".",
"cache-control": "no-cache"
},
"processData": false,
"data": JSON.stringify(jsondata)
}
$.ajax(settings).done(function(response) {
console.log(response);
$("#account-submit").prop("disabled", false);
});
})
}
)

Getting a callback after a request has been completed in a Gmail Add On in Apps Script

First of all what I am trying to do is accomplish the following.
Note: this is not my add-on.
How is this script generated? I cannot find any information about script.google.com/macros.
After this tab is closed, the add-on gets a callback that looks like this:
As I don't understand the flow my questions are:
How does the add-on script know that the tab is being closed?
How is the script created?
At which endpoint does the script call the google add-on?
The following is my add-on script:
function insertDocumentToRMS(e){
var url = "https://test.signumid.hr/v/1/rms";
var object = {
"data" : e.parameters.file.toString()
}
var payload = JSON.stringify(object);
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
};
var options = {
"method": "POST",
"contentType": "application/json",
"headers": headers,
"payload": payload,
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
Logger.log(data);
var url2 = "https://test.signumid.hr/v/1/signer/document/storage/"+ data.recordNumber;
Logger.log(url2);
var object2 = {
"SignatureProvider": "SwisscomAis",
"SignatureProviderData": {
"SwisscomRequestData": {
"mobileNumber": "+41796063855",
"language": "en",
"message": "Matej Potpišiii!",
"jurisdiction": "ZERTES",
"signatureLevel": "AES"
}
},
"Documents": [
{
"SignatureOptions": {
"Reason": "Reason",
"Location": "Location",
"SignerContactInfo": "SignerContactInfo",
"SignerName": "SignerName"
},
"Document": e.parameters.file.toString()
}
]
}
var payload2 = JSON.stringify(object2);
var headers2 = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
};
var options2 = {
"method": "GET",
"contentType": "application/json",
"headers": headers2,
"payload": payload2,
"muteHttpExceptions": true
};
var response2 = UrlFetchApp.fetch(url2, options2);
Logger.log(response2);
let actionSign = CardService.newAction().setFunctionName('test');
var actionResponse = CardService.newActionResponseBuilder()
.setOpenLink(CardService.newOpenLink()
.setUrl("https://test.signumid.hr/v/1/signer/document/storage/"+ data.recordNumber)
.setOpenAs(CardService.OpenAs.OVERLAY)
.setOnClose(CardService.OnClose.RELOAD))
.build();
return actionResponse;
}
As you can see at the end (here), I am trying to use an actionBuilder with an actionResponse that has the property OnClose, but the only parameters on OnClose are: NOTHING and RELOAD. Can I pass an action somehow or what am I supposed to do to replicate the scenario that I mentioned above?
var actionResponse = CardService.newActionResponseBuilder()
.setOpenLink(CardService.newOpenLink()
.setUrl("https://test.signumid.hr/v/1/signer/document/storage/"+ data.recordNumber)
.setOpenAs(CardService.OpenAs.OVERLAY)
.setOnClose(CardService.OnClose.RELOAD))
.build();
Basically what the add-on is doing is a 'sign in workflow' to authorize scopes. If you want to replicate that workflow you can take a look at this sample provided by Google.
Aside from that you can submit a feature request to control browser events.
Looking for any alternative options I found this and this.
As for macros using Google Apps Script, you can look here.

Can I trigger a Power Automate workflow from custom JavaSript?

How can I start/trigger any flow from my custom JavaScript code?
I am not asking about the button flow, and not any Out of the Box feature, I just want to trigger my flow from my JavaScript code
Create the flow triggers by 'Request – when a HTTP request is received', you could find the script in TechNet wiki page.
function StartMicrosoftFlowTriggerOperations() {
try {
var dataTemplate = "{\r\n \"emailaddress\":\"{0}\",\r\n \"emailSubject\": \"{1}\",\r\n \"emailBody\": \"{2}\"\r\n}";
var httpPostUrl = "<Supply with the HTTP POST Url>";
//Call FormatRow function and replace with the values supplied in input controls.
dataTemplate = dataTemplate.FormatRow($("#txtEmailAddress").val(), $("#txtEmailSubject").val(), $("#txtEmailBody").val());
var settings = {
"async": true,
"crossDomain": true,
"url": httpPostUrl,
"method": "POST",
"headers": {
"content-type": "application/json",
"cache-control": "no-cache"
},
"processData": false,
"data": dataTemplate
}
$.ajax(settings).done(function (response) {
console.log("Successfully triggered the Microsoft Flow. ");
});
}
catch (e) {
console.log("Error occurred in StartMicrosoftFlowTriggerOperations " + e.message);
}
}

ClientId is null when calling ValidateClientAuthentication with Ajax

I have the following code that are generated by POSTMAN:
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:51734/token",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
"cache-control": "no-cache",
"Postman-Token": "2879f786-3b1f-42fe-8198-b2193764d165"
},
"data": {
"grant_type": "client_credentials",
"client_id": "6E1JIQDEF0M"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
When you run the code above, the following code below are first executed:
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId = string.Empty;
string clientSecret = string.Empty;
ClientDTO client = null;
if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
{
context.TryGetFormCredentials(out clientId, out clientSecret);
}
if (context.ClientId == null)
{
//Remove the comments from the below line context.SetError, and invalidate context
//if you want to force sending clientId/secrects once obtain access tokens.
context.Validated();
//context.SetError("invalid_clientId", "ClientId should be sent.");
//return Task.FromResult<object>(null);
return;
}
}
The problem I have is that context.ClientId is always null, and I don't know why.
When I make the same request with C# it works:
var client = new RestClient("http://localhost:51734/token");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "db182d32-9eff-4150-815e-2fd7d10ebd58");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("undefined", "grant_type=client_credentials&client_id=6E1JIQDEF0M&undefined=", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
So why does it work with c# but not javascript? Anyone who has any idea?
Try to call like this from Javascript.
data : 'grant_type=client_credentials&client_id=6E1JIQDEF0M'

Insert variable value into ajax post data

I have created a form with textboxes and a dropdown menu, inside my code I've created a script which will be called when clicking "Send Form"
Lets say my field are : firstName, lastName, country (dropdown)
Here is the script:
function f1() {
var settings = {
"async": true,
"url": "https://api.TheSite.com/v2/applications/123456789/newJson.json",
"method": "POST",
"headers": {
"x-api-key": "123456789123456",
"content-type": "application/json",
},
"processData": false,
"data": "{\r\n \"deployment\": {\r\n \"revision\": \"string\",\r\n \"changelog\": \"string\",\r\n \"description\": \"string\",\r\n \"user\": \"string\"\r\n }\r\n}"
}
$.ajax(settings).done(function(response) {
console.log(response);
alert("The Form Was Sent");
});
}
I would like to insert those 3 variables' values inside the "data" string like so:
"data": "{\r\n \"deployment\": {\r\n \"revision\": \`firstName
\",\r\n \"changelog\": \"`lastName
and so on...
In the dropdown menu, I assume it will be displayed as an array. How do I include my variable inside?
First create an empty object and insert the data into it.
Next use JSON.strigify() to convert that into a JSON blob before you send it over to the server.
var data = {};
data.deployment = {};
data.deployment.revision = firstName;
data.deployment.changelog = lastName;
var settings = {
....,
data: JSON.stringify(data)
};
Since you are already using jQuery to perform your AJAX request, you should be aware that you can actually pass a native JavaScript object into the data portion of the request. You don't need to have it converted to a JSON string. If you want to, you can just stringify it.
You can actually establish default request options and then merge them with the data you want to request.
var defaults = {
url: 'https://api.TheSite.com/v2/applications/123456789/newJson.json',
method: 'POST',
contentType: 'application/json',
headers: {
'x-api-key': '123456789123456',
},
processData: false,
async: true
};
function makeXhrRequest(config) {
var xhrRequest = $.extend(true, defaults, config);
// If you want to convert the request to a json String.
//xhrRequest.data = JSON.stringify(data);
$.ajax(xhrRequest).done(function(data, textStatus, jqXHR) {
console.log(data);
alert("The Form was sent...");
});
}
var $myForm = $('form[name="my-form"]');
makeXhrRequest({
data : {
deployment : {
revision : $myForm.find('input[name="firstname"]').val(),
changelog : $myForm.find('input[name="lastname"]').val(),
description : 'string',
user : 'string'
}
}
});
SOLVED
this is the syntax that worked for me +$("#firstName")[0].value+ and this is the code :
"data":"{\r\n\deployment\: {\r\n revision\:"+"\""+$("#firstName")[0].value+"\","+"\r\n"

Categories

Resources