Trace Every Visit - Get Telegram Message on User Visits your Website

Sh Raj - Jul 22 '23 - - Dev Community

Title: Building a Notification-Enabled Website: Engaging Visitors with Personalized Messages

Introduction

In today's digital age, website owners strive to enhance user experience and engagement. One powerful way to achieve this is by implementing automatic notifications. Imagine receiving real-time alerts whenever a visitor interacts with your website, empowering you to respond promptly and create a personalized experience for each user. In this article, we will guide you through the process of building a notification-enabled website, including the addition of a user form to collect crucial data for a seamless experience.

Part 1: Setting Up Automatic Notifications

The first step in creating a notification-enabled website is to integrate the Telegram API, which will enable us to send real-time notifications to our Telegram account. To accomplish this, we'll start by creating a Telegram bot and obtaining its API token. The bot will act as the bridge between our website and the Telegram platform.

  1. Create a Telegram Bot
- Open the Telegram app and search for "BotFather."
- Initiate a chat with BotFather and use the /newbot command to create a new bot.
- BotFather will generate a unique API token for your bot; make sure to save it for later use.
Enter fullscreen mode Exit fullscreen mode
  1. Obtain Your Telegram User ID
- Find your bot in the Telegram app and initiate a chat with it.
- Visit the following URL in your web browser, replacing `YOUR_BOT_TOKEN` with the API token obtained earlier:
  `https://api.telegram.org/botYOUR_BOT_TOKEN/getUpdates`
- Look for the "chat" object in the response to find your Telegram User ID.
Enter fullscreen mode Exit fullscreen mode

Part 2: Enhancing the Notification with User Data

Now that we have the foundation for notifications, let's take it a step further by personalizing the messages sent to Telegram. We'll create a user form on our website to collect additional information from visitors, making each notification more informative and meaningful.

Use a server-side programming language (e.g., Node.js, Python, PHP) to send a notification to your Telegram account when someone visits the website for security reasons.

<!DOCTYPE html>
<html>
<head>
    <title>Notify Me Website</title>
</head>
<body>
    <h1>Welcome to the Notify Me Website</h1>
    <script>
        // Replace 'YOUR_TELEGRAM_BOT_API_TOKEN' and 'YOUR_TELEGRAM_USER_ID' with your actual token and user ID
        const botApiToken = 'YOUR_TELEGRAM_BOT_API_TOKEN';
        const userId = 'YOUR_TELEGRAM_USER_ID'; //Get it from https://t.me/userinfobot


        // Send a notification to Telegram
        async function sendNotification() {
            try {
                await fetch(`https://api.telegram.org/bot${botApiToken}/sendMessage`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        chat_id: userId,
                        text: 'Someone visited the website!',
                    }),
                });
            } catch (error) {
                console.error('Error sending Telegram notification:', error);
            }
        }

        // Send notification when the page loads
        sendNotification();
    </script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode
  1. Building the User Form
<!DOCTYPE html>
<html>
<head>
    <title>Notify Me Website</title>
</head>
<body>
    <h1>Welcome to the Notify Me Website</h1>
    <form id="userForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required><br>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required><br>

        <button type="button" onclick="sendNotification()">Notify Me</button>
    </form>

    <script>
        const botApiToken = 'YOUR_TELEGRAM_BOT_API_TOKEN';
        const userId = 'YOUR_TELEGRAM_USER_ID';

        async function getIpAddress() {
            const response = await fetch('https://api.ipify.org?format=json');
            const data = await response.json();
            return data.ip;
        }

        function getCurrentTime() {
            const now = new Date();
            return now.toLocaleString();
        }

        async function sendNotification() {
            const name = document.getElementById('name').value;
            const email = document.getElementById('email').value;
            const ipAddress = await getIpAddress();
            const currentTime = getCurrentTime();
            const currentWebAddress = window.location.href;
            const message = `New visitor!\nName: ${name}\nEmail: ${email}\nIP Address: ${ipAddress}\nTime: ${currentTime}\nWeb Address: ${currentWebAddress}`;

            try {
                await fetch(`https://api.telegram.org/bot${botApiToken}/sendMessage`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        chat_id: userId,
                        text: message,
                    }),
                });

                document.getElementById('userForm').reset();
            } catch (error) {
                console.error('Error sending Telegram notification:', error);
            }
        }
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Conclusion

By following these steps, you have successfully built a notification-enabled website that automatically sends personalized messages to your Telegram account whenever a visitor interacts with your website. The combination of real-time alerts and valuable user data allows you to engage with your audience on a deeper level, providing a tailored experience that keeps them coming back for more.

Remember to handle user data with utmost care and privacy, adhering to data protection regulations to ensure a secure and trust-building experience for your website visitors. Additionally, consider exploring more advanced features such as integrating with other messaging platforms or incorporating notification preferences for users to enhance the overall user experience further. Happy engaging!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .