Welcome to new things

[Technical] [Electronic work] [Gadget] [Game] memo writing

Slack API Usage Notes

I used Slack API before, but when I tried to use it after a long time, I completely forgot how to use it, so here are some notes on how to use Slack API in case I forgot again.

By the way, what we wanted to do with the API is as follows.

  • Submission (as an application)
  • Submission (as a user)
  • file upload
  • Obtaining a list of workspace users

Basic Structure

Basically, you first create an app, the user installs that app in their workspace, and the user uses the API through that installed app.

Slack's developer features include not only APIs to manipulate Slack

  • Ability to issue a unique URL and post it with just a URL call without a token
  • Ability to receive event notifications via webhook to a specified URL

There are a variety of functions, such as The style is to create an application first, and then develop various functions using the application as a hub.

Procedure (Preparation)

Creating Apps

Go to Slack API page

Create an app by clicking [Building Slack apps]-[Create a Slack app] button.

Memo on how to use Slack API

Memo on how to use Slack API

The application is tied to the workspace.

Installing Apps

The above will create an app, and the next step is to install the created app so that users can use the API.

[Basic Information]-[Add features and functionality]-[Permissions] Moved to

(You can also go to the same page under "OAuth & Permissions")

Memo on how to use Slack API

It is a little confusing, but on the page to which you are moving (OAuth & Permissions), you can "Set which API to use" and "Install the application".

