Template repo with boilerplate code to write Telegram bots in Go.
I implemented several bots for Telegram and each time I started by writing/copying boilerplate code. This repository is a template for a quick start of a new bot. It solves the following problems:
- App structure: follows the Standard Go Project Layout.
- Handy middlewares for HTTP-like processing updates from Telegram.
- Deploying bot as a Google Cloud Function and convenient local debugging with polling updates.
- Structured logging with zerolog lib.
- Sending custom metrics with OpenCensus to Google Cloud. See more in docs.
In short, this template will save you a couple of hours and allow you to immediately start implementing the bot's logic.
- Press "Use this template" button at the top or just follow the link.
- Clone the generated repository to your machine.
- Rename module and change import paths by calling the command (replace
github.com/author/newbot
with yours repo name):
./scripts/rename.sh github.com/author/newbot
- Fill configuration in .env file:
mv .env.example .env && nano .env
- Run your bot locally:
make run
To set up a webhook for receiving updates, fill the config in .env
file and run the following command:
./scripts/set_webhook.sh
To clear a webhook run the same script with -c
flag provided:
./scripts/set_webhook.sh -c
- Add domain-specific logic in internal/app package.
- Add update handlers in internal/app/bot/handlers package.
- The library telegram-bot-api is used to work with Telegram Bot API.
bin
- dir for compiled binary deps (look at thetools
directory).cmd/bot
- entry-point for running bot locally.internal
:internal/app
- contains business-logic layer and adapters to external world in sub-packages.internal/bot
- wrappers to work with Telegram Bot API and middlewares implementation.internal/bot/handlers
- handlers for different update types.internal/bot/middleware
- middlewares for all updates.internal/boot
- bootstrapping code for bot creation (used in local entry-point and Google Cloud Function).internal/env
- utilities for getting env-vars values.internal/logger
- logger creation code and custom log fields constants.internal/metrics
- metrics client creation code and registering of custom metrics.
scripts
- handy scripts for renaming module, changing import paths and setting up webhook URL.tools
- binary deps of a project.