Integrating Telegram api with SvelteKit.

integrating-telegram-api-with-sveltekit-5gb

Read if:

  • You know how SvelteKit works.
  • You wanna get notified on telegram when someone submit a form on your SvelteKit website.

Introduction

I was working one of my projects and i wanted to get notified with the data as soon as user submit's the data.
At the time I thought of Email, WhatsApp, SMS and Telegram.
But I check my emails twice a day which is why i dropped it while for WhatsApp and SMS services you need to pay. So, I was left with telegram.
Now telegram provides a pretty good documentation of their api's.

So, first i tried some open sourced libraries which are available on NPM but none of them worked how i wanted to so i started to make my resource for that. I checked for SvelteKit with telegram, telegram for node but didn't workout for me.

So, i started working my own and made myself go through the telegram docs.

The only feature that i needed was sendMessage using bot api.
I found the api "https://api.telegram.org/bot${Token}/sendMessage?chat_id=${chatId}&text=${botMessage}".

  • Token is your bot token that you can get from BotFather when you create a Bot on telegram.
  • chatId is your username's Id on telegram server, that you can get from RawDataBot.
  • botMessage is the message you need to send to bot and that will be seen in your chat.

Now lets get started with the integration part:

  • Create you SvelteKit App
  • In src/routes/index.svelte file make HTML Form.
<form on:submit|preventDefault={onSubmit} method="Post">
<label for="name">Name</label>
<input type="text" id="name" name="name"/>
<label for="email">Email</label>
<input type="email" id="email" name="email"/>
<label for="contact">Contact</label>
<input type="tel" id="contact" name="contact"/>
<button type="submit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode
  • Now add a onSubmit handler that we assigned to on:submit event.
<script>
function onSubmit(e) {
await fetch('/contact', {
method: 'post',
headers: {accept: 'application/json'},
body: new FormData(e.target as HTMLFormElement)
});
}
</script>
Enter fullscreen mode Exit fullscreen mode
  • Create a new file in routes index.ts or index.js on your preference. index.ts is a shadow/page endpoint (click here for docs).
import type { RequestHandler } from '@sveltejs/kit';

export const post: RequestHandler = async ({ request }) => {
    const form = await request.formData();
    const name = String(form.get('name'));
    const email = String(form.get('email'));
    const contact = String(form.get('contact'));
    const botMessage = `This is a test notification %0A Name: ${name} %0A Email: ${email} %0A Contact: ${contact}`;
// %0A is url encoded '\n' which is used for new line.
    try {
        const Token = import.meta.env.VITE_TELEGRAM_BOT_TOKEN;
        const chatId = import.meta.env.VITE_TELEGRAM_CHAT_ID;
        const url = `https://api.telegram.org/bot${Token}/sendMessage?chat_id=${chatId}&text=${botMessage}`;
        const res = await fetch(url);
        return await res.json();
    } catch (err) {
        console.error(err);
        return null;
    }
};
Enter fullscreen mode Exit fullscreen mode

This method is needed to be done on server on server side because we wanna side our chatId and bot Token for security reasons. if we make a browser request this will leak in api call.

Thank you, this is my first post here if you find any errors please let me know i'll fix them.

This is me writing for you. If you wanna ask or suggest anything please put it in comment.