cover image

What I learned from building a Telegram bot on Next.js

Dec 25 '20 / 2 min read
The future is now 🚀 Get yourself a cool sticker T-Shirt without never leaving Telegram. I wanted to try out Telegram Bot API's Payments feature so I built @StickerShirtsBot. It also comes with a frontend app stickershirts.com.

How does it work?

You send a sticker to @StickerShirtsBot, our API generates a mockup image of the result and sends it back to you. After you choose the colour and the size of the shirt you want, the bot sends you an order invoice. You input your address details and pay the order (all inside Telegram). Your order gets sent to Printful, we manually approve it for printing and the printed organic cotton T-Shirt gets automatically sent to you.
Technology
  • Telegram Payments
  • Next.js
  • Vercel
  • Jimp
  • Firestore
  • Google Cloud Storage

Next.js is a great tool for a variety of projects

Next.js might be a bit of an overkill for a chatbot, but I figured having it as an easy, standardised framework for building a function-based REST API is a good idea. Similar to Serverless framework, I like how you can deploy it anywhere and there's everything ready for building a frontend.
In my case, I'm using Telegram API's webhook feature to receive all messages sent to the bot. As most of the development work is done locally, my development bot is registered to push events to my local Next.js through ngrok endpoint.

Vercel's hobby plan might not be enough

Functions in hobby plan can only run for 10 seconds. Generating the mockup image from the sticker usually takes less than that, but there's always a chance for it taking longer. This means that sometimes the requests would fail before the user gets their mockup.
Moving the project over to a team account wasn't trivial either. Instead of a transfer feature, you have to remove the project from your account and import it manually to the new team account

Github Actions are a great companion for Vercel's hobby plan

If you wanna stick to the free hobby plan, you might want to consider an alternative solution for long-running jobs. Github actions is a good option for this.

You probably need a static file storage

Telegram caches images indefinitely, so in an ideal case, I could have generated the images to a /tmp directory temporarily and serve them once to Telegram when it requests the image. Unfortunately in the serverless world, there are no guarantees that the same /tmp directory is available when the request eventually gets made.
I first went with S3, which I then later on discarded for Google's Cloud Storage. For some reason writing to S3 sometimes took over 4 seconds for 200kB files.
Give the Telegram bot a try and tell me what you think!