Пишем бота для Slack за 1,5 минуты опыт команды Tproger


Оглавление (нажмите, чтобы открыть):

Как удалить интеграцию ботов с Slack?

Я хочу полностью удалить бота, который я создал на Slack. Я могу отключить его, но не полностью удалить его. Есть идеи?

3 ответа

Слак дал мне ответ через Twitter:

Slack API â € @SlackAPI 14 июля

В настоящее время невозможно, к сожалению. Но мы работаем с изменениями, которые позволит это. Оставайтесь с нами!

Я удалил приложения со страницы https://[yourteamname].slack.com/apps/manage .

Измените [yourteamname] имя вашей команды.

Хотя вы не можете принимать какие-либо действия на ботах на странице my.slack.com/admin, я смог перейти в раздел «apps», и там появились все мои боты. Затем я нажал на бота, который хотел удалить, и ударил «удалить приложение» в нижней части экрана. Не самая большая реализация, но, по крайней мере, похоже, что есть решение!

Я также являюсь владельцем команды, поэтому вам, вероятно, нужно будет удалить бота

Enabling interactions with bots

The rundown
Read this if: You’re still experimenting, prototyping, and exploring.
Read first: Block Kit Tools Incoming Webhooks
Read next: Messaging for Slack apps Using app_home_opened for onboarding

Enable conversations between users and apps in Slack by building bots.

New Slack apps act independently of a user token. Build a bot user powered by only the specific permissions it needs. Check out new Slack apps, now in open beta.

What are bots?

A bot is a type of Slack App designed to interact with users via conversation.

A bot is the same as a regular app: it can access the same range of APIs and do all of the magical things that a Slack App can do.

But when you build a bot for your Slack App, you’re giving that app a face, a name, and a personality, and encouraging users to talk to it.

Your bot can send DMs, it can be mentioned by users, it can post messages or upload files, and it can be invited to channels — or kicked out.

Bots are not cybernetic infiltration units, and it is unlikely that they dream of electric sheep, though we can’t rule it out. ��

Getting Started

Since your bot is capable of doing everything that a Slack App can do, we’re going to limit our focus to a common use-case for bots. The following steps will get you to the point where you have a bot waiting for messages with trigger words and sending simple responses.

From there, you can start bolting on whatever kind of amazing app logic or nuclear-powered jet-packs you can imagine.

Before you start, you’ll need a Slack App. If you don’t already have one, click the following button to create it:

That done, you’re all ready to arrange the architecture of this automaton.

1. Creating a bot user

To use your Slack App as a bot, first you’ll need to create a Bot User for it.

Head to your app’s settings page and click the Bot Users feature in the navigation menu.

You’ll be presented with a button marked Add a Bot User, and when you click on it, you’ll see a screen where you can configure your app’s bot user with the following info:

  • Display name — the name that is displayed to other users when the bot posts messages, or the bot’s profile is viewed, etc.
  • Default username — the string that is used when the bot is mentioned in a message. This username may be modified slightly from the default when it is installed to a workspace where that username is already reserved. This modification is an incrementing number appended to the username — so @username might become @username2.
  • Always Show My Bot as Online — we recommend you enable this feature, so that your bot always appears to be ready to receive input (which it probably will be). When disabled, you’ll have to programmatically set its online presence.

Once you’ve completed these fields, click the Add Bot User button and then Save Changes.

Great, you’ve just created a bouncing baby bot! Don’t leave the app settings yet though, there’s just one more bit of configuration left to do.

2. Setting up the Events API

The Events API is a bot’s equivalent of eyes and ears. It gives a bot a way to react to posted messages, changes to channels, and other activities that happen in Slack. When these events happen, a data payload will be sent to your bot, and it can use that data to form a useful response.

Giving your bot access to the Events API is pretty simple:

  • From your app’s settings, click the Event Subscriptions feature in the navigation menu.
  • Switch the Enable Events toggle to on and you’ll be presented with a new screen of options.
  • You’ll need to configure the Request URL that the data payloads will be pushed to. This URL needs to be verified first, as outlined in the Events API docs.
  • Then you’ll add some individual event subscriptions. For our bot, we’re interested in the Bot Events, so click on the Add Bot User Event button.
  • There are lots of different event types you could add, but for the purposes of our tutorial let’s add two event subscriptions — app_mention which sends events when someone mentions your bot, and message.channels which sends events when a new message is posted in a public channel.
  • Click the Save Changes buttons

Good news! Your bot is looking more and more life-like, and now it’s ready to find a home.

3. Installing the bot to a workspace

A bot user is added to a workspace by installing the app that the bot is associated with. Once you do, you’ll get a bot token that is imbued with the bot scope. This token can be used with a subset of Web API methods that we’ll discuss later.

If you had already installed your app in the past, you’ll need to reinstall to grant the additional bot scope. The process is the same either way:

  • On your app’s settings page again, click the Install App settings item in the navigation menu.
  • On this page, click a button marked Install App to your Workspace. If you had already installed your app, the button to click will instead be marked Reinstall App.
  • You’ll see a permissions authorization page, where you should click Authorize. Your app is now installed to that workspace, but you still need to invite it into individual channels.
  • You should also invite the bot to a public channel somewhere in your workspace.

Once installed, you will have generated a bot token that you should store for use later on — you can find it in your app’s settings under Install App > Bot User OAuth Access Token.

Bot tokens can also be generated using the OAuth install flow if you are distributing your app beyond your own workspace.

Your bot should now be happily dwelling in the channel picked during the install process. It will be listening out for users posting in that channel, and for posted messages that mention the bot. Now you need to tell it what to do when it hears something.

4. Handling events

In a previous step, we configured the event subscriptions for your app, but now we have to actually do something with the data that will be sent with each event.

Let’s imagine a simple conversational bot that responds to being mentioned by sending a couple of follow up messages:

There are 4 events triggered in this conversation: the first is an app_mention event from the first message that mentions the bot; the next three are message events for each of the messages posted by Johnny.

Our bot will need to be able to interpret each event and respond accordingly.

We’ve avoided showing you any specific code up until now, but in the following steps we’re going to explain the process and then show very simplified Express/Node.js examples of what your app logic should look like. These examples translate readily into most modern programming languages.

Receiving events

The first thing we need to do is create some app code that will correctly receive the events.

Each event will trigger a request, containing a JSON payload, sent to your configured Request URL. The Events API docs contain a full description of the shape of this JSON, and the reference for app_mention and the message.channels contain any details specific to each event type.

Your app has to be able to receive and parse this JSON, and then send an immediate confirmation response to each event request, as described in the Events API docs.

Here’s how we might build our code for receiving events:

Now that you’ve written code to handle an event, you can think about how to respond in a ‘bot-like’ way.

Responding to mentions using the Web API

For a bot, being mentioned is usually the triggering event for a conversation, just as a human will respond when they hear their name.

Your app code should use the type field inside the event payload to spot these app_mention events, and differentiate them from any other events it might receive.

In addition, you don’t want to respond to every mention, only the ones that are actually intended to trigger the «tell a joke» flow.

To do that, use the text field from the event payload, which contains the text of the message that the mention was contained in. When text mentions the bot and includes the words «tell me a joke», the bot will respond; otherwise it’ll just stay quiet.

Here’s what the example code might look like with this kind of logic:

With the call to chat.postMessage , the first line of the joke is sent:

To send this, your app should use that API method with the token you stored earlier. Here’s an example request:

You can read the API method reference for more info on building this request. You can, of course, use all the special formatting, attachments, and interactive components available for messages, but for now keep it simple.

So, your bot has uttered those first magical words, and you can assume that the user will reply with the standard «Who’s there?» response. Let’s find out how to keep the joke going.

Responding to other messages

As we said before, the flow we’re describing contains an app_mention event followed by three message events. In order to identify the differences between those three messages, the app logic must become a bit more complex.

The first thing you need to do is use the type field inside the event payload to look for these message events.

Next, use the text of the message in the event payload to decide which kind of response your bot should make.

Again, let’s assume the pattern of ‘knock, knock’ jokes — the first user response is always «Who’s there?», and the second user response is always «____ who?». So, you can check for messages that include these words, and use the right bot response for each. If you see any messages that don’t include either of these phrases, ignore them.

Added to the code from previous steps you’ll have something like this:

Congratulations, your first bot is now alive and talking! You should now be able to go to the channel you installed the bot into and strike up this conversation with it. Remember to laugh politely when it tells you the punchline.

Your next steps should involve adding some more complexity to your bot to make it useful.

Making more complex bots


In the steps above, we made a lot of assumptions of simplicity. For example, we expected that users would respond with a very specific spelling, we assumed a test environment where there were no other conversations happening, and so on.

For a real bot in production, some of these assumptions would break the behavior of the bot. So let’s cover some situations that you should address for your own bots — think of these as best practices rather than specific instructions to follow.

Tracking conversations

In our example bot, we’ve used a mention as the triggering point for a specific conversation, but you’ll notice that your bot will still respond if you skip some of the steps — for example if you type Who’s there? , your bot will respond to this message with A bot user , even if you didn’t mention the bot or start at the beginning of the conversation.

A solution to this might involve tracking the beginning of a conversation, the participants involved, and the progress through the flow. For example, when the user first mentions the bot, a database entry is created that identifies that user and the open workflow with them.

As the user progresses through the flow, the database records this, and the user is unable to repeat earlier steps in the conversation (unless of course that is a desired behavior). Once the workflow is completed, the database entry is also marked as complete, and the bot waits for another mention before starting anew.

Threaded messages

Be aware that a user might choose to reply to your bot’s messages in a thread rather than at the channel-level. Your bot will still receive message events for these threaded replies, but you will have to add some extra logic to ensure that your bot responds to the user in the relevant location.

Check out the Threading Messages docs for more information on how to spot the difference between messages and threaded messages.

Variations in phrasing

Because your bot will be interacting with humans, it’s unlikely that you can expect consistent spelling and phrasing across messages from different people that might be trying to invoke the same thing. For example, our simple example bot used the phrase tell me a joke to trigger the start of the workflow, but at a very basic level a user might also try typing what’s a good joke? or make me laugh .

Your bot can get more complex by broadening its understanding of natural language queries to capture a wider range of potential trigger phrases. Alternatively you can be more prescriptive about the exact phrasing to use, and provide user education to train correct usage.

Integrating with other services

The real magic of a bot comes when it is connected with external services, providing a seamless conversational interface for them from within Slack.

There’s a huge range of possibilities for what your bot could do, so it might help to start with a great resource like the Botkit Community.

Limitations

Like other APIs and integrations, bot users are free. Unlike regular users, the actions they can perform are somewhat limited. For workspaces on the Free plan, each bot user counts as a separate integration.

API methods available to bots

Bot Users, and bot tokens, can be used with a slightly restricted set of Web API methods. These methods are shown below:

Подключение бота к Slack Connect a bot to Slack

Вы можете настроить взаимодействие бота с другими пользователями с помощью программы для обмена сообщениями Slack. You can configure your bot to communicate with people using the Slack messaging app.

Создание приложения Slack для бота Create a Slack Application for your bot

Войдите в Slack и перейдите на канал для создания приложения Slack. Log into Slack and then go to create a Slack application channel.

Создание приложения и назначение группы разработки Slack Create an app and assign a Development Slack team

Введите имя приложения и выберите группу разработчиков Slack. Enter an App Name and select a Development Slack Team. Если вы еще не является членом команды разработчиков Slack, создайте ее или присоединитесь к ней. If you are not already a member of a Development Slack Team, create or join one.

Нажмите кнопку Create App (Создать приложение). Click Create App. Slack создаст приложение, а также идентификатор и секрет клиента. Slack will create your app and generate a Client ID and Client Secret.

Добавление нового URL-адреса перенаправления Add a new Redirect URL

Далее добавьте новый URL-адрес перенаправления. Next you will add a new Redirect URL.

  1. Выберите вкладку OAuth & Permissions (OAuth и разрешения). Select the OAuth & Permissions tab.
  2. Щелкните Add a new Redirect URL (Добавить новый URL-адрес перенаправления). Click Add a new Redirect URL.
  3. Укажите https://slack.botframework.com. Enter https://slack.botframework.com.
  4. Щелкните Добавить. Click Add.
  5. Нажмите кнопку Save URLs (Сохранить URL-адреса). Click Save URLs.

Создание пользователя бота Slack Create a Slack Bot User

Добавив пользователя бота, можно назначить боту имя и выбрать, будет ли он всегда находиться в сети. Adding a Bot User allows you to assign a username for your bot and choose whether it is always shown as online.

  1. Выберите вкладку Bot Users (Пользователи бота). Select the Bot Users tab.
  2. Щелкните Add a Bot User (Добавить пользователя бота). Click Add a Bot User.

Щелкните Add a Bot User (Добавить пользователя бота) для проверки параметров, выберите для параметра Always Show My Bot as Online (Бот постоянно в сети) значение Вкл. и нажмите кнопку Сохранить изменения. Click Add Bot User to validate your settings, click Always Show My Bot as Online to On, and then click Save Changes.

Подписка на события бота Subscribe to Bot Events

Выполните следующие действия для подписки на шесть определенных событий бота. Follow these steps to subscribe to six particular bot events. При этом приложение будет получать уведомления о действиях пользователя по указанному вами URL-адресу. By subscribing to bot events, your app will be notified of user activities at the URL you specify.

Дескриптор бота — это его имя. Your bot handle is the name of your bot. Для получения дескриптора бота перейдите по адресу https://dev.botframework.com/bots, выберите бот и запишите имя этого бота. To find a bot’s handle, visit https://dev.botframework.com/bots, choose a bot, and record the name of the bot.

Выберите вкладку Подписки на события. Select the Event Subscriptions tab.

Выберите для параметра Enable Events (Включить события) значение Вкл. Click Enable Events to On.

В поле URL-адрес запроса введите значение https://slack.botframework.com/api/Events/ , где обозначает дескриптор бота без фигурных скобок. In Request URL, enter https://slack.botframework.com/api/Events/ , where is your bot handle, without the braces. Для этого примера используется дескриптор ContosoBot. The bot handle used in this example is ContosoBot.

В разделе Subscribe to Bot Events (Подписаться на события ботов) щелкните Add Bot User Event (Добавить пользовательское событие бота). In Subscribe to Bot Events, click Add Bot User Event.

В списке событий выберите следующие шесть типов событий: In the list of events, select these six event types:

  • member_joined_channel
  • member_left_channel
  • message.channels
  • message.groups
  • message.im
  • message.mpim

Нажмите кнопку Сохранить изменения. Click Save Changes.

Добавление и настройка интерактивных сообщений (необязательно) Add and Configure Interactive Messages (optional)

Если ваш бот будет использовать функции Slack, например кнопки, выполните следующие действия. If your bot will use Slack-specific functionality such as buttons, follow these steps:

  1. Выберите вкладку Interactive Components (Интерактивные компоненты) и щелкните Enable Interactive Components (Включить интерактивные компоненты). Select the Interactive Components tab and click Enable Interactive Components.
  2. Введите https://slack.botframework.com/api/Actions в качестве URL-адреса запроса. Enter https://slack.botframework.com/api/Actions as the Request URL.
  3. Нажмите кнопку Save changes (Сохранить изменения). Click the Save changes button.

Получение учетных данных Gather credentials

Выберите вкладку Основные сведения и перейдите к разделу Учетные данные приложения. Select the Basic Information tab and scroll to the App Credentials section. Вы увидите идентификатор клиента, секрет клиента и токен проверки, требуемые для настройки бота Slack. The Client ID, Client Secret, and Verification Token required for configuration of your Slack bot are displayed.

Отправка учетных данных Submit credentials

В отдельном окне браузера вернитесь на сайт Bot Framework https://dev.botframework.com/ . In a separate browser window, return to the Bot Framework site at https://dev.botframework.com/ .

  1. Выберите My bots (Мои боты) и выберите бот, который нужно подключить к Slack. Select My bots and choose the Bot that you want to connect to Slack.
  2. В разделе Channels (Каналы) щелкните значок Slack. In the Channels section, click the Slack icon.
  3. В разделе Enter your Slack credentials (Ввод учетных данных Slack) вставьте учетные данные приложения с веб-сайта Slack в соответствующие поля. In the Enter your Slack credentials section, paste the App Credentials from the Slack website into the appropriate fields.
  4. URL-адрес целевой страницы является необязательным. The Landing Page URL is optional. Его можно опустить или изменить. You may omit or change it.
  5. Выберите команду Сохранить. Click Save.

Следуйте инструкциям, чтобы авторизовать доступ приложения Slack к команде разработчиков Slack. Follow the instructions to authorize your Slack app’s access to your Development Slack Team.

Включение бота Enable the bot

На странице Configure Slack (Настройка Slack) убедитесь, что ползунок возле кнопки «Сохранить» установлен в положение Включено. On the Configure Slack page, confirm the slider by the Save button is set to Enabled. Бот настроен для взаимодействия с пользователями в Slack. Your bot is configured to communicate with users in Slack.

Создание кнопки Add to Slack (Добавить в Slack) Create an Add to Slack button

