JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 376
  • Score
    100M100P100Q90906F
  • License MIT

Internal platform library for building RIZZ Chat Experiences with AI, Wallet integration, and persistent storage on Cloudflare Workers

Package Exports

  • @rizzclub/platform
  • @rizzclub/platform/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@rizzclub/platform) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

@rizzclub/platform

Internal platform library for building RIZZ Chat Experiences

โš ๏ธ Note: This package is primarily for internal RizzClub use. While publicly available, it's designed specifically for our chat experience ecosystem and may have breaking changes between versions.

A unified platform library for building production-grade conversational experiences with AI capabilities, Solana wallet integration, scheduled tasks, and persistent storage. Works seamlessly across multiple messaging platforms (Telegram, WhatsApp, SMS, Web) in both production (Cloudflare Workers) and development (mock) environments.

npm version TypeScript License: MIT

Features

  • ๐Ÿค– AI Integration: Intelligent responses from Anthropic Claude, OpenAI GPT, or Google Gemini
  • ๐Ÿ’ฐ Solana Wallet: Accept payments, send withdrawals, and manage user wallets with Web3 support
  • ๐Ÿ“ฆ KV Storage: Persistent key-value storage for user data, conversation state, and configuration
  • ๐Ÿ—„๏ธ Database: Schemaless document store with MongoDB-like query syntax
  • โฐ Scheduler: Run tasks on schedules (cron) or one-time at specific times
  • ๐ŸŒ Multi-Platform: Telegram, WhatsApp, SMS, and Web chat experiences
  • โšก Cloudflare Native: Optimized for Cloudflare Workers edge computing
  • ๐Ÿงช Mock Support: In-memory implementations for local testing
  • ๐Ÿ“˜ TypeScript First: Full type safety and IntelliSense support
  • ๐Ÿ”„ Unified API: Same code works across all platforms and environments

Supported Platforms

Build consistent chat experiences across:

  • Telegram - Rich bot interactions with inline keyboards and media
  • WhatsApp - Business messaging with templates and media support
  • SMS - Text-based conversations and two-way messaging
  • Web - Embedded chat widgets and web-based conversations

Quick Start

Installation

npm install @rizzclub/platform

Basic Example

import { Bot, webhookCallback } from 'grammy';
import { createPlatform } from '@rizzclub/platform';

export default {
  async fetch(request, env, ctx) {
    const bot = new Bot(env.BOT_TOKEN);
    const platform = createPlatform({ env, request, waitUntil: ctx.waitUntil });
    const { kv, ai, wallet } = platform.getServices();

    // Save user conversation state
    bot.command('start', async (ctx) => {
      await kv.put(`user:${ctx.from.id}`, {
        platform: 'telegram',
        username: ctx.from.username,
        conversationState: 'active'
      });
      await ctx.reply('๐Ÿ‘‹ Welcome to RIZZ Chat Experience!');
    });

    // AI-powered conversation
    bot.on('message:text', async (ctx) => {
      const answer = await ai.ask(ctx.message.text, {
        provider: 'anthropic'
      });
      await ctx.reply(answer);
    });

    // Accept payments across platforms
    bot.command('pay', async (ctx) => {
      const paymentUrl = await wallet.generatePaymentToken(
        ctx.from.id.toString(),
        0.1, // 0.1 SOL
        'Premium access',
        env.BOT_ID
      );
      await ctx.reply(`๐Ÿ’ณ Pay here: ${paymentUrl}`);
    });

    return webhookCallback(bot, 'std')(request);
  }
}

Services

๐Ÿค– AI Service

Integrate conversational AI capabilities with support for multiple providers.

Available Providers:

  • Anthropic Claude (claude-3-5-sonnet, claude-3-opus, etc.)
  • OpenAI GPT (gpt-4, gpt-3.5-turbo, etc.)
  • Google Gemini (gemini-pro, gemini-ultra, etc.)

Example:

const { ai } = platform.getServices();

// Simple conversation
const answer = await ai.ask('How can I help you today?', {
  provider: 'anthropic',
  maxTokens: 500
});

// Advanced prompt with context
const response = await ai.prompt({
  prompt: 'Explain blockchain to a beginner',
  provider: 'openai',
  model: 'gpt-4',
  temperature: 0.7,
  maxTokens: 300
});

console.log(response.text);
console.log('Tokens used:', response.tokensUsed);

Use Cases:

  • Natural conversation flow
  • Customer support automation
  • Content generation
  • Question answering
  • Multi-language support
  • Personalized recommendations

