Actual-Time Slack Verbal exchange with Your Kinsta Hosted Python Software

by | Dec 1, 2023 | Etcetera | 0 comments

Inside the realm of high-performance web hosting and versatile construction tools, Kinsta stands out as a primary platform catering to WordPress, programs, databases, and even unfastened Static Web site Webhosting.

Slack, renowned for its Slash Directions, seamlessly integrates with Kinsta-hosted apps and services and products, enabling consumers to automate tasks and significantly improve efficiency.

This data explains learn how to organize real-time dialog between Slack and a Python instrument hosted on Kinsta. By means of harnessing Slash Directions, consumers of the applying succeed in the power to abruptly create, query, and delete products.

This integration empowers them to dynamically exchange their product inventory dynamically, ensuring advised responses to purchaser needs.

Understanding Slack’s Slash Directions

Slack Slash Directions are text-based shortcuts. They begin with a forward slash (/) followed by the use of a selected keyword and no longer mandatory parameter.

Slash Directions purpose actions or directly interact with integrations all through the Slack interface. For example, /remind lets in environment reminders directly by way of Slack notifications.

With Slack integrations, you’ll configure tailored directions for your techniques. In this tutorial, your crew can with out issues query our product app’s inventory using the /check_inventory Slash Command and other directions.

Integrating Slack at the side of your apps fosters seamless interaction and streamlined workflows inside a modern place of work. It enhances dialog and productivity by way of:

  • A centralized dialog hub — Slack acts as a unified space for teams. Integrating apps into Slack consolidates channels, maintaining conversations and data in one place, and boosting efficiency.
  • Precise-time updates — Integrated apps provide speedy alerts about key events, ensuring everyone stays an expert and reacts quickly to changes or updates.
  • Streamlined workflows — Integrations automate tasks like notifications from problem regulate tools or triggering actions in CRM software, reducing down on information artwork.
  • Enhanced collaboration — Staff individuals having access to apps directly from Slack fosters seamless collaboration. They may be able to merely percentage, edit information, and discuss tasks, promoting teamwork all through functions.

How To Assemble a Python Tool on Kinsta

Let’s assemble and deploy a product regulate instrument on Kinsta. Then, mix it with Slack to find Slash Directions. Shoppers can add, delete, and query the inventory’s products by way of Slash Directions in Slack.

Should haves

To use along with this data, we predict you’ll have:

First, let’s prepare a Python problem on Kinsta. To do this, observe the steps below:

  1. Discuss with the Kinsta’s Python template on GitHub.
  2. Select Use this template > Create a brand spanking new repository to replicate the starter code proper right into a repository inside your GitHub account.
  3. Once your repository is ready, log in or create an account to view your MyKinsta dashboard.
  4. Authorize Kinsta at the side of your Git provider (Bitbucket, GitHub, or GitLab).
  5. Click on on Applications on the left sidebar, then click on on Add instrument.
  6. Select the repository and the dep. you wish to have to deploy from.
  7. Assign a unique identify on your instrument and choose a data middle location.
  8. Configure your assemble atmosphere next. Select the Standard assemble machine config with the in point of fact helpful Nixpacks risk for this demo.
  9. Use all default configurations and then click on on Create instrument.

Deployment maximum continuously takes a few minutes, and upon just right fortune, you’ll download a link on your instrument along with a dashboard containing deployment wisdom.

How To Set Up Slack Integration In Python Tool

Let’s get started by the use of creating a Slack instrument and then configure Slash directions which could be connected on your Python instrument by way of some tokens. Let’s configure a Slack app:

  1. Get admission to the Slack API dashboard.
  2. Click on on Create New App and choose From Scratch.
  3. Determine your Slack app (e.g., product-inventory).
  4. Select the workspace and click on on Create App.
See also  15 Best Magazine WordPress Themes in 2023 (Compared)

Now, for authentication:

  1. Allow Socket Mode to your Slack dashboard’s sidebar.
  2. Generate an app-level token by the use of typing a token identify and clicking Generate.
  3. Save this app-level token for configuring environmental variables later.

How To Configure Slash Directions

To prepare your app’s Slash Directions:

  1. Navigate to the Choices segment underneath Basic Wisdom inside the Slack API dashboard. Choose Slash Directions.

    Slack API dashboard with options for adding features and functions
    Slack API dashboard with possible choices for together with choices and functions.

  2. Click on on Create New Command to configure a brand spanking new command.

    Slack Create New Command page with options for command, short description, and usage hint. Also has details for escape channels, users, and links sent to your app and a preview of an autocomplete entry
    Create New Command internet web page on Slack.

  3. On the Create New Command internet web page, fill in the details for your new Slash Command. For instance, type /hi inside the Command field. Optionally, add a brief description like “Says hello!” and provide a usage hint. Click on on Save.
  4. Inside the Arrange App segment of the sidebar, click on on Set as much as Workspace.
  5. Get admission to the bot shopper OAuth token by the use of heading to OAuth & Permissions on the sidebar. Save this token for longer term reference.

