Slack API, get current location - node.js

Is there any method to get current user location. Let say I created some "slash" command /map. When I am calling this command - POST message being send to my nodejs server, and server returns some json data.
{
"channel": "#map",
"username": "test",
"unfurl_links": true,
"icon_emoji": ":world_map:",
"attachments": [
{
"fallback": "Required plain-text summary of the attachment.",
"pretext": "Beautiful Personalized Map Sharing",
"image_url": "http://static.mapjam.com/yrjkbmb/auto/640x480.jpg",
"thumb_url": "http://static.mapjam.com/yrjkbmb/auto/640x480.jpg"
}
]
}
Because I am authenticated I am able to get some Slack user info:
username
email etc..
How can I access Slack user lat, long if it is possible though

Currently there is nothing available in the user info to get the geographical position of a user from the Slack API.
Please refer to the Users Info Slack API documentation and the User Type documentation.

If you are expecting to create a slash command the slack application would have to have permissions to your devices location. Looking at the permissions on my android app id does not request permissions to the devices location.
Just spit-balling, there could be a way to do it. This is completely hypothetical simplified method. You would have to have a helper application on the device that has permissions to the location of the device. That app would listen for the /location /map request then post to the channel where the request came from.

Related

How can users upload images to a Slack app?

To provide context i have a Slack bot that allows users to create ads, i am able to use a dialog to fetch the listing title, description and price. What am looking for is a way to allow users to also add images.
The file.upload seems to allow the bot to upload files but what i want is lo be able to allow users to select the files locally and upload them, the bot will then be able to capture this and respond accordingly.
This is what i have so far
#app.route('/new', methods=['POST'])
def new_listing():
# Get payload
api_url = 'https://slack.com/api/dialog.open'
trigger_id = request.form.get('trigger_id')
dialog = {
"callback_id": "marketplace",
"title": "Create a new listing",
"submit_label": "Create",
"notify_on_cancel": True,
"state": "Item",
"elements": [
{
"type": "text",
"label": "Listing Title",
"name": "listing_title"
},
{
"type": "text",
"label": "Listing description",
"name": "listing_description"
},
{
"type": "text",
"label": "Listing Price",
"name": "listing_price"
}
]
}
api_data = {
"token": oauth_token,
"trigger_id": trigger_id,
"dialog": json.dumps(dialog)
}
res = requests.post(api_url, data=api_data)
print(res.content)
return make_response()
#app.route('/message_actions', methods=['POST'])
def message_actions():
user_id = request.form['user']['id']
submission = request.form['submission']
title = submission['listing_title']
description = submission['listing_description']
price = submission['listing_price']
# Add the listing to the database
return make_response()
There is no straight forward approach, since the Slack API (currently) does not offer a filer picker.
However, here are 3 workarounds to address this requirement:
A - Image URLs
Instead of uploading images to Slack directly, users only provide the URL of image hosted on the Internet (e.g. uploading to imgur.com). The image URL can be queried with a simple plain-text input field in your dialog.
If you can expect your users to be tech savvy enough to handle image URLs and uploads to imgur.com (or other image hosters) I think think approach works pretty well.
B - External web page
You redirect users to an external web page of your app that has a file picker. That file picker allows uploading images from the user local machine to your app.
This approach also works well. However users need to switch to a browser (and back to Slack again), so it can break the input flow a bit. It also is a lot more effort to implement, e.g. you need to maintain context between Slack and your web page in a secure way, which can be a challenge.
C - Manual upload to Slack
Users upload images manual to Slack, e.g. in the app channel. You app detects every image upload and asks them to which item of your app to attach it to.
This approach allows you to stay within the Slack eco-system, but might be confusing for users and ensuring correct linking between user uploads and your items might be a challenge.
P.S.: I had the same requirement with one of my Slack apps (Rafflebot) and went with approach A.
You don't show how you are invoking /new (with the trigger id). However - while dialogues and the new modals don't seem to have file pickers - the slack app certainly does. So what I do is start my flow off with a message to my app - THAT message can have files attached. So for example my app looks that the message 'new report' - the user, prior to sending that can attach images - and my app will both get the message AND get a "files" attributes as part of the message event.

How to get the user id from Slack to bot service