Slack предоставляет HTML-код, с помощью которого можно упростить поиск вашего бота в разделе Add the Slack button (Создание кнопки «Добавить в Slack») на этой странице. Slack provides HTML you can use to help Slack users find your bot in the Add the Slack button section of this page. Чтобы использовать этот HTML-код с ботом, замените значение href (начинается с https:// ) URL-адресом, найденным в параметрах канала Slack вашего бота. To use this HTML with your bot, replace the href value (begins with https:// ) with the URL found in your bot’s Slack channel settings. Выполните следующие действия, чтобы получить URL-адрес на замену. Follow these steps to get the replacement URL.

  1. На странице https://dev.botframework.com/bots щелкните свой бот. On https://dev.botframework.com/bots, click your bot.
  2. Выберите Channels (Каналы), щелкните правой кнопкой мыши запись с именем Slack и выберите пункт Copy link (Копировать ссылку). Click Channels, right-click the entry named Slack, and click Copy link. Этот URL-адрес теперь находится в буфере обмена. This URL is now in your clipboard.
  3. Вставьте его из буфера обмена в HTML-код, предоставленный для кнопки Slack. Paste this URL from your clipboard into the HTML provided for the Slack button. Этот URL-адрес заменяет значение href, предоставленное Slack для этого бота. This URL replaces the href value provided by Slack for this bot.

Авторизованные пользователи могут нажать кнопку Add to Slack (Добавить в Slack), предоставленную этим измененным HTML, для доступа к боту в Slack. Authorized users can click the Add to Slack button provided by this modified HTML to reach your bot on Slack.

Также предоставляется как адаптер Also available as an adapter

Этот канал также предоставляется как адаптер. This channel is also available as an adapter. См. подробнее о выборе между адаптером и каналом в списке доступных адаптеров. To help you choose between an adapter and a channel, see Currently available adapters.

How to Build Your Own Slack Bot

You’re discussing a problem with your team and need a link to the bug to show them exactly what you’re talking about. You could open your browser, search for the bug, and, once found, paste it into your conversation. Or you could type the bug’s name in your chat app, and a bot could find the bug info and share it in the conversation automatically. Perhaps you need to find someone’s contact info and then send them an invoice. Just type their name, and a bot can do both in seconds.

Bots are handy little assistants that hang out in your app, wait for commands, then find or create the thing you need. They’re another way to use your favorite apps without opening them. They’re the big new thing—a core part of Slack, Facebook Messenger, and Telegram’s newest features.

And turns out, bots are simple enough for anyone to make. Here’s how you can make a Slack Bot to do anything you want in a few minutes without any coding—along with a dozen examples of bots that real teams are using today, and a Slack bot cheat sheet for a handy reference to help build your own bots.

This article focuses on making bots in team chat app Slack, but you can also make bots in similar ways in many other chat apps, in social networks like Twitter, through SMS, and more.

Originally published 2 August 2020; updated 31 May 2020 with details about Slack’s new app editor and 1 March 2020 with updated Zapier webhooks details.

What Is a Bot?

Robots can drive cars across Mars, clean nuclear reactors, and cut precise holes in your smartphone’s metal frame.

Мастер Йода рекомендует:  Раскрутка сайта - с чего начать

Bots are a little different. They live in your apps, not in the physical world. Rather than working assembly lines, they focus processing power on looking up facts and sending notifications when you need them. They’re tiny programs without buttons or icons. Instead of clicking a search button, you’ll type a command like /giphy volcano to instruct the bot to find what you’re looking for (a volcano gif from Giphy, in this case).

Bots are a buzzword right now, the big new thing in everything from Slack to Alexa. And yet, they’re not exactly that new of an idea. Google, in many ways, is a bot that can answer lots of questions. Search for current time SF , and you’ll get the current time in San Francisco just by typing.

DOS-era programs also behaved much like a bot. Open Terminal on your Mac and type uptime , or open Command Prompt on your PC and type net statistics server , and an age-old bot will tell you how long your computer’s been turned on.


Handy, right? Instead of finding the right app and clicking the right button, you type in a quick command and get what you want.

Perhaps you don’t want to use Terminal all day—and you want something more personalized than Google offers. Say you want to find internal contact info, or make an invoice, or decide where to grab lunch as a team. You don’t need a new app, and you don’t need to open Google. All you need is your own bot, inside an app you’re already using.

What Do You Need to Build a Slack Bot?

You only need 3 things to build a bot:

  • A place to type your text
  • A bot to read your text
  • An app to do something with your text

All bots need to start is some text—the text you type that tells them what to do. That could be a Tweet (with Twitter bots that reply with flight status, say), a text message (like the y or n messages you send to your carrier to change your phone plan), or perhaps an email. Chat apps are an especially perfect place for bots. Odds are you already use a chat app—and they include both a text box to type commands into and a conversation view to see what the bot replies.

Team chat app Slack is the perfect place to build bots for anything you need—and what we’ll focus on in this tutorial. It’s free to start using, and it’s a tool where you likely already discuss ideas and projects with your team—with a text box that’s perfect for sending commands to your bot.

Bots come built into Slack. We’ll look at how to set them up in a minute, but here are the basics: Essentially, you give the bot a name, tell it where to watch, and when you type a specific word or symbol, the bot will start listening and then send that text to your app.

Apps are the tricky part. They’re famously difficult to build, and are the one step that might keep you from building your own bots. But they don’t have to be that difficult. Instead of coding your own app, you could use pre-built integrations from Zapier instead.

Zapier is a tool that connects your apps without any complicated code, so you can pass data between them. Using Zaps, or integrations inside Zapier, you can connect Slack to hundreds of other apps just by clicking through a simple wizard. For example, once you build a Slack Zap, it can watch for commands in any chat channel and kick off a workflow in another app, or track down info in one tool and send it back to Slack. That’s how you can build the most powerful bots in your own Zapier-powered slash commands, as we’ll walk you through below.

So let’s use all 3, and see what type of bots we can build.

→ Learn more about Slack in our Slack Review.

What Types of Slack Bots Can I Build?

The first time you open Slack, you’ll be greeted by a friendly Slackbot that asks your name and time zone. Type in the replies, and your account will be personalized without a click, like magic.

You can then harness that magic yourself with your own bots. These come in three varieties:

Slackbot Responses

The simplest bots come built into your Slack settings. You add a phrase for the Slackbot to watch for, and then tell it how to respond.

Say you want a simple way to find the security code for your office: just tell Slackbot to watch for messages that say office security code , then have it respond with the number. You could make more whimsical prank bots that send GIFs—or more serious bots to share important phone numbers, email addresses, or other helpful info.

To make a Slackbot Response, just go to slack.com/customize/slackbot and add the phrase and response you want. These will automatically work in any channel other than your personal Slackbot channel.

Or, you can make your own custom bots in Slack that watch Slack for text and automatically reply, either with the bot API or Zapier. We’ll look at that below.

Notification Bots

Notification bots are the next easiest Slackbot to make. Instead of watching Slack for a phrase you type, they watch another app for an update and send it to Slack.

They look like another user in Slack, with their own name and icon. They’ll show up every so often when there’s something new—a news update, new document, or trending hashtag, perhaps—and post it to your Slack channels.

There are dozens of notification bots for social networks, news, and more in the Slack App Directory. Or, you can build your own notification bots with Zapier—perhaps even using a pre-made Slack integration that you can set up in a few clicks.

We’ll look at how to make these in just a minute—but here are some popular Slack integrations if you can’t wait.

Slash Commands

If you’re looking for a bot that you can summon at will, though, slash commands are your best bet. Unlike notification-based bots, slash command bots wait for your signal, then perform some sort of task based on context that you provide.

You trigger them by typing a / followed by their name ( /giphy , say, for the Giphy bot), and then type in a command. The bot will then find what you’re looking for and post it back to Slack in a reply.

Bots can do just about anything you want: start a new meeting, compute a value, do research, and more. For that, you’ll need to either code your own app or use Zapier integrations to connect Slack to over 700 of your favorite apps.

Slack also has a number of built-in bots to mark your status as away, streamline your notifications, and more. Learn more about those in our roundup of the best hidden tools in Slack.

How to Build a Bot in Slack

Now that you know the type of bots you can build, it’s time to make your own. Let’s look at how you can make customized bots in Slack for replies, notifications, and commands—all without writing a line of code.

Tip: Be sure to download our cheat sheet for a handy reference while building your bot.

Download Slack Bot Cheat Sheet

  • Download in PDF format(618.5 KB)

Building a Slack Reply Bot

Slackbot’s default reply tool is rather limited, since it can only post the same response every time. What if you want a customized response—or perhaps a random response—each time?

For that, a Zapier-powered reply bot is your best option. First you’ll need to create a Zapier account or log into your Zapier account.

Then, click the Make a Zap button in the top right corner, and select Slack as your Trigger app. On the next page, have your Zap watch Slack for a new message posted anywhere. Alternately, if you want this bot to only work in one channel, you could have Zapier watch that specific channel.

Then you’ll need a filter to watch for a specific term—otherwise, your bot would run every time anything is posted to Slack. Add another action to your Zap from the Add a Step button on the left, and choose the Filter option. In its settings, have it watch the Text field for the term you want.

If you want the bot to run whenever those words are posted to Slack, then have the filter watch for (Text) Contains . Otherwise, if you want it to only watch for that specific phrase on its own, have the filter watch for (Text) Exactly matches .

Then, you can add your reply, creating a basic bot. Just add another step to your Zap, selecting the Slack app and the Send Channel Message action. There, in the Channel field, select «Choose a custom value» and then select the channel name from your original Slack message so the reply will end up in the same spot.

→ Learn more about filters in our Zapier Filter guide.

All that’s left is to type in the message you want to post in the «Message Text» box. Scroll on down, and you can add a name and icon to your bot—or have it post to Slack using your name, if you want. Save and turn on your Zap, and it’ll send your customized message every time.

For something more customized, though, try a Formatter action before your bot’s reply. Formatter is a handy tool that can format your text, calculate values, choose random values from a list, and more.

Say you want to make a birthday bot that sends a random GIF from a list whenever someone says «Happy birthday!» Our filter above is already watching for the correct phrase—all we need now is the Pick from list Formatter, and a few GIFs.

To add the Formatter action, click the Continue button or + on the left sidebar of your Zap to add a new action, and choose the Formatter by Zapier app. Then, select the Pick from list formatter in the Transform field, and enter the GIF links in the Input fields.

With that done, repeat those steps, only this time select Slack as your action app, and choose its Send Channel Message action. Then, in the message text box, add your birthday message and click the plus button on the right to add your random GIF from Formatter. Turn your Zap on, and the next time someone says «happy birthday» they’ll get surprised with one of your GIFs.

Building a Slack Notification Bot

Notification bots are even easier to build in Zapier. All you need is an app or site to watch for notifications, and Zapier can automatically send those to Slack for you.

Say you want to be notified in Slack whenever new tasks are added to your Trello kanban board. First make a new Zap for Trello–with the «Make a Zap with Trello» button. Then, in the Choose Trigger step, select New Card to have it watch Trello for new cards on the board you want to watch.

Next, click the plus sign + to add a Slack action. Now you can set the Zap to send a message either to a channel or as a direct message to anyone on your team. You can customize the message with any text you want. Click the + icon on the right of the message text field in Zapier to add info from Trello about the card, such its name, link, description, and more.

Tip: Slack has its own formatting rules for things such as links, bolded text, and block quotes. You’ll want to familiarize yourself with these so that your messages come out looking beautiful.

You can quickly make Slack notification bots for any of the 700+ apps that connect to Zapier, or with any site that uses RSS. Here are some popular integrations to get started with in a few clicks:

Building a Slack Slash Command Bot

Now you’re ready to build the most advanced bots in Slack: slash commands. They’re the bots that wait for a command and then do whatever you asked. Make a document, find an email address, start a call, log records–you can make a bot for that and more.

It all starts by adding a new app to your Slack account. Go to api.slack.com/apps, select Create New App, enter a name for your app, and select the correct Slack account where you want to use the new Slack bot.

Slack will then show some options to add features to your app. You can add bot users, interactive messages, and more—but each of those require coding. Instead, we’re going to select the Slash Commands button. Click Create New Command, then it’s time to set your bot up.

First, add a command with a slash in front of it—perhaps /contact if you want to look up contact info, /weather to build a weather bot, or anything else that fits your needs. You can then add a short description and usage hint.

Note: If your team already has a command with the name you picked, Slack will prompt you to choose a different name.

We skipped one field—the Request URL. Here, you’ll add a Webhook URL where Slack will send the data you typed to the command. You can use that to code your own app, pulling out the text, username, and other data from Slack from the webhook.

We’re going to build our bot without coding—so we’ll use Zapier’s Webhook integration to capture the data from Slack and put it to work. Let’s grab that URL first.

Tip: Wait: What are webhooks? Glad you asked. They’re essentially notification messages sent to a unique URL. Here’s a quick guide to webhooks to help you learn how to use them.

In a new tab or window, make a new Zap using Zapier’s Webhooks app. Select Catch Hook when setting up the Webhook integration, click Continue on the options (you don’t need to add anything here), then check the Silent Mode box and copy the Webhook link you’ll see in the testing page.

With that Webhook link copied, go back to your Slack slash command’s configuration page from before and paste the link into the Request URL field—and then save your settings.

Now it’s time to test your slash command so we can build the rest of its Zapier integration. Just open Slack, type in your command followed by text you’d like to use in the bot. I’m building a bot that will find contacts in Google Contacts and send me their email address in Slack, so I’ll enter a name that I can use to search Google Contacts.

Note: If you don’t check the Silent Mode box on the Webhooks’ settings page in Zapier, you’ll see some confirmation text when you run the bot in Slack—don’t worry, that’s just text that Slack will send to confirm the bot was triggered correctly. You can simply ignore it, or can go back and add /silent/ to the end of your Webhooks URL in Slack’s settings to turn on Silent Mode.

It’s time to make our bot smart. Go back to the tab where you’d opened Zapier, and click the OK I did this button for your webhook step. Zapier will find the data from your slash command, and you’ll be ready to put it to work.

Now, it’s time to use the data. Here are some quick ideas to try with Zapier integrations:

  • Use Formatter to split your text into sections, format the text, calculate numbers, and more.
  • Use Searches and Lookups to find info in your favorite apps—perhaps to find an entry in a spreadsheet, a contact in a CRM, a customer from your payment app, and more. There are also searches in apps like Giphy that can find info online based on your query.
  • Use standard Zapier Actions to save info to your apps—say to add a new contact, create a document, log time spent on a task, and more.

Let’s try using a search to find a contact from Google Contacts account. Add an action to the Zap, select Google Contact, then use the Find Contact action. Have it search by name, then select the text from your Slash Action as the search query.

Now that Zapier’s found your contact, it’s time to send it back to Slack. Just add another action to your Zap, and select the Send Channel Message action. Instead of selecting a specific Slack Channel to post the message to, choose Use a Custom Value at the bottom of the channel list, then use the Channel ID field from your webhook to select the channel where the slash command was used.

All you need to do now is create your message. Click the + icon beside the Message Text field to add any info you found from the Zapier search. Then, customize the bot, adding the same name and icon image as you added to Slack previously.


Test the Zap, and you’ll get the response in Slack you wanted.

Now, anytime you need a contact—or whatever you built your bot for—just type your slash command followed by the text you need to use, and Zapier will do the work for you automatically.

Want to build a more advanced bot? Try adding extra steps to your Zap—perhaps to create a template document and then post it to Slack—or use Code Steps to create advanced bots without having to code a full app.

Or, for the most advanced bots, try using Named Variables to gather more than one text item at once. Just decide what you want to gather with the bot, and a standardized name for each item, then write them followed by parentheses with the values you want. For example, say you want to gather a name and email in your bot. In Slack, type Name(Bob Smith) Email(bob@gmail.com) , and Zapier will recognize each as a separate item you can use in subsequent actions.

Then, when you build your Zap, you can select the Name and Email fields individually to add them as a new contact in Google Contacts.

With those powerful tools, combined with the hundreds of apps that connect to Zapier, you can build bots that do anything you want.

Example Bots That Help Teams Get Work Done From Slack

You could make a bot for anything—but what would actually be a useful bot for your team?

On the Zapier team, we have a number of bots both for play and productivity. The oldest slash command on our account is a GoToMeeting integration: Type /gtm anywhere in our Slack, and a bot uses Zapier to make a new GoToMeeting link and share it in the conversation for a quick way to jump on a call with team members.

Need to reserve a server for testing? /reserve does that in Zapier’s Slack. /afk lets us tell the team if we’ll be out of office like those old AIM away messages, /compute finds answers from Wolfram|Alpha, and /random gives us an easy way to make decisions with random numbers. And, when it’s time to unwind, /spyfall starts a text-based game of Spyfall using direct messages to tell each player their role.

But that only scratches the surface of what bots can do in Slack. Here are some other great Zapier-powered bots for Slack—ones that just might fit needs your team has, too.

Write Invoices and Emails

Tired of writing the same emails over and over? The Billfixers team was, too, so they built a bot to write emails.

«The need that prompted both of them was trying to find ways to increase our efficiency instead of doing things by hand, but without having to add a bunch more applications to our workflow,» says Billfixers co-founder Ben Kurland. «It was just time on our end that we weren’t actually using to help our customer, just to do what was essentially data entry.»

So, when they need to tell a customer that they just saved them money on a bill or need to send along an invoice, they can now send that person’s name to their bot. It finds their info in SalesforceIQ, uses some code to calculate the savings, creates a draft email in Gmail, then shares it to Slack. «From there, a human can add finishing touches and spend their time adding meaningful interaction with our clients, rather than having to act as a robot themselves,» says Kurland.

That worked so well, they also built another bot to create invoices in Freshbooks right from Slack.

Find Email Addresses and Other Data

Google is great for web searches—but when you need to find a contact’s email or a specific item in your database, it’s often far harder to find what you need. You have to remember which app to check, open that app, search, and finally find what you’re looking for.

Or, you could just use bots in Slack to help with all of your searches, as the 90 Minute Books team does.

Their set of search bots started out with a $whois bot built by co-founder Stuart Bell. You post someone’s email address to this bot, and it searches FullContact then returns their full contact info to Slack.

They then added a bot to shorten links, and another to generate a Book ID for new book projects. And when they need more info about a book, the $gogo bot will find all of the info about a book project from its ID.

«It gives people visibility without needing access,» says Bell. «And even for the team that do have access, a quick check often saves them having to log in to a different tool.

Choose Lunch Destinations

«What’s for lunch?» is a question everyone’s asked—and when it’s time to have a team lunch, it’s a question that’s hard to solve.

«Lunch is a serious matter, with Livestorm being French,» says CEO Gilles Bertaux. «We usually spend a lot of time looking for a place and then debate about it. So we thought it would be nice to have a little something that could help us decide and experience new meals.»

And so, they built a food bot with Zapier and Slack. They scraped the best lunch options with delivery near their office from Yelp using Import.io, and saved them to a Google Sheets spreadsheet. Then, with a Schedule Zap, they have the bot run at the same time every day, choosing a random restaurant from the spreadsheet and posting it to Slack.

It gave them handy food recommendations right when they needed them—and has inspired them to make a better curated database for more customized lunch recommendations than Yelp’s top listings.

Find Bug Info Automatically

Bots even make sure the apps for shows like The Voice UK and Britan’s Got Talent work perfectly. Tellybug, the team behind those and other tools to make TV shows engaging, wanted a simple way to collaborate on bug reports right from Slack.

«People would mention a bug number in Slack (or on a call) and then everyone would have to go search to look up the bug,» says Tellybug CTO Malcolm Box. «This seemed automatable.»

So, with a Zapier-powered Slack reply bot, the Tellybug team built a Zap that watches Slack for mentions of bugs. Whenever it finds one, it searches for the bug in Fogbugz, their bug tracking app. Then, with some filters and code to pull out the relevant info, the bot posts the correct info about the bug back into Slack.

«The bot’s made it much easier to have discussions about bugs and to keep everyone on the same page when doing bug triage,» says Box.

Run Standup Meetings in Chat

You need to know what each person on your team is working on, but you might not need to waste time with a full meeting. Instead, you could rely on a bot like the Robots and Pencils team does.

Each weekday, their bot posts a Standup Time reminder with questions about what they’re working on. Each team member can then reply, using Zapier Named Variables to list replies to each question. A Zap then saves each response to a Google Sheets spreadsheet for a log of each virtual meeting. «From here I can put together some cool burndown charts based on other spreadsheets I have created,» writes product manager Ben Myers.

Add Tasks to Your To-do List

Or, if you just need a simple way to add tasks to your project, a bot can handle that, too. Parabol CEO Jordan Husney does just that with a bot, for a quick way to add tasks to Trello that come up during their Slack-powered standup meetings.

Once again using Named Variables in Zapier, he posts a new task to his jrtask bot, and Zapier turns that text into a new card in Trello. «Lowering the friction of capturing tasks means spending more time staying focused on the task in front of you,» writes Husney—which is exactly what his Trello and Slack bot does.

Remind Your Team to Submit Timesheets

Want to spend less time reminding your team about regular tasks—and want to make sure you don’t come across as nagging?

«I found myself often sending random timesheet reminder memes to my team, so I automated this,» says devPHASE lead developer Matt Healy. So, with a bit of PHP code to pull a random timesheet meme from Google Images, and a Zap to post that image along with a reminder into Slack, he automated that task away.

Then, as Healy says, «hilarity and timesheet completion ensues.»

For a more powerful workflow, you could make a companion timesheet tool similar to the standup meeting bot above that lets your team post their time logs to your time tracking app right from Slack.

Learn About Your Team Members

Automated Insights builds tools to turn data into stories automatically—and they wanted the same automated insights about their own team. So, during a team hackathon, director of customer experience Matt Nisonger and his team turned their employee directory into a bot.

«Our head of HR collects a lot of information about each employee’s personal interests, hobbies, etc., but never did anything with it,» says Nisonger. «That spawned the idea of using a Slack bot to learn interesting things about new and existing employees.»

With a Typeform for to survey the team, Google Sheets to save the data, and their own Wordsmith app to turn the data into stories, they had everything needed to build a bot.

Now, when a new team member joins the team, they’re asked to fill out the survey, and the bot shares info about the new team member in Slack. And if you ever want some trivia about someone on the team, just send their name to the bot and it’ll reply with a fun fact about them.

That’s only one of the many ways the Automated Insights team uses bots. «we probably have 10-20 various bots integrated with Slack, everything from Intercom to bug reporting to server status reporting,» says Nisonger. «Some are better than others, but overall they’ve been positive for productivity.»

Create Support Tickets Inside Conversations

Want to make sure problems are solved for your team as quickly as possible? You could build a bot for that, as the Business Insider team did.

«Our team’s main communication tool is Slack, and we wanted to make it super easy for anyone on the team to submit a ticket through Slack,» says Business Insider team member Kyle Dowley. All their team has to do is use their ticket bot and post the problem they’re having. That has Zapier check Google Sheets for that team member’s contact info, then uses it and the Slack message to create a ticket in Zendesk. When that’s done, the Zap sends that team member a direct message in Slack to let them know the ticket’s been created—and also gives them a link to the FAQ to perhaps help them find a solution on their own.

«For many people, using this bot is now the preferred method of submitting support requests to our team,» says Dowley. «It helps to make sure all support requests are in one place with better tracking and visibility.»

And it’s simple to use: you can ask other team members if they’re having the same problem, then turn the issue into a ticket right from the same Slack conversation.

Мастер Йода рекомендует:  Подходы языка Python - забавный пример оптимизации

Download a Slack Bot Cheat Sheet

Now that you know how to build a bot, it’s time to build your own. But you’ll need a way to keep track of each step to make sure you can make every bot you need.

Just check out the cheat sheet below—or download a PDF copy—to make sure you never forget how to build bots in Slack.

Download Slack Bot Cheat Sheet

  • Download in PDF format(618.5 KB)

Go Build Your Own Bots!

Building your own robot is difficult. You’d need motors, controllers, gears, and dozens of other parts—not to mention time to code the robot and get it working the way you want.

Bots? They only take a few minutes, and they’re free!

Just make a Zapier account, open Slack, and start building a robotic buddy who can lend you a hand. Or, try building a similar bot with Twitter, Discord, Telegram, SMS messages, or any other chat-like tool Zapier supports. Need a simpler way to make appointments, a filtered notification tool that doesn’t ding every minute, or a detailed workflow to build documents in a second? You can make a bot for that.

What will your bot do?

Made a great bot in Slack or another chat app? We’d love to hear about it in the comments below!

Want to build more tools without coding? Here’s how to build a prototype app with Zapier, along with a guide to building an app with just a form.

Honda Asimo robot photo by Satoru Fujiwara via Flickr.

Get Productivity Tips In Your Inbox

Learn about workflow, company building, and how to get things done.

“Zapier is the extra team member at our agency linking our systems together and managing the push and pull of data.”

Alex Minchin, Managing Partner at Zest

Build workflows with your apps.

Connect apps. Automate tasks. Get more done.

Как создать Slack бота для автоматизации задач

How to create a Slack bot to automate tasks for you

Создайте собственного виртуального помощника. Представьте, что вы можете взять какой-то процесс и можете заставить бота не только сделать его за вас, но и делать это идеально каждый раз. Не говоря уже о том, что ваш бот может работать 24 часа в сутки, часто выполнять задания намного быстрее, чем человек, и проверять обновления систем каждые несколько секунд вместо часов или дней. ака. идеальный сотрудник.


Почти все, что вы можете придумать. Вы ограничены только вашим творчеством. Скажем, клиент хочет знать свой баланс на своем счете. Они могут отправить вам электронное письмо, а вы им ответите. Или вы можете дать им команду в слаке, чтобы они могли получить их баланс, когда захотят.

Может быть, разработчику необходимо регистрировать время работы. Они могут войти в систему учета и вручную ввести это время, а затем отправить сообщение менеджеру проекта, чтобы они закончили свою задачу. Или. вы могли бы дать этому разработчику единую команду, которая будет выполнять все эти задачи для них.

Допустим, у вас есть компания, в которой сотрудники могут подавать заявки на покупку, если захотят. Они обычно заполняли какую-то форму, передают ее секретарю, который затем передает ее генеральному директору для принятия решения. Затем этот секретарь должен предоставить эту обратную связь сотруднику, который запросил покупку.

Секретарь также будет контролировать все запросы на покупку, чтобы, если генеральный директор забыл принять решение по одному из них, этот секретарь напомнит генеральному директору.

В этом курсе мы по существу собираемся запрограммировать весь этот поток, в первую очередь, превращая человеческую секретаршу в Slack-бота. Так что единственные люди, которые будут использовать эту систему, — это генеральный директор и сотрудник, делающий запрос на покупку.

Как мы экономим $5280 в год с помощью Slack

Slack — чрезвычайно успешный корпоративный мессенджер, реинкарнация бывшего некогда очень популярным IRC.

Популярность Slack в мире привела к тому, что многие-многие компании и стартапы подключили свое API к простому API Slack. И уже сегодня мы можем использовать прелести многочисленных сервисов из одного места. И делать это с комфортом.

Мы расскажем, как.

Statsbot

Мы искренне уважаем Google Analytics, но все же крайне неудобно заходить в их монструозный Дэшборд только для того, чтобы посмотреть, например, количество вчерашних юзеров.

Спасибо команде Statsbot за возможность использования такой вот магии:

Помимо заклинаний для Google Analytics, Statsbot также дружит с Mixpanel, Salesforce, предупреждает о неожиданных выбросах, доставляет аналитику по расписанию. Однозначный must-have.

TrackJS

JavaScript-ошибки портят UX, уменьшают конверсию и, порой, вовсе прогоняют юзеров с вашего проекта.

Мы в UI Market хотим молниеносно узнавать обо всех ошибках, моментально создавать тикеты в багтрекере и стараться сразу же закрывать их.

Если же у вас простой сайт, а не SPA (одностраничное приложение), JavaScript ошибок быть не должно в принципе. Если же они появляются — это красный сигнал к тому, что что-то пошло не так: отвалились скрипты или CDN, и нужно срочно ткнуть вебмастера в проблему носом (на нашей памяти, например, CDN jQuery — https://code.jquery.com/ — падал дважды, поэтому мы используем только свои CDN).

Менеджеры, руководители, ставьте себе Slack-бота https://trackjs.com и узнавайте первыми о критических неполадках.

Zapier

Команда https://zapier.com/ предлагает по-детски простой и гениальный сервис автоматизаций. Вы можете создавать цепочки действий следующего вида:

Через Zapier мы скрестили Slack с (в том числе) Gumroad не написав ни единой строчки кода. Теперь мы получаем моментальное уведомление о новых продажах: это повышает бодрость духа в команде и позволяет продажнику моментально найти клиента и усовершенствовать нашу картину ЦА.

Кстати, Zapier поддерживает большое количество API. Через него можно связать Gmail, Evernote, Dropbox, Saleforce, Github, WordPress, Trello. Большое поле для экспериментов!

Mention + Notify

Синонимичные проекты https://mention.com/ и https://notify.ly/ выполняют схожие функции: следят за упоминаниями вашего проекта (и за упоминаниями заданных вами ключевых слов) в соц. сетях: Twitter, Facebook, Instagram, Google+, Reddit, Product Hunt & Hacker News и шлепают уведомления.

Мы не стали заморачиваться и подключили и Mention, и Notify одновременно.

Вот как выглядит вывод информации от этой социальной парочки в специальный канал в Slack:

Задержка после упоминания бренда и новым уведомлением в канале — в среднем 2 минуты. Такая скорость позволяет молниеносно реагировать на социальные взаимодействия и обсуждения нас в сети, что колоссально увеличивает лояльность юзеров.

Chatra

Chatra — простой чатбокс для сайта. Чатра удобна, гибка и нее потрясающее API. Коненчо, Чатру можно сдружить со Slack:

Больше не нужно открывать окно в браузере, логиниться, куда-то нажимать: все чаты с юзерами под рукой.

Продажники прыгают от радости комфортного общения с клиентами. И самое главное, продажники экономят свое время, а значит, ваши деньги.

Экономия

В среднем наши каналы в Slack экономят команде около 30 минут в день.

30 минут * 22 рабочих дня в месяц * 12 месяцев * $40/час (средняя ставка членов команды) = $5280 экономии в год.

Конечно, цифра очень условная, но все же приятный эффект ускорения работы в тех или иных случаях ощутим.

Забавно, что на дворе уже вот-вот 2020 год: люди высадились на Марс, на Невском каждый второй носит умные очки и заряжает их от своей Теслы, искусственный интеллект лечит людей в больницах, но по-настоящему эффект присутствия инноваций, движение прогресса нам, простым трудягам с Озерков, позволяют почувствовать вот такие приятные мелочи.

Заключение

Это, конечно, далеко не полный список полезных Slack-ботов.

Расскажите в комментариях, каких Slack-ботов используйте вы в вашей команде. Также было бы интересно услышать оправдания от тех ребят, которые все еще сидят в Скайпе.

Как использовать Slackbot

В создании этой статьи участвовала наша опытная команда редакторов и исследователей, которые проверили ее на точность и полноту.

Количество источников, использованных в этой статье: 8. Вы найдете их список внизу страницы.

Команда контент-менеджеров wikiHow тщательно следит за работой редакторов, чтобы гарантировать соответствие каждой статьи нашим высоким стандартам качества.

Slackbot является чат-ботом, который дает пояснения о том, как пользоваться Slack. Этому боту можно отправить сообщение и получить ответ; также можно установить напоминания. Администраторы команд имеют возможность запрограммировать бот так, чтобы он отправлял определенный ответ, если сообщение содержит конкретное слово.

30 возможностей Slack, о которых вы не знали

Во многих компаниях Slack является главным инструментом для общения между сотрудниками. Сервис стал таким популярным, потому что он сочетает в себе одновременно простоту и огромное количество возможностей. Вот 30 полезных и неочевидных способов, как использовать мессенджер на полную мощность.

Поиск

1. Не тратьте время на поиски, Slack поможет найти нужную информацию с помощью расширенных поисковых модификаторов. Введите эти команды в поисковой строке:

  • «in:[канал]» – чтобы найти сообщения и файлы в определенном канале;
  • «in:[@имя]» – чтобы найти сообщения в беседе с определенным человеком;
  • «to:me» – чтобы найти сообщения, отправленные вам;
  • «from:[@имя]» – чтобы найти сообщения, отправленные определенным человеком;
  • «from:me» – чтобы найти сообщения, отправленные вами;
  • “has:link” – чтобы найти сообщения, которые содержат ссылку;
  • «has:reaction» – чтобы найти сообщения, которые получили реакции;
  • «before:[число]»; «after:[число]»; «on:[число/месяц/год]»; или «during:[месяц/год]» – чтобы найти сообщения за определенный период времени.

Чтобы сделать поиски еще более эффективными, объедините несколько команд. Например, «from:me has:link during:2020», чтобы найти отправленные вами в прошлом году сообщения со ссылками.

2. Хотите сузить поиск, чтобы не видеть информацию на ненужных каналах? Откройте настройки Slack (Preference) и зайдите в раздел «Search». Тут вы можете скрыть определенные каналы, чтобы они больше не появлялись в поиске.

3. Вы можете начать искать что-то сразу в поле ввода сообщения. Все, что вам нужно сделать, – напечатать «/s» и добавить то, что вам нужно найти.

4. Для оперативного поиска используйте Quick Switcher. Это быстро перенаправит вас на нужный канал, сообщение или команду. Просто нажмите Ctrl + K (для Windows) или Cmd + K (для Mac) и напечатайте первую букву канала или пользователя. Перед вами появится список вариантов.

5. Чтобы легче найти важные сообщения или файлы, прикрепите их к каналу или личному сообщению. Нажмите на меню (три точки) над сообщением и выберете «Pin to this conversation».

Просматривайте пропущенные сообщения и отмечайте как непрочитанное

6. Если вам нужно прочесть важное сообщение, но нет времени ответить, пометьте его как непрочитанное. Для этого просто нажмите на сообщение, удерживая клавишу Option (для Mac) или Alt (для Windows). В следующий раз, как только вы откроете это обсуждение, вы сразу же будете перенаправлены на то место, которое вы сохранили.

7. Используйте функцию All Unreads, чтобы быстро просматривать те сообщения, которые пропустили. Для начала убедитесь, что она активирована. Для этого нужно зайти в настройки в секцию Sidebar. Затем просто выберите раздел All Unreads сбоку окна, и перед вами будет список всех непрочитанных сообщений.

Спрячьте картинки и гифки

8. Если вам слишком тяжело сконцентрироваться, Slack может спрятать все картинки, мемы и гифки. Напечатайте «/collapse», чтобы скрыть изображения, и «/expand», чтобы снова их вернуть.

Отформатируйте текст внутри сообщения

9. Вы наверняка знаете о базовых командах текстового форматирования – например, звездочки с обеих сторон сообщения, чтобы выделить текст жирным шрифтом; но в приложении есть более расширенные опции, которые изменят внешний вид введенного вами текста. Например:

) с обеих сторон текста – и ваше сообщение будет зачеркнутым;

  • (>) перед текстом – и ваше сообщение будет оформлено как цитата;
  • (>>>) – оформит ваше сообщение как цитату, даже если там есть несколько абзацев;
  • (`) с обеих сторон текста – сделает его красным и поместит в рамку внутри строки;
  • («`) с обеих сторон текста – выделит его в отдельный блок, обведенный рамкой, и сделает его моноширинным.
  • 10. У Slack нет собственного инструмента для составления списков, но вы можете вставить (•) в сообщения. Для этого нажмите Alt + 7 (для Windows) или Option + 8 (для Mac).

    Процитируйте сообщение

    11. Если вы хотите сослаться на что-то, что когда-то написал ваш коллега, используйте неофициальную систему Slack для цитирования старых сообщений. Скопируйте ссылку сообщения – нажмите правой кнопкой мыши на текст (для Windows) или зажмите Ctrl и кликните на сообщение (для Mac) – и вставьте URL обратно в обсуждение.

    Разошлите уведомления всем в команде

    12. Нужно привлечь внимание всех? У Slack есть несколько команд, благодаря которым вы сможете оповестить определенные группы людей. Добавьте в сообщение «@everyone», и тогда вы уведомите каждого человека в команде, «@channel» уведомит всех из текущего канала, «@group» – всех из определенной группы и «@here» – всех, кто онлайн.

    Пошлите личное сообщение прямо из канала

    13. Вы можете отправить кому-то личное сообщение отовсюду – даже из канала или обсуждения. Просто напечатайте «/msg» или «/dm» в поле ввода и имя пользователя (которое начинается с символа «@»).

    Отредактируйте документ


    14. У Slack есть встроенный редактор документов. Нажмите на «+» рядом с полем ввода в любом обсуждении или канале, выберите Post и начните писать. Слева вы увидите инструменты для форматирования текста внутри абзаца. Когда вы закончили, нажмите на зеленую кнопку Share, чтобы выбрать, куда отправить этот документ и сможет ли кто-то другой его редактировать.

    Узнайте, как выглядят определенные цвета

    15. Работаете над чем-то, что связано с дизайном? Введите шестнадцатзначный код из 6 символов. Приложение добавит рядом с сообщением соответствующий образец цвета.

    Поделитесь экраном своего компьютера

    16. Вы также можете показывать всем экран своего компьютера. Другие даже смогут рисовать на вашем экране или управлять им, если вы захотите. Нажмите на иконку «телефон» внутри любого обсуждения и выберите Share your screen (кружок, внутри которого нарисован монитор компьютера, слева от кнопки End call).

    Проведите опрос

    17. Благодаря системе реакций можно легко проводить опросы внутри каналов. Задайте вопрос с несколькими вариантами ответа, к каждому варианту прикрепите эмодзи, а затем сразу же добавьте каждый эмодзи к сообщению в качестве реакции. Ваши сотрудники затем смогут нажать на реакцию, чтобы проголосовать, и Slack покажет вам общее количество очков.

    Пошлите уведомление о том, что опаздываете

    18. Проблемы с пунктуальностью? Одним нажатием на кнопку вы сможете оповестить любой канал или человека о том, что вы опаздываете. Как установить эту кнопку? Для начала скачайте приложение IFTTT (доступно для Android и iOS). После того как вы пройдете регистрацию, активируйте виджет отправки сообщений IFTTT для Slack и следуйте инструкциям.

    Настройте оповещения по ключевым словам

    19. Активируйте оповещения, которые будут приходить только тогда, когда кто-то употребит конкретное слово в сообщении. Так вы ничего не пропустите. Вы можете использовать слова, которые имеют прямое отношение к вашим текущим проектам. Вы даже можете выбрать разные вариации своего имени, чтобы Slack присылал вам уведомления, как только кто-то вас упомянет. Откройте раздел Notifications в настройках и выберите My Keywords.

    Отключите уведомления

    20. Отдохните от постоянных уведомлений и активируйте автоматический режим Do Not Disturb на определенный период времени. Нажмите на иконку «колокольчик» в секции Sidebar и выберите Do Not Disturb Schedule, чтобы активировать функцию.

    21. Если вы хотите отключить уведомления, напечатайте «/dnd» и время в поле ввода Slack. Вы можете написать, например: «/dnd until 3:00» или «/dnd for 20 minutes». Если вы устали, напишите, например «/dnd until tomorrow morning» (до завтрашнего утра). Если вы хотите обратно включить уведомления, просто напишите «/active».

    Настройте регулярные напоминания

    22. Система напоминаний Slack позволит вам поставить любые уведомления не только для себя, но и для другого человека или даже для канала в целом. Например, «/remind @milton.waddams Купить в понедельник новый степлер», «/remind #initech Каждую пятницу отправлять отчеты» или «/remind #remotestaff Каждый месяц отправлять отчеты о расходах».

    Настройте автоматическую рассылку до начала мероприятия

    23. Ваша команда пользуется Google Calendar? Slack может автоматически отправлять напоминания каналам, группам или отдельным людям до начала мероприятия. Официальный апплет Slack-Google Calendar IFTTT поможет вам это сделать.

    24. Функции напоминания доступны также для Google Sheets и Drive. Используя бесплатные скрипты Zapier – сервиса, похожего на IFTTT, – вы сможете получать уведомления Slack, когда файлы будут добавлены в общую папку или будут внесены изменения в строку таблицы. Просто заведите аккаунт в Zapier, а затем свяжите его с Google Sheets или Google Drive.

    Импортируйте и сохраняйте себе сообщения

    25. Забудьте о копипасте. Slack может предоставить вам уникальный адрес для простого импорта сообщений. Все сообщения, которые вы отправите на этот адрес, будут отображаться в вашем чате с Slackbot, и оттуда вы уже сможете поделиться ими с другими. Для этого настройках Slack в секции Messages & Media выберите Get a Forwarding Address.

    26. Помимо этого, Slackbot – личный консьерж вашего хранилища. Перетащите файлы, которые вы хотели бы сохранить, в чат с Slackbot, и вы сможете вернуться к ним в любой момент.

    Настройте RSS-ленту

    27. Одна из «пасхалок» Slack – RSS-агрегатор. Вы можете настроить приложение таким образом, чтобы оно показывало вам новые статьи вашего любимого медиаисточника. Найдите URl подписки и перед ним введите «/feed subscribe».

    28. Slack также может импортировать любую полезную информацию в канал или обсуждение. При помощи IFTTT и Zapier вы сможете настроить приложение таким образом, чтобы оно автоматически отправляло твиты, которые соответствуют конкретному поисковому запросу, или делилось статьями с Pocket, которые содержат определенный тег.

    Отправляйте команды в другие приложения

    29. Slack может отправлять актуальную информацию и другим сервисам. Приложение может автоматически переделать сообщение в задачу на Todoist или добавить его в список в Wunderlist. Просто активируйте нужный скрипт Zapier – и расслабьтесь, пока серверы будут делать всю работу.

    30. Slack может напрямую интегрироваться со сторонними приложениями и сервисами. Просмотрите список доступных интеграций Slack и выберите ту, которая подходит для вас.

    Материалы по теме:

    Нашли опечатку? Выделите текст и нажмите Ctrl + Enter

    Подключение бота к Slack Connect a bot to Slack

    Вы можете настроить взаимодействие бота с другими пользователями с помощью программы для обмена сообщениями Slack. You can configure your bot to communicate with people using the Slack messaging app.

    Создание приложения Slack для бота Create a Slack Application for your bot

    Войдите в Slack и перейдите на канал для создания приложения Slack. Log into Slack and then go to create a Slack application channel.

    Создание приложения и назначение группы разработки Slack Create an app and assign a Development Slack team

    Введите имя приложения и выберите группу разработчиков Slack. Enter an App Name and select a Development Slack Team. Если вы еще не является членом команды разработчиков Slack, создайте ее или присоединитесь к ней. If you are not already a member of a Development Slack Team, create or join one.

    Нажмите кнопку Create App (Создать приложение). Click Create App. Slack создаст приложение, а также идентификатор и секрет клиента. Slack will create your app and generate a Client ID and Client Secret.

    Добавление нового URL-адреса перенаправления Add a new Redirect URL

    Далее добавьте новый URL-адрес перенаправления. Next you will add a new Redirect URL.

    1. Выберите вкладку OAuth & Permissions (OAuth и разрешения). Select the OAuth & Permissions tab.
    2. Щелкните Add a new Redirect URL (Добавить новый URL-адрес перенаправления). Click Add a new Redirect URL.
    3. Укажите https://slack.botframework.com. Enter https://slack.botframework.com.
    4. Щелкните Добавить. Click Add.
    5. Нажмите кнопку Save URLs (Сохранить URL-адреса). Click Save URLs.

    Создание пользователя бота Slack Create a Slack Bot User

    Добавив пользователя бота, можно назначить боту имя и выбрать, будет ли он всегда находиться в сети. Adding a Bot User allows you to assign a username for your bot and choose whether it is always shown as online.

    1. Выберите вкладку Bot Users (Пользователи бота). Select the Bot Users tab.
    2. Щелкните Add a Bot User (Добавить пользователя бота). Click Add a Bot User.

    Щелкните Add a Bot User (Добавить пользователя бота) для проверки параметров, выберите для параметра Always Show My Bot as Online (Бот постоянно в сети) значение Вкл. и нажмите кнопку Сохранить изменения. Click Add Bot User to validate your settings, click Always Show My Bot as Online to On, and then click Save Changes.

    Подписка на события бота Subscribe to Bot Events

    Выполните следующие действия для подписки на шесть определенных событий бота. Follow these steps to subscribe to six particular bot events. При этом приложение будет получать уведомления о действиях пользователя по указанному вами URL-адресу. By subscribing to bot events, your app will be notified of user activities at the URL you specify.

    Дескриптор бота — это его имя. Your bot handle is the name of your bot. Для получения дескриптора бота перейдите по адресу https://dev.botframework.com/bots, выберите бот и запишите имя этого бота. To find a bot’s handle, visit https://dev.botframework.com/bots, choose a bot, and record the name of the bot.

    Выберите вкладку Подписки на события. Select the Event Subscriptions tab.

    Выберите для параметра Enable Events (Включить события) значение Вкл. Click Enable Events to On.

    В поле URL-адрес запроса введите значение https://slack.botframework.com/api/Events/ , где обозначает дескриптор бота без фигурных скобок. In Request URL, enter https://slack.botframework.com/api/Events/ , where is your bot handle, without the braces. Для этого примера используется дескриптор ContosoBot. The bot handle used in this example is ContosoBot.

    В разделе Subscribe to Bot Events (Подписаться на события ботов) щелкните Add Bot User Event (Добавить пользовательское событие бота). In Subscribe to Bot Events, click Add Bot User Event.

    В списке событий выберите следующие шесть типов событий: In the list of events, select these six event types:

    • member_joined_channel
    • member_left_channel
    • message.channels
    • message.groups
    • message.im
    • message.mpim

    Нажмите кнопку Сохранить изменения. Click Save Changes.

    Добавление и настройка интерактивных сообщений (необязательно) Add and Configure Interactive Messages (optional)

    Если ваш бот будет использовать функции Slack, например кнопки, выполните следующие действия. If your bot will use Slack-specific functionality such as buttons, follow these steps:

    1. Выберите вкладку Interactive Components (Интерактивные компоненты) и щелкните Enable Interactive Components (Включить интерактивные компоненты). Select the Interactive Components tab and click Enable Interactive Components.
    2. Введите https://slack.botframework.com/api/Actions в качестве URL-адреса запроса. Enter https://slack.botframework.com/api/Actions as the Request URL.
    3. Нажмите кнопку Save changes (Сохранить изменения). Click the Save changes button.

    Получение учетных данных Gather credentials

    Выберите вкладку Основные сведения и перейдите к разделу Учетные данные приложения. Select the Basic Information tab and scroll to the App Credentials section. Вы увидите идентификатор клиента, секрет клиента и токен проверки, требуемые для настройки бота Slack. The Client ID, Client Secret, and Verification Token required for configuration of your Slack bot are displayed.

    Отправка учетных данных Submit credentials

    В отдельном окне браузера вернитесь на сайт Bot Framework https://dev.botframework.com/ . In a separate browser window, return to the Bot Framework site at https://dev.botframework.com/ .

    1. Выберите My bots (Мои боты) и выберите бот, который нужно подключить к Slack. Select My bots and choose the Bot that you want to connect to Slack.
    2. В разделе Channels (Каналы) щелкните значок Slack. In the Channels section, click the Slack icon.
    3. В разделе Enter your Slack credentials (Ввод учетных данных Slack) вставьте учетные данные приложения с веб-сайта Slack в соответствующие поля. In the Enter your Slack credentials section, paste the App Credentials from the Slack website into the appropriate fields.
    4. URL-адрес целевой страницы является необязательным. The Landing Page URL is optional. Его можно опустить или изменить. You may omit or change it.
    5. Выберите команду Сохранить. Click Save.

    Следуйте инструкциям, чтобы авторизовать доступ приложения Slack к команде разработчиков Slack. Follow the instructions to authorize your Slack app’s access to your Development Slack Team.

    Включение бота Enable the bot

    На странице Configure Slack (Настройка Slack) убедитесь, что ползунок возле кнопки «Сохранить» установлен в положение Включено. On the Configure Slack page, confirm the slider by the Save button is set to Enabled. Бот настроен для взаимодействия с пользователями в Slack. Your bot is configured to communicate with users in Slack.

    Создание кнопки Add to Slack (Добавить в Slack) Create an Add to Slack button

    Slack предоставляет HTML-код, с помощью которого можно упростить поиск вашего бота в разделе Add the Slack button (Создание кнопки «Добавить в Slack») на этой странице. Slack provides HTML you can use to help Slack users find your bot in the Add the Slack button section of this page. Чтобы использовать этот HTML-код с ботом, замените значение href (начинается с https:// ) URL-адресом, найденным в параметрах канала Slack вашего бота. To use this HTML with your bot, replace the href value (begins with https:// ) with the URL found in your bot’s Slack channel settings. Выполните следующие действия, чтобы получить URL-адрес на замену. Follow these steps to get the replacement URL.

    1. На странице https://dev.botframework.com/bots щелкните свой бот. On https://dev.botframework.com/bots, click your bot.
    2. Выберите Channels (Каналы), щелкните правой кнопкой мыши запись с именем Slack и выберите пункт Copy link (Копировать ссылку). Click Channels, right-click the entry named Slack, and click Copy link. Этот URL-адрес теперь находится в буфере обмена. This URL is now in your clipboard.
    3. Вставьте его из буфера обмена в HTML-код, предоставленный для кнопки Slack. Paste this URL from your clipboard into the HTML provided for the Slack button. Этот URL-адрес заменяет значение href, предоставленное Slack для этого бота. This URL replaces the href value provided by Slack for this bot.

    Авторизованные пользователи могут нажать кнопку Add to Slack (Добавить в Slack), предоставленную этим измененным HTML, для доступа к боту в Slack. Authorized users can click the Add to Slack button provided by this modified HTML to reach your bot on Slack.

    Также предоставляется как адаптер Also available as an adapter

    Этот канал также предоставляется как адаптер. This channel is also available as an adapter. См. подробнее о выборе между адаптером и каналом в списке доступных адаптеров. To help you choose between an adapter and a channel, see Currently available adapters.


    How to Build Your Own Slack Bot

    You’re discussing a problem with your team and need a link to the bug to show them exactly what you’re talking about. You could open your browser, search for the bug, and, once found, paste it into your conversation. Or you could type the bug’s name in your chat app, and a bot could find the bug info and share it in the conversation automatically. Perhaps you need to find someone’s contact info and then send them an invoice. Just type their name, and a bot can do both in seconds.

    Bots are handy little assistants that hang out in your app, wait for commands, then find or create the thing you need. They’re another way to use your favorite apps without opening them. They’re the big new thing—a core part of Slack, Facebook Messenger, and Telegram’s newest features.

    And turns out, bots are simple enough for anyone to make. Here’s how you can make a Slack Bot to do anything you want in a few minutes without any coding—along with a dozen examples of bots that real teams are using today, and a Slack bot cheat sheet for a handy reference to help build your own bots.

    This article focuses on making bots in team chat app Slack, but you can also make bots in similar ways in many other chat apps, in social networks like Twitter, through SMS, and more.

    Originally published 2 August 2020; updated 31 May 2020 with details about Slack’s new app editor and 1 March 2020 with updated Zapier webhooks details.

    What Is a Bot?

    Robots can drive cars across Mars, clean nuclear reactors, and cut precise holes in your smartphone’s metal frame.

    Bots are a little different. They live in your apps, not in the physical world. Rather than working assembly lines, they focus processing power on looking up facts and sending notifications when you need them. They’re tiny programs without buttons or icons. Instead of clicking a search button, you’ll type a command like /giphy volcano to instruct the bot to find what you’re looking for (a volcano gif from Giphy, in this case).

    Bots are a buzzword right now, the big new thing in everything from Slack to Alexa. And yet, they’re not exactly that new of an idea. Google, in many ways, is a bot that can answer lots of questions. Search for current time SF , and you’ll get the current time in San Francisco just by typing.

    DOS-era programs also behaved much like a bot. Open Terminal on your Mac and type uptime , or open Command Prompt on your PC and type net statistics server , and an age-old bot will tell you how long your computer’s been turned on.

    Handy, right? Instead of finding the right app and clicking the right button, you type in a quick command and get what you want.

    Perhaps you don’t want to use Terminal all day—and you want something more personalized than Google offers. Say you want to find internal contact info, or make an invoice, or decide where to grab lunch as a team. You don’t need a new app, and you don’t need to open Google. All you need is your own bot, inside an app you’re already using.

    What Do You Need to Build a Slack Bot?

    You only need 3 things to build a bot:

    • A place to type your text
    • A bot to read your text
    • An app to do something with your text

    All bots need to start is some text—the text you type that tells them what to do. That could be a Tweet (with Twitter bots that reply with flight status, say), a text message (like the y or n messages you send to your carrier to change your phone plan), or perhaps an email. Chat apps are an especially perfect place for bots. Odds are you already use a chat app—and they include both a text box to type commands into and a conversation view to see what the bot replies.

    Мастер Йода рекомендует:  Угрозы информационной безопасности

    Team chat app Slack is the perfect place to build bots for anything you need—and what we’ll focus on in this tutorial. It’s free to start using, and it’s a tool where you likely already discuss ideas and projects with your team—with a text box that’s perfect for sending commands to your bot.

    Bots come built into Slack. We’ll look at how to set them up in a minute, but here are the basics: Essentially, you give the bot a name, tell it where to watch, and when you type a specific word or symbol, the bot will start listening and then send that text to your app.

    Apps are the tricky part. They’re famously difficult to build, and are the one step that might keep you from building your own bots. But they don’t have to be that difficult. Instead of coding your own app, you could use pre-built integrations from Zapier instead.

    Zapier is a tool that connects your apps without any complicated code, so you can pass data between them. Using Zaps, or integrations inside Zapier, you can connect Slack to hundreds of other apps just by clicking through a simple wizard. For example, once you build a Slack Zap, it can watch for commands in any chat channel and kick off a workflow in another app, or track down info in one tool and send it back to Slack. That’s how you can build the most powerful bots in your own Zapier-powered slash commands, as we’ll walk you through below.

    So let’s use all 3, and see what type of bots we can build.

    → Learn more about Slack in our Slack Review.

    What Types of Slack Bots Can I Build?

    The first time you open Slack, you’ll be greeted by a friendly Slackbot that asks your name and time zone. Type in the replies, and your account will be personalized without a click, like magic.

    You can then harness that magic yourself with your own bots. These come in three varieties:

    Slackbot Responses

    The simplest bots come built into your Slack settings. You add a phrase for the Slackbot to watch for, and then tell it how to respond.

    Say you want a simple way to find the security code for your office: just tell Slackbot to watch for messages that say office security code , then have it respond with the number. You could make more whimsical prank bots that send GIFs—or more serious bots to share important phone numbers, email addresses, or other helpful info.

    To make a Slackbot Response, just go to slack.com/customize/slackbot and add the phrase and response you want. These will automatically work in any channel other than your personal Slackbot channel.

    Or, you can make your own custom bots in Slack that watch Slack for text and automatically reply, either with the bot API or Zapier. We’ll look at that below.

    Notification Bots

    Notification bots are the next easiest Slackbot to make. Instead of watching Slack for a phrase you type, they watch another app for an update and send it to Slack.

    They look like another user in Slack, with their own name and icon. They’ll show up every so often when there’s something new—a news update, new document, or trending hashtag, perhaps—and post it to your Slack channels.

    There are dozens of notification bots for social networks, news, and more in the Slack App Directory. Or, you can build your own notification bots with Zapier—perhaps even using a pre-made Slack integration that you can set up in a few clicks.

    We’ll look at how to make these in just a minute—but here are some popular Slack integrations if you can’t wait.

    Slash Commands

    If you’re looking for a bot that you can summon at will, though, slash commands are your best bet. Unlike notification-based bots, slash command bots wait for your signal, then perform some sort of task based on context that you provide.

    You trigger them by typing a / followed by their name ( /giphy , say, for the Giphy bot), and then type in a command. The bot will then find what you’re looking for and post it back to Slack in a reply.

    Bots can do just about anything you want: start a new meeting, compute a value, do research, and more. For that, you’ll need to either code your own app or use Zapier integrations to connect Slack to over 700 of your favorite apps.

    Slack also has a number of built-in bots to mark your status as away, streamline your notifications, and more. Learn more about those in our roundup of the best hidden tools in Slack.

    How to Build a Bot in Slack

    Now that you know the type of bots you can build, it’s time to make your own. Let’s look at how you can make customized bots in Slack for replies, notifications, and commands—all without writing a line of code.

    Tip: Be sure to download our cheat sheet for a handy reference while building your bot.

    Download Slack Bot Cheat Sheet

    • Download in PDF format(618.5 KB)

    Building a Slack Reply Bot

    Slackbot’s default reply tool is rather limited, since it can only post the same response every time. What if you want a customized response—or perhaps a random response—each time?

    For that, a Zapier-powered reply bot is your best option. First you’ll need to create a Zapier account or log into your Zapier account.

    Then, click the Make a Zap button in the top right corner, and select Slack as your Trigger app. On the next page, have your Zap watch Slack for a new message posted anywhere. Alternately, if you want this bot to only work in one channel, you could have Zapier watch that specific channel.

    Then you’ll need a filter to watch for a specific term—otherwise, your bot would run every time anything is posted to Slack. Add another action to your Zap from the Add a Step button on the left, and choose the Filter option. In its settings, have it watch the Text field for the term you want.

    If you want the bot to run whenever those words are posted to Slack, then have the filter watch for (Text) Contains . Otherwise, if you want it to only watch for that specific phrase on its own, have the filter watch for (Text) Exactly matches .

    Then, you can add your reply, creating a basic bot. Just add another step to your Zap, selecting the Slack app and the Send Channel Message action. There, in the Channel field, select «Choose a custom value» and then select the channel name from your original Slack message so the reply will end up in the same spot.

    → Learn more about filters in our Zapier Filter guide.

    All that’s left is to type in the message you want to post in the «Message Text» box. Scroll on down, and you can add a name and icon to your bot—or have it post to Slack using your name, if you want. Save and turn on your Zap, and it’ll send your customized message every time.

    For something more customized, though, try a Formatter action before your bot’s reply. Formatter is a handy tool that can format your text, calculate values, choose random values from a list, and more.

    Say you want to make a birthday bot that sends a random GIF from a list whenever someone says «Happy birthday!» Our filter above is already watching for the correct phrase—all we need now is the Pick from list Formatter, and a few GIFs.

    To add the Formatter action, click the Continue button or + on the left sidebar of your Zap to add a new action, and choose the Formatter by Zapier app. Then, select the Pick from list formatter in the Transform field, and enter the GIF links in the Input fields.

    With that done, repeat those steps, only this time select Slack as your action app, and choose its Send Channel Message action. Then, in the message text box, add your birthday message and click the plus button on the right to add your random GIF from Formatter. Turn your Zap on, and the next time someone says «happy birthday» they’ll get surprised with one of your GIFs.

    Building a Slack Notification Bot

    Notification bots are even easier to build in Zapier. All you need is an app or site to watch for notifications, and Zapier can automatically send those to Slack for you.

    Say you want to be notified in Slack whenever new tasks are added to your Trello kanban board. First make a new Zap for Trello–with the «Make a Zap with Trello» button. Then, in the Choose Trigger step, select New Card to have it watch Trello for new cards on the board you want to watch.

    Next, click the plus sign + to add a Slack action. Now you can set the Zap to send a message either to a channel or as a direct message to anyone on your team. You can customize the message with any text you want. Click the + icon on the right of the message text field in Zapier to add info from Trello about the card, such its name, link, description, and more.

    Tip: Slack has its own formatting rules for things such as links, bolded text, and block quotes. You’ll want to familiarize yourself with these so that your messages come out looking beautiful.

    You can quickly make Slack notification bots for any of the 700+ apps that connect to Zapier, or with any site that uses RSS. Here are some popular integrations to get started with in a few clicks:

    Building a Slack Slash Command Bot

    Now you’re ready to build the most advanced bots in Slack: slash commands. They’re the bots that wait for a command and then do whatever you asked. Make a document, find an email address, start a call, log records–you can make a bot for that and more.

    It all starts by adding a new app to your Slack account. Go to api.slack.com/apps, select Create New App, enter a name for your app, and select the correct Slack account where you want to use the new Slack bot.

    Slack will then show some options to add features to your app. You can add bot users, interactive messages, and more—but each of those require coding. Instead, we’re going to select the Slash Commands button. Click Create New Command, then it’s time to set your bot up.

    First, add a command with a slash in front of it—perhaps /contact if you want to look up contact info, /weather to build a weather bot, or anything else that fits your needs. You can then add a short description and usage hint.

    Note: If your team already has a command with the name you picked, Slack will prompt you to choose a different name.

    We skipped one field—the Request URL. Here, you’ll add a Webhook URL where Slack will send the data you typed to the command. You can use that to code your own app, pulling out the text, username, and other data from Slack from the webhook.

    We’re going to build our bot without coding—so we’ll use Zapier’s Webhook integration to capture the data from Slack and put it to work. Let’s grab that URL first.

    Tip: Wait: What are webhooks? Glad you asked. They’re essentially notification messages sent to a unique URL. Here’s a quick guide to webhooks to help you learn how to use them.


    In a new tab or window, make a new Zap using Zapier’s Webhooks app. Select Catch Hook when setting up the Webhook integration, click Continue on the options (you don’t need to add anything here), then check the Silent Mode box and copy the Webhook link you’ll see in the testing page.

    With that Webhook link copied, go back to your Slack slash command’s configuration page from before and paste the link into the Request URL field—and then save your settings.

    Now it’s time to test your slash command so we can build the rest of its Zapier integration. Just open Slack, type in your command followed by text you’d like to use in the bot. I’m building a bot that will find contacts in Google Contacts and send me their email address in Slack, so I’ll enter a name that I can use to search Google Contacts.

    Note: If you don’t check the Silent Mode box on the Webhooks’ settings page in Zapier, you’ll see some confirmation text when you run the bot in Slack—don’t worry, that’s just text that Slack will send to confirm the bot was triggered correctly. You can simply ignore it, or can go back and add /silent/ to the end of your Webhooks URL in Slack’s settings to turn on Silent Mode.

    It’s time to make our bot smart. Go back to the tab where you’d opened Zapier, and click the OK I did this button for your webhook step. Zapier will find the data from your slash command, and you’ll be ready to put it to work.

    Now, it’s time to use the data. Here are some quick ideas to try with Zapier integrations:

    • Use Formatter to split your text into sections, format the text, calculate numbers, and more.
    • Use Searches and Lookups to find info in your favorite apps—perhaps to find an entry in a spreadsheet, a contact in a CRM, a customer from your payment app, and more. There are also searches in apps like Giphy that can find info online based on your query.
    • Use standard Zapier Actions to save info to your apps—say to add a new contact, create a document, log time spent on a task, and more.

    Let’s try using a search to find a contact from Google Contacts account. Add an action to the Zap, select Google Contact, then use the Find Contact action. Have it search by name, then select the text from your Slash Action as the search query.

    Now that Zapier’s found your contact, it’s time to send it back to Slack. Just add another action to your Zap, and select the Send Channel Message action. Instead of selecting a specific Slack Channel to post the message to, choose Use a Custom Value at the bottom of the channel list, then use the Channel ID field from your webhook to select the channel where the slash command was used.

    All you need to do now is create your message. Click the + icon beside the Message Text field to add any info you found from the Zapier search. Then, customize the bot, adding the same name and icon image as you added to Slack previously.

    Test the Zap, and you’ll get the response in Slack you wanted.

    Now, anytime you need a contact—or whatever you built your bot for—just type your slash command followed by the text you need to use, and Zapier will do the work for you automatically.

    Want to build a more advanced bot? Try adding extra steps to your Zap—perhaps to create a template document and then post it to Slack—or use Code Steps to create advanced bots without having to code a full app.

    Or, for the most advanced bots, try using Named Variables to gather more than one text item at once. Just decide what you want to gather with the bot, and a standardized name for each item, then write them followed by parentheses with the values you want. For example, say you want to gather a name and email in your bot. In Slack, type Name(Bob Smith) Email(bob@gmail.com) , and Zapier will recognize each as a separate item you can use in subsequent actions.

    Then, when you build your Zap, you can select the Name and Email fields individually to add them as a new contact in Google Contacts.

    With those powerful tools, combined with the hundreds of apps that connect to Zapier, you can build bots that do anything you want.

    Example Bots That Help Teams Get Work Done From Slack

    You could make a bot for anything—but what would actually be a useful bot for your team?

    On the Zapier team, we have a number of bots both for play and productivity. The oldest slash command on our account is a GoToMeeting integration: Type /gtm anywhere in our Slack, and a bot uses Zapier to make a new GoToMeeting link and share it in the conversation for a quick way to jump on a call with team members.

    Need to reserve a server for testing? /reserve does that in Zapier’s Slack. /afk lets us tell the team if we’ll be out of office like those old AIM away messages, /compute finds answers from Wolfram|Alpha, and /random gives us an easy way to make decisions with random numbers. And, when it’s time to unwind, /spyfall starts a text-based game of Spyfall using direct messages to tell each player their role.

    But that only scratches the surface of what bots can do in Slack. Here are some other great Zapier-powered bots for Slack—ones that just might fit needs your team has, too.

    Write Invoices and Emails

    Tired of writing the same emails over and over? The Billfixers team was, too, so they built a bot to write emails.

    «The need that prompted both of them was trying to find ways to increase our efficiency instead of doing things by hand, but without having to add a bunch more applications to our workflow,» says Billfixers co-founder Ben Kurland. «It was just time on our end that we weren’t actually using to help our customer, just to do what was essentially data entry.»

    So, when they need to tell a customer that they just saved them money on a bill or need to send along an invoice, they can now send that person’s name to their bot. It finds their info in SalesforceIQ, uses some code to calculate the savings, creates a draft email in Gmail, then shares it to Slack. «From there, a human can add finishing touches and spend their time adding meaningful interaction with our clients, rather than having to act as a robot themselves,» says Kurland.

    That worked so well, they also built another bot to create invoices in Freshbooks right from Slack.

    Find Email Addresses and Other Data

    Google is great for web searches—but when you need to find a contact’s email or a specific item in your database, it’s often far harder to find what you need. You have to remember which app to check, open that app, search, and finally find what you’re looking for.

    Or, you could just use bots in Slack to help with all of your searches, as the 90 Minute Books team does.

    Their set of search bots started out with a $whois bot built by co-founder Stuart Bell. You post someone’s email address to this bot, and it searches FullContact then returns their full contact info to Slack.

    They then added a bot to shorten links, and another to generate a Book ID for new book projects. And when they need more info about a book, the $gogo bot will find all of the info about a book project from its ID.

    «It gives people visibility without needing access,» says Bell. «And even for the team that do have access, a quick check often saves them having to log in to a different tool.

    Choose Lunch Destinations

    «What’s for lunch?» is a question everyone’s asked—and when it’s time to have a team lunch, it’s a question that’s hard to solve.

    «Lunch is a serious matter, with Livestorm being French,» says CEO Gilles Bertaux. «We usually spend a lot of time looking for a place and then debate about it. So we thought it would be nice to have a little something that could help us decide and experience new meals.»

    And so, they built a food bot with Zapier and Slack. They scraped the best lunch options with delivery near their office from Yelp using Import.io, and saved them to a Google Sheets spreadsheet. Then, with a Schedule Zap, they have the bot run at the same time every day, choosing a random restaurant from the spreadsheet and posting it to Slack.

    It gave them handy food recommendations right when they needed them—and has inspired them to make a better curated database for more customized lunch recommendations than Yelp’s top listings.

    Find Bug Info Automatically

    Bots even make sure the apps for shows like The Voice UK and Britan’s Got Talent work perfectly. Tellybug, the team behind those and other tools to make TV shows engaging, wanted a simple way to collaborate on bug reports right from Slack.

    «People would mention a bug number in Slack (or on a call) and then everyone would have to go search to look up the bug,» says Tellybug CTO Malcolm Box. «This seemed automatable.»

    So, with a Zapier-powered Slack reply bot, the Tellybug team built a Zap that watches Slack for mentions of bugs. Whenever it finds one, it searches for the bug in Fogbugz, their bug tracking app. Then, with some filters and code to pull out the relevant info, the bot posts the correct info about the bug back into Slack.

    «The bot’s made it much easier to have discussions about bugs and to keep everyone on the same page when doing bug triage,» says Box.

    Run Standup Meetings in Chat

    You need to know what each person on your team is working on, but you might not need to waste time with a full meeting. Instead, you could rely on a bot like the Robots and Pencils team does.

    Each weekday, their bot posts a Standup Time reminder with questions about what they’re working on. Each team member can then reply, using Zapier Named Variables to list replies to each question. A Zap then saves each response to a Google Sheets spreadsheet for a log of each virtual meeting. «From here I can put together some cool burndown charts based on other spreadsheets I have created,» writes product manager Ben Myers.

    Add Tasks to Your To-do List

    Or, if you just need a simple way to add tasks to your project, a bot can handle that, too. Parabol CEO Jordan Husney does just that with a bot, for a quick way to add tasks to Trello that come up during their Slack-powered standup meetings.

    Once again using Named Variables in Zapier, he posts a new task to his jrtask bot, and Zapier turns that text into a new card in Trello. «Lowering the friction of capturing tasks means spending more time staying focused on the task in front of you,» writes Husney—which is exactly what his Trello and Slack bot does.

    Remind Your Team to Submit Timesheets

    Want to spend less time reminding your team about regular tasks—and want to make sure you don’t come across as nagging?

    «I found myself often sending random timesheet reminder memes to my team, so I automated this,» says devPHASE lead developer Matt Healy. So, with a bit of PHP code to pull a random timesheet meme from Google Images, and a Zap to post that image along with a reminder into Slack, he automated that task away.

    Then, as Healy says, «hilarity and timesheet completion ensues.»

    For a more powerful workflow, you could make a companion timesheet tool similar to the standup meeting bot above that lets your team post their time logs to your time tracking app right from Slack.

    Learn About Your Team Members

    Automated Insights builds tools to turn data into stories automatically—and they wanted the same automated insights about their own team. So, during a team hackathon, director of customer experience Matt Nisonger and his team turned their employee directory into a bot.

    «Our head of HR collects a lot of information about each employee’s personal interests, hobbies, etc., but never did anything with it,» says Nisonger. «That spawned the idea of using a Slack bot to learn interesting things about new and existing employees.»

    With a Typeform for to survey the team, Google Sheets to save the data, and their own Wordsmith app to turn the data into stories, they had everything needed to build a bot.

    Now, when a new team member joins the team, they’re asked to fill out the survey, and the bot shares info about the new team member in Slack. And if you ever want some trivia about someone on the team, just send their name to the bot and it’ll reply with a fun fact about them.

    That’s only one of the many ways the Automated Insights team uses bots. «we probably have 10-20 various bots integrated with Slack, everything from Intercom to bug reporting to server status reporting,» says Nisonger. «Some are better than others, but overall they’ve been positive for productivity.»

    Create Support Tickets Inside Conversations

    Want to make sure problems are solved for your team as quickly as possible? You could build a bot for that, as the Business Insider team did.

    «Our team’s main communication tool is Slack, and we wanted to make it super easy for anyone on the team to submit a ticket through Slack,» says Business Insider team member Kyle Dowley. All their team has to do is use their ticket bot and post the problem they’re having. That has Zapier check Google Sheets for that team member’s contact info, then uses it and the Slack message to create a ticket in Zendesk. When that’s done, the Zap sends that team member a direct message in Slack to let them know the ticket’s been created—and also gives them a link to the FAQ to perhaps help them find a solution on their own.

    «For many people, using this bot is now the preferred method of submitting support requests to our team,» says Dowley. «It helps to make sure all support requests are in one place with better tracking and visibility.»

    And it’s simple to use: you can ask other team members if they’re having the same problem, then turn the issue into a ticket right from the same Slack conversation.

    Download a Slack Bot Cheat Sheet

    Now that you know how to build a bot, it’s time to build your own. But you’ll need a way to keep track of each step to make sure you can make every bot you need.

    Just check out the cheat sheet below—or download a PDF copy—to make sure you never forget how to build bots in Slack.

    Download Slack Bot Cheat Sheet

    • Download in PDF format(618.5 KB)

    Go Build Your Own Bots!

    Building your own robot is difficult. You’d need motors, controllers, gears, and dozens of other parts—not to mention time to code the robot and get it working the way you want.

    Bots? They only take a few minutes, and they’re free!

    Just make a Zapier account, open Slack, and start building a robotic buddy who can lend you a hand. Or, try building a similar bot with Twitter, Discord, Telegram, SMS messages, or any other chat-like tool Zapier supports. Need a simpler way to make appointments, a filtered notification tool that doesn’t ding every minute, or a detailed workflow to build documents in a second? You can make a bot for that.

    What will your bot do?

    Made a great bot in Slack or another chat app? We’d love to hear about it in the comments below!

    Want to build more tools without coding? Here’s how to build a prototype app with Zapier, along with a guide to building an app with just a form.

    Honda Asimo robot photo by Satoru Fujiwara via Flickr.

    Get Productivity Tips In Your Inbox

    Learn about workflow, company building, and how to get things done.

    “Zapier helps me build processes and automation into my business like a programmer without having to learn to code.”

    Lawrence Watkins, co-founder of Great Black Speakers

    Build workflows with your apps.

    Connect apps. Automate tasks. Get more done.

    Добавить комментарий