How To Add Tokens to Kinsta’s Tool Deployment

  1. Transfer to the Setting Variables segment underneath Settings of your instrument deployment in MyKinsta.
  2. Click on on Add atmosphere variable.

    Slack Add environment variable popup with keys, values, and the option to remove them or add another
    Slack Add atmosphere variable popup.

  3. For Key 1, SLACK_BOT_TOKEN, paste the bot shopper OAuth token in Value 1. For Key 2, SLACK_APP_TOKEN, paste the app-level token in Value 2.
  4. Ensure that every possible choices are checked and click on on Deploy now so Kinsta can redeploy your instrument with the environment variables.

How To Enforce Precise-Time Verbal trade

For this demo, you use the Kinsta’s Python template, which incorporates the following information:

  • Procfile — Specifies the directions to run your instrument.
  • must haves.txt — Lists the dependencies required for the Python instrument.
  • server.py — The main document of the Python instrument, coping with server-side capacity or operations.

Kinsta automatically creates a procedure in keeping with the Procfile inside the repository root when deploying an instrument. The Procfile incorporates the following code.

web: python server.py

This command runs the code that server.py incorporates. Kinsta moreover installs the Python dependencies in must haves.txt all through deployment and redeployment.

Now, let’s use the Bolt framework to organize real-time dialog at the side of your instrument. Add the following strains on your must haves.txt document to automatically arrange Bolt on your Python instrument while you exchange the repository.

slack-bolt==1.18.0
slack-sdk==3.23.0

Moreover, add the psycopg2 library to the must haves.txt document. This could be used to connect to a Postgres database.

psycopg2-binary==2.9.9

How To Enforce a Postgres Database With Kinsta

The product inventory app needs a way to persist product wisdom that Slash Directions add to the database. To create power wisdom storage, you’ll use Kinsta’s hosted database.

  1. First, deploy a Postgres database on your Kinsta dashboard by the use of navigating to the Databases segment on the sidebar of MyKinsta’s dashboard.
  2. Click on on Create a database. Configure your database details by the use of entering a name and settling at the database type. Select the PostgreSQL risk and configure your desired size. A Database username and password is automatically generated:

    Form for creating a database. The fields include the database name, display name, database type and version, database username and password, data center location, and size. There are two buttons at the bottom of the form: Cancel and Continue
    Form for creating a database.

  3. Click on on Continue to finish setting up your database. Look ahead to the PostgreSQL database to be created.
    Once a success, to get your connection string for external get admission to on your database, navigate to the External connections segment of your deployed database dashboard and copy the External connection string.

    The info page for the deployed database dashboard. Details include resources, location, version, creation date, a list of internal connections, and information about internal connections, including the connection string.
    Database external connection wisdom.

    Now, you’ll use this connection string to connect to the database from your Python instrument.

  4. In your Python problem, create a db.py document inside your problem checklist for database initialization functions. Add the following code:
    import psycopg2
    import os
    
    # get connection string from atmosphere variable
    connection_string = os.environ.get("DATABASE_CONNECTION_STRING")
     
    def get_conn():
       # create connection
       conn = psycopg2.connect(connection_string)
    
       # Return connection to the database
       return conn
         
    def init_db():
       # get connection
       conn = get_conn()
    
       # get cursor
       cur = conn.cursor()
    
       cur.execute("""
           DROP TABLE IF EXISTS products;
                       
           CREATE TABLE products (
               id INTEGER PRIMARY KEY,
               identify TEXT UNIQUE NOT NULL,
               quantity INTEGER NOT NULL
           );
       """)
    
       cur.close()
       conn.commit()
       conn.close()

    When the get_conn() function is called, it creates and returns a connection to the deployed Kinsta database using your external connection string.

    The init_db() function gets a database connection, defines the database schema, and creates the table while moreover committing the changes. You should most simple title the init_db() function once when first of all setting up the applying server. Use the get_conn() function in subsequent calls to get a connection to the database.

See also  9 Gear Each Mission Supervisor Must Know

How To Enforce the Slash Command Handlers

