Within the realm of high-performance webhosting and flexible building gear, Kinsta sticks out as a number one platform catering to WordPress, programs, databases, or even unfastened Static Web site Webhosting.

Slack, famend for its Slash Instructions, seamlessly integrates with Kinsta-hosted apps and products and services, enabling customers to automate duties and considerably support potency.

This information explains find out how to arrange real-time conversation between Slack and a Python software hosted on Kinsta. Via harnessing Slash Instructions, customers of the appliance achieve the facility to unexpectedly create, question, and delete merchandise.

This integration empowers them to dynamically replace their product stock dynamically, making sure suggested responses to buyer wishes.

Working out Slack’s Slash Instructions

Slack Slash Instructions are text-based shortcuts. They start with a ahead slash (/) adopted by means of a particular key phrase and not obligatory parameter.

Slash Instructions cause movements or without delay engage with integrations throughout the Slack interface. For instance, /remind permits surroundings reminders without delay via Slack notifications.

With Slack integrations, you’ll configure adapted instructions to your programs. On this instructional, your group can without problems question our product app’s stock the use of the /check_inventory Slash Command and different instructions.

Integrating Slack along with your apps fosters seamless interplay and streamlined workflows inside of a contemporary administrative center. It complements conversation and productiveness by the use of:

  • A centralized conversation hub — Slack acts as a unified house for groups. Integrating apps into Slack consolidates channels, retaining conversations and information in a single position, and boosting potency.
  • Actual-time updates — Built-in apps supply fast signals about key occasions, making sure everybody remains knowledgeable and reacts temporarily to adjustments or updates.
  • Streamlined workflows — Integrations automate duties like notifications from challenge control gear or triggering movements in CRM tool, chopping down on guide paintings.
  • Enhanced collaboration — Crew contributors gaining access to apps without delay from Slack fosters seamless collaboration. They are able to simply proportion, edit recordsdata, and talk about initiatives, selling teamwork throughout purposes.

How To Construct a Python Software on Kinsta

Let’s construct and deploy a product control software on Kinsta. Then, combine it with Slack to discover Slash Instructions. Customers can upload, delete, and question the stock’s merchandise by the use of Slash Instructions in Slack.

Must haves

To apply at the side of this information, we think you might have:

First, let’s arrange a Python challenge on Kinsta. To do that, apply the stairs under:

  1. Seek advice from the Kinsta’s Python template on GitHub.
  2. Choose Use this template > Create a brand new repository to duplicate the starter code right into a repository inside of your GitHub account.
  3. As soon as your repository is able, log in or create an account to view your MyKinsta dashboard.
  4. Authorize Kinsta along with your Git supplier (Bitbucket, GitHub, or GitLab).
  5. Click on Packages at the left sidebar, then click on Upload software.
  6. Choose the repository and the department you need to deploy from.
  7. Assign a singular title for your software and select a knowledge heart location.
  8. Configure your construct setting subsequent. Choose the Same old construct system config with the really useful Nixpacks possibility for this demo.
  9. Use all default configurations after which click on Create software.

Deployment most often takes a couple of mins, and upon good fortune, you’ll obtain a hyperlink for your software at the side of a dashboard containing deployment knowledge.

How To Set Up Slack Integration In Python Software

Let’s get began by means of making a Slack software after which configure Slash instructions which might be attached for your Python software by the use of some tokens. Let’s configure a Slack app:

  1. Get right of entry to the Slack API dashboard.
  2. Click on Create New App and select From Scratch.
  3. Identify your Slack app (e.g., product-inventory).
  4. Choose the workspace and click on Create App.

Now, for authentication:

  1. Permit Socket Mode on your Slack dashboard’s sidebar.
  2. Generate an app-level token by means of typing a token title and clicking Generate.
  3. Save this app-level token for configuring environmental variables later.

How To Configure Slash Instructions

To arrange your app’s Slash Instructions:

  1. Navigate to the Options phase beneath Elementary Knowledge within the Slack API dashboard. Select Slash Instructions.

    Slack API dashboard with options for adding features and functions
    Slack API dashboard with choices for including options and purposes.
  2. Click on Create New Command to configure a brand 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 web page on Slack.
  3. At the Create New Command web page, fill in the main points to your new Slash Command. As an example, kind /hello within the Command box. Optionally, upload a temporary description like “Says hi!” and supply a utilization trace. Click on Save.
  4. Within the Set up App phase of the sidebar, click on Set up to Workspace.
  5. Get right of entry to the bot consumer OAuth token by means of heading to OAuth & Permissions at the sidebar. Save this token for long run reference.

