Introduction

Want to stay updated on Solana events in real-time? This guide will show you how to create a Telegram bot that can track on-chain activities. We'll use an NFT sales tracker as an example, but the template we're building can be easily adapted for other use cases.

Here's what our example bot will look like:

This template combines Helius webhooks for real-time Solana data with Cloudflare Workers for serverless hosting. Whether you're tracking NFT sales, monitoring DeFi protocols, or keeping an eye on specific wallets, this setup provides a solid foundation.

Setting Up Your Project

Let's get your project up and running:

‍1. Clone the repository:

   git clone https://github.com/helius-labs/cloudfare-telegram-template.git

   cd cloudfare-telegram-template

2. Install dependencies:

   npm install

3. Configure environment variables:

Open wrangler.toml and fill in the following keys:

   - TELEGRAM_BOT_TOKEN:  

  1. Open Telegram and search for @BotFather.

  2. Start a chat with BotFather and send the command /newbot

  3. Follow the prompts to choose a name and username for your bot. 

  4. Once created, BotFather will give you a token. This is your TELEGRAM_BOT_TOKEN

   - TELEGRAM_CHAT_ID:

  1. Create a channel and add your bot as an administrator.

  2. Send a message to the channel.

  3. Visit: https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates

  4. Find the "chat":{"id": field in the response. This is your TELEGRAM_CHAT_ID.

      Watch this video for a step-by-step guide:

      Create a Telegram Bot and Obtain the Chat ID - Step-by-Step Guide

   - HELIUS_API_KEY: Your Helius API key (get it from Helius)

Please be sure not to commit these values to Github.

‍4. Deploy to Cloudflare:

     npm run deploy

After running this command, you'll see your deployment URL in the console output. Make note of this URL as you'll need it in the next step.

‍5. Create your webhook:

Use the deployment URL from the previous step to create your webhook:

     curl -X POST https://your-worker-url.workers.dev/create-webhook

     (Replace your-worker-url with your actual worker URL

You'll receive a success response after running this command. You can view the new webhook you've set up on your Helius dashboard at: https://dashboard.helius.dev/webhooks

Note: It may take 2-3 minutes for the new webhook to fully spin up and become operational.

6. Edit your webhook:

After creating your webhook, you can customize it further in the Helius dashboard: 

  1. Go tohttps://dashboard.helius.dev/webhooks

  2. You should see your newly created webhook in the list. 

  3. Click on the webhook to edit its settings.

  4. Here you can modify various parameters such as:

    • Transaction types you want to track

    • Specific wallet addresses to monitor

    • Network (mainnet, devnet)

  5. Important: Keep the "Webhook URL" field unchanged. It should still point to your  Cloudflare Worker's /webhook endpoint (https://your-worker- url.workers.dev/webhook). 

          

The Code Breakdown

First, let's examine our imports and type definitions:

import { Hono } from 'hono';

type Env = {
HELIUS_API_KEY: string;
TELEGRAM_BOT_TOKEN: string;
TELEGRAM_CHAT_ID: string;
};

We're using Hono, a lightweight web framework for Cloudflare Workers. The Env type defines our environment variables for Helius and Telegram integrations.

Next, we set up our Hono app:

const app = new Hono<{ Bindings: Env }>();

app.get('/', (c) => c.text('Solana Action Bot is running!'));

This creates our app and sets up a simple health check endpoint.

Now, let's create our webhook:

app.post('/create-webhook', async (c) => {
const webhookURL = `${new URL(c.req.url).origin}/webhook`;
console.log('Setting up webhook with URL:', webhookURL);

const response = await fetch(
`https://api.helius.xyz/v0/webhooks?api-key=${c.env.HELIUS_API_KEY}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
webhookURL: webhookURL,
transactionTypes: ["NFT_SALE"],
accountAddresses: ["M2mx93ekt1fmXSVkTrUL9xVFHkmME8HTUi5Cyc5aF7K"], // Magic Eden v2 program
webhookType: "enhanced"
}),
}
);
const data = await response.json();
console.log('Helius webhook setup response:', data);
return c.json({ success: true, webhook: data, webhookURL: webhookURL });
});

This endpoint sets up our Helius webhook. In this example, we're tracking NFT sales from the Magic Eden v2 program, but you can modify the transactionTypes and accountAddresses to suit your needs.

Here's how we send messages to Telegram:

async function sendTelegramMessage(message: string, env: Env) {
const url = `https://api.telegram.org/bot${env.TELEGRAM_BOT_TOKEN}/sendMessage`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
chat_id: env.TELEGRAM_CHAT_ID,
text: message,
parse_mode: 'Markdown',
}),
});
return response.json();
}

This function formats our message and sends it to our Telegram chat.

Finally, let's handle the incoming webhook data:

app.post('/webhook', async (c) => {
console.log('Webhook endpoint hit');
console.log('Request URL:', c.req.url);

let data;
try {
data = await c.req.json();
console.log('Received webhook data:', JSON.stringify(data, null, 2));
} catch (error) {
console.error('Error parsing webhook data:', error);
return c.text('Error processing webhook', 400);
}

if (!Array.isArray(data) || data.length === 0) {
console.log('No transactions in webhook data');
return c.text('No transactions to process', 200);
}

for (const transaction of data) {
if (transaction.type === 'NFT_SALE') {
const { amount, buyer, seller, signature, nfts } = transaction.events.nft;
const message = `🎉 NFT Sale\n\n` +
`*Price*: ${amount / 1e9} SOL\n` +
`*Buyer*: \`${buyer}\`\n` +
`*Seller*: \`${seller}\`\n` +
`*Signature*: [View on Solana Explorer](https://explorer.solana.com/tx/${signature})`;

try {
const result = await sendTelegramMessage(message, c.env);
console.log('Telegram message sent:', result);
} catch (error) {
console.error('Error sending Telegram message:', error);
}
}
}

return c.text('Webhook processed');
});

This is where we process the data from Helius and send formatted messages to Telegram. Based on your use case, you can customize this part to handle different types of transactions or extract different information.

Customization Options

While our example focuses on NFT sales, you can easily adapt this template for various use cases:

1. Modify the transactionTypes in the webhook creation to track different events

2. Change the accountAddresses to monitor specific programs or wallets

3. Adjust the message formatting in the /webhook endpoint to suit your data needs

4. Implement additional logic to filter or process the incoming data

Explore the Helius webhooks documentation to discover the full range of trackable data and events. However, don't limit yourself to just the explicitly defined events! Helius webhooks are incredibly versatile and can track a wide array of on-chain activities, even those not directly parsed or mentioned in our documentation.

Here are some examples of events you could track:

  • Token transfers for specific SPL tokens

  • New program deployments

  • Raydium pool creations or liquidity additions

  • Governance proposal creations or votes

  • Metaplex candy machine launches

  • Serum market creations

  • By leveraging this template, you can create Telegram bots for a wide array of Solana monitoring tasks, from DeFi protocol events to wallet activity tracking and beyond.

If you've read this far, thank you! We hope this guide has helped get you started with creating your own Solana Telegram bot 🤖

#Solana #tradingbot