Select the API you want to use from [Scopes]-[Select Permission Scopes

Register the API you want to use with the [Save Changes] button

As an example, we registered the following API.

  • Submission (as an application)

    • chat:write:bot
  • Submission (as a user)

    • chat:write:user
  • file upload

    • files:write:user
  • User list acquisition

    • users:read

Memo on how to use Slack API

Install the app for the user (you) at [OAuth Token & Redirect URLs]-[Install App to Workspace

The application will then be registered to you and an access token will be issued, which you can then use to call the API.

Memo on how to use Slack API

Procedure (Using the API)

The token is a Bearer token, which is used by setting "Bearer \" in the "Authorization" header.

Other settings vary by API and should be set according to the API reference.

E.g.) Submitted as an application

import axios from 'axios';

(async () => {
    const token = `xoxp-XXXX`;
    const url = 'https://slack.com/api/chat.postMessage';

    const result = await axios.request({
        headers: {
            'authorization': `Bearer ${token}`
        },
        url,
        method: "POST",
        data: {
            channel: 'XXXX',
            text: 'Hello, World!',
        }
    });

    console.log(result.data);
})();

Then it will be posted like this.

Memo on how to use Slack API

Procedure (How to add, change, and delete APIs and applications)

You can go to the list of apps you have created from "Your Apps" in the upper right corner of the Slack API page.

Memo on how to use Slack API

Clicking on the app name will take you to the app's settings page.

### Add, modify, or delete APIs

  • This is done in [OAuth & Permissions]-[Scopes] in the app settings page.
  • After making changes, reissue the token by going to [OAuth & Permissions]-[OAuth Tokens & Redirect URLs]-[Reinstall App].
  • To revoke tokens issued so far, go to [OAuth & Permissions]-[Revoke All OAuth Tokens]-[Revoke Tokens].

Delete Apps

To uninstall an installed app, go to "App +" in the workspace.

Memo on how to use Slack API

To delete the app itself, use [Delete App]-[Delete App] in the app settings page.

Memo on how to use Slack API

Procedure (API Information Collection)

To use the API, it is necessary to find out what APIs are available and how to use them by referring to the reference. Refer to the reference as follows

Find out what APIs are available

On the Slack API page, go to [Reference]-[Methods] and find the API you want to use.

Memo on how to use Slack API

Find out how to use the API specifically

Click on the API name in the API list above to see how to use each API, including URL, method, and arguments.

Memo on how to use Slack API

API usage examples

Example: Posting as a user

import axios from 'axios';

(async () => {
    const token = `xoxp-XXXX`;
    const url = 'https://slack.com/api/chat.postMessage';

    const result = await axios.request({
        headers: {
            'authorization': `Bearer ${token}`
        },
        url,
        method: "POST",
        data: {
            channel: 'XXXX',
            text: 'Hello, World!',
            as_user: true,    // Posting flag as user
        }
    });

    console.log(result.data);
})();

Example: File upload

import axios from 'axios';
import * as FormData from 'form-data';
import * as fs from 'fs';

(async () => {
    const token = `xoxp-XXXX`;
    const url = 'https://slack.com/api/files.upload';
    const form = new FormData();
    form.append('file', fs.createReadStream('./data/slack_logo.png'));
    form.append('filename', 'slack_logo.png');
    form.append('channels', 'XXXX');

    const result = await axios.request({
        headers: {
            'authorization': `Bearer ${token}`,
            ...form.getHeaders(),
        },
        url,
        method: "POST",
        data: form
    });

    console.log(result.data);
});

Memo on how to use Slack API

supplementary explanation

It is easy to get stuck if you try to set the parameters of the file upload API yourself.

It is not enough to just pass the contents of the file; you must set the file type appropriately for it to work.

It is quite time-consuming to determine the type of file and set it up, so if you have a library, it is better to let it do the work for you.

For file upload, the so-called html file upload method "multipart/form-data" can be used.

The sample uses the "form-data" library that does "multipart/form-data" in Node.js, and the library is good enough to set the file type (content-type).

Example: Get a list of users in a workspace

import axios from 'axios';
import * as qs from 'qs';

(async () => {
    const token = 'xoxp-XXXX';
    const url = 'https://slack.com/api/users.list';

    let cursor = '';

    do{
        const result:any = await axios.request({
            headers: {
                'authorization': `Bearer ${token}`,
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            url,
            method: "POST",
            data: qs.stringify({
                cursor,
            })
        });

        console.log(result.data);
        cursor = result.data.response_metadata.next_cursor;

    }while(cursor);

})();

The API will be used to perform mainly posting-related operations, but there are many terms that are difficult to understand, so I will briefly explain them.

Posting Location

There are three main areas where submissions can be made

  • direct messages

    • So-called direct messages to individuals
    • In the API reference, it is sometimes described as "im
  • public channel

    • Channels that anyone can see inside.
    • In the API reference, it is sometimes described as "channel".
  • private channel

    • Channels that only members can see.
    • In the API reference, it is sometimes described as "group".

Submission Method

Posting with chat.postMessage. The word "chat" means "post", and all direct messages, public channels, and private channels are posted using this API. Posting is done with this API.

The posting destination is specified by setting the ID to "channel". The word "channel" does not mean a public channel.

In the case of direct messages, the "channel" is the user ID of the person you are sending the direct message to. In Slack, direct messages are called "im channel" and direct messages are a type of channel.

The user ID is the ID that appears at the end of the URL when the user's profile is opened. You cannot specify the posting destination by user name, so you must obtain the user ID in advance. user ID in advance.

There is no API to retrieve IDs from user names, so the only way is to write down the ID from the URL, or to retrieve the user list with conversations.list and find it yourself.

The same is true for public and private channel IDs.

How to identify posted messages

There is no unique ID for a message, but the combination of the posting destination ID and the "ts" timestamp of the message makes it a unique message. In other words, "ts" will not be duplicated and unique for the same posting destination.

return letter

You can reply to a message; you can receive multiple replies to a single message, but you cannot reply to a reply.

To reply, specify "channel" as the posting destination and "thread_ts" as the message to which you are replying.

Extra (using bots)

What is a bot?

In addition to running the API as an app, you can also create a bot and run the API as a bot.

Bots can be created from the application's settings page under "Bot Users.

Memo on how to use Slack API

When a bot is added, a token is issued for the bot, allowing it to operate the API as an app user and as a bot.

Memo on how to use Slack API

The usage of the API is the same as for an app, only the token is dedicated to bots. There is no significant difference between bots and apps when it comes to just using the API.

The biggest difference between a bot and an app is that when you register a bot, you can receive real-time event notifications via WebHook. We have separated the article to explain that since it is a separate topic from the API.

www.ekwbtblog.com

impressions

To be honest, I can't get used to Slack's structure and UI for any length of time....

I don't have what I was imagining where I was imagining it, and it's kind of unmemorable....

How do you all know how to use it....

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com