npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@openserv-labs/referrals-sdk

v1.0.0

Published

A TypeScript SDK for tracking referrals for Telegram apps

Readme

OpenServ Referrals SDK

npm version License: MIT TypeScript

A lightweight TypeScript SDK for tracking referrals in Telegram bots. This is a thin wrapper over the OpenServ Referrals API.

Installation

npm install @openserv-labs/referrals-sdk

For node-telegram-bot-api:

npm install node-telegram-bot-api

For telegraf:

npm install telegraf

Quick Start

With node-telegram-bot-api

import { register, ack } from '@openserv-labs/referrals-sdk'
const TelegramBot = require('node-telegram-bot-api')

// Set your API key
process.env.OPENSERV_REFERRALS_API_KEY = 'your-api-key-here'

const bot = new TelegramBot('YOUR_BOT_TOKEN', { polling: true })

// Register your bot - this sets up automatic /start handling
await register(bot)

// Manually acknowledge a purchase
await ack({
  userId: 12345,
  username: 'john_doe',
  action: 'purchase',
  amount: 10.99,
})

With telegraf

import { register, ack } from '@openserv-labs/referrals-sdk'
const { Telegraf } = require('telegraf')

// Set your API key
process.env.OPENSERV_REFERRALS_API_KEY = 'your-api-key-here'

const bot = new Telegraf('YOUR_BOT_TOKEN')

// Register your bot - this sets up automatic /start handling
await register(bot)

await bot.launch()

API

register(bot)

Sets up a /start command handler that automatically captures referral codes and sends them to the API. Works with both node-telegram-bot-api and telegraf.

register(bot: TelegramBot | Telegraf): Promise<void>

Example:

await register(bot)
// Now when users click https://t.me/yourbot?start=REF123
// It automatically calls ack() with: { userId, username, action: 'start', code: 'REF123' }

Important: This function validates your API key and will throw an error if it's missing or invalid.

ack(action)

Sends referral acknowledgment to the API.

ack(action: AckAction): Promise<ApiResponse>

Types:

// For registrations (when user starts with referral code)
interface StartAction {
  userId: number        // Telegram user ID
  username?: string     // Telegram username (optional)
  action: 'start'       // Action type
  code: string          // Referral code
}

// For purchases
interface PurchaseAction {
  userId: number        // Telegram user ID
  username?: string     // Telegram username (optional)
  action: 'purchase'    // Action type
  amount: number        // Purchase amount
}

type AckAction = StartAction | PurchaseAction

interface ApiResponse {
  success: true
  data?: any
  message?: string
} | {
  success: false
  error: string
}

Examples:

Registration (handled automatically by register()):

await ack({
  userId: 12345,
  username: 'john_doe',
  action: 'start',
  code: 'REF123ABC',
})

Purchase:

await ack({
  userId: 12345,
  username: 'john_doe',
  action: 'purchase',
  amount: 29.99,
})

User without username:

await ack({
  userId: 12345,
  action: 'purchase',
  amount: 9.99,
})

Complete Examples

node-telegram-bot-api Example

import { register, ack } from '@openserv-labs/referrals-sdk'
const TelegramBot = require('node-telegram-bot-api')

async function startBot() {
  process.env.OPENSERV_REFERRALS_API_KEY = 'your-api-key-here'

  const bot = new TelegramBot('YOUR_BOT_TOKEN', { polling: true })

  // Set up automatic referral tracking
  try {
    await register(bot)
    console.log('✅ Bot registered with referrals SDK')
  } catch (error) {
    console.error('❌ Failed to register:', error.message)
    process.exit(1)
  }

  // Handle purchases
  bot.onText(/\/buy (.+)/, async (msg, match) => {
    const amount = parseFloat(match[1])
    const userId = msg.from.id
    const username = msg.from.username

    const result = await ack({
      userId: userId,
      username: username,
      action: 'purchase',
      amount: amount,
    })

    if (result.success) {
      bot.sendMessage(msg.chat.id, `✅ Purchase of $${amount} processed!`)
    } else {
      bot.sendMessage(msg.chat.id, `❌ Error: ${result.error}`)
    }
  })
}

startBot()

telegraf Example

import { register, ack } from '@openserv-labs/referrals-sdk'
const { Telegraf } = require('telegraf')

async function startBot() {
  process.env.OPENSERV_REFERRALS_API_KEY = 'your-api-key-here'

  const bot = new Telegraf('YOUR_BOT_TOKEN')

  // Set up automatic referral tracking
  try {
    await register(bot)
    console.log('✅ Bot registered with referrals SDK')
  } catch (error) {
    console.error('❌ Failed to register:', error.message)
    process.exit(1)
  }

  // Handle purchases
  bot.command('buy', async ctx => {
    const args = ctx.message.text.split(' ')
    const amount = parseFloat(args[1])
    const userId = ctx.from.id
    const username = ctx.from.username

    const result = await ack({
      userId: userId,
      username: username,
      action: 'purchase',
      amount: amount,
    })

    if (result.success) {
      ctx.reply(`✅ Purchase of $${amount} processed!`)
    } else {
      ctx.reply(`❌ Error: ${result.error}`)
    }
  })

  await bot.launch()
  console.log('🤖 Bot is running!')
}

startBot()

How It Works

  1. Setup: Set your OPENSERV_REFERRALS_API_KEY environment variable
  2. Register: register(bot) validates your API key and sets up a /start handler
  3. Automatic Tracking: When users click https://t.me/yourbot?start=REF123, it automatically sends the referral data to the API
  4. Manual Tracking: Use ack() to manually send purchase events
  5. API Integration: All data is sent to the OpenServ referrals API

API Payloads

Registration (automatic)

{
  "userId": 12345,
  "username": "john_doe",
  "action": "start",
  "code": "REF123ABC"
}

Purchase (manual)

{
  "userId": 12345,
  "username": "john_doe",
  "action": "purchase",
  "amount": 29.99
}

User without username

{
  "userId": 12345,
  "action": "purchase",
  "amount": 9.99
}

Environment Variables

| Variable | Required | Description | | ---------------------------- | -------- | ------------------------------- | | OPENSERV_REFERRALS_API_KEY | Yes | Your OpenServ referrals API key |

Error Handling

The SDK will throw errors for:

  • Missing or invalid API key
  • Network failures during API key validation
  • Invalid bot objects
try {
  await register(bot)
} catch (error) {
  console.error('Failed to register bot:', error.message)
  // Handle error appropriately
}

The ack() function returns success/error in the response:

const result = await ack({ ... })
if (!result.success) {
  console.error('Failed to acknowledge action:', result.error)
}

Framework Support

This SDK supports both major Telegram bot frameworks:

  • node-telegram-bot-api - Uses onText() method for /start handling
  • telegraf - Uses start() or command() methods

The SDK automatically detects which framework you're using.

License

MIT License - see LICENSE file for details.