Sunday, November 27, 2022
HomeWeb DevelopmentConstruct a Slack bot with Slack Machine

Construct a Slack bot with Slack Machine


Slack, a messaging program initially designed for use in an workplace area, has additionally been adopted for private use. In keeping with an official assertion by the corporate, Slack has ten million each day customers with over 85,000 paying clients.

Over time, the Slack group has been constructing a strong app listing. The gathering of apps accommodates a whole bunch to 1000’s of integrations that present a large amount of flexibility to spice up firms’ effectivity.

The Slack Machine is a sturdy and extendable framework that helps you develop your Slack workspace right into a ChatOps powerhouse. On this information, we’ll go over the way to arrange the Slack Machine and implement a few of its options.

To leap forward:

The present Slack Machine challenge folder accommodates one file: local_settings.py. This file will maintain the entire configuration settings for the Slack Machine:

SlackMachine(Venture-folder)
|__local_settings.py    

Producing tokens to attach our app to the Slack Machine

Two tokens are wanted to attach our app and the Slack Machine: the app-level token and bot token. To generate these tokens:

    1. Navigate to https://api.slack.com/apps
    2. Click on on Create an App:Creating Slack App
    3. Within the pop-up window, choose From an app manifest:Selecting From An App Manifest
    4. Select the Slack workspace the place you’ll set up the Slack bot:Choosing A Slack Workspace
    5. Within the subsequent step, we have to outline a manifest. A manifest is a configuration that dictates how the Slack app will work. Learn extra on the that means of every area right here. Add the next code block to the manifest:
      display_information:
        identify: Wamaitha Slack Machine
      options:
        bot_user:
          display_name: Wamaitha Slack Machine
          always_online: false
      oauth_config:
        scopes:
          bot:
          - app_mentions:learn
          - channels:historical past
          - channels:be a part of
          - channels:learn
          - chat:write
          - chat:write.public
          - emoji:learn
          - teams:historical past
          - teams:learn
          - teams:write
          - im:historical past
          - im:learn
          - im:write
          - mpim:historical past
          - mpim:learn
          - mpim:write
          - pins:learn
          - pins:write
          - reactions:learn
          - reactions:write
          - customers:learn
          - customers:learn.e-mail
          - channels:handle
          - chat:write.customise
          - dnd:learn
          - information:learn
          - information:write
          - hyperlinks:learn
          - hyperlinks:write
          - metadata.message:learn
          - usergroups:learn
          - usergroups:write
          - customers.profile:learn
          - customers:write
      settings:
        event_subscriptions:
          bot_events:
          - app_mention
          - channel_archive
          - channel_created
          - channel_deleted
          - channel_id_changed
          - channel_left
          - channel_rename
          - channel_unarchive
          - group_archive
          - group_deleted
          - group_left
          - group_rename
          - group_unarchive
          - member_joined_channel
          - member_left_channel
          - message.channels
          - message.teams
          - message.im
          - message.mpim
          - reaction_added
          - reaction_removed
          - team_join
          - user_change
          - user_profile_changed
          - user_status_changed
        interactivity:
          is_enabled: true
        org_deploy_enabled: false
        socket_mode_enabled: true
        token_rotation_enabled: false
    6. Within the Evaluation abstract & create your app pop-up, click on Create:
      Creating The Slack Machine App
    7. As soon as the creation is finished, within the Primary Data settings tab, click on on Set up to Workspace:Installing The App To Workspace
    8. Enable permissions to the Slack app:Allowing Permissions To The Slack App
    9. The primary token we’d like is the SLACK_BOT_TOKEN. Navigate to OAuth & Permissions and replica the Bot Consumer OAuth Token to the local_settings.py:Slack Bot OAuth Token
    10. To generate the app-level token, navigate to Primary Data:Generating App-Level Token
    11. Then, scroll right down to App-Stage Tokens and click on on Generate Token and Scopes:Generate Token And Scopes
    12. Within the pop-up window, give the token a reputation, click on on the Scope dropdown, and add each scopes: connections:write and authorizations:learn:
      Adding Scopes
    13. As soon as each scopes are chosen, click on on Generate. The pop-up ought to be as proven under:
      Generating Slack App Token
    14. Copy the generated token and put it aside to the local_settings.py file as SLACK_APP_TOKEN:
      Copying The Generated Token
    15. The local_settings.py file ought to now include the next:
      SLACK_BOT_TOKEN="add_the_token_here"
      SLACK_APP_TOKEN="add_token_here"

If all the things went properly, the App-Stage Tokens tab ought to appear to be this:

Finalized App Level Tokens Tab

Configuring Slack

Now, head over to the workspace on Slack. It’s best to discover the Slack Machine added below the Apps tab:

Slack Workspace Apps Tab

It’s endorsed to make use of the Slack Machine in a digital setting. A digital setting secludes the dependencies used for the app with out conflicting with these put in globally on the system.

Making a digital setting with Python

