How to Send Logs and Errors to Telegram bot from JavaScript

How to Send Logs and Errors to Telegram bot from Anywhere

Alexander
5 min readSep 28, 2024

--

In this article I will give you a step-by-step guide on how to create your first Telegram bot for logging, host it on Supabase and use it to log errors from your projects. Enjoy 📕

Tech stack:

  • Typescript
  • grammY bot framework
  • Supabase Edge Functions (free plan)

By the way, you can try my Telegram Logger in just 1-click ⚡ for free and later move to your own implementation. Use promo code NICE to get +69 requests for free.

1. Create your bot using BotFather

Open @BotFather bot in Telegram and follow his instructions. He will give you token that you need to keep secure and store safely. This token allows you (and only you) to control the bot.

Creating Telegram bot using BotFather

2. Decide where and how you will host your bot

There are many options that you can use, for example, you can use this guide to explore them. I will use Supabase Edge Functions because you can implement and host them really fast.

To run Supabase commands below you need to have Supabase CLI installed.

Create Supabase project:

mkdir logger-bot
cd logger-bot
supabase init

Add bot function which you will use only once locally to get your Telegram user id, so you can send messages to youself:

supabase functions new bot

Then add log function which will the the endpoint that you will call to send logs to yourself:

supabase functions new log

By now your project structure should look like this:

Supabase project structure

Now let’s start Supabase Edge Functions locally and get your user id:

supabase start
supabase functions serve

In order to run Supabase locally, you need to have Docker installed.

3. Implement the bot

First, let’s implement the /start command to get your user id:

import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { Bot } from "https://deno.land/x/grammy@v1.30.0/mod.ts";

const botToken = Deno.env.get("BOT_TOKEN");

if (!botToken) {
throw new Error("BOT_TOKEN is not set");
}

const bot = new Bot(botToken);

bot.command("start", (ctx) => ctx.reply(`Welcome! Your ID is ${ctx.from?.id}`));

Deno.serve(async () => {
await bot.start();
return new Response();
});

Because we don’t need this bot to respond to messages in production, we can implement this function using long polling. This is the limitation of the Supabase Edge Functions. There is an alternative method that will work — webhooks, but we don’t need it for this bot. More on it you can find at the end of the guide.

Now trigger this function using curl in your terminal and then send /start command to your bot:

curl http://127.0.0.1:54321/functions/v1/bot
Getting your user id from Telegram bot

Then, let’s implement the log endpoint:

import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { Bot } from "https://deno.land/x/grammy@v1.30.0/mod.ts";

const botToken = Deno.env.get("BOT_TOKEN");

if (!botToken) {
throw new Error("BOT_TOKEN is not set");
}

const bot = new Bot(botToken);

Deno.serve(async (req) => {
const { message } = await req.json();

// User ID from the previous step
await bot.api.sendMessage(386062027, message);

return new Response();
});

Finally, to send your first log you can run the following command in your terminal:

curl http://127.0.0.1:54321/functions/v1/log \
-d '{ "message": "Hello World!" }'

The code is ready. Now you just need to host your Telegram bot on Supabase or whatever service you chose.

4. Deploy to Supabase

To begin, you need to create a new Supabase project in the console and link your local project to remote project using supabase link command. Then add your BOT_TOKEN to Supabase Edge Functions Secrets Management:

Supabase Edge Functions Secrets Managment

And finally deploy your Telegram bot log function to Supabase with the following command in your terminal:

supabase functions deploy log

5. Use your bot

To use your bot you will need to get production endpoint and JWT token from Supabase console. After you done it, your request should look like this:

curl -L -X POST ‘https://zdywmlftpexepvakrnnn.supabase.co/functions/v1/log' \
-H ‘Authorization: Bearer [YOUR ANON KEY]’ \
— data ‘{“message”:”Hello World!”}’

Run it in your terminal and your bot will send you the message:

Telegram bot to send logs to yourself

Congratulations 🎉 You just created and hosted your personal bot for logging errors from your projects to your Telegram bot 🤖

And to use it in your own projects, you can create some function similar to what I use in Typescript:

export async function telegramLog(message: string) {
try {
await fetch('https://zdywmlftpexepvakrnnn.supabase.co/functions/v1/log', {
method: 'POST',
headers: { Authorization: `Bearer ${Deno.env.get('TELEGRAM_LOGGER')}` },
body: JSON.stringify({
message,
}),
});
} catch (err) {
console.error('Failed to send log to the logger', err);
}
}

or Flutter / Dart:

import 'package:dio/dio.dart';
import 'package:travel_exchanger/config/env.dart';

final dio = Dio();

Future<void> telegramLog(String message) async {
await dio.post<Map<String, dynamic>>(
'https://zdywmlftpexepvakrnnn.supabase.co/functions/v1/log',
options: Options(
headers: {
'Authorization': 'Bearer ${Env.telegramLoggerToken}',
},
),
data: {
'message': message,
},
);
}

Telegram Logger — 1-click solution

If you want to save your time, you can skip ALL above steps in just 1-CLICK ⚡ using my Telegram Logger 🤖. You can even try Telegram Logger for FREE and move to your own bot later. Don’t procrastinate and ship fast 🚀

🎁 PROMO CODE for +69 free requests: NICE

Short demo:

Telegram Logger — Start logging errors to Telegram in 1-click

Thank you for reading 👋

--

--