I created a chat bot using the JAVA Api, based on the sample code from the documentation,
the Bot uses a service account.
The Bot works fine in one Room, but when I try to use it with a new Room I am experiencing an error.
After adding the Bot to the new Room and trying to post a message I receive
{ "code" : 403, "errors" : [ { "domain" : "global", "message" : "The caller does not have permission", "reason" : "forbidden" } ], "message" : "The caller does not have permission", "status" : "PERMISSION_DENIED" }
Is there any additional step necessary after adding the Bot to a room before posting messages ?
Any help with this problem would be greatly appreciated!
Code used:
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = new JacksonFactory();
HangoutsChat.Builder builder = new HangoutsChat.Builder(httpTransport, jsonFactory, credentials);
builder.setApplicationName(bot);
HangoutsChat service = builder.build();
ListSpacesResponse response = service.spaces().list().execute();
// Look for space Space _space = null;
while (response.getSpaces() != null && _space == null) {
for(Space s : response.getSpaces()) {
if(s.getDisplayName().equals(space)) {
_space = s;
}
}
if (_space == null && response.getNextPageToken() != null && !response.getNextPageToken().isEmpty()) {
String pageToken = response.getNextPageToken();
response = service.spaces().list().setPageToken(pageToken).execute();
} else {
break;
}
}
if(_space != null) {
Message m = new Message();
byte[] data = {0x0A};
m.setText(text.replace("\\r", "").replace("\\n", new String(data)));
Message r = service.spaces().messages().create(_space.getName(), m).setThreadKey(thread).execute();
Element el = new Element("message");
el.setAttribute("space", r.getSpace().getDisplayName());
el.setAttribute("text", r.getText());
el.setAttribute("thread", r.getThread().getName());
outNode.addContent(el);
} else {
throw new Exception("SendHangouts failed " + "Space " + space + " not found");
}
Related
I am trying to use block.io API, before few months I tried and implemented, it was working perfect, and now they have changed signed signature method, All APIs working correct, only withdrawal API not working, Response of curl is showing success, but says required more_signatures_needed , I don't know how to do this, Can anyone help me? I will be thankful.
protected void Page_Load(object sender, EventArgs e)
{
myPage.Text = readHtmlPage("https://block.io/api/v2/withdraw_from_addresses/");
//fecth response
String myUri = Session["myPagecc"].ToString();
//display response
Label1.Text = myUri.ToString();
}
private String readHtmlPage(string url)
{
String api_key = "myapikey";
double amounts = "btcamount";
String to_addresses = "receiveraddress";
string FROM_ADDRESS = "myaddress";
string NEWCODE = Guid.NewGuid().ToString().Substring(0, 5);
string priority="medium";
String result = "";
String strPost = "api_key=" + api_key + "&from_addresses=" + FROM_ADDRESS + "&to_addresses="+to_addresses +"&amounts="+amounts+"&priority="+priority+"&nonce="+NEWCODE;
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally
{
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return result;
}
"status" : "success", "data" : { "reference_id" : "70ab0922cf036481533e7f345068c0bed36f9681d644d8", "more_signatures_needed" : true, "inputs" : [ { "input_no" : 0, "signatures_needed" : 1, "data_to_sign" : "3916022666e29882298d54c2c8f2ab3306cc4e774594f5db9", "signers" : [ { "signer_address" : "jhE397dsNaNLByJ8WV43emD1mhSpPtwDV", "signer_public_key" : "a34b48a3a18373020d8d96fb53b733d373cd3ba9b5bbfd2c9f8105c8939058130d", "signed_data" : null } ] } ], "encrypted_passphrase" : { "signer_address" : "NaNLmhSByJ8WV43emD1jhE397dspPtwDV", "signer_public_key" : "373cd3ba9b5bbfd2c9f8020d8d96fb53b733d373a34b48a3a18105c8939058130d", "passphrase" : "r20/Wyy5iTVFmpcmn1Y8JOMR8mP7jAqaBrMf2UOW2aEBQSQ1XfxpgonIyFLDOKkmuqH84sETSjXTFsl3dpo5niABB2rL69vnsLbS4DaXMw1o33NH0zgHyzdkAYmIoeGe85YVPMkrQsNhLrGQ6JUaubT+W3rIBxP7rCqYznnMnt8QxG4wu5LSh2EY8fja6AI1" }, "unsigned_tx_hex" : "010000000127d8d4654bc8cf69c9b1980c1afa67e51b5b28241ac080100000023220020200d0c2118ad382e8dab4f3c2ddf5ab8ca1d8ac3ffa3d910a0a2aa86cb69cb77bb62e2a7f12fbc8a699ffffffff076a914103ee4139219756a503842b0ad01000000000019caf5a381440b66bd81188ac64a401000000000017a9145af1577250a83928e306b35f8463047d72d9e3408700000000" } }
Any solution for this please.
With Block.IO token withdrawal it seems we need to send some extra secure pins
as per their doc: https://block.io/api/simple/signing
Like to know how to send cURL to execute ?
Their sample cURL is not working: /api/v2/withdraw_from_addresses/?api_key=API KEY&from_addresses=ADDRESS1,ADDRESS2,...&to_addresses=ADDRESS1,ADDRESS2,...&amounts=AMOUNT1,AMOUNT2,...
response is:
{[status, success]}
{[data, {
"reference_id": "24fe5a.....",
"more_signatures_needed": true,
"inputs": [
{
"input_no": 0,
"signatures_needed": 1,
"data_to_sign": "2498d....",
"signers": [
{
"signer_address": "1H4.....",
"signer_public_key": "037710.....",
"signed_data": null
}
]
}
],
"encrypted_passphrase": {
"signer_address": "1H4...",
"signer_public_key": "0377....",
"passphrase": "fDCM0...."
},
"unsigned_tx_hex": "01000...."
}]}
if possible: expecting some sample in asp.net vb please
I wish to read google spreadsheets conditional format information with script. I do it as below:
function readConditionalFormatInfo() {
var url = "https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId?fields=sheets(properties(title,sheetId),conditionalFormats)"
var response = UrlFetchApp.fetch(url)
Logger.log(response)
}
But error happen:
Request failed for https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId?fields=sheets(properties(title,sheetId),conditionalFormats) returned code 403. Truncated server response: { "error": { "code": 403, "message": "The request is missing a valid API key.", "status": "PERMISSION_DENIED" } } (use muteHttpExceptions option to examine full response) (line 214, file "Code")
Maybe I should not run REST API in GAS but I don't know how to do it in script!
Appreciate if anyone can help!
Something like below:
function readConditionalFormat() {
var sheet = SpreadsheetApp.getActive().getActiveSheet();
var rules = sheet.getConditionalFormatRules();
if (rules != null) {
for (var i=0;i<rules.length;i++) {
var rule = rules[i].getBooleanCondition()
var criteria = rule.getCriteriaType()
var value = rule.getCriteriaValues()
var bakcolor = rule.getBackground()
Logger.log(criteria+ " -> " + value + ":" + bakcolor);
}
} else {
Logger.log('Conditional Format rule null')
}
}
I'm writing a Hangouts Chat bot in C# that uses pub/sub so I can host the bot on our side of a firewall. Everything seems to work well except interactive buttons within cards. If I create a button with a specific action method name, the bot does receive the CARD_CLICKED message with the appropriate action method name. However, it doesn't seem like the card in the Hangouts Chat app knows a response was sent because the bot ends up getting the CARD_CLICKED message three times before the Hangouts Chat app finally says "Unable to contact Bot. Try again later". I've been using the Google.Apis.HangoutsChat.v1 and Google.Cloud.PubSub.V1 packages from NuGet for the bot.
This is speculation, but it seems like the issue might be that interactive buttons don't work properly through pub/sub. Any help would be appreciated.
Here is a snippet of the code I have:
SubscriptionName subscriptionName = new SubscriptionName(PROJECT_ID, SUBSCRIPTION_ID);
SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();
GoogleCredential credential = GoogleCredential.FromFile(CREDENTIALS_PATH_ENV_PROPERTY).CreateScoped(HANGOUTS_CHAT_API_SCOPE);
HangoutsChatService chatService = new HangoutsChatService(new BaseClientService.Initializer
{
ApplicationName = "My Bot",
HttpClientInitializer = credential
});
while (true)
{
PullResponse response = client.Pull(subscriptionName, false, 3, CallSettings.FromCallTiming(CallTiming.FromExpiration(Expiration.FromTimeout(TimeSpan.FromSeconds(90)))));
if ((response.ReceivedMessages == null) || (response.ReceivedMessages.Count == 0))
Console.WriteLine("Pulled no messages.");
else
{
foreach (ReceivedMessage message in response.ReceivedMessages)
{
try
{
byte[] jsonBytes = message.Message.Data.ToByteArray();
JObject json = JObject.Parse(Encoding.UTF8.GetString(jsonBytes));
string messageType = (string)json["type"];
switch (messageType)
{
case "MESSAGE":
{
// Get text
string messageText = (string)json["message"]["text"];
Console.WriteLine($"[{messageType}] {messageText}");
// Send response
string spaceName = (string)json["space"]["name"];
SpacesResource.MessagesResource.CreateRequest request = chatService.Spaces.Messages.Create(new Message
{
Cards = new[]
{
new Card
{
Header = new CardHeader
{
Title = "Message Received!"
},
Sections = new[]
{
new Section
{
Widgets = new[]
{
new WidgetMarkup
{
Buttons = new[]
{
new Button
{
TextButton = new TextButton
{
Text = "Click Me!",
OnClick = new OnClick
{
Action = new FormAction
{
ActionMethodName = "ClickedAction"
}
}
}
}
}
}
}
}
}
}
},
Thread = new Thread
{
Name = (string)json["message"]["thread"]["name"]
}
}, spaceName);
Message responseMsg = request.Execute();
break;
}
case "CARD_CLICKED":
{
string actionMethodName = (string)json["action"]["actionMethodName"];
Console.WriteLine($"[{messageType}] {actionMethodName} at {((DateTime)json["message"]["createTime"]).ToString()}");
// Send response
string spaceName = (string)json["space"]["name"];
SpacesResource.MessagesResource.CreateRequest request = chatService.Spaces.Messages.Create(new Message
{
ActionResponse = new ActionResponse
{
Type = "UPDATE_MESSAGE"
},
Text = $"You clicked on '{actionMethodName}'.",
Thread = new Thread
{
Name = (string)json["message"]["thread"]["name"]
}
}, spaceName);
Message responseMsg = request.Execute();
break;
}
default:
{
Console.WriteLine($"[{messageType}]");
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing message: {ex}");
}
}
// Acknowledge the message so we don't see it again.
string[] ackIds = new string[response.ReceivedMessages.Count];
for (int i = 0; i < response.ReceivedMessages.Count; ++i)
ackIds[i] = response.ReceivedMessages[i].AckId;
client.Acknowledge(subscriptionName, ackIds);
}
}
Using buttons with Hangouts Chat API requires a custom answer including:
{
'thread': {
'name': thread_id
},
'actionResponse': {
'type': 'UPDATE_MESSAGE'
}
}
I'd recommend using Hangouts Chat API with a bot URL.
I want to create an user using the rest API. Rest API returns an error (bad request), when I made the request. There are not any other error messages.
JSON:
Required Parameters : login, password, email
http://quickblox.com/developers/Users#API_User_Sign_Up
{
"user":
{
"login":"user123456",
"password":"User11#2015",
"email":"xxx#ccc.com.tr",
"blob_id":null,
"external_user_id":null,
"facebook_id":null,
"twitter_id":null,
"full_name":null,
"phone":null,
"website":null,
"custom_data":null,
"tag_list":null
}
}
Rest API Result:
Response Status Code : BadRequest.
Response Content is empty. No error message.
I do not understand the error. Can you help me?
Code :
public NotificationUser CreateUser(string token, NotificationUser notificationUser)
{
var user = new QuickbloxUser()
{
email = notificationUser.Email,
password = notificationUser.Password,
login = notificationUser.Login
};
var jsonBody = JsonConvert.SerializeObject(user);
var request = new RestRequest("users.json", Method.POST);
request.AddHeader("QB-Token", token);
request.AddParameter("user", jsonBody);
var response = _restClient.Execute<RootUser<QuickbloxUserResponse>>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
notificationUser.Id = response.Data.user.id;
notificationUser.Email = response.Data.user.email;
notificationUser.Login = response.Data.user.login;
return notificationUser;
}
return null;
}
I am trying to upload image to parse.com using REST API, and associating to an object as shown in docs
I am getting the fileUrl from phonegap / appgyver-supersonic camera api.
The Image is uploaded successfully and also associated successfully to the "receipt" object but accessing the url gives 403 error.
How do I access the URL and view the uploaded image, I get a white page (with broken image icon) and 403 error.
File :
http://files.parsetfss.com/68087456-8a5a-403a-820f-13912d2c0911/tfss-5d0edbdb-730b-4cd6-a44f-f0ce1e2ab120-pic.jpg
My receipt class has public write/read access.
Here is my code :
$scope.send = function(fileURL, mimeType){
function win(r) {
$scope.textvar = r;
var response = JSON.parse(r.response);
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
var req = {
method: 'POST',
url: 'https://api.parse.com/1/classes/receipt',
headers: {
'X-Parse-Application-Id':'XXXXXXXXXXXXX',
'X-Parse-REST-API-Key':'XXXXXXXXXXXXXXXX',
"Content-Type": "application/json"
},
data: {"name": "user_receipts",
"images": {
"name": response.name,
"__type" : "File"
}
}
}
$http(req).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("image association success ");
console.log(data);
console.log(headers);
console.log(status);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
function fail(error) {
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
console.log("upload error http-code " + error.http_status);
}
var uri = encodeURI("https://api.parse.com/1/files/pic.jpg");
var options = new FileUploadOptions();
options.fileKey="data-binary";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType=mimeType;
var headers = {"X-Parse-Application-Id": "XXXXXXXXXXXXXXXXX",
"X-Parse-REST-API-Key":"XXXXXXXXXXXXXXXX",
"Content-Type":"image/jpeg"};
options.headers = headers;
var ft = new FileTransfer();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
console.log("length : "+progressEvent.loaded/progressEvent.total);
} else {
console.log("loaded : "+progressEvent.loaded);
}
};
ft.upload(fileURL, uri, win, fail, options);
};
I have wasted 5 days on this already, Please Help.
I am no expert in either appgyver / phonegap or parse.com