Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Build and Host a Slackbot in Python on a Linux VPS

Create a Slack app, build a Python bot with Bolt, choose Socket Mode or HTTP delivery, secure a Linux VPS, and keep the service running with systemd.
WorldPython on a Linux VPS Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The most straightforward production setup is a Python Slack app built with Bolt for Python, using Socket Mode on a hardened Linux VPS and supervised by systemd. Socket Mode keeps your bot off the public internet: the VPS opens an outbound WebSocket to Slack, so you do not need a domain, TLS certificate, or inbound application port. You need a Slack bot token (xoxb-), an app-level token (xapp- with connections:write), a Python virtual environment, and a non-root service account.

What you are building

A Slack bot has three separate pieces:

  • Slack app configuration: the app, event subscriptions, bot scopes, and installation in a workspace.
  • Python process: your listeners and business logic, using the official Bolt framework.
  • Host operations: a Linux VPS, firewall, secrets file, service supervisor, logs, updates, and recovery procedures.

Most single-workspace bots use two credentials. The xoxb- bot token authorizes Web API calls and is created when the app is installed. The xapp- app-level token authorizes Socket Mode; create it with the connections:write scope. A user token (xoxp-) represents a person and is not a substitute for a bot token.

As an Amazon Associate I earn from qualifying purchases.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Slack’s guidance is explicit: “Treat your tokens like passwords and keep them safe.” Keep credentials out of source control, paste them only into a root-protected environment file, and load them through environment variables.

Prerequisites and a safe target architecture

  • A Slack development workspace where you can create and install an app.
  • A current Ubuntu Server image or another supported Linux distribution.
  • SSH access to the VPS and permission to create a service account and install packages.
  • Python 3.7 or newer, as documented by the Bolt for Python project.
  • A decision about event delivery: Socket Mode or an HTTPS endpoint.

For a small bot, the target architecture is: Slack workspace → outbound WebSocket from the VPS → Bolt application → systemd service. The process listens on no public port. For HTTP delivery, the architecture becomes Slack → public HTTPS reverse proxy → Bolt’s /slack/events endpoint → application.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Step 1: Create and install the Slack app

Create the app in a development workspace

  1. Open Slack’s API app management page and create an app in your development workspace.
  2. Choose the features your bot actually needs. Start with the smallest set of bot scopes; add a scope only when a feature requires it.
  3. Install the app to the workspace. The installation produces the bot token that begins with xoxb-.

Scopes are capability grants, not a checklist to maximize. A message-reply bot may need fewer permissions than one that reads history, uploads files, or manages channels. Removing an unused scope later is safer than discovering that a compromised token had broad access.

Create the app-level token for Socket Mode

  1. In the app settings, open the app-level token area and create a token.
  2. Grant connections:write.
  3. Copy the resulting xapp- value once and store it in your secret store or root-only environment file.

Enable the Events API and subscribe to only the event types your listeners handle. If you use interactive buttons, menus, or modals, enable the corresponding interactivity features as well. Slack may require you to reinstall the app after changing scopes so the new permissions are reflected in the bot token.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Step 2: Create a Python project with Bolt

Use a dedicated directory and virtual environment so the bot’s dependencies do not alter the operating system’s Python installation.

sudo mkdir -p /opt/slackbot
sudo chown "$USER":"$USER" /opt/slackbot
cd /opt/slackbot
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -U pip slack_bolt

The documented minimum is Python 3.7+. Use the newest interpreter supported by your chosen Linux distribution and by the versions you intend to deploy. Record the resolved packages after installation:

python -m pip freeze > requirements.txt

The Python Slack SDK is downloaded about 8.6 million times per month and Bolt for Python about 1.5 million times per month, according to Slack’s April 14, 2026 Python development article. Those are download figures, not a guarantee of performance or uptime.

Step 3: Write a minimal Socket Mode bot

Create /opt/slackbot/app.py:

import os

from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler

app = App(token=os.environ["SLACK_BOT_TOKEN"])


@app.message("hello")
def message_hello(message, say):
    say(f"Hey there <@{message['user']}>!")


if __name__ == "__main__":
    SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start()

The @app.message decorator registers a listener for matching message text. Other listeners use decorators such as @app.event. Bolt parses Slack payloads, dispatches them to your functions, and exposes helpers such as say for replies.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Before deploying, run it interactively with temporary environment variables:

export SLACK_BOT_TOKEN='xoxb-your-token'
export SLACK_APP_TOKEN='xapp-your-token'
/opt/slackbot/.venv/bin/python /opt/slackbot/app.py

Invite the bot to a test channel and send a message containing “hello”. Stop it with Ctrl+C after confirming the reply. Never put real token values in app.py, shell history, screenshots, issue tickets, or a public repository.

Socket Mode or HTTP: choose the delivery model

