slack bot error: 'user_is_bot' for channels.join - slack-api

I am trying to create a new channel using slack api https://api.slack.com/methods/channels.join but getting this response
info: ** API CALL: https://slack.com/api/channels.join
Response : { ok: false, error: 'user_is_bot' }
I tried this
controller.hears('hello', ['direct_message', 'direct_mention', 'mention'], function (bot, message) {
bot.api.channels.join({'name':'nag'}, function (err, response) {
console.log("Response : ",response);
})
});
If I am mistaken please let me know. I have started learning slack api.

The reason you are getting user_is_bot is that channels.join can not be used by a bot user. As it says in the documentation for this method:
user_is_bot: This method cannot be called by a bot user.
To create channel you will want to use channels.create. However, that method can also not be used by a bot user.
The common solution is to use the full access_token, not the bot_access_token that your Slack app received from Slack after installing it with OAuth for all methods that bot users can not use, e.g. creating a new channel.
Here is the example from the OAuth documentation on how the response from Slack with both tokens look like:
{
"access_token": "xoxp-XXXXXXXX-XXXXXXXX-XXXXX",
"scope": "incoming-webhook,commands,bot",
"team_name": "Team Installing Your Hook",
"team_id": "XXXXXXXXXX",
"incoming_webhook": {
"url": "https://hooks.slack.com/TXXXXX/BXXXXX/XXXXXXXXXX",
"channel": "#channel-it-will-post-to",
"configuration_url": "https://teamname.slack.com/services/BXXXXX"
},
"bot":{
"bot_user_id":"UTTTTTTTTTTR",
"bot_access_token":"xoxb-XXXXXXXXXXXX-TTTTTTTTTTTTTT"
}
}

Related

google-api-nodejs-client API key - 401 Login required

I am trying to use the google-api-nodejs library to manage some resources in the google Campaign Manager API.
I have confirmed that we currently have a GCP project configured, and that this project has the google Campaign Manager API enabled (screenshot at the bottom).
I have tried several ways of authenticating myself (particularly API keys, OAuth2, and Service account credentials). This question will focus on using an API key though, as theoretically it is the simplest (and I will raise a separate question for the issues I am facing using Service account credentials).
Now, I have generated an API key and I have restricted it to have access to the Campaign Manager API (this is visible in the screenshots below). I configured my code
following the using-api-key section of the library's repo (https://github.com/googleapis/google-api-nodejs-client/#using-api-keys):
import { assert } from "chai";
import { google } from "googleapis";
it("can query userProfiles using API Key", async () => {
try {
const api_key = "AIza ****";
const df = google.dfareporting({
version: "v3.5",
auth: api_key,
});
const res = await df.userProfiles.list({}); // error thrown on this line
console.log("res: ", res);
assert(true);
} catch (e) {
console.error("error: ", e);
assert(false);
}
});
Unfortunately, this code results in an error with the message Login required:
{
"code": 401,
"errors": [
{
"message": "Login Required.",
"domain": "global",
"reason": "required",
"location": "Authorization",
"locationType": "header"
}
]
}
It is worth noting that:
While the API key seems to be correctly configured (that is, it matches what is visible in the Google API), changing the value of the API key in our code does not change the result - the error is still exactly the same
Moreover, changing the auth attribute from google.dfareporting to userProfiles.list results in the same error.
const df = google.dfareporting({
version: "v3.5",
});
const res = await df.userProfiles.list({
auth: api_key, // error thrown on this line
});
If you check the documentation for userProfiles.list
You will find it states
This means in order to access this method you need to be authorized by a user using oauth2 with one of those scopes.
Api keys will only give you access to public data not private user data.
you sould check the Google api node.js client for information on authorization with this library.
const {google} = require('googleapis');
const oauth2Client = new google.auth.OAuth2(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);
// generate a url that asks permissions access
const scopes = ['https://www.googleapis.com/auth/dfareporting'
];
const url = oauth2Client.generateAuthUrl({
// 'online' (default) or 'offline' (gets refresh_token)
access_type: 'offline',
// If you only need one scope you can pass it as a string
scope: scopes
});

Microsoft Graph API Errors for ServiceNow