Now, assemble the applying server code.

  1. Delete the server.py document’s contents and import the following libraries:
    import os
    from slack_bolt import App
    from slack_bolt.adapter.socket_mode import SocketModeHandler
    from db import get_conn, init_db
    from psycopg2 import DatabaseError

    The ones are required for Slack app capacity, database connections, and mistake coping with.

  2. Add the following code to the server.py document after the import statements:
    # Initialize your app at the side of your bot token
    app = App(
      token=os.environ.get("SLACK_BOT_TOKEN"),
    )

    The App class from slack_bolt is used to create an instance of the Slack app. It initializes the app with the bot shopper OAuth token retrieved from the environment variable SLACK_BOT_TOKEN.

  3. Next, deploy a handler for the /hi Slash Command you added on your Slack instrument earlier. Add the following strains to the server.py document.
    # The hi command simply sends once more a greeting
    @app.command("/hi")
    def send_hello(ack, answer, command):
      # Acknowledge command request
      ack()
      answer(f"Hello!")

    The @app.command() creates a listener for the command string passed as an argument and maps the following function for that Slash Command’s requests. The send_hello() function handles the request not unusual sense.

    The code moreover passes the request variables ack, answer, and command for the function to use. Identify ack to acknowledge the Slash Command request, as this is the first step quicker than continuing processing, and speak to answer to send once more a text response.

    When the patron sorts the Slash Command /hi to your Slack workspace, they get the response, “Hello!”

  4. Return on your Slack instrument dashboard and add the following directions.
    Command Fast Description Usage Hint
    /add_product Add a product to the inventory. product_id, product_name, product_quantity
    /check_inventory Take a look at for a product with an equivalent ID in inventory. product_id
    /delete_product Delete product with matching ID from inventory. product_id

    Now, your Slash Directions internet web page should seem to be the following screenshot containing a list of directions and their details.

    Slash Commands page listing each one's name and description with options to edit or delete, and a Create New Command button
    Slack API Slash Directions internet web page.

  5. Add the /add_product handler to the server.py document.
    # command with the intention to upload products
    @app.command("/add_product")
    def add_product(ack, answer, command, request):
     #Acknowledge command request
     ack()
    
     # Extract payload from request
     payload = request.body['text']
     id, identify, quantity = [i.strip() for i in payload.split(",")]
      
     # conn object
     conn = None
    
     check out:
       # get conn
       conn = get_conn()
    
       # get cursor
       cur = conn.cursor()
    
       # Insert product into the database
       cur.execute(
         "INSERT INTO products (id, identify, quantity) VALUES (%s, %s, %s)",
           (int(id), identify, int(quantity))
       )
       
       # close dialog with postgresql
       cur.close()
       
       # commit changes
       conn.commit()
       
       # Response
       answer(f"""Added product to inventory:
         id - {id},
         identify - {identify},
         quantity - {quantity}
       """)
    
     aside from DatabaseError:
       # Send a response
       answer(f"Product with ID {id} exists in inventory!")
      
     finally:
       # close connection
       if conn is not None:
         conn.close()

    request.body accesses the overall request payload Slack sends all through the coping with process.

    When a client sorts the /add_product Slash Command, the applying sends the following trend JSON payload as a POST request.

    {
        'token': , 
        'team_id': , 
        'team_domain': , 
        'channel_id': , 
        'channel_name': , 
        'user_id': , 
        'user_name': , 
        'command': '/add_product', 
        'text': '1, pocket guide, 5', 
        'api_app_id': , 
        'is_enterprise_install': , 
        'response_url': , 
        'trigger_id': 
    }

    The command and text fields are built-in. command incorporates the introduced on Slash Command while text incorporates its additional text. For example, if the patron sorts the command /add_product 1, pocket guide, 5, text incorporates “1, pocket guide, 5”.

    The add_product handler extracts the product’s ID, identify, and quantity from the patron’s request and connects to the database using the get_conn() helper function. It moreover executes an insert SQL operation with the intention to upload the product to the database. If the product ID already exists inside the database, the code handles the error and responds that the ID already exists.

  6. Now, add the rest of the command handlers to the server.py document.
    # command to check inventory for a product_id
    @app.command("/check_inventory")
    def check_inventory(ack, answer, command, request):
       # Acknowledge command request
       ack()
    
       # Extract payload from request
       id = request.body['text'].strip()
    
       # Get a database connection
       conn = None
       check out:
           # get conn
           conn = get_conn()
    
           # get cursor
           cur = conn.cursor()
     
           # Fetch matching product with ID from database
           cur.execute(
               "SELECT * FROM products WHERE id=%s",
               (int(id),)
           )
    
           product = cur.fetchone()
    
           # close comms
           cur.close()
    
           if product is None:
               answer(f"No product with matching ID {id} found out.")
           else:
               # Deconstruct tuple if the product exists
               _, identify, quantity = product
              
               answer(f"""Product with ID {id} found out:
                          identify - {identify},
                          quantity - {quantity}
                      """)
             
       aside from Exception as e:
           print("Connection error: %s", e)
             
       finally:
           # close connection
           if conn is not None:
               conn.close()
    
    # command to delete the matching product_id from inventory
    @app.command("/delete_product")
    def delete_product(ack, answer, command, request):
        #Acknowledge command request
        ack()
    
        # Extract payload from request
        id = request.body['text'].strip()
        
        # Get connection
        conn = None
        check out:
            # Get connection
            conn = get_conn()
       	 
            # get cursor
            cur = conn.cursor()
       	 
            # Insert the product into the database
            cur.execute(
            	"DELETE FROM products WHERE id = %s",
            	(int(id),)
            )
            cur.close()
            conn.commit()
       	 
            # Response
            answer(f"Product with ID {id} deleted from inventory!")
        aside from Exception as e:
            print("Connection error: %s", e)
        finally:
            # close connection
            if conn is not None:
                conn.close()
    

    The ones two command handlers query and delete the matching product ID inside the inventory, respectively.

