IntroductionIntroduction about our nxcreator.com#

Welcome to our bot creation platform, where we're transforming the way developers build and manage bots. Here’s why we stand out:

Unique Approach:

Forget the complex command-based setups—our platform utilizes a traditional JavaScript syntax, making it easier and more intuitive for developers to get started.

Community Building:

We're not just a platform; we're a community. Our goal is to cultivate a thriving network of developers and users who inspire and innovate together.

Customization:

Take control and customize your bot to match your style and needs. With our platform, every detail can be tailored to enhance your bot’s uniqueness.

Learning Opportunity:

Every moment spent building and maintaining bots with us is a step towards enhancing your skills. Our platform is designed for growth and learning.

No Point System:

Our platform caters especially to creators with large audiences. We’ve eliminated the point-based system to give you unrestricted freedom to expand and engage.

Free Plan:

Speed and efficiency at no cost—enjoy our services for free! While we might offer paid plans down the road, rest assured that a free option will always be available.

Summary 💡

No Limits, No Points , No Worry!

Getting StartedGetting started with creating your first bot#

To get started and create your first telegram bot using NxCreator, follow these steps:

Generate Telegram Bot Token#

First, you need to generate an access telegram bot token to create your telegram bot with us.

Bot Token Example : 6791038971:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Generating Access Token
  1. First of All, Create a Official Telegram Bot and copy its https token from @BotFather.
  2. Now go and Grab Your Bot API Token And Go To nxcreate.com(Nxcreate.com)
  3. Go To Page
  4. Now Click on the Button on Home Page
    Add Bot
  5. It Would Ask for the token previously we copied, paste that thing here and we are ready to go! Congrats You have created your first bot!

Warning

Keep your Bot Token, Api Key and BotID safe and never share it with others. Unauthorized access to your data can occur if someone gains access to your telegram or nxcreator credentials.

Read our privacy policy Here

Understanding BasicsLets make an idea about our platform's Basic Knowledge to get Started#

Before starting next steps you need to know our all basics, usage and all requirements and how to use it.

Telegraf Logic: #

This platform is designed to work with the Telegraf library, enabling bots to perform operations such as sending messages and interacting with users. It supports all Telegraf available methods. Below is the detailed description of the basic endpoints using Telegraf's logic. For more updates or detailed methods description, head to the official Telegraf documentation.

Note: Unlike regular Telegraf, there are some exceptions. These were necessary to ensure everyone has a good time while developing Telegram bots.

Telegraf Documentation Link

Let's Get Some Basic Knowledge#


Snippet for Sending "hello World" to every user starting bot:



bot.command('start', (ctx) => {
  ctx.reply('Hello World');
});


1.1 Variables and Parameters in NxCreator

Variables in NxCreator allow you to customize responses and interact dynamically with users.

You can use ctx.from.first_name to personalize messages when handling commands. Example:



bot.command('start', async (ctx) => {
    const firstName = ctx.from.first_name;
    ctx.reply(`Hello ${firstName}, welcome to my bot!`);
});


Handling Command Parameters:

Commands can accept parameters provided by users. For example, in /start 12345, the parameter 12345 can be accessed as:




bot.command('start', async (ctx) => {
    const args = ctx.message.text.split(' ').slice(1);
    if (args.length > 0) {
        const referId = args[0];
        ctx.reply(`You were referred by ID: ${referId}.`);
    } else {
        ctx.reply('Welcome! No referral ID provided.');
    }
});

1.2 UserScenes in NxCreator

Scenes in NxCreator allow you to handle multi-step user interactions efficiently. You can use scenes to collect user input, guide users through processes, and store temporary data.. For Example, if you need to ask a user his age, bot must listen to user's input. This Work is Performed in this logic.

To create a scene object:

use the predefined answerHandler function. This function returns a scene object that can be used to handle user input:



const scene1 = answerHandler('scene1');

scene1.on('text', async (ctx) => {
    const userInput = ctx.message.text;
    ctx.reply(`You entered: ${userInput}`);
    ctx.scene.leave(); // End the scene after receiving input 
});




Entering and Leaving a Scene:

You can manually enter or leave a scene in a command or another part of your bot’s logic.




