How to Get User Token for Slack API

Viewed 2875

I have a completely script-based python Slack App I want to run, but it needs a User (not a bot) token. I can use legacy tokens fine, but I want to get a token via oauth. I'm having a lot of trouble figuring out how to do this, though! I've added a local redirect to the app and I've tried this code:

def _get_credentials(self):

    credential_dir = os.path.join(PATH, '.credentials')

    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)

    credential_path = os.path.join(credential_dir,
                                   CREDENTIALS_LOCATION)

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()

    if not credentials or credentials.invalid:

        clientSecretPath = os.path.join(PATH, CLIENT_SECRET_FILE)
        flow = client.flow_from_clientsecrets(clientSecretPath, SCOPES)
        flow.user_agent = APPLICATION_NAME

        #### START PROBLEM ###

        credentials = tools.run_flow(flow, store)

        #### BREAKS ####

        print('Storing credentials to ' + credential_path)

    return credentials 

All the problems I experience are on the line designated by the hash-tags.

The first is that if the credentials file doesn't exist, instead of creating it, it breaks.

If I create an empty file with the name I want, then the web browser opens and asks the user to authenticate. If they do, they go to a page that says the "authentication process was complete." However, in terminal it shows Authentication has failed: Invalid response: 302 and nothing is stored to the credentials file.

In either case, it never hits the line after #### BREAKS ####

What am I doing wrong, or better yet, how do I do this right?

2 Answers

I was also trying to make API calls from a script (in my case: slackchannel2pdf), and was able to do so using the user token that appears on the Install App page of the Slack App I had to create for this purpose:

Install App page of custom Slack App

Full disclosure: I have no idea what I'm doing, I just tried googling and following random instructions until it worked.

  1. Requesting these permissions is easy:

  2. Load up the settings for your app from the app management page(https://api.slack.com/apps).

  3. In the navigation menu, choose the OAuth & Permissions feature.

  4. Scroll down to the Scopes section, and pick channels:read and channels:history from the drop down menu.

  5. Click save changes.

  6. Scroll back to the top of this page and look for the button that says Install App to Workspace (or Reinstall App if you've done this before). Click it.

You'll now see a permission request screen to install your app to its original workspace.

Related