๐Ÿ’ฐ Wallet Service

Enable payment acceptance, withdrawals, and Web3 wallet management across all chat platforms.

Features:

  • Accept SOL and SPL token payments
  • Send withdrawals to user wallets
  • Link/unlink Solana wallets
  • Deposit fund management
  • Transaction webhooks
  • Cross-platform payment links

Example:

import { TOKENS } from '@rizzclub/platform/wallet';

const { wallet } = platform.getServices();

// Request SOL payment
const solPaymentUrl = await wallet.generatePaymentToken(
  userId,
  1.5, // Amount in SOL
  'Premium subscription',
  botId
);

// Request USDC payment
const usdcPaymentUrl = await wallet.generatePaymentToken(
  userId,
  10, // Amount in USDC
  'Service fee',
  botId,
  undefined, // botName
  TOKENS.USDC.mint,
  TOKENS.USDC.symbol,
  TOKENS.USDC.decimals
);

// Get wallet info
const walletInfo = await wallet.getWallet(userId);
if (walletInfo) {
  console.log(`Balance: ${walletInfo.balance} SOL`);
  console.log(`Address: ${walletInfo.address}`);
}

Supported Tokens:

  • SOL (native Solana)
  • USDC (USD Coin)
  • USDT (Tether)
  • Custom SPL tokens

๐Ÿ“ฆ KV Storage

Persistent key-value storage for conversation state, user preferences, and configuration.

API:

const { kv } = platform.getServices();

// Store conversation state
await kv.put(`conversation:${userId}`, {
  platform: 'whatsapp',
  lastMessage: 'Hello',
  context: { topic: 'support', lang: 'en' }
});

// Store with expiration (session management)
await kv.put(`session:${sessionId}`, sessionData, {
  expirationTtl: 3600, // 1 hour
  metadata: { platform: 'web' }
});

// Retrieve state
const conversation = await kv.get(`conversation:${userId}`, 'json');

// List by prefix
const sessions = await kv.list({ prefix: 'session:', limit: 10 });

Use Cases:

  • Conversation state management
  • User preferences across platforms
  • Session tracking
  • Message history
  • Cache frequently accessed data
  • Platform-specific configurations

๐Ÿ—„๏ธ Database Service

Schemaless document store for structured data with MongoDB-like queries.

Example:

const { db } = platform.getServices();
const conversations = db.collection('conversations');

// Store conversation
await conversations.insert({
  userId: 'user123',
  platform: 'telegram',
  messages: [],
  metadata: {
    startedAt: Date.now(),
    language: 'en'
  }
});

// Query across platforms
const activeConvos = await conversations.find({
  'metadata.startedAt': { $gt: Date.now() - 86400000 }
});

// Update conversation
await conversations.update(
  { userId: 'user123' },
  { $push: { messages: newMessage } }
);

โฐ Scheduler Service

Schedule tasks for reminders, notifications, and recurring events across all platforms.

Example:

const { scheduler } = platform.getServices();

// Schedule one-time reminder
await scheduler.scheduleTask({
  name: 'payment-reminder',
  webhookUrl: 'https://your-chat-bot.com/webhook/reminder',
  webhookSecret: env.WEBHOOK_SECRET,
  scheduledTime: new Date('2025-12-25T09:00:00Z'),
  metadata: { userId: 'user123', platform: 'whatsapp' }
});

// Schedule daily broadcast
await scheduler.scheduleTask({
  name: 'daily-updates',
  webhookUrl: 'https://your-chat-bot.com/webhook/broadcast',
  webhookSecret: env.WEBHOOK_SECRET,
  cron: '0 9 * * *', // Every day at 9 AM
  timezone: 'America/New_York'
});

Use Cases:

  • Scheduled notifications
  • Reminder systems
  • Daily/weekly broadcasts
  • Appointment confirmations
  • Follow-up messages
  • Time-based campaigns

Configuration

Production Setup (Cloudflare Workers)

wrangler.jsonc:

{
  "name": "my-chat-experience",
  "main": "src/index.ts",
  "compatibility_date": "2024-01-01",
  "kv_namespaces": [
    {
      "binding": "KV_NAMESPACE",
      "id": "your-kv-namespace-id"
    }
  ],
  "vars": {
    "BOT_TOKEN": "your-bot-token",
    "BOT_ID": "my-chat-bot"
  },
  "secrets": {
    "RIZZCLUB_API_KEY": "Get from https://rizz.club"
  }
}

Environment Variables:

  • BOT_TOKEN - Your messaging platform token (required)
  • BOT_ID - Unique identifier for your chat experience (required)
  • RIZZCLUB_API_KEY - API key for AI, Wallet, and Scheduler services
  • KV_NAMESPACE - Cloudflare KV namespace binding (auto-injected)

Development/Testing

const platform = createPlatform(
  {
    env: {
      BOT_TOKEN: 'test-token',
      BOT_ID: 'test-bot',
      RIZZCLUB_API_KEY: 'test-key'
    },
    request: mockRequest,
    waitUntil: () => {}
  },
  {
    mock: true,
    debug: true
  }
);

Complete Examples

Multi-Platform AI Assistant

import { Bot, webhookCallback } from 'grammy';
import { createPlatform } from '@rizzclub/platform';

export default {
  async fetch(request, env, ctx) {
    const bot = new Bot(env.BOT_TOKEN);
    const platform = createPlatform({ env, request, waitUntil: ctx.waitUntil });
    const { ai, kv } = platform.getServices();

    // Determine platform from request
    const chatPlatform = env.PLATFORM || 'telegram'; // telegram, whatsapp, sms, web

    bot.command('start', async (ctx) => {
      await kv.put(`user:${ctx.from.id}`, {
        platform: chatPlatform,
        preferences: { language: 'en' }
      });
      await ctx.reply(`๐Ÿ‘‹ Welcome! Ask me anything via ${chatPlatform}!`);
    });

    bot.on('message:text', async (ctx) => {
      await ctx.replyWithChatAction('typing');

      try {
        // Get conversation context
        const context = await kv.get(`conversation:${ctx.from.id}`, 'json') || [];

        // Get AI response with context
        const answer = await ai.ask(ctx.message.text, {
          provider: 'anthropic',
          maxTokens: 500
        });

        // Save conversation
        context.push({
          question: ctx.message.text,
          answer,
          timestamp: Date.now(),
          platform: chatPlatform
        });
        await kv.put(`conversation:${ctx.from.id}`, context.slice(-10));

        await ctx.reply(answer);
      } catch (error) {
        await ctx.reply('โŒ Sorry, I encountered an error. Please try again.');
      }
    });

    return webhookCallback(bot, 'std')(request);
  }
}

Cross-Platform Payment System

import { Bot, webhookCallback } from 'grammy';
import { createPlatform } from '@rizzclub/platform';
import { TOKENS } from '@rizzclub/platform/wallet';

export default {
  async fetch(request, env, ctx) {
    const bot = new Bot(env.BOT_TOKEN);
    const platform = createPlatform({ env, request, waitUntil: ctx.waitUntil });
    const { wallet, kv } = platform.getServices();

    bot.command('link', async (ctx) => {
      const linkUrl = await wallet.generateLinkToken(
        ctx.from.id.toString(),
        env.BOT_ID,
        'RIZZ Chat'
      );
      await ctx.reply(`๐Ÿ”— Link your wallet:\n${linkUrl}`);
    });

    bot.command('balance', async (ctx) => {
      const walletInfo = await wallet.getWallet(ctx.from.id.toString());
      if (!walletInfo) {
        await ctx.reply('โŒ No wallet linked. Use /link first.');
        return;
      }

      await ctx.reply(
        `๐Ÿ’ฐ Your Balance:\n` +
        `SOL: ${walletInfo.balance}\n` +
        `Address: ${walletInfo.address.slice(0, 8)}...`
      );
    });

    bot.command('premium', async (ctx) => {
      const paymentUrl = await wallet.generatePaymentToken(
        ctx.from.id.toString(),
        0.1, // 0.1 SOL
        'Premium Chat Features',
        env.BOT_ID
      );

      await ctx.reply(
        `โœจ Upgrade to Premium\n\n` +
        `Features:\n` +
        `โ€ข Unlimited AI conversations\n` +
        `โ€ข Priority support\n` +
        `โ€ข Cross-platform sync\n\n` +
        `Pay: ${paymentUrl}`
      );
    });

    // Handle payment webhook
    if (request.url.includes('/webhook/payment')) {
      const payload = await request.json();

      if (payload.status === 'completed') {
        const user = await kv.get(`user:${payload.userId}`, 'json') || {};
        user.premium = true;
        await kv.put(`user:${payload.userId}`, user);

        await bot.api.sendMessage(
          payload.userId,
          '๐ŸŽ‰ Premium activated across all platforms!'
        );
      }

      return new Response('OK', { status: 200 });
    }

    return webhookCallback(bot, 'std')(request);
  }
}

Scheduled Multi-Platform Broadcasts

import { Bot, webhookCallback } from 'grammy';
import { createPlatform } from '@rizzclub/platform';

export default {
  async fetch(request, env, ctx) {
    const bot = new Bot(env.BOT_TOKEN);
    const platform = createPlatform({ env, request, waitUntil: ctx.waitUntil });
    const { scheduler, db } = platform.getServices();
    const users = db.collection('users');

    bot.command('subscribe', async (ctx) => {
      await users.insert({
        userId: ctx.from.id.toString(),
        platform: env.PLATFORM || 'telegram',
        subscribed: true,
        preferences: { updates: true }
      });

      // Schedule daily updates
      await scheduler.scheduleTask({
        name: `daily-${ctx.from.id}`,
        webhookUrl: `${env.BOT_URL}/webhook/daily`,
        webhookSecret: env.WEBHOOK_SECRET,
        cron: '0 9 * * *', // 9 AM daily
        metadata: { userId: ctx.from.id }
      });

      await ctx.reply('โœ… Subscribed to daily updates!');
    });

    // Handle daily broadcast webhook
    if (request.url.includes('/webhook/daily')) {
      const payload = await request.json();
      const allUsers = await users.find({ subscribed: true });

      for (const user of allUsers) {
        await bot.api.sendMessage(
          user.userId,
          `๐Ÿ“ฐ Your daily update on ${user.platform}!`
        );
      }

      return new Response('OK', { status: 200 });
    }

    return webhookCallback(bot, 'std')(request);
  }
}

API Reference

Platform Initialization

createPlatform(context: PlatformContext, options?: PlatformOptions): RizzClubPlatform

PlatformContext:

interface PlatformContext {
  env: {
    BOT_TOKEN: string;
    BOT_ID?: string;
    RIZZCLUB_API_KEY?: string;
    KV_NAMESPACE?: KVNamespace;
  };
  request: Request;
  waitUntil: (promise: Promise<any>) => void;
}

PlatformOptions:

interface PlatformOptions {
  mock?: boolean;        // Use mock implementations
  debug?: boolean;       // Enable debug logging
  apiKey?: string;       // Override API key
  sessionToken?: string; // For mock mode with auth
}

Platform Types

The platform field supports:

  • 'telegram' - Telegram messaging
  • 'whatsapp' - WhatsApp Business
  • 'sms' - SMS messaging
  • 'web' - Web chat experiences

TypeScript Support

Full TypeScript support with complete type definitions:

import type {
  PlatformServices,
  PlatformContext,
  PlatformOptions,
  Platform,
  KVStorage,
  AIService,
  WalletService,
  DBService,
  SchedulerService,
  PromptRequest,
  PromptResponse,
  WalletInfo,
  TokenInfo,
  ScheduledTask
} from '@rizzclub/platform';

Development

Building

npm run build     # Compile TypeScript
npm run dev       # Watch mode
npm run clean     # Clean dist/

Testing

npm run type-check  # TypeScript validation

Troubleshooting

"RIZZCLUB_API_KEY not configured"

"KV_NAMESPACE not found"

  • Create a KV namespace: npx wrangler kv:namespace create KV_NAMESPACE
  • Add the binding to wrangler.jsonc

"Mock mode not working"

  • Pass { mock: true } in options
  • Check that you're using the development environment

Roadmap

Current (v0.0.3)

  • โœ… Multi-platform support (Telegram, WhatsApp, SMS, Web)
  • โœ… KV Storage
  • โœ… AI Service (Anthropic, OpenAI, Gemini)
  • โœ… Wallet Service (SOL + SPL tokens)
  • โœ… Database Service (MongoDB-like)
  • โœ… Scheduler Service (cron + one-time)
  • โœ… Mock implementations
  • โœ… TypeScript support

Future

  • ๐Ÿ“ง Email notifications
  • ๐Ÿ“Š Analytics and metrics
  • ๐Ÿ” Enhanced authentication
  • ๐ŸŒ Multi-chain wallet support
  • ๐Ÿ“ฑ Push notifications
  • ๐ŸŽจ Rich media handling
  • ๐Ÿ”„ Cross-platform conversation sync

Connect

License

MIT ยฉ RizzClub


Built with โค๏ธ for the conversational AI community