Read if:
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}".
Now lets get started with the integration part:
<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>
<script>
function onSubmit(e) {
await fetch('/contact', {
method: 'post',
headers: {accept: 'application/json'},
body: new FormData(e.target as HTMLFormElement)
});
}
</script>
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;
}
};
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.
Our service will help you design and develop your product.