telegram-auth-package
v1.0.1
Published
A TypeScript library for Telegram bot authentication and messaging
Maintainers
Readme
Telegram Authentication and Messaging Package
This package provides a simple and robust solution to integrate Telegram authentication and messaging into your web applications. It allows for easy authentication of users via Telegram OAuth, as well as the ability to send messages to Telegram users using a Telegram bot.
Features
- Telegram Authentication Integration: This package allows your application to authenticate users via Telegram OAuth. The authentication process is secure, and it ensures that the Telegram user's details (like name, username, photo) are captured and sent to your application.
- Secure Authentication Flow: By verifying the origin of the authentication request, this package ensures that only trusted websites can receive authentication data from the Telegram authentication service.
- Sending Messages via Telegram Bot: Once authenticated, you can send messages to users using the Telegram bot API. The package handles communication with the Telegram servers to send messages to specified chat IDs.
- Easy to Use: With simple, intuitive methods to start the authentication process, handle incoming authentication data, and send messages, this package is designed to be easy to integrate into any web application.
Installation
To use this package in your web application, you can either:
- Download the
telegramAuth.tsfile and place it in yoursrc/helpersdirectory, or - Install the package using npm or yarn (if available through package registries).
npm install telegram-auth-packageOr
yarn add telegram-auth-packageSetup
Before you start using the package, you need to set up a Telegram bot. Follow these steps to obtain the necessary credentials:
Step 1: Create a Telegram Bot
- Open Telegram and search for the BotFather.
- Type
/newbotand follow the instructions to create a new bot. - After creating the bot, BotFather will provide you with a bot token.
- Save the bot token, as you will need it to initialize the bot in the package.
Step 2: Set Up Your Telegram Bot ID
- After creating the bot, you will also need the bot ID. You can get the bot's ID by accessing the Telegram API or using tools like @userinfobot to retrieve the ID of your bot.
- Save the bot ID for initialization.
How to Use the Package
Step 1: Initialize the TelegramAuth Class
First, you need to import and initialize the TelegramAuth class in your application by providing the botToken and botId.
import { TelegramAuth } from './helpers/telegramAuth';
// Replace with your actual bot token and bot ID
const botToken = 'YOUR_BOT_TOKEN';
const botId = 'YOUR_BOT_ID';
const telegramAuth = new TelegramAuth(botToken, botId);Step 2: Start the Authentication Flow
To start the authentication process, call the initiateLogin() method. This method will open a new window where the user can authenticate with their Telegram account.
telegramAuth.initiateLogin();This will open a Telegram OAuth window for the user to authenticate with your Telegram bot. Once the user grants access, the authentication data will be sent back to your website.
Step 3: Listen for Authentication Data
To capture the authentication data sent back to your website, you can use the listenForAuthData() method. This method accepts a callback function, which will receive the authenticated user's data when the authentication is complete.
telegramAuth.listenForAuthData((user) => {
console.log('Authenticated user:', user);
// Handle the authenticated user data
});The user object contains the following properties:
id: Unique identifier for the userauth_date: Authentication date (timestamp)hash: Authentication hash for verificationfirst_name: The user's first name (optional)last_name: The user's last name (optional)username: The user's username (optional)photo_url: URL to the user's photo (optional)
Step 4: Send Messages to Telegram Users
Once you have authenticated the user, you can send messages to them via your Telegram bot. To do this, use the sendMessage() method, providing the chatId and the message to be sent.
const chatId = 123456789; // Replace with the recipient's chat ID
const message = 'Hello, this is a test message from your bot!';
telegramAuth
.sendMessage(chatId, message)
.then(() => {
console.log('Message sent successfully!');
})
.catch((error) => {
console.error('Error sending message:', error);
});Handling Errors
The package is designed to handle errors gracefully. If any of the requests fail, it will throw an error with a detailed message, which you can catch and handle in your application.
try {
await telegramAuth.sendMessage(chatId, message);
} catch (error) {
console.error('Error occurred:', error);
}Step 5: Clean Up
Once the authentication process is complete, you should clean up the event listeners to avoid memory leaks. The listenForAuthData() method returns a function that you can use to remove the event listener.
const stopListening = telegramAuth.listenForAuthData((user) => {
console.log('Authenticated user:', user);
// Handle user authentication data
});
// Later, to stop listening for authentication data:
stopListening();Example Flow
- The user visits your website and clicks on the "Login with Telegram" button.
- The
initiateLogin()method opens the Telegram authentication window. - The user authenticates and the authentication data is sent to your site.
- The
listenForAuthData()method receives the data and your callback is triggered. - You can now send a message to the user or take other actions based on their data.
Conclusion
This package simplifies integrating Telegram authentication and messaging into your web applications. It abstracts away the complexities of interacting with the Telegram API, enabling you to focus on building your app's features.
With this package, you can easily authenticate users, receive their information, and send messages through a Telegram bot—all within a few lines of code!
License
This package is released under the MIT License. See the LICENSE file for more details.