How To Upload Tokens to Kinsta’s Software Deployment

  1. Move to the Surroundings Variables phase beneath Settings of your software deployment in MyKinsta.
  2. Click on Upload setting variable.

    Slack Add environment variable popup with keys, values, and the option to remove them or add another
    Slack Upload setting variable popup.
  3. For Key 1, SLACK_BOT_TOKEN, paste the bot consumer OAuth token in Worth 1. For Key 2, SLACK_APP_TOKEN, paste the app-level token in Worth 2.
  4. Make sure that each choices are checked and click on Deploy now so Kinsta can redeploy your software with the surroundings variables.

How To Put into effect Actual-Time Verbal exchange

For this demo, you employ the Kinsta’s Python template, which accommodates the next recordsdata:

  • Procfile — Specifies the instructions to run your software.
  • necessities.txt — Lists the dependencies required for the Python software.
  • server.py — The primary record of the Python software, dealing with server-side capability or operations.

Kinsta robotically creates a procedure in response to the Procfile within the repository root when deploying an software. The Procfile accommodates the next code.

internet: python server.py

This command runs the code that server.py accommodates. Kinsta additionally installs the Python dependencies in necessities.txt throughout deployment and redeployment.

Now, let’s use the Bolt framework to arrange real-time conversation along with your software. Upload the next traces for your necessities.txt record to robotically set up Bolt in your Python software whilst you replace the repository.

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

Additionally, upload the psycopg2 library to the necessities.txt record. This might be used to hook up with a Postgres database.

psycopg2-binary==2.9.9

How To Put into effect a Postgres Database With Kinsta

The product stock app wishes a approach to persist product knowledge that Slash Instructions upload to the database. To create continual knowledge garage, you’ll use Kinsta’s hosted database.

  1. First, deploy a Postgres database in your Kinsta dashboard by means of navigating to the Databases phase at the sidebar of MyKinsta’s dashboard.
  2. Click on Create a database. Configure your database main points by means of getting into a reputation and settling on the database kind. Choose the PostgreSQL possibility and configure your required dimension. A Database username and password is robotically 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
    Shape for making a database.
  3. Click on Proceed to complete putting in your database. Watch for the PostgreSQL database to be created.
    As soon as a hit, to get your connection string for exterior get right of entry to for your database, navigate to the Exterior connections phase of your deployed database dashboard and duplicate the Exterior 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 exterior connection knowledge.

    Now, you’ll use this connection string to hook up with the database out of your Python software.

  4. For your Python challenge, create a db.py record inside of your challenge listing for database initialization purposes. Upload the next code:
    import psycopg2
    import os
    
    # get connection string from setting variable
    connection_string = os.environ.get("DATABASE_CONNECTION_STRING")
     
    def get_conn():
       # create connection
       conn = psycopg2.attach(connection_string)
    
       # Go back connection to the database
       go back conn
         
    def init_db():
       # get connection
       conn = get_conn()
    
       # get cursor
       cur = conn.cursor()
    
       cur.execute("""
           DROP TABLE IF EXISTS merchandise;
                       
           CREATE TABLE merchandise (
               identification INTEGER PRIMARY KEY,
               title TEXT UNIQUE NOT NULL,
               amount INTEGER NOT NULL
           );
       """)
    
       cur.shut()
       conn.dedicate()
       conn.shut()

    When the get_conn() serve as is named, it creates and returns a connection to the deployed Kinsta database the use of your exterior connection string.

    The init_db() serve as will get a database connection, defines the database schema, and creates the desk whilst additionally committing the adjustments. You must simplest name the init_db() serve as as soon as when to begin with putting in the appliance server. Use the get_conn() serve as in next calls to get a connection to the database.

How To Put into effect the Slash Command Handlers

