Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Building a Google Gemini Digital Assistant Slack Bot : A Step-by-Step Guide

10 min read

In an era where efficiency is key, integrating a digital assistant into Slack using Google Gemini’s AI technology offers a transformative solution. This guide will walk you through every step, from obtaining API keys to deployment, enabling you to build a smart, responsive bot that enhances productivity within your team. Whether you’re a developer or a tech enthusiast, you’ll find valuable insights to create a personalized assistant that revolutionizes your digital workspace.

Step 1: Obtain the Google Gemini API Key

  • Visit the Google AI website, typically at ai.google.dev.
  • Click on Get API key in Google AI Studio
  • Goto the Google AI Studio and click on Get API Key and generate a new API key for the Gemini API. This may involve creating a project and enabling the Gemini API for that project.
  • Once generated, copy the API key for later use.

Step 2: Generate the Slack App

Create a new Slack app in the Slack API dashboard.

Visit the Slack API Website: Go to api.slack.com/apps

Create New App: Click on the “Create New App” button. Choose an App Name and Pick a Workspace where the App needs to be Installed.

Once your app is created, you’ll be directed to the Basic Information page. Here, you can see your app’s credentials (Client ID, Client Secret, etc.) and configure settings.

Under Display Information, you can customize how your app appears in Slack, including its name, description, and icons.

Step 3 : Get the OAuth Token

Step 4: Add the OAuth Bot Token Scopes

Configure your Slack app with the necessary OAuth scopes for your bot to function correctly. These include app_mentions:read, channels:history, chat:write, im:history, im:write, and mpim:history.

Step 5: Setup the Event Subscription Bot Events

In the Slack app’s settings, go to “Event Subscriptions” and subscribe to bot events such as app_mention, message.im, and message.mpim to listen for and respond to messages.

Step 5: Install Your App to Your Workspace

  • Before your app can interact with Slack, you need to install it to your workspace. Go to “OAuth & Permissions” to add scopes (permissions) and Event Subscriptions your app needs, then install the app to your workspace.

Step 6: Open Visual Studio Code Editor

Use Visual Studio Code Editor or your preferred IDE to develop the bot.

Step 7: Create a Python Virtual Environment

Create and activate a Python virtual environment for your project to manage dependencies effectively.

A Python virtual environment is a self-contained directory that contains a Python installation for a particular version of Python, plus several additional packages. Virtual environments are used to manage dependencies for different projects, ensuring that each project has access to the specific versions of libraries it needs and that these dependencies don’t interfere with each other.

Install venv library

pip install venv

You can create a virtual environment using Python’s built-in venv module or with virtual environment wrappers like virtualenv. Here’s how to do it with venv:

Navigate to Your Project Directory: Open a terminal and navigate to the directory where you want your project to reside.

Create the Virtual Environment: Run the following command to create a virtual environment. Replace python3.10 with the appropriate command for your Python 3.10 installation, and myenv with your preferred environment name.

python3.10 -m venv myenv

Activate the Virtual Environment: Before you install packages, you need to activate the virtual environment. The activation command varies by operating system:

Windows:

myenv\Scripts\activate.bat

macOS and Linux:

source myenv/bin/activate

Once activated, your command prompt should indicate that you’re now working inside the virtual environment.

Open a New Folder Inside the Virtual Environment using VS Code

Goto File -> Open Folder in the VS Editor and Create a New Folder where you are going to store your entire project. Ensure your folder is kept inside the virtual environment folder

Ensure Virtual Environment is activated

Step 8: Create .env Files

Create a .env file to store sensitive information such as your Google API Key, Slack Bot Token, and Bot User ID. This approach enhances security and makes your application more portable.

Sample .env file:

GOOGLE_API_KEY='your_google_api_key_here'
SLACK_BOT_TOKEN='your_slack_bot_token_here'
BOT_USER_ID='your_bot_user_id_here'
FLASK_APP = "app.py"

Step 9: Install Python Necessary Libraries

Ensure your project has all the necessary dependencies by installing the required libraries which include Flask, various Google and Slack SDKs, and other utility libraries.

