Skip to main content

Keep your Python bots alive with a zero-config, production-ready background web server.

Project description

StayPresent

StayPresent Logo

PyPI version Python versions License: MIT

🛖 About

A lightweight Python package designed to keep your bots and background scripts alive by running a dedicated Flask web server alongside your main application.

Perfect for deploying on platforms like Render, Railway, Koyeb, Heroku, or any host that requires an active HTTP port to keep your service running.


Contents


🚀 Features

  • Zero-Friction Setup: Get running with just one line of code.
  • Production-Ready by Default: Automatically detects and uses waitress to avoid Flask's "development server" warnings.
  • Auto-Restarts & Crash Recovery: Automatically respawns your bot process if it crashes, complete with customizable delays and max-restart limits.
  • Flexible Responses: Serve custom plain text, JSON (default), or full HTML templates.
  • Static Asset Serving: Automatically serves CSS, JS, and images located next to your HTML templates.
  • Advanced Control: Easily pass custom command-line arguments and environment variables directly to your bot process.
  • Fail-Safe Logging: Logs a clear error if the underlying web server dies unexpectedly.

📦 Installation

Install via pip:

pip install staypresent

Recommended for Production: To automatically use a production WSGI server and suppress Flask development warnings, install the prod extra. This pulls in waitress.

pip install staypresent[prod]

(Note: If waitress isn't installed, StayPresent gracefully falls back to Flask's built-in development server and logs a one-time warning.)


💻 Usage Guide

Basic Usage (Text Response)

import staypresent

staypresent.web.text("Made With ❤️")
staypresent.run("bot.py")

*Navigating to http://localhost:8080 will return plain text: Made With ❤️*

Note: If you don't configure a response, StayPresent defaults to a JSON response of {"message": "I'm Present"} at the root / route.

JSON Response

A safe copy of your dictionary is stored. If you need to update live data, just call staypresent.web.json() again.

import staypresent

staypresent.web.json({
    "status": "online",
    "developer": "John",
    "message": "Made With Love ❤️"
})

staypresent.run("bot.py")

HTML Response (with Static Files)

Serve a full HTML page. The file is read fresh on every request, allowing you to edit your HTML on disk without restarting your bot.

import staypresent

# The path is validated immediately and will raise a FileNotFoundError if missing
staypresent.web.html("template/index.html")
staypresent.run("bot.py")

Serving Static Assets: Any files (CSS, JS, images) in the same directory as your HTML file are automatically served. Path traversal is strictly blocked for security.

<!-- template/index.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>My Bot</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1>I'm alive!</h1>
    <img src="images/logo.png">
  </body>
</html>

Custom Host, Port, and Threads (Complete Example)

import staypresent

staypresent.web.json({
    "status": "Running",
    "version": "1.0.0"
})

staypresent.run(
    "bot.py",
    host="0.0.0.0",
    port=8080,
    threads=8  # Increase if receiving real web traffic
)

⚙️ API Reference

staypresent.run(...)

Launch your bot script alongside the web server.

Parameter Type Default Description
bot_file str Required Path to the Python script to run alongside the server.
host str "0.0.0.0" Host to bind the web server to.
port int 8080 Port to bind the web server to.
production bool True Uses waitress if installed. Set to False to force the Flask dev server.
threads int 4 Number of worker threads for waitress. Increase this if serving real web traffic rather than just keep-alive pings. (Requires production=True and waitress).
restart_on_crash bool True Relaunch the bot process if it exits with a non-zero exit code.
max_restarts int 5 Maximum restart attempts after a crash before giving up.
restart_delay float 2.0 Seconds to wait before relaunching the bot process after a crash.
restart_reset_after float 60.0 Seconds the bot must stay alive to reset the consecutive crash counter back to 0.
bot_args list None Extra command-line arguments to pass to bot_file (e.g., ["--verbose"]).
env dict None Extra environment variables for the bot process. Merges over the current environment.

Note: port, threads, max_restarts, restart_delay, and restart_reset_after are validated up front — passing an invalid value (e.g. threads=0, a negative port) raises a ValueError immediately instead of failing silently or deep inside waitress.

Crash Recovery Details

StayPresent automatically monitors your bot process. If it exits with a non-zero exit code, StayPresent restarts it based on your configuration:

  • Clean Exits: An exit code of 0 is considered intentional and will not trigger a restart.
  • Manual Shutdowns: Stopping StayPresent via Ctrl+C (SIGINT) or SIGTERM shuts down both the server and the bot cleanly.
  • Smart Counters: The max_restarts limit applies to consecutive crashes. If your bot runs successfully for the duration of restart_reset_after (default 60 seconds), the crash counter resets.

Built-in Health Check

A dedicated /health endpoint is automatically exposed, returning {"status": "ok"}. This is incredibly useful for platform pingers and uptime monitors that require a dedicated health-check path separate from your root / response.

Inspecting the Current Response

staypresent.web.get()
# -> {"type": "json", "value": {"message": "I'm Present"}}

Returns whatever text() / json() / html() last configured, as {"type": ..., "value": ...}. Mainly useful for debugging or unit-testing your own code around StayPresent.


📝 Logging

StayPresent logs to its own "staypresent" logger, not the root logger — it never calls logging.basicConfig() globally. This means it won't clobber, duplicate, or reformat logging you've already set up elsewhere in your script for unrelated loggers.

To change the log level or format, configure it like any other logger:

import logging
logging.getLogger("staypresent").setLevel(logging.WARNING)

🛠 Requirements

  • Python 3.8+
  • Flask
  • waitress (optional, but highly recommended for production)

💡 Use Cases

  • Discord & Telegram Bots
  • Background Workers & Automation Scripts
  • Keeping deployments alive on Render, Railway, Koyeb, and Heroku

License: MIT License

Made with ❤️ using Python.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

staypresent-1.3.4.tar.gz (13.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

staypresent-1.3.4-py3-none-any.whl (12.0 kB view details)

Uploaded Python 3

File details

Details for the file staypresent-1.3.4.tar.gz.

File metadata

  • Download URL: staypresent-1.3.4.tar.gz
  • Upload date:
  • Size: 13.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for staypresent-1.3.4.tar.gz
Algorithm Hash digest
SHA256 00dba47f6fb4895442dce5adc74cdf263d84f00a1d96b05afb9f05233a5a1b4b
MD5 e23553a477a9e749b43c4df20f92558d
BLAKE2b-256 2610ce1c31f5f8eb666ceed05b9284862b3922cef8233c025359103db8aa9260

See more details on using hashes here.

Provenance

The following attestation bundles were made for staypresent-1.3.4.tar.gz:

Publisher: python-publish.yml on NTDevLops/StayPresent

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file staypresent-1.3.4-py3-none-any.whl.

File metadata

  • Download URL: staypresent-1.3.4-py3-none-any.whl
  • Upload date:
  • Size: 12.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for staypresent-1.3.4-py3-none-any.whl
Algorithm Hash digest
SHA256 45068b4898347c9df00f3c5c324d45fbd566c72779296370711eb02d7ffb7b07
MD5 26a4a6e48fe3a06ab9665a557d40a73f
BLAKE2b-256 b4c1d72aa4e7f871f61db65d438dbbc8c5d0b5b1b25224ac23a0566fd09e0643

See more details on using hashes here.

Provenance

The following attestation bundles were made for staypresent-1.3.4-py3-none-any.whl:

Publisher: python-publish.yml on NTDevLops/StayPresent

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page