Zero-dependency async SQLite cloud backup and auto-restore to private Telegram channels for ephemeral bot hosts.
pip install tg-sqlite-sync Copy PIP instructions
Zero-dependency async Python library to persist and back up SQLite databases directly to a private Telegram storage channel. Perfect for Telegram bots hosted on ephemeral platforms like Render, Railway, Fly.io, and Heroku.
Modern serverless and container hosts (Render, Railway, Fly.io) offer great free or low-cost hosting for Telegram bots, but their filesystems are ephemeral. Whenever your container restarts, sleeps, or redeploys, your local SQLite .db file is completely wiped.
Spinning up a managed PostgreSQL or MySQL database adds unnecessary cost, connection pools, and latency.
tg-sqlite-sync solves this elegantly: It uses a private Telegram channel as an infinite, free, persistent cloud backup engine. On startup, your bot automatically pulls the latest pinned SQLite database snapshot. When your bot updates data, it safely syncs consistent snapshots back to the channel.
tg-sqlite-sync --find-channel --token "YOUR_BOT_TOKEN" (Or python -m tg_sqlite_sync --find-channel)
Post a quick message in your channel, and it will immediately detect and print your CHANNEL_ID!
pip install tg-sqlite-sync (Or add tg-sqlite-sync to your requirements.txt / pyproject.toml)
from tg_sqlite_sync import TelegramSQLiteSync sync = TelegramSQLiteSync( bot_token="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", channel_id=-1001234567890, db_path="bot_data.db" ) # On Startup (before handling requests): await sync.restore() # Whenever data changes: sync.schedule_sync() # Debounced, throttled & async! # On Shutdown: await sync.close() 🛠️ Framework Integration Examples 🤖 python-telegram-bot (v20+) import os import sqlite3 from pathlib import Path from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes from tg_sqlite_sync import TelegramSQLiteSync DB_PATH = Path("bot.db") sync = TelegramSQLiteSync( bot_token=os.getenv("BOT_TOKEN"), channel_id=int(os.getenv("STORAGE_CHANNEL_ID")), db_path=DB_PATH, debounce_seconds=5.0 ) async def post_init(application): # Auto-restore on startup await sync.restore() async def post_shutdown(application): # Flush pending writes on shutdown await sync.close() async def add_item(update: Update, context: ContextTypes.DEFAULT_TYPE): # Perform database operations conn = sqlite3.connect(DB_PATH) conn.execute("INSERT INTO items (name) VALUES (?);", ("Widget",)) conn.commit() conn.close() # Request debounced cloud sync sync.schedule_sync() await update.message.reply_text("Item saved and cloud backup scheduled!") def main(): app = ( ApplicationBuilder() .token(os.getenv("BOT_TOKEN")) .post_init(post_init) .post_shutdown(post_shutdown) .build() ) app.add_handler(CommandHandler("add", add_item)) app.run_polling() if __name__ == "__main__": main() ⚡ aiogram (v3.x) import os import sqlite3 from pathlib import Path from aiogram import Bot, Dispatcher, types from aiogram.filters import Command from tg_sqlite_sync import TelegramSQLiteSync DB_PATH = Path("bot.db") sync = TelegramSQLiteSync( bot_token=os.getenv("BOT_TOKEN"), channel_id=int(os.getenv("STORAGE_CHANNEL_ID")), db_path=DB_PATH ) dp = Dispatcher() bot = Bot(token=os.getenv("BOT_TOKEN")) @dp.startup() async def on_startup(): await sync.restore() @dp.shutdown() async def on_shutdown(): await sync.close() @dp.message(Command("save")) async def save_cmd(message: types.Message): conn = sqlite3.connect(DB_PATH) conn.execute("INSERT INTO logs (text) VALUES (?);", (message.text,)) conn.commit() conn.close() sync.schedule_sync() await message.answer("Saved to SQLite & sync queued!") ⚙️ Configuration Reference TelegramSQLiteSync Parameters Parameter Type Default Description bot_token str Required Telegram Bot API token from @BotFather. channel_id int | str Required Private storage channel ID (usually starts with -100). db_path str | Path Required Local path to the SQLite database file. compress bool True Automatically compress database snapshots with gzip (~85% size savings). retention_count int 1 Number of recent backups to keep. Default 1 keeps channel 100% spotless (only 1 pinned backup). Set to 3+ for multi-backup history. debounce_seconds float 5.0 Quiet window duration before executing debounced sync. auto_delete_old_backup bool True Automatically purge backups exceeding retention_count. raise_on_failure bool False Whether to raise exceptions on network/Telegram failures. timeout float 60.0 HTTP request timeout in seconds. 📖 API Methods await sync.restore(target_path=None) -> bool: Downloads the latest pinned database snapshot and atomically replaces the local file. Returns True if restored, or False if channel has no previous backup.
await sync.backup(custom_caption=None) -> bool: Executes an immediate, consistent SQLite snapshot, uploads it to Telegram, pins the message, and purges the old backup.
sync.schedule_sync() -> None: Non-blocking call to schedule a debounced backup. Repeated calls within debounce_seconds reset the quiet-window timer.
sync.start_periodic_sync(interval_seconds=300.0) -> None: Starts an autonomous background task that triggers a backup every N seconds.
sync.stop_periodic_sync() -> None: Cancels the background periodic backup task.
await sync.flush() -> None: Immediately executes any pending debounced backup without waiting for the timer.
await sync.close() -> None: Stops periodic tasks and flushes pending backups. Ideal for container shutdown hooks (SIGTERM).
git clone https://github.com/EvoXx42/tg-sqlite-sync.git cd tg-sqlite-sync pip install -e ".[dev]" Run tests:
python -m unittest discover tests 🤝 Contributing Contributions, bug reports, and feature suggestions are warmly welcomed! Feel free to open an issue or submit a Pull Request:
telegram sqlite backup sync persistence ephemeral railway render flyio telegram-bot aiogram python-telegram-bot
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
None of the files in this release were uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