Flask
google-ai-generativelanguage
google-api-core
google-auth
google-generativeai
googleapis-common-protos
gunicorn
requests
slack_sdk
colorama
python-dotenv

Step 10: Implement Your Slack Bot

When creating a Slack bot, Flask, Gunicorn, and the Slack SDK each serve specific, complementary roles in the development and deployment process. Understanding the use and importance of each can help in effectively building, deploying, and running Slack bots. Here’s a breakdown of their roles:

Flask Library

Flask is a lightweight WSGI (Web Server Gateway Interface) web application framework in Python. It’s designed to make getting started quick and easy, with the ability to scale up to complex applications. For Slack bots, Flask is typically used to:

  • Create endpoints for Slack events, commands, and interactions. Slack sends HTTP requests to these endpoints, such as when a user interacts with your bot or when your bot is mentioned in a channel.
  • Handle requests from Slack, such as processing commands entered by users in Slack and sending appropriate responses back to Slack.
  • Serve dynamic content related to the bot’s functionality, for example, interactive web pages for configuring the bot or viewing help documentation.

Gunicorn Library

Gunicorn (Green Unicorn) is a Python WSGI HTTP Server for UNIX, providing a powerful interface for deploying web applications served by Flask. Gunicorn is particularly useful for Slack bots because it:

  • Manages multiple worker processes, allowing your Flask application to handle multiple requests simultaneously. This is crucial for bots that may need to respond to many Slack events or commands at once.
  • Serves as an intermediary between your Flask application and the internet, which is especially important when deploying on cloud platforms or when interfacing with webhooks from Slack.
  • Improves performance and reliability compared to the default Flask server, which isn’t designed for production use. Gunicorn ensures that your Slack bot remains responsive and available to users.

Slack SDK Library

The Slack SDK for Python simplifies the process of interacting with the Slack API. It offers a range of functionalities crucial for Slack bot development, such as:

  • Sending messages to Slack channels or users, allows your bot to communicate with users.
  • Listening for events in Slack, such as messages to the bot or mentions of the bot in channels, and reacting to these events.
  • Interacting with Slack’s Web API, making it easier to perform actions like querying for user or channel information, managing permissions, and handling Slack app installations and OAuth flows.

Implement your Slack bot using Flask and the Slack SDK. Your bot will use the Google Gemini API to generate responses to messages. The provided Python code demonstrates how to set up your Flask application, handle events from Slack, generate content using Google Gemini, and post messages back to Slack.

Python Flask App for Slack Bot

from flask import Flask, request, jsonify
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
import threading
import pathlib
import textwrap
import os
from dotenv import load_dotenv

import google.generativeai as genai
from threading import Thread

processed_ids = set()

# Load environment variables from .env file
load_dotenv()

# Define Google API Key and Set Gemini Pro Model
google_api_key = os.getenv('GOOGLE_API_KEY')
genai.configure(api_key=google_api_key)
model = genai.GenerativeModel('gemini-pro')

# Initialize a Web Client with the Slack bot token from the environment variables
slack_token = os.getenv('SLACK_BOT_TOKEN')
client = WebClient(token=slack_token)

# Get BOT_USER_ID from environment variables
BOT_USER_ID = os.getenv('BOT_USER_ID')
app = Flask(__name__)


def handle_event_async(data):
    thread = Thread(target=handle_event, args=(data,), daemon=True)
    thread.start()

def handle_event(data):
    event = data["event"]
    print(f'Received Event Text {event["text"]}')
    
    # Check if the event is a message without a subtype (excluding bot messages, etc.)
   

    if "text" in event and event["type"] == "message" and event.get("subtype") is None:
        print(f'Received Event Text: {event["text"]}')
        # Ignore messages from the bot itself
        if event.get("user") == BOT_USER_ID:
            return

        # Handle direct message or app mention
        if event["channel"].startswith('D') or event.get("channel_type") == 'im':
            # Handle direct message event
            try:
                gemini = model.generate_content(event["text"])
                textout = gemini.text.replace("**", "*")
                print(textout)
                response = client.chat_postMessage(
                    channel=event["channel"],
                    text=textout,
                    mrkdwn=True
                )
            except SlackApiError as e:
                print(f"Error posting message: {e.response['error']}")

  

    elif event["type"] == "app_mention" and event.get("client_msg_id") not in processed_ids:
            try:
                gemini = model.generate_content(event["text"])
                textout = gemini.text.replace("**", "*")
                print(textout)
                response = client.chat_postMessage(
                    channel=event["channel"],
                    text=textout,
                    mrkdwn=True
                )
                processed_ids.add(event.get("client_msg_id"))
            except SlackApiError as e:
                print(f"Error posting message: {e.response['error']}")

