Setting Up the Kindness Slackbot

This guide will walk you through the process of setting up the Kindness Slackbot, which sends a random image to a channel when a user types the /kindness command.

Prerequisites

  1. Python 3.6 or higher
  2. A Slack workspace and administrative access to create and manage apps

Step 1: Create a new Slack app

  1. Go to the Slack API dashboard and click on the "Create New App" button.
  2. Choose "From scratch" and fill in the "App Name" and "Development Slack Workspace". Click "Create App" when you're done.

Step 2: Configure the app

  1. In the "Features" section, click on "Slash Commands" and then "Create New Command".
  2. Fill in the following details:
  3. Click "Save".
  4. In the "Features" section, click on "OAuth & Permissions".
  5. Scroll down to the "Scopes" section and click on "Add an OAuth Scope" under "Bot Token Scopes".
  6. Add the following scopes:

Step 3: Installing the App to a Workspace

  1. Click on "Install App" in the sidebar.
  2. Click on the "Install to Workspace" button and follow the prompts to authorize the app in your workspace.
  3. After installation, you will see "Bot User OAuth Token" and "App Token" in the "OAuth & Permissions" section. Save these tokens as you will need them later.

Step 4: Set up the Python environment

  1. Create a new directory for your Slackbot project and navigate to it in your terminal or command prompt.
  2. Install the required Python packages by running the following command: pip install slack-sdk slack-bolt python-dotenv

Step 5: Create the Slackbot script and .env file

  1. Create a new file named random_image_slackbot.py in your project directory and copy the following Python script:
  2. import os
        import random
        from slack_bolt import App
        from slack_bolt.adapter.socket_mode import SocketModeHandler
        from dotenv import load_dotenv
        
        # Load environment variables
        load_dotenv()
        
        # Set up Slack app and handler
        slack_app_token = os.environ['SLACK_APP_TOKEN']
        slack_bot_token = os.environ['SLACK_BOT_TOKEN']
        app = App(token=slack_bot_token)
        
        @app.command("/kindness")
        def handle_kindness(ack, respond, command):
            # Acknowledge the command request
            ack()
        
            # Generate random image URL
            random_num = random.randint(1, 30)
            image_url = f"https://kindness.equalexperts.com/images/{random_num}.png"
        
            # Get the channel information
            try:
                channel_info = app.client.conversations_info(
                    token=slack_bot_token,
                    channel=command["channel_id"]
                )
                is_bot_member = channel_info["channel"]["is_member"]
            except Exception as e:
                print(f"Error fetching channel info: {e}")
                is_bot_member = False
        
            # Send the random image to the channel
            try:
                if is_bot_member:
                    response = app.client.chat_postMessage(
                        token=slack_bot_token,
                        channel=command["channel_id"],
                        text="Here's a random image for you!",
                        blocks=[
                            {
                                "type": "image",
                                "block_id": "random_image",
                                "image_url": image_url,
                                "alt_text": "Random image",
                            }
                        ],
                    )
                else:
                    response = respond(
                        text="Here's a random image for you!",
                        blocks=[
                            {
                                "type": "image",
                                "block_id": "random_image",
                                "image_url": image_url,
                                "alt_text": "Random image",
                            }
                        ],
                    )
        
                print(f"Image sent: {image_url}")
            except Exception as e:
                print(f"Error sending message: {e}")
        
        
        if __name__ == "__main__":
            handler = SocketModeHandler(app, slack_app_token)
            handler.start()
  3. Create a new file named .env in your project directory and add the following lines, replacing your_app_token_here and your_bot_token_here with the actual tokens you obtained in Step 3:
    SLACK_APP_TOKEN=your_app_token_here
    SLACK_BOT_TOKEN=your_bot_token_here

Step 6: Run the Slackbot

  1. In your terminal or command prompt, navigate to your project directory and run the following command: python random_image_slackbot.py
  2. Your Slackbot is now running and listening for the /kindness command.

Step 7: Test the Slackbot

  1. Go to your Slack workspace and type /kindness in a channel where the bot is a member.
    Sends to everyone if if the bot also exists in the channel
  2. The bot will send a random image to the channel. If the bot is not a member of the channel, it will send an ephemeral message visible only to you.
    Only visible by the user who sent the command when the bot isn't in the channel.

Conclusion

You have successfully set up the Kindness Slackbot. Users can now use the /kindness command to receive random Acts of Kindness.