I am integrating ServiceNow with Teams specifically to push notifications to users and channels using microsoft graph api.
Issue #1 -
I have configured an OAuth profile for azure app to utilize microsoft graph API, setup required API permissions and calling various chat related API functions. For 'Create Chat' request I am getting below error:
responseBody: {
"error": {
**"code": "UnknownError",**
"message": "",
"innerError": {
"date": "2021-01-29T09:20:53",
"request-id": "90a99bf5-048f-445b-b58c-ee46fc30edf3",
"client-request-id": "90a99bf5-048f-445b-b58c-ee46fc30edf3"
}
}
}
API call -
var restMessage = new sn_ws.RESTMessageV2();
restMessage.setHttpMethod("POST");
restMessage.setEndpoint("https://graph.microsoft.com/beta/chats");
restMessage.setRequestHeader('Content-Type', 'application/json');
restMessage.setRequestHeader('Authorization', 'Bearer ' + retrieveToken()); //retrieveToken() function creates access token.
restMessage.setAuthenticationProfile('oauth', 'a5325df007022010f60df7fc7c1ed0a2');
restMessage.setRequestBody(global.JSON.stringify(
{"chatType": "oneOnOne","members":
[
{
"#odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"user#odata.bind": "https://graph.microsoft.com/beta/users('<userID>')"
},
{
"#odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"user#odata.bind": "https://graph.microsoft.com/beta/users('<userID>')"
}
]
}
));
var response = restMessage.executeAsync();
var responseBody = response.getBody();
gs.info('responseBody: '+responseBody);
Most of the suggestions are to set appropriate API permissions. This is already set correctly on Azure (both delegated and apppication permissions) and in OAuth entity scope in servicenow.
Issue #2 -
For the same setup instead of usign scripted API, I defined REST Message record and trying to get the token by clicking 'Get OAuth Token' related link and getting following error:
https://dev72030.service-now.com/oauth_redirect.do?error=invalid_client&error_description=AADSTS650053%3a+The+application+%27msgraph-client-app%27+asked+for+scope+%27**Chat.Read.All%27+that+doesn%27t+exist+on+the+resource**+%2700000003-0000-0000-c000-000000000000%27.+Contact+the+app+vendor.%0d%0aTrace+ID%3a+b0b9ff39-fd1a-49c9-85fa-3c8c71943600%0d%0aCorrelation+ID%3a+9c276922-3a77-4cc1-890b-23177ffd1845%0d%0aTimestamp%3a+2021-01-29+10%3a31%3a27Z&state=-1877865371#
This say I need to set 'Chat.Read.All' API permission. This is already provided on both sides, Azure app and OAUth profile in SNOW.
What am I missing
Could you please check this docs? For second issue: Could you please check the permissions on src by going through the jwt.io

slack doen't sent POST request on button

