title: Kgffk
emoji: π€
colorFrom: blue
colorTo: green
sdk: docker
pinned: false
Telegram Bot Hoster on Hugging Face Spaces
This guide will help you deploy your Telegram bot on Hugging Face Spaces, ensuring it runs permanently and loads sensitive information securely from environment variables.
1. Project Structure
Your project structure should look like this:
. (root directory, e.g., your-space-name)
βββ hoster/
β βββ hoster/
β β βββ host.py
β β βββ requirements.txt
β βββ Procfile
βββ README.md
2. Hugging Face Space Setup
Follow these steps to set up your bot on Hugging Face Spaces:
a. Create a New Space
- Go to Hugging Face Spaces.
- Click on "Create new Space".
- Choose a Space name (e.g.,
my-telegram-bot). - Select "Docker" as the Space SDK.
- Choose "Python" as the Docker template.
- Click "Create Space".
b. Upload Files
- Once your Space is created, navigate to the "Files" tab.
- Click on "Add file" -> "Upload file" or use Git to clone the repository and push your files.
- Upload the
hosterdirectory (containinghoster/host.py,hoster/requirements.txt) and theProcfileto the root of your Space.
c. Configure Environment Variables (Secrets)
Sensitive information like your bot token and IDs should be stored as secrets on Hugging Face Spaces.
In your Space, go to the "Settings" tab.
Scroll down to the "Repository secrets" section.
Add the following environment variables:
BOT_TOKEN: Your Telegram Bot API Token (from BotFather).OWNER_ID: Your Telegram User ID (numeric).ADMIN_ID: Your Telegram User ID (numeric, can be the same as OWNER_ID).YOUR_USERNAME: Your Telegram username (e.g.,@your_username).UPDATE_CHANNEL: Your Telegram update channel link (e.g.,@your_channel_link).
Example:
Name Value BOT_TOKEN1234567890:ABCDEFGHIJKLMN_OPQRSTUVWOWNER_ID123456789ADMIN_ID123456789YOUR_USERNAME@my_telegram_usernameUPDATE_CHANNEL@my_update_channel
d. Ensure Dependencies are Installed
Hugging Face Spaces will automatically install dependencies listed in requirements.txt. Make sure your requirements.txt includes:
telebot
requests
flask
gunicorn
psutil
sqlite3
...
3. Auto-Ping Mechanism (Keep-Alive)
To prevent your bot from sleeping on Hugging Face Spaces, an auto-ping mechanism has been integrated into host.py:
- A Flask web server runs on port
8081(as defined inhost.py). Hugging Face will expose this as the main web service. - A separate thread periodically pings this Flask server (
http://localhost:8081) every 5 minutes. - This continuous activity keeps the Space active and prevents it from being idled by Hugging Face's resource management policies.
4. Running the Bot
The Procfile tells Hugging Face how to start your application:
web: python hoster/host.py
This command will execute your host.py script, which starts the Telegram bot polling and the Flask keep-alive server.
Your bot should now be running permanently on Hugging Face Spaces!