Now, construct the appliance server code.

  1. Delete the server.py record’s contents and import the next 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

    Those are required for Slack app capability, database connections, and blunder dealing with.

  2. Upload the next code to the server.py record after the import statements:
    # Initialize your app along with your bot token
    app = App(
      token=os.environ.get("SLACK_BOT_TOKEN"),
    )

    The App magnificence from slack_bolt is used to create an example of the Slack app. It initializes the app with the bot consumer OAuth token retrieved from the surroundings variable SLACK_BOT_TOKEN.

  3. Subsequent, deploy a handler for the /hello Slash Command you added for your Slack software previous. Upload the next traces to the server.py record.
    # The hello command merely sends again a greeting
    @app.command("/hello")
    def send_hello(ack, reply, command):
      # Recognize command request
      ack()
      reply(f"Hi!")

    The @app.command() creates a listener for the command string handed as a controversy and maps the next serve as for that Slash Command’s requests. The send_hello() serve as handles the request common sense.

    The code additionally passes the request variables ack, reply, and command for the serve as to make use of. Name ack to recognize the Slash Command request, as this is step one sooner than proceeding processing, and make contact with reply to ship again a textual content reaction.

    When the consumer varieties the Slash Command /hello on your Slack workspace, they get the reaction, “Hi!”

  4. Go back for your Slack software dashboard and upload the next instructions.
    Command Quick Description Utilization Trace
    /add_product Upload a product to the stock. product_id, product_name, product_quantity
    /check_inventory Test for a product with an identical ID in stock. product_id
    /delete_product Delete product with matching ID from stock. product_id

    Now, your Slash Instructions web page must appear to be the next screenshot containing a listing of instructions and their main points.

    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 Instructions web page.
  5. Upload the /add_product handler to the server.py record.
    # command so as to add merchandise
    @app.command("/add_product")
    def add_product(ack, reply, command, request):
     #Recognize command request
     ack()
    
     # Extract payload from request
     payload = request.frame['text']
     identification, title, amount = [i.strip() for i in payload.split(",")]
      
     # conn object
     conn = None
    
     take a look at:
       # get conn
       conn = get_conn()
    
       # get cursor
       cur = conn.cursor()
    
       # Insert product into the database
       cur.execute(
         "INSERT INTO merchandise (identification, title, amount) VALUES (%s, %s, %s)",
           (int(identification), title, int(amount))
       )
       
       # shut conversation with postgresql
       cur.shut()
       
       # dedicate adjustments
       conn.dedicate()
       
       # Reaction
       reply(f"""Added product to stock:
         identification - {identification},
         title - {title},
         amount - {amount}
       """)
    
     with the exception of DatabaseError:
       # Ship a reaction
       reply(f"Product with ID {identification} exists in stock!")
      
     in the end:
       # shut connection
       if conn isn't None:
         conn.shut()

    request.frame accesses the total request payload Slack sends throughout the dealing with procedure.

    When a consumer varieties the /add_product Slash Command, the appliance sends the next pattern JSON payload as a POST request.

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

    The command and textual content fields are integrated. command accommodates the brought on Slash Command whilst textual content accommodates its further textual content. For instance, if the consumer varieties the command /add_product 1, pocket book, 5, textual content accommodates “1, pocket book, 5”.

    The add_product handler extracts the product’s ID, title, and amount from the consumer’s request and connects to the database the use of the get_conn() helper serve as. It additionally executes an insert SQL operation so as to add the product to the database. If the product ID already exists within the database, the code handles the mistake and responds that the ID already exists.

  6. Now, upload the remainder of the command handlers to the server.py record.
    # command to test stock for a product_id
    @app.command("/check_inventory")
    def check_inventory(ack, reply, command, request):
       # Recognize command request
       ack()
    
       # Extract payload from request
       identification = request.frame['text'].strip()
    
       # Get a database connection
       conn = None
       take a look at:
           # get conn
           conn = get_conn()
    
           # get cursor
           cur = conn.cursor()
     
           # Fetch matching product with ID from database
           cur.execute(
               "SELECT * FROM merchandise WHERE identification=%s",
               (int(identification),)
           )
    
           product = cur.fetchone()
    
           # shut comms
           cur.shut()
    
           if product is None:
               reply(f"No product with matching ID {identification} discovered.")
           else:
               # Deconstruct tuple if the product exists
               _, title, amount = product
              
               reply(f"""Product with ID {identification} discovered:
                          title - {title},
                          amount - {amount}
                      """)
             
       with the exception of Exception as e:
           print("Connection error: %s", e)
             
       in the end:
           # shut connection
           if conn isn't None:
               conn.shut()
    
    # command to delete the matching product_id from stock
    @app.command("/delete_product")
    def delete_product(ack, reply, command, request):
        #Recognize command request
        ack()
    
        # Extract payload from request
        identification = request.frame['text'].strip()
        
        # Get connection
        conn = None
        take a look at:
            # Get connection
            conn = get_conn()
       	 
            # get cursor
            cur = conn.cursor()
       	 
            # Insert the product into the database
            cur.execute(
            	"DELETE FROM merchandise WHERE identification = %s",
            	(int(identification),)
            )
            cur.shut()
            conn.dedicate()
       	 
            # Reaction
            reply(f"Product with ID {identification} deleted from stock!")
        with the exception of Exception as e:
            print("Connection error: %s", e)
        in the end:
            # shut connection
            if conn isn't None:
                conn.shut()
    

    Those two command handlers question and delete the matching product ID within the stock, respectively.

