Slack_api_token



  1. Slack Bearer Token
  2. Slack Api Token For Channel

Slack is a remarkable tool. Its success is recognized globally, and its popularity continues to grow to this day.

Apart from its intuitive design and game-like structure, it offers much more than just a traditional chat tool. Powered by reactions, easy link embedding, mentions, groups, threads, and much more, it offers a complete communication experience.

For those who still seek more, there is always the option of extending Slack's native functionality; either by installing an app or integration from Slack's Public Directory or by creating your own.

You can use this example to create multiple schedules with different parameter values, to send a report to different Slack. The API token, API secret. In addition to delivering content to Looker's built-in destinations, you can deliver content to third-party services integrated with.In addition to delivering content to Looker's built-in.

If you happen to be that person who still is not satisfied by what's offered 'out of the box', you might start to wonder how difficult it would be to create your own Slack integration or app. The answer to that varies; it could be either very difficult or quite easy, depending on what steps you choose to take.

On its own, Slack does not support any services other than their APIs. There are several: the Web API, Events API, RTM API, and Conversation API. We will focus on the Web API for now.

The Web API allows for interaction with most of the built-in functionalities of Slack. You can, for example, get information on channels, users, or chat messages. You can also create new channels and post messages directly to users or in channels. That is just a fraction of the possibilities the Web API provides. For full and up-to-date list, I direct you to the official documentation https://api.slack.com/web.

But the Slack APIs' main purpose is to handle outside requests to Slack. What about another way of communication? Is Slack capable of interacting with external services? Yes, it is, and for that purpose, there is a set of tools you will most likely need to use in any of the apps or integrations you might want to create.

To initiate communication with the outside world from the Slack chat, you can use slash commands, interactive components, events, bots, and links. All of them would need a dedicated blog post explaining their usage, but in this article, we will focus on slash commands. Using slash command combined with the Web API makes for a complete integration or app, and it requires the least amount of configuration and coding.

The Code

To demonstrate how quickly it is possible to create a slack integration, we will pick the easiest components to build with. Slash commands are designed to be accessible from anywhere in the chat area in Slack. You can run them in a channel, group, or direct message. Each slash command starts with a / and is followed by a command name. Optionally, it might take one argument, which is the text you provide after the command name with a single space in between. For example:

/my-command some text

There is a single action done each time you activate a slash command, and that is sending a request to an outside web service. You need to specify an URL (https) when you configure your custom command.

We will prepare a simple slash command which will send back a chat message with the text provided as the command's parameter. So looking at above code example, after running that command, I would expect to get back a public response in the same channel saying: Hello, you wrote: 'some text'.

Let's talk about the required infrastructure for such an integration. If we look at this step by step, there are some actions taking place in the public domain and some secretly, 'under the hood'.

  • We run a slash command with a text parameter
  • Slack picks up that action and forms a request payload to the specified external web service
  • The web service (which is outside of the Slack platform) receives the request and handles it on its own
  • The web service sends a request to the Web API's endpoint
  • The Web API validates and authenticates the request from the web service
  • The Web API sends a chat message to the Slack team's chat channel, which is visible to all channel participants

As we can see, in such case we have the Slack platform, and we have the web service part, which is not provided by Slack. The web service we will either have to provide on our own or use some of the available services. I will explain a complete setup using Node.js and Express.js libraries for the web service in another blog post, but since we are aiming to configure this in 3 minutes, we will have to pick something much simpler.

We will place the web service in https://webtask.io and here is why:

  • It has an online editor ready to use right away
  • It's free for what we want to achieve
  • You can sign up using your social media/work account in no time
  • It provides an https:// endpoint out of the box (required for slack)
  • It works really fast

As opposed to Zapier or IFTTT, which are also very quick to set up, this approach allows you to run your own code the same way as you would on your own machine. To demonstrate that, I will show in a later post the same code running in a local setup.

To get the expected behavior from our integration, you will need to do these steps:

Start with Webtask to get your web service URL:

  • Go to https://webtask.io/
  • Click 'Create a new One' to create new Webtask
  • Create an Empty Webtask Function with your custom name
  • Copy the https endpoint generated in the footer

Let's switch to the Slack configuration and wrap all configurations before coding:

  • You will need to be logged into your Slack team
  • Go to https://.slack.com/apps/manage/custom-integrations
  • Click the 'Slash Command' and then 'Add Configuration' buttons
  • Select a name for your slash command and click the button below
  • Change 'Method' to 'GET'
  • You can close the 'Outgoing Payload and Responses' section as it's not relevant at this point
  • Paste in the URL you copied from the Webtask editor
  • Save the 'Token' for later
  • Head over to 'Autocomplete help text', select the checkbox, and add your description and usage hint
  • Click 'Save Integration'