bot.command('startscene', async (ctx) => {
    ctx.reply('Please enter some text:');
    ctx.scene.enter('scene1');
});

To exit a scene within the scene logic, use ctx.scene.leave().




scene1.on('text', async (ctx) => {
    ctx.reply('Thank you! Exiting scene...');
    ctx.scene.leave();
});

Handling User Input in a Scene

Scenes allow you to handle specific types of input dynamically.




scene1.on('text', async (ctx) => {
    const input = ctx.message.text;
    ctx.reply(`Processing your input: ${input}`);
    ctx.scene.leave();
});
// For storing something to database 

scene1.on('text', async (ctx) => {
    const userResponse = ctx.message.text;
    await db.operation.setProp(ctx.from.id, 'tempData', userResponse);
    ctx.reply('Got it! Your response is saved.');
    ctx.scene.leave();
});

Using Scenes for Multi-Step Input:

If you need multiple inputs, you can chain scenes or handle different steps within a single scene:




const userInfoScene = answerHandler('userInfoScene');

userInfoScene.on('text', async (ctx) => {
    await db.operation.setProp(ctx.from.id, 'name', ctx.message.text);
    ctx.reply('Thanks! Now, please enter your age:');
    ctx.scene.enter('ageScene');
});

const ageScene = answerHandler('ageScene');

ageScene.on('text', async (ctx) => {
    await db.operation.setProp(ctx.from.id, 'age', ctx.message.text);
    ctx.reply('All set! Your information has been saved.');
    ctx.scene.leave();
});

To start this chain scene,




bot.command('userinfo', async (ctx) => {
    ctx.reply('Please enter your name:');
    ctx.scene.enter('userInfoScene');
});

1.3 Special Handlers in NxCreator

NxCreator allows you to handle all unmatched inputs and execute a global middleware before any other execution events..

For Catching unknown inputs messages(this would act as a global fallback for text messages*)

Note: You Must Place this Snippet on ending of your code otherwise the text handlers present under this would not function as it catches all upcoming text updates hereonly.




bot.on('text', async (ctx) => {
    const message = ctx.message.text;
    
    ctx.reply("Sorry, I didn’t understand that. Type /help for a list of commands.");
});


* Text Messages refer to plain messages without any photos, videos, GIFs, or other media attachments. For example, if a user sends a photo, video, sticker, or GIF, it will not be captured by bot.on('text'). If you want to handle all types of messages, including media, use bot.on('message').


Global middleware before any execution events:

This handler runs before any other event or anything.

Example Use Cases: logging user activity, validating input, or check user explicit ban status.




bot.use(async (ctx, next) => {
    const isBanned = await db.operation.getProp(ctx.from.id, 'banned');
    if (isBanned) {
        return ctx.reply('You are banned from using this bot.');
    }
    await next();
});



Should bot.use() be placed at the top of the code, before defining specific command or action handlers?
Ans: Yes.

Why?

Middleware added via bot.use() executes before commands or other handlers.

It ensures middleware-type logic (like logging, filtering, or modifying context) is applied before the bot handles updates or messages.

1.4 Error Handling in NxCreator

Enables you to handle errors efficiently and without interfering with other users.

For Global Error Handling:

Use bot.catch() to capture errors from any command, middleware, or scene.




bot.catch(async (err, ctx) => {
    console.error('An error occurred:', err);
    ctx.reply('Oops! Something went wrong. Please try again later.');
});




bot.catch() should be placed at the end of your bot setup, after defining all commands, scenes, and event handlers.
Why?
It acts as a global error handler, catching any unhandled errors from previous middleware, commands, or scenes. If placed at the start, it may not catch errors from later-defined handlers.


1.5 For Making WebRequests in NxCreator



NxCreator allows making web requests using axios, which is predefined and globally available. You can use axios.get() for GET requests and axios.post() for sending data.




bot.command('news', async (ctx) => {
    try {
        const response = await axios.get('https://api.example.com/news');
        const news = response.data.headline;
        ctx.reply(`Latest news: ${news}`);
    } catch (err) {
        console.error('API request failed:', err);
        ctx.reply('Failed to fetch news. Please try again later.');
    }
});

// for post request

bot.command('submit', async (ctx) => {
    try {
        const response = await axios.post('https://api.example.com/submit', {
            userId: ctx.from.id,
            message: 'Hello from NxCreator bot!',
        });

        ctx.reply(`Server response: ${response.data.message}`);
    } catch (err) {
        console.error('POST request failed:', err);
        ctx.reply('Failed to send data. Please try again.');
    }
});

For Sending User Input, Example:

Using Previously Mentioned Scenes Logic to Collect userInput Before Sending to API:


const userScene = answerHandler('userScene');

userScene.on('text', async (ctx) => {
    try {
        const userInput = ctx.message.text;
        const response = await axios.get(`https://api.example.com/info?query=${encodeURIComponent(userInput)}`);
        
        ctx.reply(`Result: ${response.data.result}`);
        ctx.scene.leave();
    } catch (err) {
        console.error('API request error:', err);
        ctx.reply('Failed to fetch information.');
    }
});

bot.command('ask', async (ctx) => {
    ctx.reply('Enter your question:');
    ctx.scene.enter('userScene');
});

1.6 Database Operations in NxCreator



NxCreator allows database operations through mongodb. You can use db.method or db.operation.method for operations. All modules supported by MongoDB is also supported by it. Also We have added some easier methods in db.operation such as setProp,getProp etc. for making it simplified for newbies.




  // Example using `db` directly
const user = await db.findOne("users", { userId: 12345 });
console.log(user);

// Example using `db.operation`
const user2 = await db.operation.findOne("users", { userId: 12345 });
console.log(user2);

// Example inserting data
await db.insertOne("users", { userId: 12345, balance: 1000 });

// Example updating a property
await db.setProp("users", { userId: 12345 }, "balance", 2000);

// Example retrieving a property
const balance = await db.getProp("users", { userId: 12345 }, "balance");
console.log(`User balance: ${balance}`);

// Example incrementing a property
await db.incrementProp("users", { userId: 12345 }, "balance", 500);

Note:

The MongoDB we use is the same as the native MongoDB, except you don't have to worry about connection or security.

For a complete guide on MongoDB queries/operations, I recommend you visit the following comprehensive guide and learning tutorial: MongoDB Guide - W3Schools

Code Examples#

In this section, you'll find practical code snippets and examples demonstrating how to use various logic effectively.

Each example is designed to help you understand how to implement flow and handle user interactions, making it easier to dive into your creation. It doesn't matter whether you're newbie or veteran developer,this would surely help you in developing bots.

Lets Start With Popular Bot Example#

For Creating an AIChatBOT Using GEMINI_API_KEY :


    
    
const GEMINI_API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const TELEGRAM_MESSAGE_LIMIT = 4096;

bot.command('start', async (ctx) => {
    await db.collection('chatHistory').insertOne({ userId: ctx.from.id, messages: [] });
    ctx.reply('👋 How can I help you today?');
});

bot.on('text', async (ctx) => {
    const userId = ctx.from.id;
    const userMessage = ctx.message.text;

    await ctx.sendChatAction('typing');


    let chatHistoryDoc = await db.collection('chatHistory').findOne({ userId: userId });
    let chatHistory = chatHistoryDoc ? chatHistoryDoc.messages : [];
    

    chatHistory.push({ role: 'user', text: userMessage });
    chatHistory = chatHistory.slice(-2); // Keep only the last 10 entries


    await db.collection('chatHistory').updateOne({ userId: userId }, { $set: { messages: chatHistory } });

    const awaitingMsg = await ctx.reply('Awaiting response...', { parse_mode: 'HTML' });

    try {
        const aiResponse = await getGeminiResponse(chatHistory);
        await ctx.deleteMessage(awaitingMsg.message_id);

        chatHistory.push({ role: 'bot', text: aiResponse });
        await db.collection('chatHistory').updateOne({ userId: userId }, { $set: { messages: chatHistory } });

        await sendLongMessage(ctx, aiResponse);
    } catch (err) {
        console.error('AI API Error:', err);
        await ctx.reply('Failed to fetch AI response. Please try again later.');
    }
});

async function getGeminiResponse(chatHistory) {
    const response = await axios.post(
        `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${GEMINI_API_KEY}`,
        {
            contents: [{ parts: chatHistory.map((msg) => ({ text: `${msg.role}: ${msg.text}` })) }]
        },
        { headers: { 'Content-Type': 'application/json' } }
    );

    return response.data.candidates?.[0]?.content?.parts?.[0]?.text || 'Sorry, I could not process that.';
}

async function sendLongMessage(ctx, text) {
    while (text.length > 0) {
        const part = text.slice(0, TELEGRAM_MESSAGE_LIMIT);
        text = text.slice(TELEGRAM_MESSAGE_LIMIT);
        await ctx.reply(part);
    }
}

🔥 Generate Free GEMINI API KEY Here

Note:

We would regularly share such bots made by us/community in our official telegram group. Consider joining it it would be a wonderful experience!

Link:Telegram Group

Some Use Cases

The **Usage** section showcases creative ways to use NxCreator’s existing functionalities. These examples help developers build feature-rich Telegram bots without worries.

1️⃣ Tracking User Activity

Command : /track

NxCreator :


bot.command('track', async (ctx) => {
    const userId = ctx.from.id;
    await db.operation.incrementProp('users', { telegramId: userId }, 'messagesSent');
    await db.operation.setProp('users', { telegramId: userId }, 'lastActive', new Date());
    ctx.reply('✅ Your activity has been recorded.');
});
        
2️⃣ Randomized User Rewards

Command : /claimreward

NxCreator :


bot.command('claimreward', async (ctx) => {
    const userId = ctx.from.id;
    const lastClaimed = await db.operation.getProp('users', { telegramId: userId }, 'lastRewardTime');

    if (lastClaimed && Date.now() - lastClaimed < 86400000) {
        return ctx.reply('⏳ You can only claim once per day!');
    }

    const rewards = ['50 Coins', '100 Coins', '500 Coins', 'Jackpot 🎰'];
    const reward = rewards[Math.floor(Math.random() * rewards.length)];

    await db.operation.setProp('users', { telegramId: userId }, 'lastRewardTime', Date.now());
    ctx.reply(`🎁 You won: ${reward}`);
});
        
3️⃣ Generating One-Time Codes

Command : /getcode

NxCreator :


bot.command('getcode', async (ctx) => {
    const userId = ctx.from.id;
    const tempCode = Math.random().toString(36).substring(2, 8).toUpperCase();

    await db.operation.setProp('users', { telegramId: userId }, 'otpCode', tempCode);
    ctx.reply(`🔑 Code: ${tempCode} (Valid for 5 mins)`);

    setTimeout(() => db.operation.removeProp('users', { telegramId: userId }, 'otpCode'), 300000);
});
        
4️⃣ Fetching User Leaderboard

Command : /leaderboard

NxCreator :


bot.command('leaderboard', async (ctx) => {
    const users = await db.operation.findAll('users', {}, { sort: { messagesSent: -1 }, limit: 5 });

    if (!users.length) return ctx.reply('🏆 No users on the leaderboard yet!');

    let leaderboard = '🏆 **Top Users**\n\n';
    users.forEach((user, index) => {
        leaderboard += `${index + 1}. ${user.username || 'Unknown'} - ${user.messagesSent || 0} messages\n`;
    });

    ctx.reply(leaderboard);
});
        
5️⃣ Custom Inline Poll Voting

Command : /poll

NxCreator :


bot.command('poll', async (ctx) => {
    ctx.reply('🗳️ Vote:', {
        reply_markup: {
            inline_keyboard: [
                [{ text: '✅ Yes', callback_data: 'vote_yes' }],
                [{ text: '❌ No', callback_data: 'vote_no' }]
            ]
        }
    });
});

bot.on('callback_query', async (ctx) => {
    const vote = ctx.callbackQuery.data === 'vote_yes' ? 'Yes' : 'No';
    await db.operation.incrementProp('poll_votes', { option: vote }, 'count');
    ctx.answerCbQuery(`You voted: ${vote}`);
});
        
6️⃣ Reminder Bot

Command : /remindme 10 Take a break

NxCreator :


bot.command('remindme', async (ctx) => {
    const args = ctx.message.text.split(' ').slice(1);
    const time = parseInt(args[0], 10);
    const message = args.slice(1).join(' ') || 'Reminder!';

    if (!time || isNaN(time)) return ctx.reply('⚠️ Invalid time! Example: /remindme 10 Take a break.');

    setTimeout(() => {
        ctx.reply(`⏰ Reminder: ${message}`);
    }, time * 60000);

    ctx.reply(`✅ Reminder set for ${time} minutes.`);
});
        
7️⃣ User Feedback Collector

Command : /feedback

NxCreator :


const feedbackScene = answerHandler('feedback');

feedbackScene.on('text', async (ctx) => {
    await db.operation.insertOne('feedback', { userId: ctx.from.id, message: ctx.message.text });
    ctx.reply('✅ Feedback saved! Thanks for your input.');
    ctx.scene.leave();
});

bot.command('feedback', (ctx) => ctx.scene.enter('feedback'));
        

Note

All examples above use **NxCreator's built-in functionalities** without extra libraries. Replace database properties as needed.

Extra Functionalities Lets learn about some extra functionality of NxCreator.#

This section would provide you some extra functionalities which you can use in NxCreator.

NxCreator Extra Functionalities #

  • Use setTimeout to Delay a Response:

    Send a message after a delay of 5 seconds.

                        
    bot.command('remindme', async (ctx) => {
        ctx.reply('I will remind you in 5 seconds...');
        setTimeout(() => {
            ctx.reply('⏰ Reminder: 5 seconds passed!');
        }, 5000);
    });
                        
                    
  • Schedule Repeating Messages with setInterval:

    Send a message every 10 seconds.

                        
    bot.command('startreminder', async (ctx) => {
        const intervalId = setInterval(() => {
            ctx.reply('🔔 This is a recurring message every 10 seconds.');
        }, 10000);
        ctx.session.intervalId = intervalId;
    });
    
    bot.command('stopreminder', (ctx) => {
        if (ctx.session.intervalId) {
            clearInterval(ctx.session.intervalId);
            ctx.reply('✅ Reminder stopped.');
        } else {
            ctx.reply('No active reminders.');
        }
    });
                        
                    
  • Fetching Cryptocurrency Prices:

    Get real-time Bitcoin price.

                        
    bot.command('price', async (ctx) => {
        const response = await axios.get('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd');
        ctx.reply(`Bitcoin Price: $${response.data.bitcoin.usd}`);
    });
                        
                    
  • Creating a Custom Inline Keyboard:

    Display buttons in a message.

                        
    bot.command('menu', (ctx) => {
        ctx.reply('Choose an option:', {
            reply_markup: {
                inline_keyboard: [
                    [{ text: 'Option 1', callback_data: 'opt1' }],
                    [{ text: 'Option 2', callback_data: 'opt2' }]
                ]
            }
        });
    });
    
    bot.action('opt1', (ctx) => ctx.reply('You selected Option 1!'));
    bot.action('opt2', (ctx) => ctx.reply('You selected Option 2!'));
                        
                    
  • Encrypting & Decrypting Messages Using crypto:

    Encrypt a message using AES-256.

                        
    const algorithm = 'aes-256-cbc';
    const key = crypto.randomBytes(32);
    const iv = crypto.randomBytes(16);
    
    function encrypt(text) {
        const cipher = crypto.createCipheriv(algorithm, key, iv);
        let encrypted = cipher.update(text, 'utf8', 'hex');
        encrypted += cipher.final('hex');
        return { encryptedData: encrypted, iv: iv.toString('hex') };
    }
    
    function decrypt(encryptedData, ivHex) {
        const decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(ivHex, 'hex'));
        let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
        decrypted += decipher.final('utf8');
        return decrypted;
    }
    
    const data = 'Hello, NxCreator!';
    const encrypted = encrypt(data);
    console.log('Encrypted:', encrypted);
    
    const decrypted = decrypt(encrypted.encryptedData, encrypted.iv);
    console.log('Decrypted:', decrypted);
                        
                    

Tip

Before deploying, test your bot’s extra functionalities to ensure smooth user experience.

Report Bugs

New Features Coming Very Soon ...




Join Us On Telegram For Latest Updates