We’ll use the venv Python module to create a digital setting. The command for this follows this construction:

python -m venv name_of_environment

On this case, our digital setting identify can be venv. We create it utilizing the command under:

python -m venv venv

N.B., When you have a couple of model of Python put in, you could have to specify which Python model venv ought to use. Extra about this may be discovered within the venv documentation.

At this level, the challenge folder construction turns into:

SlackMachine(Venture-folder)
      |__local_settings.py    
      |__venv

To activate the digital setting, you want to run the next instructions.

On Home windows, run:

venvScriptsactivate.bat

Activating The Virtual Environment For Windows

On Linux and macOS, run:

supply tutorial-env/bin/activate

Interacting with the Slack Machine

Now, we’ll set up the Slack Machine module utilizing pip. The module permits us to work together with the Slack API from Python.

Set up the Slack Machine utilizing:

pip set up slack-machine

Run the bot on the foundation folder utilizing the Slack Machine as proven under:

Running The Bot On The Root Folder

As soon as the connection succeeds, return to Slack. Proper-click on the Slack Machine app and click on on View app particulars:

View App Details

Within the pop-up, add the app to a channel:

Add The App To A Channel

Adding The App To Desired Channel

You’ll be able to add it to any channel of your alternative. For this instance, I added it to the #slack-machine channel. Navigate to the channel and ship the bot a howdy message:

Slack Bot Hello Message

By default, the Slack Machine masses the HelloPlugin and the PingPongPlugin. The HelloPlugin responds with a “howdy” or “hello” when the bot is greeted. The PingPongPlugin responds with “ping” or “pong” no matter point out.

Constructing customized plugins

Due to the versatile nature of the Slack Machine, we will construct our personal customized plugins. For this, we have to create a plugin bundle. Create a brand new plugins folder and, in it, create a customPlugin.py file.

The up to date challenge folder construction is as proven under:

SlackMachine(Venture-folder)
      |__local_settings.py    
      |__venv
      |__plugins
           |__customPlugin.py

In customPlugin.py, we create a category that can include all of our customized plugin functionalities. Our first performance instructs the Slack app to generate a dad joke. The complete code for that is:

from machine.plugins.base import MachineBasePlugin
from machine.plugins.decorators import respond_to
import requests
import json

class OurCustomPluginClass(MachineBasePlugin):
    """
    Customized plugin class for interacting with the slack-machine
    """

    # tells a dad joke
    @respond_to(r"^Make me giggle")
    async def dad_jokes(self, msg):
        """
        Returns a dad joke and replies the joke to the person
        """
        random_dad_joke = requests.get("https://icanhazdadjoke.com/",
                                       headers={"Settle for": "software/json"})
        random_dad_joke = json.masses(random_dad_joke.textual content)["joke"]
       
        await msg.reply(random_dad_joke)

OurCustomPluginClass extends the MachineBasePlugin from the Slack Machine. Our dad_joke operate has the respond_to decorator. The respond_to decorator acts on messages which have the Slack bot talked about, with the precise key phrases handed as a regex to the decorator.

The requests module will make an HTTP request to the dad_joke API. The JSON module comes put in with Python and is used to remodel the API response right into a JSON format.

The requests library may be put in utilizing pip on the terminal:

pip set up requests

The customized plugin must be included within the local_settings.py to run the Slack Machine.

In local_settings.py, add the code as proven:

SLACK_APP_TOKEN = "xapp-"
SLACK_BOT_TOKEN = "xoxb-"

PLUGINS = ["plugins.customPlugin.OurCustomPluginClass"]

Then re-run Slack Machine on the terminal within the root folder:

Running The Bot On Slack Machine's Root Folder

The output ought to present that the plugin class has been loaded.

The respond_to decorator requires the person to say the bot on Slack with the desired key phrases. In our case, we have to point out the bot, adopted by “Make me giggle” to set off the dad_joke operate:

Slack Bot Dad Joke Function

The respond_to decorator may also be used to emit customized occasions. Occasions are a technique to alternate information between plugins or expose API endpoints different plugins can use. Occasions are emitted utilizing self.emit(). Our customized occasion will acquire person emails and ship them to an e-mail channel.

First, create an e-mail channel: #registration-emails:

Creating Slack Email Channel

The code for gathering emails is as proven under:

from machine.plugins.base import MachineBasePlugin
from machine.plugins.decorators import respond_to, on, 
import requests
import json
import re


class OurCustomPluginClass(MachineBasePlugin):
   """
   Customized plugin class for interacting with the slack-machine
   """


   @respond_to(r"register (?P<e-mail>.*)")
   async def register_emails(self, msg, e-mail):
       """
       Accumulate registration e-mail from person
       """

       e-mail = e-mail.break up("|")[1][:-1]
       email_regex = "^[a-z0-9]+[._]?[a-z0-9]+[@]w+[.]w{2,3}$"
       person = msg.at_sender
       if re.search(email_regex, e-mail):
           self.emit('new_registration', e-mail=e-mail, person=person)
       else:
           await msg.reply_dm(f'Hey {person}, your registration e-mail handle {e-mail} is                invalid.')

   @on("new_registration")
   async def collect_emails(self, **kwargs):
       """
         Pay attention for brand spanking new emails
      """

       await self.say("registration-emails", f"{kwargs['user']} - {kwargs['email']}")
                      ]}")