See also  Dorik vs Divi AI: Head-to-Head Comparison (2024)

How To Run the Server

  1. To hold the database initialization and socket connection together, add the following strains on your server.py document.
    # Get began your app
    if __name__ == "__main__":
        # Initialize database on get began
        init_db()
    
        # Connect socket
        handler = SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"])
        handler.get began()

    You must initialize SocketModeHandler at the side of your app-level token. Use the SLACK_APP_TOKEN to get admission to the environment variable deployed inside the Kinsta instrument.

  2. Dedicate the changes on your some distance off repository to deploy them to Kinsta automatically. Now, server.py initializes the database and establishes the socket connection. Kinsta will purpose an automatic re-deployment of your Python instrument.

Take a look at and Troubleshoot Your Tool

You’ll be ready to try your instrument on Slack using the configured Slash Directions.

    1. Transfer to the workspace similar at the side of your app. Kind the slash (‘/’) persona to view the app’s directions:

      Kinsta-demo channel with a list of commands, including check inventory product ID, add product ID, name, or quantity, delete product ID, and Hi
      The kinsta-demo channel.

    2. Take a look at each and every Slash Command. For example, type /hi. You get the response “Hello!”

      Response to the Hi command with the message 'Hello!'
      Response to Hi command.

    3. Take a look at what happens while you add the an identical product two instances. Run the slash command /add_product 1, notepad, 2 two circumstances.
      Result of running the add product command twice. It shows a quantity of 2
      Together with a product two instances.

      For the reason that screenshot above shows, the main command worked. It added a brand spanking new product. The second command prompted the response that the ID already exists.

    4. Take a look at querying for the product ID we merely added. Kind /check_inventory 1.
      Querying a product ID with the check inventory command. It lists the ID, name, and quantity
      Checking the inventory.

      The query returned the product with the matching ID.

    5. Finally, check out deleting the product you added. Kind /delete_product 1.

      After deleting the product, the message says, Product with ID 1 deleted from inventory!
      Deleting a product.

How To Troubleshoot

When configuring and deploying your instrument, chances are high that you’ll come across errors to unravel for your instrument to function correctly. Take a look at the following how you can come across and fix typical errors.

      • Take a look at your tokens: You should definitely configure your app-level token correctly with the connections:write scope to allow get admission to using Socket Mode. Moreover, use the proper tokens for the app class. The bot shopper token begins with xoxb-. Use the app-level token (xapp-) for the SocketModeHandler class.
      • Take a look at your slash directions: You should definitely’ve configured the Slash Directions on your Slack app’s dashboard and configured the proper handlers to your instrument server code.
      • Make use of upper error coping with: Ensure that your instrument not unusual sense correctly handles errors, as an example, when executing database operations.

Summary

In this data, you found out learn how to build a Python instrument with real-time dialog by way of Slack’s Slash directions. You moreover found out learn how to deploy the applying to Kinsta.

Integrating a Kinsta-hosted instrument with Slack lets in consumers to quickly make changes using Slash Directions, improving interactivity and workflow efficiency while offering fast get admission to to real-time wisdom. Team of workers can now seamlessly add, delete, or check out product inventory without leaving their communications platform, boosting productivity all through a busy artwork day.

Kinsta’s PaaS provides a lot more possibilities—you’ll connect techniques and databases, deploying full-stack solutions for companies and firms. And the most efficient phase? Your first $20 is roofed by means of us!

The submit Actual-Time Slack Verbal exchange with Your Kinsta Hosted Python Software appeared first on Kinsta®.

WP Hosting

[ continue ]

WordPress Maintenance Plans | WordPress Hosting

read more

0 Comments

Submit a Comment

DON'T LET YOUR WEBSITE GET DESTROYED BY HACKERS!

Get your FREE copy of our Cyber Security for WordPress® whitepaper.

You'll also get exclusive access to discounts that are only found at the bottom of our WP CyberSec whitepaper.

You have Successfully Subscribed!