Checking the 'Autocomplete help text' adds your new command to a very helpful list of commands that is shown when you start typing any command:

We will need to generate a token to access and authorize our Web API Request. With that token, the Web API will validate your request, check scopes and permissions, and most importantly, it will use it to identify your Slack team — after all, you are posting to a public API route. To set this up:

  • Go to https://api.slack.com/custom-integrations/legacy-tokens
  • Create a legacy token and save it for later

You might wonder about the 'Legacy' part in the custom integrations section and tokens. We are in fact using a legacy functionality of Slack which may sooner or later be deprecated. For now, it's still active, and it is the easiest way to configure a simple integration. In a future post, I will show the 'correct' way of configuring a Slack app which uses a slash command. In that case, we will need to deal with some more complicated configuration, but having gone through the initial legacy setup, you will have a better understanding of the process.

Running the command

Now, out of the box, when you run this command, Slack will print out whatever is in the response text from the endpoint and show it to the user that triggered the command as an 'ephemeral message'. This type of messages is only visible to the user who triggered them and will only exist in the current channel window until a refresh or log out. It is handy for some of the interactions and debugging but it's not what we are going for in this example.

Let's replace the existing code with what we would like to use for this example:

As you can see, we specified several NPM packages we require to run this code. You will need to add them manually using the Settings icon in the top left corner of the editor under the 'NPM Modules' section. Using that tool, add 'webtask-tools', 'express', 'body-parser', and 'request' packages.

We also need to use the API Token granted by Slack to access the Web API. Webtask allows you to create a Secret, which is a simple env variable, which they call a 'Context variable'. We need to go to Settings and 'Secrets' where you can add the 'token' secret with the value of your granted token. It will be available in the function code under req.webtaskContext.secrets.token.

Security

As you may remember, there was another token generated when we created our slash command. You can add it as a second secret and call it the verification_token. Then, you can add a simple check for request verification to prevent unwanted usage of the script:

The token value generated on the slash command config page (which can be regenerated as needed) is sent with each request from Slack. That way, you know it's slack and not someone else trying to abuse your web service.

You can save your progress and run the command in Slack chat.

With this setup, you can try using more complicated packages and services as well as other Web API methods, too. Good luck!

Slack_api_token

Bots are a useful way to interact with chat services such asSlack. If you have never built a bot before, thispost provides an easy starter tutorial for combining theSlack API with Python to create your first bot.

We will walk through setting up your development environment, obtaining aSlack API bot token and coding our simple bot in Python.

Tools We Need

Our bot, which we will name 'StarterBot', requires Python and the Slack API.To run our Python code we need:

  • Either Python 2 or 3
  • pip andvirtualenv to handle Pythonapplication dependencies
  • Free Slack account - you need to be signed into atleast one workspace where you have access to building apps.

It is also useful to have the Slack API docs handywhile you're building this tutorial.

Slack Bearer Token

All the code for this tutorial is available open source under the MIT licensein the slack-starterbot publicrepository.

Establishing Our Environment

We now know what tools we need for our project so let's get our developmentenvironment set up. Go to the terminal (or Command Prompt on Windows) andchange into the directory where you want to store this project. Withinthat directory, create a new virtualenv to isolate our applicationdependencies from other Python projects.

Activate the virtualenv:

Your prompt should now look like the one in this screenshot.

The official slackclient API helper library built by Slack can send andreceive messages from a Slack channel. Install the slackclient library withthe pip command:

Slack Api Token For Channel

When pip is finished you should see output like this and you'll beback at the prompt.

We also need to create a Slack App to recievean API token for your bot. Use 'Starter Bot' as your App name. If you are signedinto more than one workspace, pick a Development Workspace from the dropdown.

After submitting the form, keep the app configuration page open.

Slack APIs and App Configuration

We want our Starter Bot to appear like any other user in your team - it willparticipate in conversations inside channels, groups, and DMs. In a SlackApp, this is called a bot user, whichwe set up by choosing 'Bot Users' under the 'Features' section. Afterclicking 'Add a Bot User', you should choose a display name, choose adefault username, and save your choices by clicking 'Add Bot User'. You'llend up with a page that looks like the following:

The slackclient library makes it simple to use Slack'sRTM API and Web API.We'll use both to implement Starter Bot, and they each require authentication.Conveniently, the bot user we created earlier can be used to authenticate forboth APIs.

Click on the 'Install App' under the 'Settings' section. The button on this pagewill install the App into our Development Workspace. Once the App is installed,it displays a bot user oauth access token for authentication as the bot user.

A common practice for Python developers is to export secret tokens asenvironment variables. Back in your terminal, export the Slack token with thename SLACK_BOT_TOKEN:

Nice, now we are authorized to use the Slack RTM and Web APIs as a bot user.

Coding Our Starter Bot

We've got everything we need to write the Starter Bot code. Create a new filenamed starterbot.py and include the following code in it.

With our dependencies imported we can use them to obtain the environmentvariable values and then instantiate the Slack client.

The code instantiates the SlackClient client with our SLACK_BOT_TOKENexported as an environment variable. It also declares a variable we can use tostore the Slack user ID of our Starter Bot. A few constants are also declared,and each of them will be explained as they are used in the code that follows.

The Slack client connects to the Slack RTM API. Once it's connected, it calls aWeb API method (auth.test) to findStarter Bot's user ID.

Each bot user has a user ID for each workspace the Slack App is installedwithin. Storing this user ID will help the program understand if someone hasmentioned the bot in a message.

Create slack api token

Next, the program enters an infinite loop, where each time the loop runs theclient recieves any events that arrived from Slack's RTM API. Notice thatbefore the loop ends, the program pauses for one second so that it doesn't looptoo fast and waste your CPU time.

For each event that is read, the parse_bot_commands() function determines ifthe event contains a command for Starter Bot. If it does, then command willcontain a value and the handle_command() function determines whatto do with the command.

We've laid the groundwork for processing Slack events and calling Slack methodsin the program. Next, add three new functions above the previous snippet tocomplete handling commands:

The parse_bot_commands() function takes events from Slack and determinesif they are commands directed at Starter Bot. There are manyevent types that our bot will encounter, but tofind commands we only want to considermessage events. Message events also havesubtypes, but the commands we want to find won't have any subtype defined. Thefunction filters out uninteresting events by checking these properties. Now weknow the event represents a message with some text, but we want to find outif Starter Bot is being mentioned in the text. The parse_direct_mention()function will figure out of the message text starts with a mention, and thenwe compare that to the user ID we stored earlier for Starter Bot. If they arethe same, then we know this is a bot command, and return the command text withthe channel ID.

The parse_direct_mentions() function uses a regular expression to determineif a user is being mentioned at the beginning of the message. It returnsthe user ID and the remaining message (and None, None if no mention wasfound).

The last function, handle_command() is where in the future you'll add all theinteresting commands, humor, and personality for Starter Bot. For now, it hasjust one example command: do. If the command starts with a known command, itwill have an appropriate response. If not, a default response is used. Theresponse is sent back to Slack by calling thechat.postMessage Web APImethod with the channel.

Here is how the entire program should look when it's all put together(you can alsoview the file in GitHub):

Now that all of our code is in place we can run our Starter Bot on thecommand line with the python starterbot.py command.

In Slack, create a new channel and invite Starter Bot or invite it to anexisting channel.

Now start giving Starter Bot commands in your channel.

Additional Note: Currently there's an issue with the websocket package and the CA certificate it uses, so if you encounter an error like:

There are a couple of things that can be done:1. Downgrading the websocket-client library to 0.47.02. Or, download the certificate (wget https://www.tbs-certificats.com/issuerdata/DigiCertGlobalRootCA.crt), then set the environment variable export WEBSOCKET_CLIENT_CA_BUNDLE=DigiCertGlobalRootCA.crt

Wrapping Up

Alright, now you've got a simple Starter Bot with a bunch of places in thecode you can add whatever features you want to build.

There is a whole lot more that could be done using the Slack RTM API and Python.Check out these posts to learn what you could do:

  • Attach a persistent relational database orNoSQL back-end such asPostgreSQL, MySQL or SQLiteto save and retrieve user data
  • Add another channel to interact with the botvia SMSorphone calls
  • Integrate other web APIs such asGitHub or Twilio
  • Explore other Slack Platform APIs and the reasons you might use one over another.
  • Build an onboarding bot using the Slack Events API

Questions? Contact me via Twitter@fullstackpythonor @mattmakai. I'm also on GitHub withthe username mattmakai.

See something wrong in this post? Forkthis page's source on GitHuband submit a pull request.