@app.route('/gemini', methods=['GET']) 
def helloworld(): 
    if request.method == 'GET': 
        gemini = model.generate_content("Hi")
        return gemini.text

@app.route("/slack/events", methods=["POST"])
def slack_events():
    data = request.json
    if "challenge" in data:
        return jsonify({"challenge": data["challenge"]})
    
    if "event" in data:
        handle_event_async(data)
    
    return "", 200

if __name__ == "__main__":
    app.run(debug=True)

Use Flask’s Development Server

For development purposes, you can use Flask’s built-in server by running:

flask run

Make sure to set the environment variable FLASK_APP set to ‘app.py’ to your application file before running it

FLASK_APP = "app.py"

Step 11: Deploy Your Application

Deploy your application using tools like ngrok for local tunneling or Google Cloud AppEngine for hosting. Ngrok allows you to expose your local development server to the internet, which is useful for testing. For production, deploying to a cloud service like Google Cloud AppEngine provides scalability and reliability.

Deploy Using ngrok for local testing


Ngrok is a valuable tool for developing and testing Slack bot apps, especially during the initial development phases or when you’re working in an environment without a publicly accessible web server.

When developing a Slack bot, you typically work on your local machine (localhost). Slack, however, needs to send HTTP requests (events, commands, etc.) to your bot. Without needing to deploy your app to a public server, ngrok allows you to test your bot’s integration with Slack immediately

Step 1: Download ngrok

  1. Go to the ngrok portal and signup and visit the download section for windows.
  2. Select the Windows version and download the ZIP file.

Step 2: Extract the ZIP File

  • After downloading, extract the ZIP file to a folder of your choice. This will extract an executable file named ngrok.exe.

Step 3 : Add ngrok Path to the Environmental Variable

To add ngrok to your environment variables or system path, you need to make sure that the ngrok executable is accessible from the command line regardless of the current directory. Here’s how you can do it on different operating systems:

For Windows:

  1. Download ngrok from the official website.
  2. Unzip the ngrok executable to a desired directory (e.g., C:\ngrok\).
  3. Right-click on ‘This PC’ or ‘Computer’ on your desktop and select ‘Properties’.
  4. Click on ‘Advanced system settings‘.
  5. Click on the ‘Environment Variables‘ button.
  6. In the ‘System variables’ section, find and select the ‘Path‘ variable, then click ‘Edit’.
  7. Click ‘New’ and add the path to the directory where you unzipped ngrok (e.g., C:\ngrok\).
  8. Click ‘OK’ to close the dialogs and apply the changes.

After adding the directory to the system path, you will be able to run ngrok from the command line.

For macOS or Linux:

  1. Download ngrok from the official website.
  2. Open a terminal and unzip ngrok to a directory that is on your system’s PATH (e.g., /usr/local/bin).Here’s a command that might be used to move ngrok to /usr/local/bin (requires administrator privileges):
sudo mv ngrok /usr/local/bin
  • To use all of ngrok’s features, you’ll need to connect your ngrok account. If you don’t already have an ngrok account, you’ll need to create one on the ngrok website.
  • Once you have an account, retrieve your auth token from the ngrok dashboard.
  • Open Command Prompt and navigate to the directory where you extracted ngrok.exe.
  • Run the following command to add your auth token (replace <your_auth_token> with your actual ngrok auth token):
ngrok.exe authtoken <your_auth_token>

Step 5: Start an HTTP Tunnel

  • To start an HTTP tunnel forwarding to your local application (e.g., a Flask app running on port 5000), run:
ngrok.exe http 5000
  • This will start ngrok and display a UI in your command prompt with the public URL that ngrok provides (both http and https versions).

