This repository contains an example of a Telegram bot built using FastAPI, running with Uvicorn, and utilizing ngrok to handle the Telegram webhook in a local environment.
-
Clone the repository:
git clone https://github.com/Vadilonga/telegram-bot-fast-api-uvicorn cd telegram-bot-fast-api-uvicorn
-
Create a virtual environment and activate it:
python3 -m venv venv venv\Scripts\activate # On Ubuntu use: source venv/bin/activate
-
Install the required dependencies:
pip install -r requirements.txt
-
Create a
.env
file in the project root and add your Telegram Bot API token:BOT_API_TOKEN=your-telegram-bot-token DOMAIN_URL=https://your-ngrok-url/
-
Download or install ngrok, you can find the download here https://ngrok.com/download
-
Start ngrok to expose the local server with a public URL:
./ngrok http 8000
-
Copy the public URL provided by ngrok into the
.env
file under DOMAIN_URL
-
Start the bot using Uvicorn:
uvicorn main:app --host 0.0.0.0 --port 8000
-
Set the webhook by accessing the
/setwebhook
endpoint in the browser. The page may ask you to confirm that you want to visit the site, click the button to confirm. Once you have set the webhook, if everything is set up correctly, you should see a response indicating "webhook setup ok". -
Open telegram, find your bot chat and send the
/start
command. If the bot is set up properly, it should respond to your message.