The register_emails operate emits an occasion that forwards emails to the #registration-emails channel. The occasion additionally emits the person’s ID and the precise e-mail as a part of the arguments:
Slack Register Emails Function

Event Emitted By Register Emails Function

The occasion emitted has a singular identify, in our case new-registrations. To hearken to the new-registrations occasion, we’d like the @on decorator.

The decorator wants the occasion identify to look out for. When the new-registrations occasion is emitted, the collect_emails operate is triggered. This operate forwards the person’s identify and e-mail to the #registration-emails channel.

If the person supplies an invalid e-mail handle, the Slack app sends the person a direct message:

Slack Direct Message

Slack Machine storage capabilities

The Slack Machine additionally supplies storage capabilities. Information is saved in key-value pairs in-memory or utilizing exterior databases. To exhibit in-memory capabilities, we’ll generate tokens and have the person retrieve and delete them at will.

The code for this may be seen under:

from machine.plugins.base import MachineBasePlugin
from machine.plugins.decorators import respond_to, on
import requests
import json
import re
import random


class OurCustomPluginClass(MachineBasePlugin):
   """
   Customized plugin class for interacting with the slack-machine
   """

   @respond_to(r"generate")
   async def gen_token(self, msg):
       """
       Generate random token
       """
       person = msg.at_sender
       token = random.randint(1, 1000)
       await self.storage.set(person, token)
       await msg.reply_dm(f"Hey {person} your generated token is {token}")

   @respond_to(r"retrieve")
   async def retrieve_token(self, msg):
       """
       Retrieve the saved token
       """
       person = msg.at_sender
       token = await self.storage.get(person)
       if token:21
           await msg.reply_dm(f"Hey {person} your token is {token}")
       else:
           await msg.say("Key not discovered! Generate a brand new token")

   @respond_to(r"delete")
   async def delete_token(self, msg):
       """
       delete tokens
       """
       person =msg.at_sender
       await self.storage.delete(person)
       await msg.say(f"information in <{person}> deleted!")

The in-memory storage capabilities come constructed into the MachineBasePlugin class. Nonetheless utilizing the respond_to decorator, we’ve got three capabilities:

  1. gen_token: This operate generates a random token between one and 1000. The token is saved to the in-memory database utilizing the set methodology. The set methodology takes in two arguments: the important thing and the worth. We’ve set the person’s sender ID as the important thing and the generated token as the worth:Slack Generate Token
    Slack Generated Token
  2. retrieve_token: This operate will test the in-memory storage for a worth that has the person’s sender ID. If a key exists, a personal direct message of the token worth is shipped to the person. In any other case, the person is knowledgeable that the important thing doesn’t exist:Slack Retrieve Function
  3. delete_token: This operate deletes the person’s saved token:Slack Delete Function

The listen_to decorator works the identical because the respond_to decorator with the important thing distinction being that the person doesn’t want to say the Slack app.

For instance, we will make the app pay attention to assist messages utilizing the code under:

from machine.plugins.base import MachineBasePlugin
from machine.plugins.decorators import respond_to, on, listen_to,course of
import requests
import json
import re
import random


class OurCustomPluginClass(MachineBasePlugin):
   """
   Customized plugin class for interacting with the slack-machine
   """
   @listen_to(r"^assist")
   async def help_details(self, msg):
       """
       one thing
       """
       await msg.say("Consult with the #help-channel for assist")

Slack Help Request

Slack treats most interactions with the person as occasions. Each time the person performs an motion on Slack, the Slack occasions API is fired. We will hearken to particular occasions utilizing the @course of decorator. The decorator takes within the particular occasion we need to hearken to.


Extra nice articles from LogRocket:


Within the code under, the Slack app will ship a notification to the #random channel when a person creates a brand new channel. The entire record of occasions may be discovered right here:

from machine.plugins.base import MachineBasePlugin
from machine.plugins.decorators import respond_to, on, listen_to,course of
import requests
import json
import re
import random


class OurCustomPluginClass(MachineBasePlugin):
   """
   Customized plugin class for interacting with the slack-machine
   """
   @course of("channel_created")
   async def check_channel_created(self):
       """
       one thing
       """
       await self.say("random", "Now we have a brand new channel")

New Slack Channel

Conclusion

On this article, we reviewed the way to construct a Slack bot utilizing the Slack Machine. The Slack Machine is jam-packed with extra performance within the API documentation. Its flexibility and customization skills assist customers make extra apps for particular enterprise use instances.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments