Skip to main content

Telegram Bot Integration

What is this? A Telegram bot that rewards your community members with LTZ tokens for participating in your channel or group.

Use this if you're: Running a Telegram community, channel, or group and want to reward active members.

You'll need:

  • A Telegram account (that's it!)
  • Basic understanding of Node.js (we'll walk you through it)
  • 30 minutes

Overview

Telegram has 800M+ users globally. Reward your Telegram community for:

  • ✅ Joining your channel
  • ✅ Sending messages
  • ✅ Forwarding content
  • ✅ Completing tasks
  • ✅ Participating in polls
  • ✅ Inviting friends
Advanced Feature: OAuth Pregeneration

Want to reward users BEFORE they log in?

With OAuth Pregeneration, you can:

  • Award LTZ to users based on their Telegram ID
  • Even if they've never logged into Loyalteez
  • When they log in with Telegram → all rewards are waiting!

Perfect for: Game bots, contests, engagement campaigns

Learn more: OAuth Pregeneration Guide

Quick Start (Step-by-Step)

Step 1: Create Your Bot (5 minutes)

Plain English: You need to tell Telegram "hey, I want to make a bot." Telegram has a special bot (called BotFather) that creates other bots.

  1. Open Telegram on your phone or computer
  2. Search for @BotFather (this is Telegram's official bot maker)
  3. Send /newbot to BotFather
  4. Choose a name (like "Loyalteez Rewards Bot")
  5. Choose a username (must end in "bot", like loyalteez_rewards_bot)
  6. Copy the token BotFather gives you (looks like: 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11)

What just happened? You created a bot account on Telegram. The token is like a password that lets your code control the bot.

Step 2: Set Up Your Computer (5 minutes)

Plain English: You need Node.js installed. Think of Node.js as a way to run JavaScript code on your computer (not just in browsers).

Check if you have Node.js:

node --version

If you see a version number (like v18.0.0), you're good!

If not, install Node.js:

  • Go to nodejs.org
  • Download the "LTS" version (left button)
  • Install it (just click "Next" a bunch of times)

Step 3: Create Your Bot Project (3 minutes)

Plain English: You're creating a folder for your bot's code.

# Create a folder for your bot
mkdir telegram-rewards-bot
cd telegram-rewards-bot

# Initialize a Node.js project (creates a package.json file)
npm init -y

# Install the libraries you need
npm install node-telegram-bot-api axios dotenv

What are these libraries?

  • node-telegram-bot-api - Makes it easy to control your Telegram bot
  • axios - Sends HTTP requests to Loyalteez API
  • dotenv - Lets you store secrets (like your bot token) safely

Step 4: Create Your Bot Code (10 minutes)

Plain English: Now you're writing the actual code that makes your bot work.

Create a file called bot.js:

// ============================================
// IMPORT THE LIBRARIES
// ============================================
// Think of this like getting tools out of a toolbox
const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');
require('dotenv').config();

// ============================================
// CONFIGURATION
// ============================================
// These are your bot's settings
const BOT_TOKEN = process.env.BOT_TOKEN; // Your bot's password
const LOYALTEEZ_API = 'https://api.loyalteez.app/loyalteez-api/manual-event';
const BRAND_ID = process.env.BRAND_ID; // Your Loyalteez Brand ID

// ============================================
// CREATE THE BOT
// ============================================
// This creates your bot and tells it to listen for messages
const bot = new TelegramBot(BOT_TOKEN, { polling: true });

console.log('🤖 Bot is running! Send it a message on Telegram!');

// ============================================
// HELPER FUNCTION: Track Event to Loyalteez
// ============================================
// This function sends events to Loyalteez and rewards users
// Think of it like pressing a "Give Reward" button
async function rewardUser(telegramUserId, username, event, metadata = {}) {
try {
// Create an email for this user
// We use their Telegram ID so each user gets a unique wallet
const email = `telegram_${telegramUserId}@loyalteez.app`;

// Send the event to Loyalteez
const response = await axios.post(LOYALTEEZ_API, {
event: event,
email: email,
metadata: {
platform: 'telegram',
telegram_username: username,
telegram_id: telegramUserId,
brand_id: BRAND_ID,
...metadata
}
});

// Get how much LTZ they earned
const ltzEarned = response.data.ltzDistributed || 0;

return {
success: true,
ltzEarned: ltzEarned,
wallet: response.data.walletAddress
};
} catch (error) {
console.error('Error rewarding user:', error.message);
return { success: false, error: error.message };
}
}

// ============================================
// COMMAND: /start
// ============================================
// When someone types /start, welcome them and give them LTZ
bot.onText(/\/start/, async (msg) => {
const chatId = msg.chat.id;
const userId = msg.from.id;
const username = msg.from.username || msg.from.first_name;

// Reward them for joining!
const result = await rewardUser(userId, username, 'telegram_join', {
chat_id: chatId,
action: 'start'
});

if (result.success && result.ltzEarned > 0) {
bot.sendMessage(chatId,
`🎉 Welcome ${username}!\n\n` +
`You earned ${result.ltzEarned} LTZ just for joining!\n\n` +
`Your wallet: ${result.wallet}\n\n` +
`Stay active to earn more rewards! 💰`
);
} else {
bot.sendMessage(chatId, `Welcome ${username}! 👋`);
}
});

// ============================================
// COMMAND: /rewards
// ============================================
// Show users their wallet info
bot.onText(/\/rewards/, async (msg) => {
const chatId = msg.chat.id;
const userId = msg.from.id;
const email = `telegram_${userId}@loyalteez.app`;

bot.sendMessage(chatId,
`🎁 Your Loyalteez Rewards\n\n` +
`Email: ${email}\n\n` +
`Check your balance at:\n` +
`https://marketplace.loyalteez.xyz\n\n` +
`Keep chatting to earn more! 💬`
);
});

// ============================================
// REWARD FOR MESSAGES
// ============================================
// Give LTZ for every message (with a 5-minute cooldown)
const recentlyRewarded = new Set(); // Tracks who got rewards recently

bot.on('message', async (msg) => {
// Ignore commands (they start with /)
if (msg.text && msg.text.startsWith('/')) return;

const userId = msg.from.id;
const username = msg.from.username || msg.from.first_name;
const chatId = msg.chat.id;

// Check if we rewarded this user in the last 5 minutes
const cooldownKey = `${userId}_${Date.now().toString().slice(0, -5)}`; // 5 min chunks

if (recentlyRewarded.has(cooldownKey)) {
// They got a reward recently, don't reward again yet
return;
}

// Reward them for the message!
const result = await rewardUser(userId, username, 'telegram_message', {
chat_id: chatId,
message_length: msg.text?.length || 0,
has_photo: !!msg.photo,
has_video: !!msg.video
});

if (result.success && result.ltzEarned > 0) {
// Remember that we rewarded them
recentlyRewarded.add(cooldownKey);

// Remove from cooldown after 5 minutes
setTimeout(() => {
recentlyRewarded.delete(cooldownKey);
}, 5 * 60 * 1000); // 5 minutes in milliseconds

// Tell them they earned LTZ!
bot.sendMessage(chatId,
`${username} earned ${result.ltzEarned} LTZ for being active! Keep it up! 💪`
);
}
});

// ============================================
// REWARD FOR NEW MEMBERS
// ============================================
// When someone new joins, welcome them with LTZ
bot.on('new_chat_members', async (msg) => {
const chatId = msg.chat.id;

// Loop through all new members
for (const member of msg.new_chat_members) {
const userId = member.id;
const username = member.username || member.first_name;

// Don't reward bots
if (member.is_bot) continue;

// Reward the new member!
const result = await rewardUser(userId, username, 'telegram_member_join', {
chat_id: chatId,
join_date: new Date().toISOString()
});

if (result.success && result.ltzEarned > 0) {
bot.sendMessage(chatId,
`🎉 Welcome ${username}!\n\n` +
`You earned ${result.ltzEarned} LTZ for joining!\n\n` +
`Type /rewards to see your wallet! 💰`
);
}
}
});

// ============================================
// ERROR HANDLING
// ============================================
// If something goes wrong, log it (don't crash the bot)
bot.on('polling_error', (error) => {
console.error('Polling error:', error.message);
});

What does this code do?

  1. Creates a bot that listens for messages on Telegram
  2. Rewards users when they:
    • Type /start (join the bot)
    • Send messages (with a 5-minute cooldown so they can't spam)
    • Join your group/channel as new members
  3. Shows wallet info when they type /rewards
  4. Tracks everything to Loyalteez API

Step 5: Configure Your Bot (2 minutes)

Plain English: You need to tell your bot your secrets (bot token and Brand ID).

Create a file called .env:

# Your bot's password (from BotFather)
BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11

# Your Loyalteez Brand ID (from Partner Portal)
BRAND_ID=your_brand_id_here

Where do I get my Brand ID?

  1. Go to partners.loyalteez.app
  2. Login
  3. Go to Settings
  4. Copy your Brand ID

Step 6: Run Your Bot! (1 minute)

Plain English: Time to start your bot and see it work!

node bot.js

You should see:

🤖 Bot is running! Send it a message on Telegram!

Now test it:

  1. Open Telegram
  2. Search for your bot (the username you chose)
  3. Send /start
  4. You should get a welcome message with LTZ rewards! 🎉

Reward Strategies

Strategy 1: Welcome Bonus

What it does: New members get LTZ when they join.

Why use this: Encourages people to join your community.

Already included in the code above! ✅

Strategy 2: Activity Rewards

What it does: Reward people for sending messages.

Why use this: Keeps your community active and engaged.

Customization:

// Change cooldown time (currently 5 minutes)
setTimeout(() => {
recentlyRewarded.delete(cooldownKey);
}, 10 * 60 * 1000); // Now 10 minutes

Strategy 3: Quality Content Rewards

What it does: Give more LTZ for longer messages or messages with media.

Why use this: Rewards people who contribute valuable content.

Add this code:

bot.on('message', async (msg) => {
if (msg.text && msg.text.startsWith('/')) return;

let event = 'telegram_message';
let bonusLTZ = 0;

// Longer messages get more rewards
if (msg.text && msg.text.length > 200) {
event = 'quality_message';
bonusLTZ = 10;
}

// Messages with photos/videos get more rewards
if (msg.photo || msg.video) {
event = 'media_message';
bonusLTZ = 15;
}

await rewardUser(userId, username, event, {
bonus: bonusLTZ
});
});

Strategy 4: Referral Rewards

What it does: Reward users who invite friends.

Why use this: Grows your community organically.

Add this code:

// Track referrals
bot.onText(/\/invite/, async (msg) => {
const userId = msg.from.id;
const chatId = msg.chat.id;

// Create a unique invite link
const inviteLink = `https://t.me/your_bot?start=ref_${userId}`;

bot.sendMessage(chatId,
`👥 Invite Friends, Earn LTZ!\n\n` +
`Share this link:\n${inviteLink}\n\n` +
`You'll earn 100 LTZ for each friend who joins! 🎁`
);
});

// When someone uses a referral link
bot.onText(/\/start ref_(.+)/, async (msg, match) => {
const referrerId = match[1]; // Who referred them
const newUserId = msg.from.id; // The new user

if (referrerId !== newUserId.toString()) {
// Reward the referrer!
await rewardUser(referrerId, 'Referrer', 'referral_success', {
referred_user: newUserId
});

bot.sendMessage(msg.chat.id,
`🎉 Welcome! You were invited by a friend!\n` +
`They earned 100 LTZ for inviting you! 💰`
);
}
});

Configure Reward Amounts

Plain English: You control how much LTZ each action gives.

Go to partners.loyalteez.app/settings → LTZ Distribution:

EventLTZ AmountCooldown
telegram_join100Once per user
telegram_message55 minutes
quality_message155 minutes
media_message105 minutes
telegram_member_join50Once per group
referral_success100Per referral

Deployment (Make It Run Forever)

Plain English: Right now, your bot only runs while your computer is on. Let's put it on a server so it runs 24/7.

Option 1: Railway (Easiest, Free)

  1. Go to railway.app
  2. Sign up (free)
  3. Click "New Project"
  4. Select "Deploy from GitHub"
  5. Connect your GitHub account
  6. Push your bot code to GitHub
  7. Railway automatically deploys it!

Add environment variables in Railway:

  • BOT_TOKEN = your bot token
  • BRAND_ID = your brand ID

Option 2: Heroku

# Install Heroku CLI
# Go to heroku.com and sign up

# Login
heroku login

# Create app
heroku create your-bot-name

# Add environment variables
heroku config:set BOT_TOKEN=your_token_here
heroku config:set BRAND_ID=your_brand_id_here

# Deploy
git init
git add .
git commit -m "Initial commit"
git push heroku main

Option 3: Your Own Server

# Install PM2 (keeps bot running forever)
npm install -g pm2

# Start bot
pm2 start bot.js --name telegram-rewards-bot

# Make it restart on server reboot
pm2 startup
pm2 save

Testing Your Bot

Test Checklist:

  • Send /start to bot
  • Receive welcome message with LTZ
  • Send a regular message
  • Receive activity reward
  • Send /rewards
  • See wallet information
  • Check Partner Portal analytics
  • Verify events are tracked
  • Verify LTZ is distributed

Troubleshooting

"Bot doesn't respond"

Check:

  1. Is node bot.js running?
  2. Did you copy the right bot token?
  3. Is your .env file in the same folder?

Fix:

# Make sure you're in the right folder
pwd

# Check .env file exists
ls -la

# Run bot with error logging
node bot.js 2>&1 | tee bot.log

"Events not tracking"

Check:

  1. Is your Brand ID correct?
  2. Is the API URL correct?
  3. Check Partner Portal for events

Fix:

// Add logging to see what's being sent
console.log('Sending event:', {
event, email, metadata
});

"Too many rewards being given"

Check:

  • Is cooldown working?
  • Are there duplicate event handlers?

Fix:

// Increase cooldown time
setTimeout(() => {
recentlyRewarded.delete(cooldownKey);
}, 15 * 60 * 1000); // 15 minutes instead of 5

Advanced Features

Add Buttons (Inline Keyboard)

bot.sendMessage(chatId, 'Choose an action:', {
reply_markup: {
inline_keyboard: [
[
{ text: '💰 Check Balance', callback_data: 'balance' },
{ text: '🎁 Claim Reward', callback_data: 'claim' }
]
]
}
});

// Handle button clicks
bot.on('callback_query', async (query) => {
if (query.data === 'balance') {
// Show balance
} else if (query.data === 'claim') {
// Claim reward
}
});

Create Polls with Rewards

bot.sendPoll(chatId, 'What feature do you want next?', [
'Feature A',
'Feature B',
'Feature C'
]);

bot.on('poll_answer', async (answer) => {
// Reward users for voting
await rewardUser(answer.user.id, 'User', 'poll_vote');
});

Common Questions

Q: Do users need crypto wallets?

A: Nope! Loyalteez creates wallets automatically using their Telegram ID.

Q: Do users need ETH for gas?

A: Nope! Loyalteez pays all gas fees.

Q: Can I change reward amounts later?

A: Yes! Change them anytime in the Partner Portal.

Q: What if someone spams messages?

A: The cooldown prevents this. You can also add rate limiting.

Q: Can I use this in groups?

A: Yes! Just add your bot to a group as an admin.

Next Steps

  • ✅ Add more commands (/leaderboard, /help)
  • ✅ Create custom reward rules for your community
  • ✅ Add admin commands for managing rewards
  • ✅ Integrate with your website or other platforms

Support

Your Telegram community now earns real rewards! 🎉


Summary for Non-Technical People

What you did:

  1. Created a Telegram bot (like a robot assistant)
  2. Taught it to give rewards (LTZ tokens) when people do things
  3. Made it run 24/7 so it's always working

What your community gets:

  • Real rewards (LTZ tokens) for being active
  • A wallet with actual blockchain tokens
  • Motivation to engage more

What you control:

  • How much LTZ each action gives
  • What actions get rewarded
  • Who can get rewards

No blockchain knowledge needed. No coding required after setup. Just run it! 🚀