@wasserstoff/mangi-tg-bot
Version:
A powerful Telegram Bot SDK with built-in authentication, session management, and database integration
229 lines • 11.2 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const index_1 = require("./index");
// ---
// 1. JWT Authentication Example
// ---
const configWithJwtAuth = {
botToken: "YOUR_BOT_TOKEN", // Replace with your actual token
botMode: "polling",
botAllowedUpdates: ["message", "callback_query"],
redisUrl: "YOUR_REDIS_URL",
isDev: true,
useAuth: "fully", // All routes require JWT authentication
jwtSecret: "your_jwt_secret_here",
};
async function createJwtAuthBot() {
index_1.logger.info("Starting bot with JWT authentication:", configWithJwtAuth);
const bot = new index_1.Bot(configWithJwtAuth);
await bot.initialize();
const botManager = bot.getBotManager();
botManager.handleCommand("start", async (ctx) => {
await ctx.api.sendMessage(ctx.chat.id, "Welcome! You are authenticated with JWT.");
});
botManager.handleCommand("whoami", async (ctx) => {
await ctx.api.sendMessage(ctx.chat.id, `Your chat ID: <code>${ctx.from.id}</code>`, { parse_mode: "HTML" });
});
}
// ---
// 2. Admin Authentication/Approval Example
// ---
const configWithAdminAuth = {
botToken: "YOUR_BOT_TOKEN", // Replace with your actual token
botMode: "polling",
botAllowedUpdates: ["message", "callback_query"],
redisUrl: "YOUR_REDIS_URL",
isDev: true,
useAuth: "none",
adminAuthentication: true, // Enable admin approval system
adminChatIds: [123456789, 987654321], // Replace with your admin Telegram chat IDs
};
async function createAdminAuthBot() {
index_1.logger.info("Starting bot with admin authentication:", configWithAdminAuth);
const bot = new index_1.Bot(configWithAdminAuth);
await bot.initialize();
const botManager = bot.getBotManager();
botManager.handleCommand("start", async (ctx) => {
await ctx.api.sendMessage(ctx.chat.id, "Welcome! If you see this, you are approved by an admin.");
});
botManager.handleCommand("whoami", async (ctx) => {
await ctx.api.sendMessage(ctx.chat.id, `Your chat ID: <code>${ctx.from.id}</code>`, { parse_mode: "HTML" });
});
botManager.handleCommand("secret", async (ctx) => {
await ctx.api.sendMessage(ctx.chat.id, "This is a secret command only for approved users!");
});
}
// ---
// 3. Session CRUD Operations Example
// ---
const configWithSessionCrud = {
botToken: "YOUR_BOT_SESSION", // Replace with your actual token
botMode: "polling",
botAllowedUpdates: ["message", "callback_query"],
redisUrl: "YOUR_REDIS_URL",
isDev: true,
useAuth: "none",
};
async function createSessionCrudBot() {
index_1.logger.info("Starting bot with session CRUD example:", configWithSessionCrud);
const bot = new index_1.Bot(configWithSessionCrud);
await bot.initialize();
const botManager = bot.getBotManager();
botManager.handleCommand("setvar", async (ctx) => {
// Demonstrate setCustom
const setResult = ctx.session.setCustom("foo", "bar");
// Demonstrate getCustom (should return 'bar')
const foo = ctx.session.getCustom("foo");
// Demonstrate updateCustom
const updateResult = ctx.session.updateCustom({ hello: "world", count: 1 });
// Demonstrate deleteCustom (should return true)
const deleteResult = ctx.session.deleteCustom("count");
// Demonstrate deleteCustom for non-existent key (should return false)
const deleteMissing = ctx.session.deleteCustom("notfound");
// Demonstrate getCustom for non-existent key (should return undefined)
const missing = ctx.session.getCustom("notfound");
await ctx.api.sendMessage(ctx.chat.id, `Session custom variable 'foo' set: ${setResult}\n
Value of 'foo': ${foo}\n
Update result: ${updateResult}\n
Delete 'count' result: ${deleteResult}\n
Delete 'notfound' result: ${deleteMissing}\n
Get 'notfound': ${missing}`, { parse_mode: "HTML" });
});
botManager.handleCommand("getvar", async (ctx) => {
const foo = ctx.session.getCustom("foo");
await ctx.api.sendMessage(ctx.chat.id, `Current value of 'foo': ${foo}`);
});
}
// ---
// 4. Combined Example: JWT Auth + Admin Auth + Session CRUD
// ---
const configCombined = {
botToken: "YOUR_BOT_TOKEN", // Replace with your actual token
botMode: "polling",
botAllowedUpdates: ["message", "callback_query"],
redisUrl: "YOUR_REDIS_URL",
isDev: true,
useAuth: "fully", // JWT auth required for all routes
jwtSecret: "aman1211",
adminAuthentication: true, // Enable admin approval system
adminChatIds: [6469050225], // Replace with your admin Telegram chat IDs
};
async function createCombinedBot() {
index_1.logger.info("Starting combined bot with JWT, admin auth, and session CRUD:", configCombined);
const bot = new index_1.Bot(configCombined);
await bot.initialize();
const botManager = bot.getBotManager();
botManager.setMyCommands([
{ command: "start", description: "Start the bot" },
{ command: "whoami", description: "Get your chat ID" },
{ command: "setvar", description: "Secret command" },
]);
// Only accessible if JWT is valid AND user is approved by admin
botManager.handleCommand("start", async (ctx) => {
await ctx.api.sendMessage(ctx.chat.id, "Welcome! You are authenticated and approved by an admin.");
});
// Handle all messages or other events : ComputeFilterQueryList | ComputeFilterQueryList[]
botManager.handleEvent("message:text", async (ctx) => {
console.log(ctx.message.text, `<---------ctx.message.text`);
});
// Session CRUD helpers
botManager.handleCommand("setvar", async (ctx) => {
// Demonstrate setCustom
const chain = "level2";
const setResult = ctx.session.setCustom("foo", "bar");
const setResult1 = ctx.session.setCustom(`level1.${chain}.level3`, "60 rs");
// Demonstrate getCustom (should return 'bar')
const foo = ctx.session.getCustom("foo");
// Demonstrate updateCustom
const updateResult = ctx.session.updateCustom({ hello: "i am helo world" });
// Demonstrate deleteCustom (should return true)
const deleteResult = ctx.session.deleteCustom("count");
// Demonstrate deleteCustom for non-existent key (should return false)
const deleteMissing = ctx.session.deleteCustom("notfound");
// Demonstrate getCustom for non-existent key (should return undefined)
const missing = ctx.session.getCustom("notfound");
await ctx.api.sendMessage(ctx.chat.id, `Session custom variable 'foo' set: ${setResult}\n` +
`'2nd' set: ${setResult1}\n` +
`Value of 'foo': ${foo}\n` +
`Update result: ${updateResult}\n` +
`Delete 'count' result: ${deleteResult}\n` +
`Delete 'notfound' result: ${deleteMissing}\n` +
`Get 'notfound': ${missing}`);
});
botManager.handleCommand("getvar", async (ctx) => {
const foo = ctx.session.getCustom("foo");
await ctx.api.sendMessage(ctx.chat.id, `Current value of 'foo': ${foo}`);
});
// Show user their chat ID (useful for admin setup)
botManager.handleCommand("whoami", async (ctx) => {
await ctx.api.sendMessage(ctx.chat.id, `Your chat ID: <code>${ctx.from.id}</code>`, { parse_mode: "HTML" });
});
botManager.handleCommand("generate", async (ctx) => {
await ctx.api.sendMessage(ctx.chat.id, "Click the button below to generate an image (this will take a few seconds):", {
reply_markup: {
inline_keyboard: [[{ text: "🖼️ Generate Image", callback_data: "generate_image" }]]
}
});
});
// Example of handling long-running operations (like image generation)
botManager.handleCallback((ctx) => ctx.callbackQuery.data === "generate_image", async (ctx) => {
try {
// Send a "processing" message first
const processingMsg = await ctx.api.sendMessage(ctx.chat.id, "🔄 Generating your image... Please wait.");
// Simulate a long-running image generation process
// In real usage, this would be your image generation API call
await new Promise(resolve => setTimeout(resolve, 45000)); // 45 second delay
// Send the generated image (or result)
await ctx.api.sendPhoto(ctx.chat.id, "https://images.app.goo.gl/PXqYPMSfFdR2QiwA7", {
caption: "Here's your generated image! 🎨",
reply_markup: {
inline_keyboard: [[
{ text: "Generate Another", callback_data: "generate_image" },
{ text: "Done", callback_data: "done" }
]]
}
});
// Delete the processing message
await ctx.api.deleteMessage(ctx.chat.id, processingMsg.message_id);
}
catch (error) {
// If there's an error, send an error message
await ctx.api.sendMessage(ctx.chat.id, "❌ Sorry, there was an error generating your image. Please try again.", {
reply_markup: {
inline_keyboard: [[{ text: "Try Again", callback_data: "generate_image" }]]
}
});
}
});
// Example of a simple "done" callback
botManager.handleCallback((ctx) => ctx.callbackQuery.data === "done", async (ctx) => {
await ctx.api.sendMessage(ctx.chat.id, "✅ Great! Let me know if you need anything else.");
});
// Example: Only approved users with valid JWT can access this command
botManager.handleCommand("secret", async (ctx) => {
await ctx.api.sendMessage(ctx.chat.id, "This is a secret command only for authenticated and approved users!");
});
botManager.handleMessage((ctx) => ctx.message.text === "xyz2", async (ctx) => {
await ctx.api.sendMessage(ctx.chat.id, "This is xyz2 message response!", { parse_mode: "HTML", reply_markup: { inline_keyboard: [[{ text: "Click me", callback_data: "xyz" }]] } });
});
botManager.handleMessage((ctx) => ctx.message.text === "xyz", async (ctx) => {
await ctx.api.sendMessage(ctx.chat.id, "This is xyz message response!", { parse_mode: "HTML", reply_markup: { inline_keyboard: [[{ text: "Click me", callback_data: "xyz" }]] } });
});
// Example message to trigger image generation
botManager.handleMessage((ctx) => ctx.message.text === "generate", async (ctx) => {
await ctx.api.sendMessage(ctx.chat.id, "🎨 Image Generation Demo\n\nClick the button below to generate an image (this will take a few seconds):", {
reply_markup: {
inline_keyboard: [[{ text: "🖼️ Generate Image", callback_data: "generate_image" }]]
}
});
});
}
// ---
// To test a use case, uncomment the corresponding function call below and provide your bot token and admin IDs.
// Only run ONE bot at a time.
// ---
// createJwtAuthBot();
// createAdminAuthBot();
// createSessionCrudBot();
createCombinedBot();
//# sourceMappingURL=example.js.map