How to host a Python bot or app for your community
Run a Python bot, web app or scheduled worker on a panel: layout, requirements.txt, secrets, ports, signals and crash loops, logging, updates and memory.
Maybe it is a Telegram bot that greets new members of your group. Maybe it is a FastAPI app that serves your community's tournament bracket, or a worker that checks your game server every five minutes and posts in chat when it goes down. Whatever it is, it is written in Python, it works on your machine, and now it needs to run without you.
This guide covers hosting a general Python project for your own community on a panel: the layout, dependencies, secrets, ports, shutdowns, logs, updates and memory. Discord bots have extra steps (intents, command sync) covered in how to host a discord.py bot for your community.
How a panel runs your Python project
Your project runs as a single long-lived process inside a container with fixed limits for memory, CPU and disk. The panel starts it with a command such as python main.py, shows standard output in a console, and lets you stop, start and restart it. Packages are installed from your requirements.txt file.
Choose your Python version deliberately. Use a version that is still supported (the release schedule is on python.org), develop on the same minor version you run on the server, and check that your important packages support it.
A layout that deploys cleanly
community-worker/
main.py (entry point: reads config, starts the app)
requirements.txt
.env.example (variable names, no values)
.env (real values, never committed)
app/
__init__.py
config.py
jobs.py
web.py
data/
state.db
Two habits help a lot on servers:
- One entry point. Whatever the panel runs should be one file that sets things up and starts the work. Avoid code that only runs when you import a module from a notebook or an IDE.
- Paths relative to the code, not the working directory. On a server, the working directory may not be where you think. Build paths from the file's location:
from pathlib import Path
BASE = Path(__file__).resolve().parent
DB_PATH = BASE / "data" / "state.db"requirements.txt, pinned
requirements.txt lists what to install. Generate it from a clean virtual environment so it contains only this project's packages:
python -m venv .venv
source .venv/bin/activate
pip install python-telegram-bot fastapi uvicorn python-dotenv
pip freeze > requirements.txt
Pinned versions (package==1.2.3) mean the server installs exactly what you tested. Without pins, a restart that reinstalls packages can silently pull in a new major version and break the app. Upgrade on purpose: update at home, test, regenerate the file, deploy.
Do not upload .venv. It contains paths and compiled files tied to your machine. If a package fails to install on the server with a "building wheel" error, it is usually a compiled package without a prebuilt wheel for the server's Python version. Check for a newer release of the package, or a Python version it supports, before reaching for build tools.
Configuration and secrets
Keep every secret in environment variables: bot tokens, API keys, database URLs, webhook secrets. Load them in one place and fail at startup if anything is missing:
import os
from dotenv import load_dotenv
load_dotenv()
def need(name):
value = os.environ.get(name)
if not value:
raise SystemExit(f"Missing environment variable {name}")
return value
TELEGRAM_TOKEN = need("TELEGRAM_TOKEN")
Rules for a shared server:
.envgoes in.gitignorebefore the first commit..env.exampledocuments names with empty values.- Helpers get their own panel access, not a copy of your secrets.
- If a secret leaks, revoke it at the source (for a Telegram bot, the BotFather; for other services, their dashboard) before anything else.
Ports for web apps
A bot in polling mode only makes outgoing connections and needs no port. A web app, a webhook receiver or a dashboard needs to listen on the port the panel allocated, on all interfaces:
uvicorn app.web:app --host 0.0.0.0 --port "$SERVER_PORT"
Check which environment variable carries the allocated port on your panel, or use the number shown in its network section. For Flask, run a production server such as Gunicorn rather than the built-in development server, which is not meant for public traffic and listens only on localhost by default.
Polling or webhooks for chat bots
Telegram and several other chat platforms let a bot receive updates in one of two ways, and the choice changes how you host it.
- Polling: the bot repeatedly asks the platform for new updates. It needs no inbound port and no public address, works behind any firewall and is the simplest option for a community bot. The cost is a constant, small stream of outgoing requests.
- Webhooks: the platform sends each update to a URL you register. The bot needs an open port, a reachable address and, for Telegram, HTTPS. It reacts faster under heavy traffic, but it is more to set up and more to break.
For a bot that serves one group or a few channels, polling is almost always the right choice. Switch to webhooks only when you have a reason, such as many busy chats, and when you have a plan for the HTTPS part. Never run polling and a webhook for the same bot token at once: the platform will reject one of them, and the error is confusing if you do not know why.
The same thinking applies to scheduled jobs. If your worker only needs to reach out (check a server, call an API, post a message), it should not listen on a port at all. Fewer open ports means fewer things that can go wrong.
Signals, shutdown and crash loops
When you stop or restart the server, Python receives a termination signal. If you write to SQLite or files, make sure you close them cleanly. A simple pattern for an asyncio worker:
import asyncio, signal
async def main():
stop = asyncio.Event()
loop = asyncio.get_running_loop()
loop.add_signal_handler(signal.SIGTERM, stop.set)
worker = asyncio.create_task(run_jobs(stop))
await stop.wait()
await worker
A crash loop is when the process fails during startup again and again. Common Python causes: a missing environment variable, a module not installed, a wrong relative path, or a syntax error in a half-edited file. Stop the server, read the first traceback after startup and fix that. Pressing restart on a crash loop only fills the console.
In long-running loops, catch exceptions per iteration and log them, so one bad response from an API does not end the whole worker:
while not stop.is_set():
try:
await check_server()
except Exception:
log.exception("check_server failed")
await asyncio.sleep(300)Logs you can trust
Python buffers output when it is not writing to a terminal. On a panel console, that means lines can arrive late, or be lost when the process crashes. Run with python -u main.py or set PYTHONUNBUFFERED=1.
Use the logging module rather than print, with timestamps and levels:
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
log = logging.getLogger("worker")
Log actions and IDs, never secrets or private messages. If you also log to files, rotate them with logging.handlers.RotatingFileHandler, or old logs will eventually fill the disk.
Memory and resource limits
Your process shares a fixed memory limit with nothing else, and Python will not warn you before it hits it. The biggest factor is usually imports: heavy data and image libraries cost memory just by being loaded. Other common causes of growth are lists or dicts that only get new entries and caches without a size limit (functools.lru_cache with maxsize=None is a classic).
Watch the memory graph for a few days after deploying. Flat with small bumps is healthy. A slope that never comes down is a leak worth finding before it becomes a nightly crash.
Updating
- Take a backup that includes
data/. - Upload the changed files.
- Reinstall packages if
requirements.txtchanged. - Restart and watch the startup lines.
If you plan a Python version upgrade, test it at home first with a fresh virtual environment. Some packages lag behind new Python releases.
Doing it through a branded panel with Enzonic for Resellers
If you run a few projects for your community, maybe next to game servers, Enzonic for Resellers gives you a panel with your own name and colours. Opening a site is free, and panel-only mode serves only sign-in and the customer panel, with no storefront.
The panel has a live console with power controls and CPU, memory and disk stats, a file manager and SFTP, backups (also on a schedule), scheduled tasks, subusers for co-admins and network ports for web apps. With Enzonic for Resellers, Python apps runs on Enzonic nodes in Europe, North America and Asia and on your own Pterodactyl or Pelican Wings nodes, so you can sell it without running any hardware. You can also connect your own Pterodactyl Wings or Pelican Wings machine. Servers you grant on Enzonic nodes have their base price charged monthly from your credits.
Running other languages too? See the guides for Node.js, Go and Java. Open a site when you are ready.
Frequently asked questions
Why does my Python app show no output in the console?
Output is buffered when Python is not attached to a terminal. Start it with python -u or set PYTHONUNBUFFERED=1, and prefer the logging module for anything important.
Should I upload my virtual environment?
No. Upload requirements.txt and install on the server. A virtual environment contains machine-specific paths and compiled files.
How do I run a Python job every hour?
Either keep the process running and sleep between runs, with errors caught per run, or use the panel's scheduled tasks. A continuously running worker with clear logs is easier to debug.
My Flask app works locally but not on the server. Why?
The development server listens only on localhost by default and uses its own port. Run it with a production server bound to 0.0.0.0 on the allocated port.