How To Run the Server

  1. To carry the database initialization and socket connection in combination, upload the next traces for your server.py record.
    # Get started your app
    if __name__ == "__main__":
        # Initialize database on get started
        init_db()
    
        # Attach socket
        handler = SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"])
        handler.get started()

    You should initialize SocketModeHandler along with your app-level token. Use the SLACK_APP_TOKEN to get right of entry to the surroundings variable deployed within the Kinsta software.

  2. Devote the adjustments for your far off repository to deploy them to Kinsta robotically. Now, server.py initializes the database and establishes the socket connection. Kinsta will cause an automated re-deployment of your Python software.

Check and Troubleshoot Your Software

You’ll be able to take a look at your software on Slack the use of the configured Slash Instructions.

    1. Move to the workspace related along with your app. Sort the slash (‘/’) personality to view the app’s instructions:

      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. Check every Slash Command. For instance, kind /hello. You get the reaction “Hi!”

      Response to the Hi command with the message 'Hello!'
      Reaction to Hello command.
    3. Check what occurs whilst you upload the similar product two times. Run the slash command /add_product 1, notepad, 2 two instances.
      Result of running the add product command twice. It shows a quantity of 2
      Including a product two times.

      Because the screenshot above presentations, the primary command labored. It added a brand new product. The second one command precipitated the reaction that the ID already exists.

    4. Check out querying for the product ID we simply added. Sort /check_inventory 1.
      Querying a product ID with the check inventory command. It lists the ID, name, and quantity
      Checking the stock.

      The question returned the product with the matching ID.

    5. In the end, take a look at deleting the product you added. Sort /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 software, chances are you’ll come upon mistakes to get to the bottom of to your software to serve as accurately. Check out the next how one can stumble on and attach conventional mistakes.

      • Test your tokens: Be sure to configure your app-level token accurately with the connections:write scope to permit get right of entry to the use of Socket Mode. Additionally, use the right kind tokens for the app magnificence. The bot consumer token starts with xoxb-<...>. Use the app-level token (xapp-<...>) for the SocketModeHandler magnificence.
      • Test your slash instructions: Be sure to’ve configured the Slash Instructions in your Slack app’s dashboard and configured the right kind handlers on your software server code.
      • Make use of higher error dealing with: Make sure that your software common sense accurately handles mistakes, for instance, when executing database operations.

Abstract

On this information, you discovered find out how to construct a Python software with real-time conversation by the use of Slack’s Slash instructions. You additionally discovered find out how to deploy the appliance to Kinsta.

Integrating a Kinsta-hosted software with Slack permits customers to temporarily make adjustments the use of Slash Instructions, bettering interactivity and workflow potency whilst providing quick get right of entry to to real-time knowledge. Group of workers can now seamlessly upload, delete, or take a look at product stock with out leaving their communications platform, boosting productiveness throughout a hectic paintings day.

Kinsta’s PaaS gives much more chances—you’ll attach programs and databases, deploying full-stack answers for firms and companies. And the most productive section? Your first $20 is roofed by means of us!

The put up Actual-Time Slack Verbal exchange with Your Kinsta Hosted Python Software seemed first on Kinsta®.

WP Hosting

[ continue ]