Socket Mode is the practical default for a small VPS that does not already run a public web service. Slack supplies and refreshes a WebSocket URL at runtime; your server makes the outbound connection. HTTP mode is a better fit when you already operate a public HTTPS service, require a stable Request URL, or are building a broadly distributed application.

Decision point Socket Mode HTTP endpoint
Inbound exposure No public application listener is required; the VPS initiates the connection. Slack must reach a public HTTPS endpoint.
Domain and TLS No domain or certificate is needed for the bot connection. Use a domain, certificate, and reverse proxy in front of Bolt.
Firewall and corporate networks Usually simpler because outbound HTTPS/WebSocket traffic is allowed in many networks. Requires an inbound HTTPS rule and correctly routed DNS.
Application configuration Start SocketModeHandler with the app-level token. Configure Slack’s Request URL, commonly /slack/events, and give Bolt the signing secret.
Scaling and load balancing Each running connection is a live WebSocket; plan connection ownership before running replicas. Stateless HTTP workers can sit behind a load balancer, provided signing verification and event handling are consistent.
Marketplace distribution Slack’s legacy Socket Mode documentation says Socket Mode apps are not currently allowed in the public Marketplace; verify the current policy before depending on that restriction. HTTP is the conventional choice for a broadly distributed or Marketplace-oriented app.

Do not expose a random port just because a tutorial does. In Socket Mode, keeping the bot process unbound to a public interface reduces attack surface. In HTTP mode, expose only the reverse proxy’s HTTPS port and keep the Python process on a local socket or loopback address.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Step 4: Provision and harden the Linux VPS

Create a least-privilege account

Use a separate account for deployment and another dedicated account for the running service. The service account should own only the files it must read and should not have administrative privileges.

sudo adduser --system --group --home /opt/slackbot slackbot
sudo chown -R slackbot:slackbot /opt/slackbot

Use SSH keys rather than password-only access, disable or restrict direct root SSH login according to your provider’s recovery process, and grant administrative rights only to the account used for setup and maintenance. Ubuntu’s security guidance emphasizes least privilege, SSH, a firewall, and automatic security updates.

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Apply firewall rules carefully

Ubuntu identifies ufw as its default firewall frontend. Confirm your actual SSH port and source restrictions before enabling it:

sudo ufw allow OpenSSH
sudo ufw enable
sudo ufw status verbose

If SSH uses a nonstandard port, replace OpenSSH with the matching rule before running ufw enable. Locking yourself out is avoidable: keep an existing SSH session open while testing a second connection. For Socket Mode, allow SSH and outbound HTTPS/WebSocket traffic and do not open an inbound bot port. For HTTP mode, allow only the HTTPS port used by the reverse proxy. Configure the VPS provider’s security group and the host firewall consistently; a permissive cloud rule can undo a restrictive host rule.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep the operating system patched

Ubuntu normally installs unattended-upgrades and runs it daily through systemd timers. Review its logs, reboot policy, and whether package updates restart services. Schedule maintenance for updates that can replace Python, OpenSSL, or other runtime components, and test that the bot returns after a reboot.

Step 5: Store secrets outside the project

Create a root-owned environment file:

sudo install -d -m 0750 -o root -g slackbot /etc/slackbot
sudo install -m 0600 -o root -g slackbot /dev/null /etc/slackbot/slackbot.env
sudoedit /etc/slackbot/slackbot.env

Put only environment assignments in that file:

SLACK_BOT_TOKEN=xoxb-replace-this-value
SLACK_APP_TOKEN=xapp-replace-this-value

Because the service runs as slackbot, the group permission must let that account read the file while keeping all other users out. Verify the mode and ownership, and ensure the file is excluded from backups that are not encrypted. If a token is exposed, revoke or rotate it in Slack immediately, update the file, and restart the service.

Step 6: Run it continuously with systemd

SSH sessions are not process supervisors. Closing a terminal, losing a network connection, or rebooting the VPS should not stop the bot. Create /etc/systemd/system/slackbot.service:

[Unit]
Description=Slackbot
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=slackbot
WorkingDirectory=/opt/slackbot
EnvironmentFile=/etc/slackbot/slackbot.env
ExecStart=/opt/slackbot/.venv/bin/python /opt/slackbot/app.py
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

Load, enable, and inspect it:

sudo systemctl daemon-reload
sudo systemctl enable --now slackbot
sudo systemctl status slackbot
sudo journalctl -u slackbot -f

Restart=on-failure handles crashes, while RestartSec=5 prevents an immediate tight restart loop. A clean stop remains intentional. If you change the unit, run daemon-reload; if you change only the environment file, restart the service:

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC
sudo systemctl restart slackbot

Systemd is Ubuntu’s native configuration for long-running processes. The journal gives you a first diagnostic source without writing tokens or ad-hoc log files into the application directory.

Step 7: Configure the HTTP branch when Socket Mode is not suitable