I am creating a simple bot using Azure LUIS and this is my first one. I made some decent progress after doing some research and also now integrated with Slack as channel to test it.
The bot functionality is working fine, but I am looking to identify the user. So that I can personalize the bot conversation and also to pull the user specific information from his profile table.
Is there anyway, that I can get a UID or any reference ID of the slack user and so I can store that in my user table along with user profile?
So next time, when the user greets the bot, the bot can say "Hello, John." instead of justing say "Hello."
Thanks!
Yes. You can use the channelData object to get the ApiToken, and user values. For example, in C#, you could use turnContext.Activity.ChannelData to get those values in JSON:
{{
"SlackMessage": {
"token": "............",
"team_id": "<TEAM ID>",
"event": {
"type": "message",
"text": "thanks",
"user": "<USER WHO MESSAGED>",
"channel": "............",
"channel_type": "channel"
},
"type": "event_callback",
"event_id": ""............",
"event_time": 1553119134,
"authed_users": [
"............",
"<USER WHO MESSAGED>"
]
},
"ApiToken": "<ACTUAL TOKEN HERE>"
}}
Then, using those two pieces of information, you can then retrieve info from Slack.
https://slack.com/api/users.info?token=<ACTUAL TOKEN HERE>&user=<USER WHO MESSAGED>&pretty=1
And get a response that has the info you need:
{
"ok": true,
"user": {
"id": "<USER WHO MESSAGED>",
"team_id": "<TEAM ID>",
"real_name": "Dana V",
Ideally, you would would probably want to have bot user state setup and check that first, then if not there, then make the API call to Slack, then store in state. Therefore further requests don't need to go to Slack, but will just pull from the state store.
Basically, you could/should do this in the onTurn event. First, create your user state storage such as here.
Then you could check for that value and write to it if not populated. This example on simple prompts, might be helpful. You won't need to prompt for your user's name, as this example does, but does read/write username from state. You could still use dialogs, but you won't need them for the name prompting as you are doing that dynamically.
You can see here where username is being set and here where it is being retrieved. In this case, it is in the dialogs, but again; you would/could just do in the turn context (using logic to get and if not there, set).
I found the solution by priting the whole session object, which is having all the required informaiton. This could be same as mentioned by Dana above, but after debugging, this follwing made simple without making any changes.
var slackID = session.message.address.user.id
With above, I am able to identify the user.
Thanks.

Microsoft bot: How to log each conversation step?

I'm learning how to build a Microsoft Bot and I need to send every message (ie log the user progress through the bot) to an API.
Let's say I have these dialogs with 3 steps each:
/
/welcome
/onboarding
/finish
When a user joins the conversation (Root dialog), I need to make a POST to our API with the following data:
{
"conversationId": "8n21b2mkmdb9abi26",
"dialog": "root",
"step": 1
}
And then, for each following user message, I would update that conversation in our server with the dialog and step.
I tried to use the middleware hook, but it doesn't have the information of which dialog/step the user is currently in.
Any suggestion?
The middleware feature gives you access to the session object. Store the metadata you need in the session object, then access it in your logging middleware.
For a code example, check out: Microsoft/BotBuilder-Samples - Middleware and Logging with BotBuilder Node SDK

Posting on facebook via unificationengine

Hi I'd like to post to facebook via unification engine. I've already created a user, added and tested successfully a facebook connection, but when I post I get the following response:
{"Status":{"facebook":{"status":190,"info":"Error validating access token: Session does not match current stored session. This may be because the user changed the password since the time the session was created or Facebook has changed the session for security reasons.: "}},"URIs":[]}
When I use the facebook token, that was used for creating the connection, to post to facebook directly (without unificationengine), then it works just fine. What might be the problem here? Status 190 is neither documented on facebook nor on unificationengine.
#unificatinengine developers: it would be practical, if the errors returned by the service would be passed on inside the unificationengine response, this way debugging such errors would be easier, and the errors could also be processed programmatically.
Additional info
Today I seem not to be able to reproduce the response of yesterday. The postfields I use to post the message to facebook (the same as yesterday) are as follows:
{
"message":{
"receivers":[
{
"name":"me",
"address":"https://graph.facebook.com/v2.1/me/feed",
"Connector":"facebook"
}
],
"sender":{
"address":"sender address"
},
"subject":"test",
"parts":[
{
"id":"0",
"contentType":"text/plain",
"type":"body",
"size":25,
"data":"this is the plain message"
},
{
"id":"1",
"contentType":"text/html",
"type":"body",
"size":42,
"data":"<div>this is the <b>html</b> message</div>"
},
{
"id":"2",
"contentType":"text/plain",
"type":"link",
"size":17,
"data":"http://www.web.de"
},
{
"id":"3",
"contentType":"text/plain",
"type":"link_description",
"size":21,
"data":"some link description"
},
{
"id":"4",
"contentType":"text/plain",
"type":"link_title",
"size":10,
"data":"link title"
}
]
}
}
But today I get the following message back from unificationengine
{
"Status":{
"facebook":{
"status":100,
"info":"Unsupported post request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api: "
}
},
"URIs":[]
}
Unfortunately this does not tell me, what unificationengine does internally for posting to facebook (which should not concern me), and what goes wrong there.
Does the "/v2/connection/info" show the details of the facebook connection that you have added? If not can you please update the connection with a new access token, using the same connection identifier for the "v2/connection/add" api endpoint, and check if it works.
unificationengine

Instagram how to get my user id from username?

I'm in the process of embedding my image feed in my website using JSON, the URL needs my user id so I can retrieve this feed.
So, where can I find/get my user id?
Update in Jun-5-2022, Instagram API no longer use Bearer Token for authentication. But I find another useful API. All you need is added extra header X-IG-App-ID with "magic value".
https://i.instagram.com/api/v1/users/web_profile_info/?username=therock
Use can use my docker container Insta-Proxy-Server to bypass the authentication.
https://hub.docker.com/repository/docker/dockerer123456/insta-proxy-server
Demo video (I just run directly from source code): https://www.youtube.com/watch?v=frHC1jOfK1k
Update in Mar-19-2022, the API is require login now. Sorry for the bad news.
But we can solve this problem in two ways.
Using my C# lib, login using your account (without any Instagram app token stuff and graph api.)
In case the lib failed (I'm no longer maintain it long time ago), create a proxy server with logged in instagram account.
[Your app] --> [Proxy server] --> [Instagram] --> [Proxy server] -(forward)-> [Your app]
For Proxy server, you can use Nodejs app which install Chromium headless module (Puppeteer for example), logged in with an instagram account.
Proof of concept:
https://www.youtube.com/watch?v=ZlnNBpCXQM8
https://www.youtube.com/watch?v=eMb9us2hH3w
Update in June-20-2019, the API is public now. No authentication required.
Update in December-11-2018, I needed to confirm that this endpoint still work.
You need to login before sending request to this site because it's not public endpoint anymore.
Update in Apr-17-2018, it's look like this endpoint still working (but its not public endpoint anymore), you must send a request with extra information to that endpoint. (Press F12 to open developer toolbar, then click to Network Tab and trace the request.)
Update in Apr-12-2018, cameronjonesweb said that this endpoint doesn't work anymore. When he/she trying to access this endpoint, 403 status code return.
You can get user info when a request is made with the url below:
https://www.instagram.com/{username}/?__a=1
E.g:
This url will get all information about a user whose username is therock
https://www.instagram.com/therock/?__a=1
Enter this url in your browser with the users name you want to find and your access token
https://api.instagram.com/v1/users/search?q=[USERNAME]&access_token=[ACCESS TOKEN]
Working solution without access token as of October-14-2018:
Search for the username:
https://www.instagram.com/web/search/topsearch/?query=<username>
Example:
https://www.instagram.com/web/search/topsearch/?query=therock
This is a search query. Find the exact matched entry in the reply and get user ID from the entry.
Easily Get USER ID and User Details
https://api.instagram.com/v1/users/search?q=[ USER NAME ]&client_id=[ YOU APP Client ID ]
For Example:
https://api.instagram.com/v1/users/search?q=zeeshanakhter2009&client_id=enter_your_id
Result:
{"meta":{"code":200},"data":[{"username":"zeeshanakhter2009","bio":"http://about.me/zeeshanakhter","website":"http://zeeshanakhter.com","profile_picture":"http://images.ak.instagram.com/profiles/profile_202090411_75sq_1377878261.jpg","full_name":"Zeeshan
Akhter","id":"202090411"}]}
Most of the methods are obsolete since June, 1/2016 api changes
Below worked for me,
access instagram on your browser say chrome, safari or firefox.
Launch developer tools, go to console option.
on command prompt enter below command and hit enter:
window._sharedData.entry_data.ProfilePage[0].user.id
If you are lucky, you will get at first attempt, if not, be patient, refresh the page and try again. keep doing until you see user-id. Good luck!!
Instead of using the API, one can examine the Instagram userpage to get the id. Example code in PHP:
$html = file_get_contents("http://instagram.com/<username>");
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$js = $xpath->query('//body/script[#type="text/javascript"]')->item(1)->nodeValue;
$start = strpos($js, '{');
$end = strrpos($js, ';');
$json = substr($js, $start, $end - $start);
$data = json_decode($json, true);
$data = $data["entry_data"]["UserProfile"][0];
# The "userMedia" entry of $data now has the same structure as the "data" field
# in Instagram API responses to user endpoints queries
echo $data["user"]["id"];
Of course, this code has to be adapted if Instagram changes its page format.
Currently there is no direct Instagram API to get user id from user name. You need to call the GET /users/search API and then iterate the results and check if the username field value is equal to your username or not, then you grab the id.
I wrote this tool for retrieving Instagram IDs by username: Instagram User ID Lookup.
It utilizes the python-instagram library to access the API and includes a link to the source code (written on Django), which illustrates various implementations of the Instagram API.
Update: Added source code for port to Ruby on Rails.
I tried all the aforementioned solutions and none works. I guess Instagram has accelerated their changes. I tried, however, the browser console method and played around a bit and found this command that gave me the user ID.
window._sharedData.entry_data.ProfilePage[0].graphql.user.id
You just visit a profile's page and enter this command in the console. You might need to refresh the page for this to work though. (I had to post this as an answer, because of my low reputation)
You need to use Instagrams API to convert your username to id.
If I remember correctly you use users/search to find the username and get the id from there
Most of these answers are invalid after the 6/1/2016 Instagram API changes. The best solution now is here. Go to your feed on instagram.com, copy the link address for any of your pictures, and paste it into the textbox on that page. Worked like a charm.
to get your id, make an authenticated request to the Instagram API users/self/feed endpoint. the response will contain, among other data, the username as well as the id of the user.
Go to the api console & copy link https://api.instagram.com/v1/users/self in text field and authenticate using your instagram id & password, you will get your id in response
This can be done through apigee.com Instagram API access here on Instagram's developer site. After loging in, click on the "/users/search" API call. From there you can search any username and retrieve its id.
{
"data": [{
"username": "jack",
"first_name": "Jack",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_66_75sq.jpg",
"id": "66",
"last_name": "Dorsey"
},
{
"username": "sammyjack",
"first_name": "Sammy",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_29648_75sq_1294520029.jpg",
"id": "29648",
"last_name": "Jack"
},
{
"username": "jacktiddy",
"first_name": "Jack",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_13096_75sq_1286441317.jpg",
"id": "13096",
"last_name": "Tiddy"
}]}
If you already have an access code, it can also be done like this:
https://api.instagram.com/v1/users/search?q=USERNAME&access_token=ACCESS_TOKEN
Well you can just call this link
http://jelled.com/ajax/instagram?do=username&username=[USER_NAME_GOES_HERE]&format=json
Although it's not listed on the API doc page anymore, I found a thread that mentions that you can use self in place of user-id for the users/{user-id} endpoint and it'll return the currently authenticated user's info.
So, users/self is the same as an explicit call to users/{some-user-id} and contains the user's id as part of the payload. Once you're authenticated, just make a call to users/self and the result will include the currently authenticated user's id, like so:
{
"data": {
"id": "1574083",
"username": "snoopdogg",
"full_name": "Snoop Dogg",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1574083_75sq_1295469061.jpg",
"bio": "This is my bio",
"website": "http://snoopdogg.com",
"counts": {
"media": 1320,
"follows": 420,
"followed_by": 3410
}
}
If you are using implicit Authentication must have the problem of not being able to find the user_id
I found a way for example:
Access Token = 1506417331.18b98f6.8a00c0d293624ded801d5c723a25d3ec
the User id is 1506417331
would you do a split single seperated by . obtenies to acces token and the first element
I think the best, simplest and securest method is to open your instagram profile in a browser, view source code and look for user variable (ctrl+f "user":{") inside main javascript code. The id number inside user variable should be your id.
This is the code how it looked in the moment of writing this answer (it can, and probably will be changed in future):
"user":{"username":"...","profile_picture":"...","id":"..........","full_name":"..."}},
Here is how you can retrieve your user id from a username:
$url = "https://api.instagram.com/v1/users/search?q=[username]&access_token=[your_token]";
$obj = json_decode(#file_get_contents($url));
echo $obj->data[0]->id;
You can do this by using Instagram API ( User Endpoints: /users/search )
how-to in php :
function Request($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function GetUserID($username, $access_token) {
$url = "https://api.instagram.com/v1/users/search?q=" . $username . "&access_token=" . $access_token;
if($result = json_decode(Request($url), true)) {
return $result['data'][0]['id'];
}
}
// example:
echo GetUserID('rathienth', $access_token);
Here is a really easy website that works well for me:
http://www.instaid.co.uk/
Or you can do the following replacing 'username' with your Instagram username
https://www.instagram.com/username/?__a=1
Or you can login to your Instagram account and use google dev tools and look at the cookies that have been stored. 'ds_user_id' is your user ID
Working Solution December 14, 2020
For simple usage like 3rd party tools that require an Instagram user ID (like embedding an image feed) I tend to use:
https://www.thekeygram.com/find-instagram-user-id/
because it makes it really easy to copy and paste the Instagram user ID that I am looking for. Unlike most tools I get the results fast, it's free and there are no ads. I recommend you watch the youtube video before using it so you can see how simple it is and get an idea of how it's used:
https://www.youtube.com/watch?v=9HvOroY-YBw
For more advanced usage I recommend:
https://www.instagram.com/{username}/?__a=1
(replace username with the requested username)
For example to find the user ID of the username "instagram" you would use:
https://www.instagram.com/instagram/?__a=1
This is the most advanced way which returns a JSON response and it's great if you are building an app that requires the raw data. You can save it in a database or build some type of front end UI to display it. Example: for a dashboard or on a website. Also, using the url is great because you can get additional attributes about users such as their total follower count and profile bio.
Since adding ?__a=1 to a profile URL is not working anymore to get a user ID from a username, we can do it with cURL and jq (the new API endpoint can be found in the network requests of Instagram web version, for example with Firefox Developer Tools):
curl -s 'https://i.instagram.com/api/v1/users/web_profile_info/?username=alanarblanchard' -H 'X-IG-App-ID: 936619743392459' | jq -r .data.user.id
If you are using Instagram in a web browser, you don't need to use the command above and can check the response of the HTTP request directly.
You may also be interested in finding the username from a user ID, in case someone changes frequently the username. I added an answer here: Instagram get username from userId
https://api.instagram.com/v1/users/search?q="[USERNAME]"&access_token=[ACCESS TOKEN]
Please notice the quotation marks.
This does not always return a valid result but more often than non-quoted one:
https://api.instagram.com/v1/users/search?q="self"&count=1&access_token=[ACCESS TOKEN]
returns user "self" (id: 311176867)
https://api.instagram.com/v1/users/search?q=self&count=1&access_token=[ACCESS TOKEN]
returns user "super_selfie" (id: 1422944651)
Working solution ~2018
I've found that, providing you have an access token, you can perform the following request in your browser:
https://api.instagram.com/v1/users/self?access_token=[VALUE]
In fact, access token contain the User ID (the first segment of the token):
<user-id>.1677aaa.aaa042540a2345d29d11110545e2499
You can get an access token by using this tool provided by Pixel Union.
Python solution with Instaloader external library (install it first with pip)
import instaloader
YOUR_USERNAME = "Your username here"
USERNAME_OF_INTEREST = "Username of interest here"
L = instaloader.Instaloader()
L.interactive_login(YOUR_USERNAME)
profile = instaloader.Profile.from_username(L.context, USERNAME_OF_INTEREST)
print(profile.userid)
With this kind of questions about constantly changing private APIs, I recommend to rely on actively developing libraries, not on the services or answers.
First Create an Application on Instagram and get Client Id for your application
http://instagram.com/developer/
Now just copy paste following Url into browser window by replacing your Username and your Client Id
https://api.instagram.com/v1/users/search?q=[Your-username]&client_id=[Your-Client-Id]
you will get a Json Result containing General Information about your account along with your Numeric user Id
UPDATED 2021
Just go to Facebook Apps choose your app connected with Instagram and you will see your Instagram ID: ********
Note https://www.instagram.com/{username}/?__a=1 was NOT working for me, so this is not a solution in 2021 if you want to use the Instagram Graph API
As of june 2022, you can to run or intercept a special HTTP request in order to successfully get the user data (and user ID). If you use Puppeteer, you can intercept the request that Instagram makes in the browser, and read its response. Example code:
const username = 'user.account';
const page = await browser.newPage();
const [foundResponse] = await Promise.all([
page.waitForResponse((response) => {
const request = response.request();
return request.method() === 'GET' && new RegExp(`https:\\/\\/i\\.instagram\\.com\\/api\\/v1\\/users\\/web_profile_info\\/\\?username=${encodeURIComponent(username.toLowerCase())}`).test(request.url());
}),
page.goto(`https://instagram.com/${encodeURIComponent(username)}`),
]);
const json = JSON.parse(await foundResponse.text());
console.log(json.data.user);
See discussion here: https://github.com/mifi/SimpleInstaBot/issues/125#issuecomment-1145354294
See also working code here: https://github.com/mifi/instauto/blob/2de64d9a30dad16c89a8c45f792e10f137a8e6cb/src/index.js#L250

Resources