hanki.dev

Host Telegram bot for free (with database!)

‼️ This doesn't work anymore since Heroku decided to ditch their free plan. Check out my updated tutorial!

Heroku allows you to run a single app 24/7 if you have a verified account. Free Heroku dynos restart every day which means that you'll lose any data saved. If you want to persist your apps data you can use Heroku Postgres free plan. In this post I'm using a bot made with node.js but Heroku supports other languages as well.

Add Express

The app will crash immediately unless you're hosting some kind of web page. I'm using Express for this but I'm sure you can find more lightweight solution if needed.

const express = require("express");

// BOT LOGIC

// Needed for heroku
const port = process.env.PORT || 3000;
const expressApp = express();
expressApp.get("/", (req, res) => res.send("Working! ( ͡° ͜ʖ ͡°)"));
expressApp.listen(port, () => console.log(`Listening on port ${port}`));

Deploy to Heroku

Create an app from Heroku dashboard. Should be pretty self-explanatory. Then either connect the app to your GitHub repo, or push the code to Heroku with git push heroku master.

Add environment variables

I guess this is optional but highly recommended. I always create 2 Telegram bots with Botfather: one for developing and one for production. So go to Heroku app settings → Config Vars and add your production BOT_TOKEN. This way you can keep developing using your other token, while the bot is safely running in production.

Verify your account

Without verification you only have 550 free dyno hours a month. This is almost 200 hours less than we actually have hours in a month. If you verify your account you get additional 450 hours, which allows your app to run 24/7! Note that the hours are shared across all your apps, so you can't run 2 apps 24/7 at the sime time (but you can verify another account with same credit card 🙃)

Give your app some drugs

Heroku apps will sleep after 1 hour of no traffic. You can prevent this by pinging it every hour, which is easiest with Kaffeine

Add PostgreSQL

Like I said in the intro, if you need persistent storage you can use Postgres free plan. It allows you to store 1GB or 10,000 rows, which is probably more than enough for a simple Telegram bot. I'm total noob when it comes to databases but this tutorial helped me a ton!