I'm trying to implement following:
python script sends message to slack with button and payload,
user clicks on button in the slack message,
button sends POST with payload to Request URL (aws api)
Currently button doesn't send POST.
I forge message with following python script
slack_token = 'xoxp-1111-111-111-qqqqqq'
sc = slack.WebClient(slack_token)
sc.chat_postMessage(
channel="QQQQQ",
blocks=[
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "send post"
}
}
]
}
]
)
I added https://here.aws.api.amazonaws.com/default/lambda as "Request url" in the "Interactive Components" and "Event Subscriptions" of my slack app.
When I send message to bot POST request is sent to aws api.
When I click button POST request is not sent.
Tried with both tokens xoxp- and xoxb-
The problem is:
slack generates http request in strange way. Instead of json, it puts "blocks" into following structure:
{ ...... 'body': (byte[])\"payload=%7B%22type%22%3A%22block_actions%2 ...}
after decoding it is equal to:
{...payload={"type": "block_actions",...}
That isn't readable like json.
AWS API rejected these slack requests.
AWS cloudwatch helps to investigate problem.
To avoid this is necessary to enable "Use Lambda Proxy integration" option during method adding.

Office API getAccessTokenAsync result yields InvalidAuthenticationToken response from Graph

i have been trying to tackle this issues for a while now, i am workin on an Office-js addin for Outlook and is trying to access Microsoft Graph data through my addin.
But i have been unable to authenticate the token i recieve from getAccessTokenAsync.
If i attempt to use the authenticator from Office-JS-Helpers i can get access, but i would prefer to use the built in function of the addin for it.
the code i am trying to use is this:
Office.initialize = () => {
var options = { forceAddAccount: true, forceConsent: true } as Office.AuthOptions;
Office.context.auth.getAccessTokenAsync(options, getAccessTokenAsyncCallback);
}
function getAccessTokenAsyncCallback(accessTokenResponse) {
console.log(accessTokenResponse.value)
client = MicrosoftGraph.Client.init({
authProvider: (done) => {
done(null, accessTokenResponse.value);
},
debugLogging: false
})
client.api("/me")
.get((err, res, rawResponse) => {
console.log(err)
console.log("rawResponse")
console.log(rawResponse)
})
}
and my WebApplicationInfo in my manifest is:
<WebApplicationInfo>
<Id>{AppUID}</Id>
<Resource>api://localhost:3000/{AppUID}</Resource>
<Scopes>
<Scope>profile</Scope>
<Scope>user.read</Scope>
</Scopes>
</WebApplicationInfo>
</VersionOverrides>
and the rights has been set up in my app on the Application Registration Portal.
as far as i can see when validating/decoding the JSON Web Token i recieve from getAccessTokenAsync, it should be valid.
but whenever i try to connect using this token i get this response:
{
"statusCode": 401,
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"requestId": "4a0ce952-0e90-XXXXXXXXX-db20c6cca94e",
"date": "2018-08-30T05:37:43.000Z",
"body": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"innerError": {
"request-id": "4a0ce952-0e90-XXXXXXXXX-db20c6cca94e",
"date": "2018-08-30T07:37:43"
}
}
}
i simply can't figure out what the issue is here, am i wrong in that the token returned from getAccessTokenAsync is the one i need for this?
oh yes and i am running up against an Office365 environment with Outlook 2016 version 1807 build 10325.20118 click to run
The token that is returned by getAccessTokenAsync, called the bootstrap token, does NOT give your add-in access to MS Graph directly. Instead it gives the Office host application, Outlook in this case, access to your add-in's web application. Your add-in's web application then uses that token to get an access token to Microsoft Graph. It does this by using the "on behalf of" OAuth flow. Please see the extensive documentation at this node: SSO in Office Add-ins and, for Outlook-specific guidance, also see Authenicate a user in an Outlook Add-in with an SSO token.

Authentication fails on google home (oauth2)

I'm trying to connect to google home using OAuth2.0 mechanism. However, hitting with an issue where I'm not able to retrieve success message.
The failing request is - https://oauthintegrations.googleapis.com/v1/token:getForService
with the response payload as redirectState. I know about redirect but what is redirectState? I tried to search a bit over this one, but failed.
Any help would be appreciated.
Note:I have followed all the necessary steps mentioned in doc, I can receive authorisation code, but not able to make token request to desired endpoint.
The docs are https://developers.google.com/actions/identity/oauth2-code-flow and https://developers.google.com/actions/identity/account-linking.
In configuration settings we have Linking type as Oauth -> Authorization Code.
In dialog flow in Integration -> Integration Settings we have checked in for 'Sign in required' for Default Welcome Intent and have the firebase function as
app.intent('Default Welcome Intent', (conv) => {
conv.ask(new SignIn());
});
according to https://developers.google.com/actions/identity/account-linking document and I am currently using API version V2.
After the auth code is received as mentioned it does not call token url, we receive this screen :
Bad response from IdP in Auth Code Exchange & what is redirect_state
The https://gala-demo.appspot.com/app#redirect_state=XXX&state=yyy&service=abc when inspected fails at https://oauthintegrations.googleapis.com/v1/token:getForService as mentioned by #rajesh with status code 400, but when this request is made through postman it return the response. Here is the body and response for the request.
Body :
{
"credential" : {
"redirectState": "XXX"
},
"scopes": [],
"gdiState": "APP_AUTH",
"serviceId": "tapclicks-integration-adac2_dev"
}
RESPONSE :
{
"serviceInfo": {
"authUrl": "https://-domain-/authorization",
"name": "tapclicks dashboard",
"logoUrl": "https://placeholder.com/",
"clientId": "zdqexVMaVvxIMQ7Frjwa",
"tokenUrl": "https://-domian-/token_url",
"privacyPolicyUrl": "https://placeholder.com/",
"tosUrl": "https://placeholder.com/",
"id": "tapclicks-integration-adac2_dev"
},
"completionInfo": {
"appauthInfo": {
"appauthRedirectUrl": "https://-domain-/authorization?response_type=code&client_id=zdqexVMaVvxIMQ7Frjwa&redirect_uri=https://oauth-redirect.googleusercontent.com/r/tapclicks-integration-adac2&scope=gmail&state=yyy",
"appauthRedirectState": "abcxxx"
},
"oauthAuthorizationUrl": "https://-domain-/authorization?response_type=code&client_id=zdqexVMaVvxIMQ7Frjwa&redirect_uri=https://oauth-redirect.googleusercontent.com/r/tapclicks-integration-adac2&scope=gmail&state=yyy"
},
"gdiState": "APP_AUTH",
"header": {}
}
Can you please tell if i might be making any configuration mistake or any other info you need.
Authorization Url : https://kprb95tye7.execute-api.us-east-1.amazonaws.com/authorization/
Token Url : https://9343j46f16.execute-api.us-east-1.amazonaws.com/token_url/
Thanks

Resources