In my case

ngrok public url : https://dfc1-106-222-201-217.ngrok-free.app
slack request url : https://dfc1-106-222-201-217.ngrok-free.app/slack/events

Step 6: Use the Public URL

  • Use the provided public URL (e.g., https://<random_string>.ngrok.io) in your Slack application configuration as the endpoint for events, commands, or interactivity components.

Deploy Using Google Cloud App Engine

Deploying your Slack bot on Google Cloud App Engine offers a scalable, managed environment, letting you focus on developing your bot’s features without worrying about infrastructure management.

Here’s a step-by-step guide on how to deploy a Slack bot on Google Cloud, specifically using Google App Engine, a platform-as-a-service (PaaS) that abstracts away infrastructure so you can focus on code:

Step 1: Prepare Your Slack Bot

  • Ensure your Slack bot is working locally and all dependencies are correctly specified in a requirements.txt file.
  • Your Flask app should be ready, with the entry point typically named app.py or defined in a file specified by the FLASK_APP environment variable.

Step 2: Create a Google Cloud Project

  1. Go to the Google Cloud Console.
  2. Click on the project dropdown at the top of the page and select “New Project.”
  3. Enter a project name, select a billing account, and click “Create.”

Step 3: Enable App Engine

  1. In the Cloud Console, navigate to the “App Engine” dashboard.
  2. Select the project you created.
  3. Click “Create Application.”
  4. Choose a region for your application. This is where your application’s resources will be located.
  5. Click “Create.”

Step 4: Prepare Your Application for Deployment

  • Create an app.yaml file in the root of your project directory. This file specifies your app’s runtime configuration. For a basic Flask application, your app.yaml might look like this:
runtime: python310
entrypoint: gunicorn -b :$PORT app:app

handlers:
- url: /.*
  script: auto

env_variables:
  GOOGLE_API_KEY: 'your_google_api_key_here'
  SLACK_BOT_TOKEN: 'your_slack_bot_token_here'
  BOT_USER_ID: 'your_bot_user_id_here'
  FLASK_APP: 'app.py'
  • Replace python310 with the appropriate runtime for your application and add any necessary environment variables.

Step 5: Install and Initialize the Google Cloud SDK

  1. Download and install the Google Cloud SDK for your operating system.
  2. After installation, open a terminal or command prompt and initialize the SDK by running gcloud init.
  3. Follow the on-screen instructions to log in and set your default project to the one you created.

Step 6: Deploy Your Application to AppEngine

  1. Navigate to your project’s root directory in your terminal or command prompt.
  2. Deploy your application using the Google Cloud SDK by running:

Note down the AppEngine URL

Appengine URL : https://yourapp_name.appspot.com
Slack Requested URL : https://yourapp_name.appspot.com/slack/events

Step 12: Configure Slack Event Subscriptions

After deployment, set the request URL under “Event Subscriptions” in your Slack app settings to your deployed application’s endpoint. This URL will receive events from Slack and allow your bot to respond accordingly.

Step 13: Accessing Your Slack Bot

Finally, access your Slack bot either by direct message or by adding the application to a Slack channel. Your bot is now ready to interact with users, providing AI-powered responses generated by the Google Gemini API.

Accessing the SlackBot from Slack Channel with an App Mention

Accessing the SlackBot Using Direct Message

By following these steps, you can create a powerful and personalized digital assistant within Slack, leveraging the capabilities of Google’s Gemini API to enhance your team’s communication and productivity.

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

[Course] Building Stock Market Based Telegram Bots using Python

Learn how to build powerful Telegram bots for the stock market using Python. This hands-on course guides you through creating bots that fetch real-time...
Rajandran R
1 min read

Understanding Object-Oriented Programming (OOP) Concepts in Python for Traders…

For traders and investors, having well-structured code can greatly improve the efficiency and manageability of trading applications. Object-Oriented Programming (OOP) in Python offers a...
Rajandran R
3 min read

How I Built a Trader-Friendly Stock Market Dashboard using…

As both a developer and an avid market watcher, I set out to create a tool that could give traders and investors a clear,...
Rajandran R
2 min read

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More