HTTP mode requires Slack to reach a configured Request URL. Set the URL to the Bolt endpoint, commonly /slack/events, and provide the app’s signing secret to Bolt so incoming requests can be verified. Place a reverse proxy in front of the Python application, terminate TLS there, and bind Bolt to loopback or a private socket rather than a public interface.

Your deployment then needs DNS, a valid certificate, an inbound HTTPS firewall rule, proxy timeouts compatible with Slack requests, and a health and log strategy for both proxy and application. Keep the endpoint fast: acknowledge Slack’s request before doing slow work, then queue or perform the longer operation separately. Slack can retry Events API deliveries when requests fail, so handlers must tolerate duplicates.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

HTTP mode does not eliminate token hygiene. Keep the bot token, signing secret, and any app-level token in the same protected configuration system, and rotate each credential independently when required.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Design listeners for retries and restarts

Acknowledge quickly

Slack expects prompt acknowledgement. A listener that waits on a slow database query, external API, or file operation before responding is more likely to trigger a retry. Return an acknowledgement first, then process slow work in a queue or background worker where the feature requires it.

Make work idempotent

Retries and process restarts can deliver the same logical event more than once. Use Slack’s event or request identifiers, your own durable job key, or a database constraint to ensure that a repeated delivery does not duplicate a payment, ticket, message, or other side effect.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Log useful context without secrets

Log event type, request or event ID, execution time, and outcome. Redact tokens, signing secrets, authorization headers, and sensitive message content. Alert on repeated restarts rather than treating every single restart as an outage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Updating the bot without losing control

  1. Keep source code, requirements.txt (or a lock file), the environment-file template, and deployment notes in a private repository or encrypted backup. Never commit the real environment file.
  2. Review dependency changes before installing them. Upgrade the virtual environment rather than system packages used by other applications.
  3. Run a syntax or smoke test with the service stopped or in a staging directory.
  4. Install the new code, restart with sudo systemctl restart slackbot, and watch sudo journalctl -u slackbot -f.
  5. Keep the previous release and dependency set available so you can roll back if startup, authentication, or event handling fails.

Test the rollback procedure whenever you upgrade Python, Bolt, or the operating system. A backup that has never been restored is only an assumption.

Troubleshooting by symptom

The process exits immediately

Run sudo systemctl status slackbot and inspect sudo journalctl -u slackbot -n 100 --no-pager. Common causes are a wrong ExecStart path, a missing virtual environment, a syntax error, or an environment file that systemd cannot read. Confirm that /opt/slackbot/.venv/bin/python exists and that the service account can read the application and environment file.

Socket Mode never connects

Check that the app-level token is an xapp- token with connections:write, that the bot token belongs to the intended workspace, and that outbound HTTPS/WebSocket traffic is permitted by both the cloud security group and the host firewall. Do not add an inbound listener merely to make Socket Mode work.

Slack shows an authorization or scope error

Compare the listener’s required capability with the app’s bot scopes. After changing scopes, reinstall the app if Slack requests it, then replace the bot token in the environment file and restart the service.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

HTTP requests fail verification

Verify the signing secret, the exact Request URL, proxy forwarding, system clock, and TLS certificate. Ensure that the reverse proxy forwards the request body without modification that would break signature verification. Keep the application endpoint private behind the proxy.

The bot replies twice

Look for Slack retries and for duplicate processing in your own code. Record event IDs, acknowledge promptly, and make the side effect idempotent before adding more aggressive retry settings.

The bot stopped after a reboot or update

Check that the unit is enabled with systemctl is-enabled slackbot, inspect the journal around boot, and confirm that the environment file and virtual environment still exist. Review automatic-update logs and your reboot policy; a package update may have restarted the process while leaving a configuration or dependency problem behind.

Production readiness checklist

  • Only required Slack bot scopes are granted.
  • xoxb- and xapp- tokens are outside source control and readable only by the service.
  • The bot runs as a dedicated non-root account.
  • SSH access is tested through the firewall before ufw is enabled.
  • Socket Mode has no unnecessary inbound application port; HTTP mode exposes only HTTPS through a reverse proxy.
  • The service is enabled in systemd and restarts after a failure.
  • Logs are useful, redacted, retained, and monitored for restart loops.
  • Listeners acknowledge quickly and handle duplicate deliveries safely.
  • Operating-system security updates, reboot behavior, and maintenance windows are understood.
  • Source, dependency metadata, configuration templates, and persistent state are backed up, and a rollback has been rehearsed.

Bottom line

For a single-workspace Slackbot on a Linux VPS, use Bolt for Python in a virtual environment, keep credentials in a root-protected environment file, choose Socket Mode unless you genuinely need a public HTTP service, and run the process under systemd as a dedicated user. Add HTTPS, a reverse proxy, signing-secret verification, and stricter inbound firewall rules only for the HTTP architecture. Treat retries, token rotation, updates, logs, backups, and rollback as part of the build rather than tasks to postpone after the first successful reply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.