▎Day 2: Bot Commands and Responses 🎉
Welcome to Day 2 of the 30-Day Bots.Business JavaScript (BJS) Learning Session! 🚀 Yesterday, we covered the basics of Bots.Business and created a simple bot with a /start command. Today, we’ll dive deeper into commands and learn how to make your bot respond to user input dynamically. 💬
---
▎What Are Commands? ❓
In Bots.Business, commands are the backbone of your bot. Each command is a specific trigger that tells your bot how to respond when a user sends a particular message. Commands can have predefined text responses or JavaScript code for more dynamic actions. ⚙️
---
▎How to Create Commands 🛠️
1. Step 1: Open the Command Editor
Go to your bot’s Commands section in the Bots.Business dashboard. 📊
2. Step 2: Add a New Command
Create a new command by typing its name (e.g., /info, /help). ✏️
Add the response or JavaScript code you want the bot to execute when the command is triggered. 🔄
3. Step 3: Save and Test
Save the command and test it in Telegram by typing the command in your bot's chat. 📱
---
▎Static Response Example 📜
Let’s create a simple command called
• Command Name:
• Response: "Welcome to the help section! Use /start to begin or /info to learn more about me." 🆘
When a user types
---
▎Dynamic Response Example Using JavaScript 💻
You can use JavaScript to make responses more dynamic. For example, let’s create a
• Create a command
• Add the above script to the command.
• Save and test it by typing
If the user’s first name is John, the bot will reply:
"Hello, John! How can I assist you today?" 👋
---
▎Handling Custom Inputs 🎨
You can also create commands to handle inputs from users. For instance, let’s create a
To handle the user’s reply, you can create another command to capture their response. For example:
---
▎Assignment for Day 2 📚
1. Create a command
"This is a demo bot created with Bots.Business JavaScript. Stay tuned for more!" 🎊
2. Create a dynamic command
3. Optional Challenge:
Create a command
---
▎What’s Next? 🔮
Tomorrow, in Day 3, we’ll explore Variables in Bots.Business JavaScript. Variables will allow us to store and manipulate user data to create more personalized and interactive bots. Keep practicing and experimenting! 💪
Welcome to Day 2 of the 30-Day Bots.Business JavaScript (BJS) Learning Session! 🚀 Yesterday, we covered the basics of Bots.Business and created a simple bot with a /start command. Today, we’ll dive deeper into commands and learn how to make your bot respond to user input dynamically. 💬
---
▎What Are Commands? ❓
In Bots.Business, commands are the backbone of your bot. Each command is a specific trigger that tells your bot how to respond when a user sends a particular message. Commands can have predefined text responses or JavaScript code for more dynamic actions. ⚙️
---
▎How to Create Commands 🛠️
1. Step 1: Open the Command Editor
Go to your bot’s Commands section in the Bots.Business dashboard. 📊
2. Step 2: Add a New Command
Create a new command by typing its name (e.g., /info, /help). ✏️
Add the response or JavaScript code you want the bot to execute when the command is triggered. 🔄
3. Step 3: Save and Test
Save the command and test it in Telegram by typing the command in your bot's chat. 📱
---
▎Static Response Example 📜
Let’s create a simple command called
/help that responds with a static message:• Command Name:
/help • Response: "Welcome to the help section! Use /start to begin or /info to learn more about me." 🆘
When a user types
/help, the bot will reply with this predefined text.---
▎Dynamic Response Example Using JavaScript 💻
You can use JavaScript to make responses more dynamic. For example, let’s create a
/greet command that uses the user’s name to greet them:Bot.sendMessage("Hello, " + user.first_name + "! How can I assist you today?");
• Create a command
/greet in the Command Editor. ✨ • Add the above script to the command.
• Save and test it by typing
/greet in your bot’s chat. ✅If the user’s first name is John, the bot will reply:
"Hello, John! How can I assist you today?" 👋
---
▎Handling Custom Inputs 🎨
You can also create commands to handle inputs from users. For instance, let’s create a
/ask command that prompts the user for their favorite color:Bot.sendMessage("What’s your favorite color?");
To handle the user’s reply, you can create another command to capture their response. For example:
Bot.sendMessage("Nice choice! I love that color too.");
---
▎Assignment for Day 2 📚
1. Create a command
/about with the static response: "This is a demo bot created with Bots.Business JavaScript. Stay tuned for more!" 🎊
2. Create a dynamic command
/myname that replies with the user’s name. Use this script: Bot.sendMessage("Hi, " + user.first_name + "! Nice to meet you.");
3. Optional Challenge:
Create a command
/askcolor that asks the user their favorite color and responds dynamically to their input. (Hint: Use a callback command to handle the input.) 🎯---
▎What’s Next? 🔮
Tomorrow, in Day 3, we’ll explore Variables in Bots.Business JavaScript. Variables will allow us to store and manipulate user data to create more personalized and interactive bots. Keep practicing and experimenting! 💪
👍7❤2🔥1
Coding Skill Builder 💪📚(Full AI Based)
Bot.sendMessage("Hi, " + user.first_name + "! Nice to meet you.");
To add both the first name and last name in the message, you can modify the code as follows:
By adding
Bot.sendMessage("Hi, " + user.first_name + " " + user.last_name + "! Nice to meet you.");
By adding
user.last_name next to user.first_name with a space in between, you will include both the first name and last name in the greeting message. This code will now address the user by their first name and last name, making the message more personalized.1❤3👍3
▎Day 3: Using Variables in Bots.Business JavaScript (BJS)
Welcome to Day 3! Today, we’ll dive deeper into using variables in your bot to enhance its interactivity and personalization.
---
▎What Are Variables?
Variables are essential components in programming that allow you to store and manage data. In the context of Bots.Business JavaScript, variables can help you:
• Remember user-specific information: such as names, ages, and preferences.
• Track statistics: like the number of interactions or scores.
• Pass data between commands.
You can store various types of data in variables, including strings (text), numbers, and more.
---
▎How to Use Variables in BJS
1. Declaring a Variable
To create a variable and assign it a value:
2. Using a Variable
You can use the variable to send messages or perform actions:
3. Modifying a Variable
To change the value of a variable:
---
▎Working with User-Specific Variables
In Bots.Business, user-specific data is often managed using
▎Storing Data: User.setProperty()
To store user-specific data:
• key: Unique identifier (e.g., "name", "age").
• value: The data to store (e.g., "John", 25).
• type: The type of data (e.g., "string", "number", "boolean").
Example:
▎Retrieving Data: User.getProperty()
To retrieve stored data:
---
▎Example: Storing and Using a Name
Let’s create two commands:
1. Command: /setname
2. Command: /getname
---
▎Example: Counting User Interactions
You can track how many times a user interacts with your bot using variables.
1. Command: /interact
---
▎Assignment for Day 3
1. Create a command
• Hint: Use
2. Create a command
• Hint: Use
3. Bonus Challenge:
• Create a command
• Hint: Use
---
▎What’s Next?
In Day 4, we will explore conditions (if/else statements) and how to make your bot respond differently based on user input or stored variables. Keep practicing what you’ve learned today, and feel free to share your progress! Happy coding!
Welcome to Day 3! Today, we’ll dive deeper into using variables in your bot to enhance its interactivity and personalization.
---
▎What Are Variables?
Variables are essential components in programming that allow you to store and manage data. In the context of Bots.Business JavaScript, variables can help you:
• Remember user-specific information: such as names, ages, and preferences.
• Track statistics: like the number of interactions or scores.
• Pass data between commands.
You can store various types of data in variables, including strings (text), numbers, and more.
---
▎How to Use Variables in BJS
1. Declaring a Variable
To create a variable and assign it a value:
let myVariable = "Hello, World!";
2. Using a Variable
You can use the variable to send messages or perform actions:
Bot.sendMessage(myVariable);
3. Modifying a Variable
To change the value of a variable:
let myVariable = "Goodbye, World!";
---
▎Working with User-Specific Variables
In Bots.Business, user-specific data is often managed using
User.setProperty and User.getProperty methods.▎Storing Data: User.setProperty()
To store user-specific data:
User.setProperty("key", value, "string");
• key: Unique identifier (e.g., "name", "age").
• value: The data to store (e.g., "John", 25).
• type: The type of data (e.g., "string", "number", "boolean").
Example:
User.setProperty("name", "John", "string");
▎Retrieving Data: User.getProperty()
To retrieve stored data:
let name = User.getProperty("name");
Bot.sendMessage("Your name is: " + name);
---
▎Example: Storing and Using a Name
Let’s create two commands:
/setname to store the user’s name and /getname to retrieve it.1. Command: /setname
// Assume user input is captured in userInput
User.setProperty("name", userInput, "string"); // Replace userInput with actual input
Bot.sendMessage("Your name has been saved!");
2. Command: /getname
let name = User.getProperty("name");
Bot.sendMessage("Your saved name is: " + name);
---
▎Example: Counting User Interactions
You can track how many times a user interacts with your bot using variables.
1. Command: /interact
let count = User.getProperty("interaction_count") || 0; // Default to 0 if not set
count += 1;
User.setProperty("interaction_count", count, "number");
Bot.sendMessage("You have interacted with this bot " + count + " times!");
---
▎Assignment for Day 3
1. Create a command
/saveage that asks the user for their age and stores it in a variable.• Hint: Use
User.setProperty("age", userInput, "number");.2. Create a command
/getage that retrieves and displays the saved age.• Hint: Use
User.getProperty("age");.3. Bonus Challenge:
• Create a command
/reset that clears the saved age and interaction count.• Hint: Use
User.setProperty("key", null); to reset a variable.---
▎What’s Next?
In Day 4, we will explore conditions (if/else statements) and how to make your bot respond differently based on user input or stored variables. Keep practicing what you’ve learned today, and feel free to share your progress! Happy coding!
👍5🔥3
Hey learners! 👋
You've completed 3 days of the Bots.Business learning session. It's time to put your knowledge to the test! 💪
You've completed 3 days of the Bots.Business learning session. It's time to put your knowledge to the test! 💪
1️⃣ What will this script do?
Bot.sendMessage("Hello, " + user.first_name + "!");👍4
3️⃣ What will this code do?
let count = User.getProperty("interaction_count") || 0;
count += 1;
User.setProperty("interaction_count", count, "number");
Bot.sendMessage("You’ve interacted " + count + " times!");👍1
Day 4: Leveraging Conditions (if/else) in Bots.Business JavaScript
Welcome to Day 4 of the 30-Day Bots.Business JavaScript (BJS) Learning Session! So far, we’ve explored commands, variables, and how to store user data. Today, we’re excited to elevate your bot-building skills by introducing conditions. With conditions, your bot can make informed decisions and respond differently based on user input or stored data.
---
▎What Are Conditions?
Conditions enable your bot to evaluate specific scenarios and take appropriate actions. The most common way to implement conditions in BJS is through if/else statements.
---
▎Basic Syntax
---
▎Example 1: Greeting Based on User’s Name
Let’s create a command
---
▎Example 2: Check User's Age
We can utilize conditions to assess a user’s age and provide tailored responses:
Command:
---
▎Example 3: Using Inputs Dynamically
Let’s implement a command that verifies if the user sends a specific input (e.g., a password):
Command:
---
▎Nested Conditions
You can also nest if statements within one another for more complex logic. Here’s an example:
---
▎Assignment for Day 4
1️⃣ Create a command
Utilize a stored variable (e.g.,
• If the user is an admin, send:
"Welcome, Admin! You have full access."
• Otherwise, send:
"Access denied! You are not an admin."
2️⃣ Create a command
Prompt the user for a test score and respond based on the value:
• If the score is 80 or above, reply:
"Great job! You passed!"
• If the score is below 80, reply:
"Keep trying! You can do better!"
3️⃣ Bonus Challenge:
Develop a bot that asks for a user’s favorite number.
• If the number is divisible by 2, respond:
"That’s an even number!"
• If it’s not, respond:
"That’s an odd number!"
---
▎What’s Next?
In Day 5, we’ll delve into Bots.Business Libraries and discover how to enhance your bot’s functionality with pre-built tools such as ResourcesLib, Guard, and more. Keep practicing, and don’t forget to test your bot commands! 🚀
Welcome to Day 4 of the 30-Day Bots.Business JavaScript (BJS) Learning Session! So far, we’ve explored commands, variables, and how to store user data. Today, we’re excited to elevate your bot-building skills by introducing conditions. With conditions, your bot can make informed decisions and respond differently based on user input or stored data.
---
▎What Are Conditions?
Conditions enable your bot to evaluate specific scenarios and take appropriate actions. The most common way to implement conditions in BJS is through if/else statements.
---
▎Basic Syntax
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
---
▎Example 1: Greeting Based on User’s Name
Let’s create a command
/checkname that checks whether the user’s name is stored and responds accordingly:let name = User.getProperty("name");
if (name) {
Bot.sendMessage("Hello, " + name + "! Welcome back!");
} else {
Bot.sendMessage("I don’t know your name yet. Please set it using /setname.");
}
---
▎Example 2: Check User's Age
We can utilize conditions to assess a user’s age and provide tailored responses:
Command:
/checkagelet age = User.getProperty("age");
if (!age) {
Bot.sendMessage("I don't know your age yet. Use /saveage to set it.");
} else if (age < 18) {
Bot.sendMessage("You’re under 18! Some features might not be available.");
} else {
Bot.sendMessage("You’re 18 or older! Enjoy all the features of this bot.");
}
---
▎Example 3: Using Inputs Dynamically
Let’s implement a command that verifies if the user sends a specific input (e.g., a password):
Command:
/checkpasswordlet userPassword = "secret123"; // Define a password
if (message == userPassword) {
Bot.sendMessage("Access granted! ✅");
} else {
Bot.sendMessage("Access denied! ❌ Incorrect password.");
}
---
▎Nested Conditions
You can also nest if statements within one another for more complex logic. Here’s an example:
let age = User.getProperty("age");
if (age) {
if (age < 18) {
Bot.sendMessage("You’re under 18!");
} else {
Bot.sendMessage("You’re 18 or older!");
}
} else {
Bot.sendMessage("I don’t know your age yet. Use /saveage to set it.");
}
---
▎Assignment for Day 4
1️⃣ Create a command
/checkaccess:Utilize a stored variable (e.g.,
User.getProperty("isAdmin")) to determine if a user is an admin or not.• If the user is an admin, send:
"Welcome, Admin! You have full access."
• Otherwise, send:
"Access denied! You are not an admin."
2️⃣ Create a command
/testscore:Prompt the user for a test score and respond based on the value:
• If the score is 80 or above, reply:
"Great job! You passed!"
• If the score is below 80, reply:
"Keep trying! You can do better!"
3️⃣ Bonus Challenge:
Develop a bot that asks for a user’s favorite number.
• If the number is divisible by 2, respond:
"That’s an even number!"
• If it’s not, respond:
"That’s an odd number!"
---
▎What’s Next?
In Day 5, we’ll delve into Bots.Business Libraries and discover how to enhance your bot’s functionality with pre-built tools such as ResourcesLib, Guard, and more. Keep practicing, and don’t forget to test your bot commands! 🚀
👍5❤1
Day 5: Introduction to Bots.Business Libraries
Welcome to Day 5 of the 30-Day Bots.Business JavaScript (BJS) Learning Session! Today, we’re diving into one of the most powerful features of Bots.Business: Libraries. These pre-built tools simplify the process of extending your bot’s functionality and incorporating advanced features without the need to code everything from scratch.
---
What Are Bots.Business Libraries?
Libraries in Bots.Business consist of pre-designed scripts that offer specific features or tools for your bots. Rather than manually coding complex functionalities, you can leverage libraries to efficiently manage tasks such as user resource management, bot protection, or data synchronization with external applications.
---
Popular Libraries in Bots.Business
Here are some commonly utilized libraries you’ll be working with:
1. ResourcesLib
This library assists in managing user resources like coins, points, energy, etc.
Example: Track how many virtual coins a user possesses.
2. Guard
This library safeguards your bot from spammers and abusive behaviors.
Example: Limit the frequency with which a command can be executed within a specified timeframe.
3. CooldownLib
This library establishes cooldown periods for commands.
Example: Prevent users from executing a command too frequently.
4. DatetimeFormatLib
This library formats and handles dates and times.
Example: Display the current date in a user-friendly format.
5. TopBoardLib
This library tracks leaderboards for competitive features.
Example: Showcase the top 10 users based on their points.
---
How to Use Libraries
Libraries come pre-installed in Bots.Business. To utilize one:
1. Include the library in your bot by adding its script at the top of your command.
2. Employ the library’s methods within your bot’s code.
For instance, to utilize the ResourcesLib, you would write:
This code creates a resource called "coins" for each user.
---
Example 1: ResourcesLib (User Resources)
Let’s develop a system to manage virtual coins for users.
Command 1: /addcoins
Add coins to the user’s account:
Command 2: /checkcoins
Check the user’s current coin balance:
Command 3: /spendcoins
Spend coins if the user has enough:
---
Example 2: CooldownLib
Cooldowns ensure that users can’t spam a command repeatedly.
Command: /claimreward
Allow users to claim a reward only once every 24 hours:
---
Example 3: TopBoardLib (Leaderboard)
Create a leaderboard to track user scores.
Command 1: /addscore
Add a user’s score to the leaderboard:
Command 2: /leaderboard
Show the top 5 users:
Welcome to Day 5 of the 30-Day Bots.Business JavaScript (BJS) Learning Session! Today, we’re diving into one of the most powerful features of Bots.Business: Libraries. These pre-built tools simplify the process of extending your bot’s functionality and incorporating advanced features without the need to code everything from scratch.
---
What Are Bots.Business Libraries?
Libraries in Bots.Business consist of pre-designed scripts that offer specific features or tools for your bots. Rather than manually coding complex functionalities, you can leverage libraries to efficiently manage tasks such as user resource management, bot protection, or data synchronization with external applications.
---
Popular Libraries in Bots.Business
Here are some commonly utilized libraries you’ll be working with:
1. ResourcesLib
This library assists in managing user resources like coins, points, energy, etc.
Example: Track how many virtual coins a user possesses.
2. Guard
This library safeguards your bot from spammers and abusive behaviors.
Example: Limit the frequency with which a command can be executed within a specified timeframe.
3. CooldownLib
This library establishes cooldown periods for commands.
Example: Prevent users from executing a command too frequently.
4. DatetimeFormatLib
This library formats and handles dates and times.
Example: Display the current date in a user-friendly format.
5. TopBoardLib
This library tracks leaderboards for competitive features.
Example: Showcase the top 10 users based on their points.
---
How to Use Libraries
Libraries come pre-installed in Bots.Business. To utilize one:
1. Include the library in your bot by adding its script at the top of your command.
2. Employ the library’s methods within your bot’s code.
For instance, to utilize the ResourcesLib, you would write:
let resource = Libs.ResourcesLib.userRes("coins");
This code creates a resource called "coins" for each user.
---
Example 1: ResourcesLib (User Resources)
Let’s develop a system to manage virtual coins for users.
Command 1: /addcoins
Add coins to the user’s account:
let coins = Libs.ResourcesLib.userRes("coins");
coins.add(10); // Adds 10 coins
Bot.sendMessage("You have been given 10 coins! Total coins: " + coins.value());
Command 2: /checkcoins
Check the user’s current coin balance:
let coins = Libs.ResourcesLib.userRes("coins");
Bot.sendMessage("Your total coins: " + coins.value());
Command 3: /spendcoins
Spend coins if the user has enough:
let coins = Libs.ResourcesLib.userRes("coins");
if (coins.have(5)) {
coins.remove(5);
Bot.sendMessage("You spent 5 coins! Remaining coins: " + coins.value());
} else {
Bot.sendMessage("You don’t have enough coins!");
}
---
Example 2: CooldownLib
Cooldowns ensure that users can’t spam a command repeatedly.
Command: /claimreward
Allow users to claim a reward only once every 24 hours:
let cooldown = Libs.CooldownLib;
if (!cooldown.checkCooldown("daily_reward")) {
Bot.sendMessage("You’ve already claimed your reward today. Try again later.");
return;
}
cooldown.setCooldown("daily_reward", 24 * 60 * 60); // 24 hours in seconds
Bot.sendMessage("You’ve claimed your daily reward!");
---
Example 3: TopBoardLib (Leaderboard)
Create a leaderboard to track user scores.
Command 1: /addscore
Add a user’s score to the leaderboard:
let leaderboard = Libs.TopBoardLib;
leaderboard.addUser("game_scores", user.telegramid, 100); // Adds 100 points
Bot.sendMessage("You’ve been awarded 100 points!");
Command 2: /leaderboard
Show the top 5 users:
let leaderboard = Libs.TopBoardLib;
let top = leaderboard.getTop("game_scores", 5);
Bot.sendMessage("Top 5 Users:\n" + top);
👍4
Coding Skill Builder 💪📚(Full AI Based)
Day 5: Introduction to Bots.Business Libraries Welcome to Day 5 of the 30-Day Bots.Business JavaScript (BJS) Learning Session! Today, we’re diving into one of the most powerful features of Bots.Business: Libraries. These pre-built tools simplify the process…
▎Assignment for Day 5 🎉
1. Create a Coin System: 💰
Implement commands /addcoins, /checkcoins, and /spendcoins using ResourcesLib.
Bonus: Introduce a feature allowing users to gift coins to other users. 🎁
2. Set Up a Cooldown Command: ⏳
Create a command /dailybonus that grants users 50 coins but only once every 24 hours. 🌟
3. Create a Leaderboard: 📊
Utilize TopBoardLib to track and display a leaderboard of user points. 🏆
1. Create a Coin System: 💰
Implement commands /addcoins, /checkcoins, and /spendcoins using ResourcesLib.
Bonus: Introduce a feature allowing users to gift coins to other users. 🎁
2. Set Up a Cooldown Command: ⏳
Create a command /dailybonus that grants users 50 coins but only once every 24 hours. 🌟
3. Create a Leaderboard: 📊
Utilize TopBoardLib to track and display a leaderboard of user points. 🏆
❤1👍1
Day 6: Unlocking the Power of Advanced Libraries – Supercharge Your Bot! 🚀
Welcome to Day 6 of our thrilling 30-day learning adventure! 🎉 Today, we’re diving deep into some of the most powerful libraries available in Bots.Business, designed to elevate your bot's functionality and intelligence. These tools will empower you to protect, organize, and expand your bot with ease and efficiency.
---
▎Libraries We’ll Explore Today
1️⃣ Guard Library (For Command Limitations)
2️⃣ DatetimeFormatLib (Handling Dates and Times)
3️⃣ ReferralLib (Building Referral Systems)
---
▎1. Guard Library: Enforce Command Limits 🛡️
The Guard Library enables you to manage how frequently users can access specific commands, ensuring a smoother user experience.
Example: Temporarily Block a Command for 5 Minutes
---
▎2. DatetimeFormatLib: Master Dates Times ⏰
This library simplifies the manipulation of dates and times in various formats, making it easy to present time-sensitive information to your users.
Example: Display the Current Date and Time
---
▎3. ReferralLib: Build an Engaging Referral Program 🌟
The Referral Library is your ticket to creating a robust referral system, allowing you to track user invitations and reward them accordingly.
Example: Reward Users for Referrals
---
▎Day 6 Challenge 🏆
Put your newfound knowledge to the test with these exciting challenges:
1️⃣ Set a Command Cooldown: Use the Guard Library to limit a command to be executed once every 10 minutes.
2️⃣ Create a Countdown Timer: Utilize DatetimeFormatLib to display a countdown to a significant date (e.g., New Year).
3️⃣ Implement a Referral Bonus: Leverage ReferralLib to reward users who successfully invite their friends.
---
▎What’s Next?
Join us tomorrow as we explore dynamic user interactions that will make your bots even more engaging and interactive! Keep practicing, and remember to share your progress with the community! 💪✨
Welcome to Day 6 of our thrilling 30-day learning adventure! 🎉 Today, we’re diving deep into some of the most powerful libraries available in Bots.Business, designed to elevate your bot's functionality and intelligence. These tools will empower you to protect, organize, and expand your bot with ease and efficiency.
---
▎Libraries We’ll Explore Today
1️⃣ Guard Library (For Command Limitations)
2️⃣ DatetimeFormatLib (Handling Dates and Times)
3️⃣ ReferralLib (Building Referral Systems)
---
▎1. Guard Library: Enforce Command Limits 🛡️
The Guard Library enables you to manage how frequently users can access specific commands, ensuring a smoother user experience.
Example: Temporarily Block a Command for 5 Minutes
if (Libs.Guard.isBlocked()) {
Bot.sendMessage("❌ You can only use this command once every 5 minutes.");
return;
}
Libs.Guard.blockCommand(5 * 60); // Block for 5 minutes
Bot.sendMessage("✅ Command executed successfully!");
---
▎2. DatetimeFormatLib: Master Dates Times ⏰
This library simplifies the manipulation of dates and times in various formats, making it easy to present time-sensitive information to your users.
Example: Display the Current Date and Time
let currentDate = Libs.DatetimeFormat.format(new Date(), "dddd, MMMM DD YYYY, HH:mm:ss");
Bot.sendMessage("📅 Current Date and Time: " + currentDate);
---
▎3. ReferralLib: Build an Engaging Referral Program 🌟
The Referral Library is your ticket to creating a robust referral system, allowing you to track user invitations and reward them accordingly.
Example: Reward Users for Referrals
let refUser = Libs.ReferralLib.getAttractedByUser();
if (refUser) {
let referrerCoins = Libs.ResourcesLib.anotherUserRes("coins", refUser.telegramid);
referrerCoins.add(10);
Bot.sendMessageToChatWithId(refUser.telegramid, "🎉 You earned 10 coins for referring a new user!");
}
Bot.sendMessage("✅ Referral tracked successfully!");
---
▎Day 6 Challenge 🏆
Put your newfound knowledge to the test with these exciting challenges:
1️⃣ Set a Command Cooldown: Use the Guard Library to limit a command to be executed once every 10 minutes.
2️⃣ Create a Countdown Timer: Utilize DatetimeFormatLib to display a countdown to a significant date (e.g., New Year).
3️⃣ Implement a Referral Bonus: Leverage ReferralLib to reward users who successfully invite their friends.
---
▎What’s Next?
Join us tomorrow as we explore dynamic user interactions that will make your bots even more engaging and interactive! Keep practicing, and remember to share your progress with the community! 💪✨
👍3🔥2
Day 7: Handling Dynamic User Inputs – Creating Interactive Bots! 💬
Welcome to Day 7 of our exciting journey! Today, we're diving into the world of dynamic user inputs to transform your bot into a truly interactive assistant. With these new skills, your bot will be able to engage users by asking questions, collecting responses, and taking action based on their answers. Let’s get started! 🚀
---
▎How It Works:
1️⃣ Ask a Question: Utilize
2️⃣ Process the Response: Implement
3️⃣ Store or Validate Data: Use
---
▎Examples:
1. Collect and Save User Data
Command 1: /askname
Command 2: /savename
---
2. Validate a Password
Prompt the user for a password and verify it:
---
3. Mini Calculator
Gather two numbers and perform addition:
---
▎Assignment:
1️⃣ Build a User Registration System: Create a process to collect and save a user’s name and email address effectively.
2️⃣ Create a Password Validator: Implement a system that grants or denies access based on user-provided passwords.
3️⃣ Develop an Interactive Calculator: Design a calculator that can perform addition, subtraction, multiplication, and division based on user inputs.
---
▎Looking Ahead:
Get ready for Day 8, where we’ll explore user management and advanced bot logic! Keep practicing and enhancing your skills! 🌟
Welcome to Day 7 of our exciting journey! Today, we're diving into the world of dynamic user inputs to transform your bot into a truly interactive assistant. With these new skills, your bot will be able to engage users by asking questions, collecting responses, and taking action based on their answers. Let’s get started! 🚀
---
▎How It Works:
1️⃣ Ask a Question: Utilize
Bot.sendMessage() to prompt the user for information. 2️⃣ Process the Response: Implement
Bot.runCommand() to handle the user's reply in a subsequent command. 3️⃣ Store or Validate Data: Use
User.setProperty() to save responses for future use or validation.---
▎Examples:
1. Collect and Save User Data
Command 1: /askname
Bot.sendMessage("What is your name?");
Bot.runCommand("/savename");Command 2: /savename
User.setProperty("name", message, "string");
Bot.sendMessage("Thank you, " + message + "! Your name has been successfully saved.");---
2. Validate a Password
Prompt the user for a password and verify it:
let correctPassword = "botsbusiness";
if (message == correctPassword) {
Bot.sendMessage("✅ Access granted! Welcome aboard!");
} else {
Bot.sendMessage("❌ Incorrect password. Please try again.");
}
---
3. Mini Calculator
Gather two numbers and perform addition:
let num1 = User.getProperty("num1");
let num2 = parseInt(message);
Bot.sendMessage("The sum of " + num1 + " and " + num2 + " is: " + (num1 + num2));---
▎Assignment:
1️⃣ Build a User Registration System: Create a process to collect and save a user’s name and email address effectively.
2️⃣ Create a Password Validator: Implement a system that grants or denies access based on user-provided passwords.
3️⃣ Develop an Interactive Calculator: Design a calculator that can perform addition, subtraction, multiplication, and division based on user inputs.
---
▎Looking Ahead:
Get ready for Day 8, where we’ll explore user management and advanced bot logic! Keep practicing and enhancing your skills! 🌟
👍2🔥2
Day 8: Advanced User Management – Personalize Your Bots! 👤
Welcome to Day 8! Today, we’ll dive into advanced user management techniques that empower your bot to store, retrieve, and utilize personalized data, enhancing interactivity and user engagement.
---
▎Why Manage Users?
User management allows your bot to:
• Remember user-specific details like name, age, preferences, or scores.
• Personalize responses based on stored data.
• Create features such as progress tracking or user-specific leaderboards.
---
▎How It Works:
1️⃣ Use
2️⃣ Use
3️⃣ Employ conditional logic to provide tailored responses.
---
▎Examples:
▎1. Save and Retrieve User Preferences
Save the user's favorite color and use it in future responses.
Command 1:
Command 2:
Command 3:
---
▎2. Track and Display User Progress
Create a bot that tracks user points or achievements.
Command 1:
Command 2:
---
▎3. Create User-Specific Access Levels
Grant admin privileges to certain users.
Command 1:
Command 2:
---
▎Assignment:
1️⃣ Create a user profile system that stores a user’s name, age, and favorite color. Use commands to retrieve and display this information.
2️⃣ Track user-specific scores or points and display a message when they reach a milestone (e.g., 100 points).
3️⃣ Build an access control system using user-specific admin roles to restrict certain commands.
---
Tomorrow, in Day 9, we’ll explore custom APIs to connect your bot with external systems and services. Stay tuned and keep experimenting! 🚀
Welcome to Day 8! Today, we’ll dive into advanced user management techniques that empower your bot to store, retrieve, and utilize personalized data, enhancing interactivity and user engagement.
---
▎Why Manage Users?
User management allows your bot to:
• Remember user-specific details like name, age, preferences, or scores.
• Personalize responses based on stored data.
• Create features such as progress tracking or user-specific leaderboards.
---
▎How It Works:
1️⃣ Use
User.setProperty() to store user-specific data. 2️⃣ Use
User.getProperty() to retrieve data later. 3️⃣ Employ conditional logic to provide tailored responses.
---
▎Examples:
▎1. Save and Retrieve User Preferences
Save the user's favorite color and use it in future responses.
Command 1:
/setcolor Bot.sendMessage("What’s your favorite color?"); Bot.runCommand("/savecolor");Command 2:
/savecolor User.setProperty("color", message, "string"); Bot.sendMessage("Got it! Your favorite color is " + message + ".");Command 3:
/getcolor let color = User.getProperty("color");
if (color) {
Bot.sendMessage("Your favorite color is " + color + ".");
} else {
Bot.sendMessage("I don’t know your favorite color yet. Use /setcolor to tell me!");
}
---
▎2. Track and Display User Progress
Create a bot that tracks user points or achievements.
Command 1:
/addpoints let points = User.getProperty("points") || 0;
points += 10; // Add 10 points
User.setProperty("points", points, "integer");
Bot.sendMessage("You’ve earned 10 points! 🎉 Total points: " + points);
Command 2:
/checkpoints let points = User.getProperty("points") || 0;
Bot.sendMessage("Your total points: " + points);
---
▎3. Create User-Specific Access Levels
Grant admin privileges to certain users.
Command 1:
/setadmin (for bot owner) User.setProperty("isAdmin", true, "boolean"); Bot.sendMessage("This user is now an admin.");Command 2:
/checkadmin let isAdmin = User.getProperty("isAdmin");
if (isAdmin) {
Bot.sendMessage("Welcome, Admin! You have full access.");
} else {
Bot.sendMessage("❌ You are not an admin.");
}
---
▎Assignment:
1️⃣ Create a user profile system that stores a user’s name, age, and favorite color. Use commands to retrieve and display this information.
2️⃣ Track user-specific scores or points and display a message when they reach a milestone (e.g., 100 points).
3️⃣ Build an access control system using user-specific admin roles to restrict certain commands.
---
Tomorrow, in Day 9, we’ll explore custom APIs to connect your bot with external systems and services. Stay tuned and keep experimenting! 🚀
🔥3👍2
Day 9: Harnessing the Power of Custom APIs – Connect Your Bot to the World! 🌐
Welcome to Day 9 of our journey! Today, we’re diving into the exciting world of Custom APIs, unlocking new dimensions of functionality for your bot. By leveraging APIs, you can enable your bot to interact with external systems, retrieving valuable data such as weather forecasts, stock market trends, and even integrating with a variety of third-party services.
---
▎What Is an API?
An API (Application Programming Interface) serves as a bridge for communication between two systems, allowing them to exchange data seamlessly. With APIs at your disposal, your bot can:
• Fetch real-time information from the internet (e.g., current weather, trending news).
• Perform advanced functions like currency conversion or language translation.
• Send or retrieve data to and from external databases effortlessly.
---
▎How It Works in Bots.Business:
1️⃣ Utilize
2️⃣ Implement callback commands to handle and process the API responses.
3️⃣ Parse and present the data using JavaScript for a dynamic user experience.
---
▎Example 1: Fetching a Joke Using HTTP.get()
Let’s lighten the mood by fetching a joke from a free joke API.
Command 1:
Command 2:
---
▎Example 2: Fetching Current Weather
Now, let’s check the weather for a specific city using OpenWeatherMap’s API.
Command 1:
Command 2:
Command 3:
---
▎Example 3: Sending Data with HTTP.post()
Let’s see how to send user data to a third-party system using
Command:
Callback Command:
---
▎Error Handling
Always implement error handling when working with APIs to ensure a smooth user experience:
Command for Error Handling:
---
▎Assignment:
1️⃣ Create a command that fetches and displays random jokes using an API.
2️⃣ Build a weather bot that retrieves and presents current weather information for any given city.
3️⃣ Utilize
---
Join us tomorrow for Day 10, where we’ll explore webhooks and learn how to receive real-time updates from external services. Stay engaged and keep pushing the boundaries of what your bot can do! 🚀
Welcome to Day 9 of our journey! Today, we’re diving into the exciting world of Custom APIs, unlocking new dimensions of functionality for your bot. By leveraging APIs, you can enable your bot to interact with external systems, retrieving valuable data such as weather forecasts, stock market trends, and even integrating with a variety of third-party services.
---
▎What Is an API?
An API (Application Programming Interface) serves as a bridge for communication between two systems, allowing them to exchange data seamlessly. With APIs at your disposal, your bot can:
• Fetch real-time information from the internet (e.g., current weather, trending news).
• Perform advanced functions like currency conversion or language translation.
• Send or retrieve data to and from external databases effortlessly.
---
▎How It Works in Bots.Business:
1️⃣ Utilize
HTTP.get() or HTTP.post() to initiate API requests. 2️⃣ Implement callback commands to handle and process the API responses.
3️⃣ Parse and present the data using JavaScript for a dynamic user experience.
---
▎Example 1: Fetching a Joke Using HTTP.get()
Let’s lighten the mood by fetching a joke from a free joke API.
Command 1:
/getjokeHTTP.get({
url: "https://official-joke-api.appspot.com/random_joke",
success: "/processjoke"
});
Command 2:
/processjokelet response = JSON.parse(content); // Parse the API response
let joke = response.setup + "\n" + response.punchline;
Bot.sendMessage("😂 Here’s a joke for you:\n" + joke);
---
▎Example 2: Fetching Current Weather
Now, let’s check the weather for a specific city using OpenWeatherMap’s API.
Command 1:
/getweatherBot.sendMessage("Please enter the name of your city:");
Bot.runCommand("/fetchweather");
Command 2:
/fetchweatherlet city = message;
let apiKey = "your_openweathermap_api_key";
HTTP.get({
url: "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey + "&units=metric",
success: "/processweather"
});
Command 3:
/processweatherlet response = JSON.parse(content);
let temp = response.main.temp;
let description = response.weather[0].description;
Bot.sendMessage("🌤️ The current temperature in " + response.name + " is " + temp + "°C with " + description + ".");
---
▎Example 3: Sending Data with HTTP.post()
Let’s see how to send user data to a third-party system using
HTTP.post().Command:
/senddataHTTP.post({
url: "https://example.com/api/save",
body: { user_id: user.telegramid, name: user.first_name },
success: "/dataresponse"
});
Callback Command:
/dataresponseBot.sendMessage("✅ Your data has been sent successfully!");
---
▎Error Handling
Always implement error handling when working with APIs to ensure a smooth user experience:
HTTP.get({
url: "https://api.example.com/data",
success: "/onsuccess",
error: "/onerror"
});
Command for Error Handling:
/onerrorBot.sendMessage("❌ Failed to fetch data. Please try again later.");
---
▎Assignment:
1️⃣ Create a command that fetches and displays random jokes using an API.
2️⃣ Build a weather bot that retrieves and presents current weather information for any given city.
3️⃣ Utilize
HTTP.post() to send user data (e.g., name, ID) to an external API and confirm successful transmission.---
Join us tomorrow for Day 10, where we’ll explore webhooks and learn how to receive real-time updates from external services. Stay engaged and keep pushing the boundaries of what your bot can do! 🚀
👍10
🚀 Test Your Knowledge: Days 1-10 Challenge! 🎯
Hey learners! 👋 You’ve successfully completed 10 days of the 30-Day Bots.Business JavaScript (BJS) learning journey. Now, it’s time to put your knowledge to the test and see how much you’ve learned so far! 💡
---
Challenge Questions
1️⃣ Day 1:
What does the following command do?
A) Sends a message to the user.
B) Creates a new bot.
C) Saves data for later use.
---
2️⃣ Day 2:
How do you save and retrieve a user’s name?
Save:
Retrieve:
Fill in the blank:
---
3️⃣ Day 4:
What does this condition do?
A) It asks the user a question.
B) It checks the user’s input and responds based on their answer.
C) It saves the user’s input for later.
---
4️⃣ Day 5:
How do you add 10 coins to a user’s account using ResourcesLib?
Write the correct code:
---
5️⃣ Day 7:
How do you handle user inputs in multiple steps?
A) Use
B) Use
C) Use
---
6️⃣ Day 9:
Which method would you use to fetch data from an API?
A)
B)
C)
---
7️⃣ Day 10:
What is a webhook used for in Bots.Business?
A) To track user points.
B) To receive real-time updates from external services.
C) To manage access to commands.
---
💬 Post your answers below or send them directly! Let’s see how well you’ve mastered the first 10 days! 🎉
Stay tuned for more exciting lessons, and keep pushing your bots to the next level! 🚀
Hey learners! 👋 You’ve successfully completed 10 days of the 30-Day Bots.Business JavaScript (BJS) learning journey. Now, it’s time to put your knowledge to the test and see how much you’ve learned so far! 💡
---
Challenge Questions
1️⃣ Day 1:
What does the following command do?
Bot.sendMessage("Hello, Bots.Business!"); A) Sends a message to the user.
B) Creates a new bot.
C) Saves data for later use.
---
2️⃣ Day 2:
How do you save and retrieve a user’s name?
Save:
User.setProperty("name", "John", "string"); Retrieve:
Fill in the blank:
let name = ____;---
3️⃣ Day 4:
What does this condition do?
if (message == "yes") {
Bot.sendMessage("You chose YES!");
} else {
Bot.sendMessage("You chose NO.");
}
A) It asks the user a question.
B) It checks the user’s input and responds based on their answer.
C) It saves the user’s input for later.
---
4️⃣ Day 5:
How do you add 10 coins to a user’s account using ResourcesLib?
Write the correct code:
let coins = Libs.ResourcesLib.userRes("coins");
__;
Bot.sendMessage("You now have " + coins.value() + " coins!");
---
5️⃣ Day 7:
How do you handle user inputs in multiple steps?
A) Use
Bot.sendMessage() and Bot.runCommand() to link commands. B) Use
HTTP.get() for user responses. C) Use
Libs.CooldownLib to handle user input.---
6️⃣ Day 9:
Which method would you use to fetch data from an API?
A)
HTTP.get() B)
Bot.sendMessage() C)
User.setProperty()---
7️⃣ Day 10:
What is a webhook used for in Bots.Business?
A) To track user points.
B) To receive real-time updates from external services.
C) To manage access to commands.
---
💬 Post your answers below or send them directly! Let’s see how well you’ve mastered the first 10 days! 🎉
Stay tuned for more exciting lessons, and keep pushing your bots to the next level! 🚀
👍1
Day 10: Webhooks – Unlock Real-Time Communication for Your Bot! 🌐
Welcome to Day 10 of our journey! Today, we’re diving into the powerful world of webhooks—an advanced technique that empowers your bot to receive real-time updates from external services. With webhooks, your bot can respond instantly to events such as payments, form submissions, or any external triggers, enhancing its interactivity and responsiveness.
---
▎What Is a Webhook?
Think of a webhook as a notification system that operates in real-time. When an event occurs in an external service, it sends data (known as a payload) to your bot’s designated webhook URL. This allows your bot to process the incoming data and take immediate action, creating a seamless user experience.
---
▎How Webhooks Work in Bots.Business:
1️⃣ Set Up a Webhook Listener: Utilize
2️⃣ Process the Payload: Parse the incoming data and integrate it into your bot’s commands for dynamic responses.
3️⃣ Trigger Actions: Respond to events in real-time based on the information received from the webhook data.
---
▎Step-by-Step Example: Payment Webhook
Let’s build a bot that listens for payment notifications and automatically confirms payments.
▎Step 1: Set Up a Webhook Listener
Create a command
---
▎Step 2: Process the Webhook Payload
Now, create a command
---
▎Example 2: Form Submission Webhook
Next, let’s create a bot that listens for data from Google Form submissions.
▎Step 1: Set Up Webhook Listener
Create a command
---
▎Step 2: Process the Submitted Data
Create a command
---
▎Error Handling in Webhooks
In case something goes wrong during webhook processing, implement error handling:
Error Command:
---
▎Tips for Effective Webhooks:
1️⃣ Ensure your bot’s webhook URL is publicly accessible (typically provided by Bots.Business).
2️⃣ Test the webhook functionality using tools like Postman or services like Webhook.site to simulate events.
3️⃣ Always implement graceful error handling to prevent disruptions in service and enhance user satisfaction.
---
▎Assignment:
1️⃣ Create a webhook that listens for payment updates and promptly notifies users upon receiving their payments.
2️⃣ Set up a webhook to process Google Form submissions and dynamically display the collected data.
3️⃣ Enhance your webhook processing commands with robust error handling to manage potential failures effectively.
---
Join us tomorrow for Day 11, where we’ll explore advanced logic and automation techniques to elevate your bot-building skills even further. Keep experimenting with webhooks, and let your creativity shine! 🚀
Welcome to Day 10 of our journey! Today, we’re diving into the powerful world of webhooks—an advanced technique that empowers your bot to receive real-time updates from external services. With webhooks, your bot can respond instantly to events such as payments, form submissions, or any external triggers, enhancing its interactivity and responsiveness.
---
▎What Is a Webhook?
Think of a webhook as a notification system that operates in real-time. When an event occurs in an external service, it sends data (known as a payload) to your bot’s designated webhook URL. This allows your bot to process the incoming data and take immediate action, creating a seamless user experience.
---
▎How Webhooks Work in Bots.Business:
1️⃣ Set Up a Webhook Listener: Utilize
WebhookLib to enable your bot to listen for incoming webhook events effortlessly. 2️⃣ Process the Payload: Parse the incoming data and integrate it into your bot’s commands for dynamic responses.
3️⃣ Trigger Actions: Respond to events in real-time based on the information received from the webhook data.
---
▎Step-by-Step Example: Payment Webhook
Let’s build a bot that listens for payment notifications and automatically confirms payments.
▎Step 1: Set Up a Webhook Listener
Create a command
/setupwebhook to enable the webhook:Libs.Webhooks.setupWebhook({
url: "your-bot-webhook-url",
command: "/processpayment" // Command to handle the webhook data
});
Bot.sendMessage("✅ Webhook is successfully set up and ready to receive payment updates!");
---
▎Step 2: Process the Webhook Payload
Now, create a command
/processpayment to manage incoming payment data:let payment = JSON.parse(content); // Parse the webhook payload
let userId = payment.user_id;
let amount = payment.amount;
Bot.sendMessageToChatWithId(userId, "🎉 Payment of $" + amount + " has been received! Thank you for your support!");
---
▎Example 2: Form Submission Webhook
Next, let’s create a bot that listens for data from Google Form submissions.
▎Step 1: Set Up Webhook Listener
Create a command
/setupformwebhook:Libs.Webhooks.setupWebhook({
url: "your-bot-webhook-url",
command: "/processform"
});
Bot.sendMessage("✅ Webhook for form submissions is now set up!");
---
▎Step 2: Process the Submitted Data
Create a command
/processform to handle the incoming form data:let formData = JSON.parse(content);
let userName = formData.name;
let userResponse = formData.response;
Bot.sendMessage("📋 New form submission received:\nName: " + userName + "\nResponse: " + userResponse);
---
▎Error Handling in Webhooks
In case something goes wrong during webhook processing, implement error handling:
Error Command:
/webhookerrorBot.sendMessage("❌ An error occurred while processing the webhook. Please try again later.");
---
▎Tips for Effective Webhooks:
1️⃣ Ensure your bot’s webhook URL is publicly accessible (typically provided by Bots.Business).
2️⃣ Test the webhook functionality using tools like Postman or services like Webhook.site to simulate events.
3️⃣ Always implement graceful error handling to prevent disruptions in service and enhance user satisfaction.
---
▎Assignment:
1️⃣ Create a webhook that listens for payment updates and promptly notifies users upon receiving their payments.
2️⃣ Set up a webhook to process Google Form submissions and dynamically display the collected data.
3️⃣ Enhance your webhook processing commands with robust error handling to manage potential failures effectively.
---
Join us tomorrow for Day 11, where we’ll explore advanced logic and automation techniques to elevate your bot-building skills even further. Keep experimenting with webhooks, and let your creativity shine! 🚀
👍2
Day 11: Advanced Logic and Automation – Crafting Smarter, More Powerful Bots! 🤖
Welcome to Day 11! Today, we’re diving deep into the realm of advanced logic and automation techniques that will transform your bots into intelligent, efficient companions. By harnessing the power of conditional statements, loops, and event-driven actions, you can create bots capable of solving complex problems, automating tedious tasks, and dynamically responding to user interactions. Let’s get started on this exciting journey!
---
▎Key Concepts for Today
1️⃣ Complex Conditions (Nested Logic): Master the art of handling multiple conditions to deliver tailored responses that meet user needs.
2️⃣ Loops: Streamline repetitive tasks and manage data collections effortlessly.
3️⃣ Event-Driven Automation: Trigger commands or actions based on user events or changes in bot state, creating a more interactive experience.
---
▎1. Nested Conditions for Complex Logic
Example: Multi-Level Access Control
Let’s build a bot that checks the user’s role and responds accordingly, ensuring a personalized experience.
---
▎2. Using Loops for Repetitive Tasks
Example: List User Data
Loops empower you to perform actions repeatedly without the hassle of coding each step individually.
Let’s create a command that lists all items in a user’s inventory:
---
▎3. Automate Repeating Actions with Intervals
You can leverage
Example: Hourly Reward
Automatically reward users with coins every hour:
Utilize
---
▎4. Event-Driven Actions
Trigger commands based on user activities or changes in stored state for a more engaging experience.
Example: Award Milestone Rewards
Reward users when they reach a score of 100 points:
---
▎Assignment for Day 11
1️⃣ Create an Access Control System:
Implement nested conditions to establish multi-level roles (e.g., Admin, Moderator, User). Control access to specific commands based on the user’s role.
2️⃣ Build an Inventory Manager:
Utilize loops to display a comprehensive list of items in a user’s inventory. Add functionality to allow users to add or remove items seamlessly.
3️⃣ Automate Milestone Rewards:
Set up triggers to award users when they achieve a specific score, followed by resetting their score for future challenges.
---
Tomorrow, on Day 12, we’ll explore how to integrate multi-command workflows for more complex bot interactions. Keep pushing your bots to new heights and unleash their full potential! 🚀
Welcome to Day 11! Today, we’re diving deep into the realm of advanced logic and automation techniques that will transform your bots into intelligent, efficient companions. By harnessing the power of conditional statements, loops, and event-driven actions, you can create bots capable of solving complex problems, automating tedious tasks, and dynamically responding to user interactions. Let’s get started on this exciting journey!
---
▎Key Concepts for Today
1️⃣ Complex Conditions (Nested Logic): Master the art of handling multiple conditions to deliver tailored responses that meet user needs.
2️⃣ Loops: Streamline repetitive tasks and manage data collections effortlessly.
3️⃣ Event-Driven Automation: Trigger commands or actions based on user events or changes in bot state, creating a more interactive experience.
---
▎1. Nested Conditions for Complex Logic
Example: Multi-Level Access Control
Let’s build a bot that checks the user’s role and responds accordingly, ensuring a personalized experience.
let role = User.getProperty("role");
if (role == "admin") {
Bot.sendMessage("👮 Welcome, Admin! You have full access to all features.");
} else if (role == "moderator") {
Bot.sendMessage("🛡️ Welcome, Moderator! You have limited access to manage content.");
} else {
Bot.sendMessage("👤 Welcome, User! Enjoy your basic access and explore our features.");
}
---
▎2. Using Loops for Repetitive Tasks
Example: List User Data
Loops empower you to perform actions repeatedly without the hassle of coding each step individually.
Let’s create a command that lists all items in a user’s inventory:
let items = User.getProperty("inventory") || [];
let message = "🎒 Your Inventory:\n";
for (let i = 0; i < items.length; i++) {
message += (i + 1) + ". " + items[i] + "\n";
}
Bot.sendMessage(message);
---
▎3. Automate Repeating Actions with Intervals
You can leverage
Libs.ResourcesLib or commands to automate recurring actions, such as awarding coins every hour.Example: Hourly Reward
Automatically reward users with coins every hour:
let coins = Libs.ResourcesLib.userRes("coins");
coins.add(10); // Add 10 coins
Bot.sendMessage("💰 You’ve received 10 coins! Your total balance is now: " + coins.value());
Utilize
Libs.CooldownLib to ensure this command runs only once per hour when triggered by users.---
▎4. Event-Driven Actions
Trigger commands based on user activities or changes in stored state for a more engaging experience.
Example: Award Milestone Rewards
Reward users when they reach a score of 100 points:
let score = User.getProperty("score") || 0;
if (score >= 100) {
Bot.sendMessage("🎉 Congratulations! You’ve reached an impressive milestone of 100 points!");
User.setProperty("score", 0, "integer"); // Reset score for new challenges
} else {
Bot.sendMessage("Your current score: " + score + ". Keep going to reach that milestone!");
}
---
▎Assignment for Day 11
1️⃣ Create an Access Control System:
Implement nested conditions to establish multi-level roles (e.g., Admin, Moderator, User). Control access to specific commands based on the user’s role.
2️⃣ Build an Inventory Manager:
Utilize loops to display a comprehensive list of items in a user’s inventory. Add functionality to allow users to add or remove items seamlessly.
3️⃣ Automate Milestone Rewards:
Set up triggers to award users when they achieve a specific score, followed by resetting their score for future challenges.
---
Tomorrow, on Day 12, we’ll explore how to integrate multi-command workflows for more complex bot interactions. Keep pushing your bots to new heights and unleash their full potential! 🚀
👍2❤1
Day 12: Multi-Command Workflows – Mastering Complex Interactions! 🔄
Welcome to Day 12 of our exciting journey! Today, we’re diving into the world of multi-command workflows, a powerful feature that enables your bot to handle intricate tasks in a step-by-step manner. This approach is ideal for creating forms, managing multi-step processes, or engaging in scenarios that require multiple user inputs. Get ready to enhance your bot's interactivity!
---
▎What Are Multi-Command Workflows?
Multi-command workflows allow you to break down complex tasks into manageable steps. Each step corresponds to a separate command, making it easier to guide users through the process. Here’s how it typically unfolds:
1. Initial Interaction: The bot poses a question in Command 1.
2. User Response: The user's reply triggers Command 2.
3. Processing Input: Command 2 processes the input and seamlessly transitions to Command 3.
This structured approach ensures that your bot can efficiently manage lengthy interactions while providing a smooth user experience.
---
▎How to Build Multi-Command Workflows
1️⃣ Engage Users: Use
2️⃣ Link Commands: Utilize
3️⃣ Store Responses: Save user inputs with
---
▎Example 1: User Registration
Step 1: Start Registration
Command:
Step 2: Save the Name
Command:
Step 3: Save the Age
Command:
---
▎Example 2: Quiz Workflow
Step 1: Start the Quiz
Command:
Step 2: Check Answer 1
Command:
Step 3: Ask Question 2
Command:
Step 4: Check Answer 2 and Display Results
Command:
---
▎Example 3: Multi-Step Order Form
Step 1: Ask for Product
Command:
Step 2: Ask for Quantity
Command:
Step 3: Confirm the Order
Command:
---
▎Assignment for Day 12
1️⃣ Create a Registration Workflow:
Collect the user’s name, email, and age using multiple commands. Display the saved data in the final step.
2️⃣ Build a Quiz Bot:
Welcome to Day 12 of our exciting journey! Today, we’re diving into the world of multi-command workflows, a powerful feature that enables your bot to handle intricate tasks in a step-by-step manner. This approach is ideal for creating forms, managing multi-step processes, or engaging in scenarios that require multiple user inputs. Get ready to enhance your bot's interactivity!
---
▎What Are Multi-Command Workflows?
Multi-command workflows allow you to break down complex tasks into manageable steps. Each step corresponds to a separate command, making it easier to guide users through the process. Here’s how it typically unfolds:
1. Initial Interaction: The bot poses a question in Command 1.
2. User Response: The user's reply triggers Command 2.
3. Processing Input: Command 2 processes the input and seamlessly transitions to Command 3.
This structured approach ensures that your bot can efficiently manage lengthy interactions while providing a smooth user experience.
---
▎How to Build Multi-Command Workflows
1️⃣ Engage Users: Use
Bot.sendMessage() to pose questions and gather input.2️⃣ Link Commands: Utilize
Bot.runCommand() to connect each step of the workflow.3️⃣ Store Responses: Save user inputs with
User.setProperty() for future reference in subsequent steps.---
▎Example 1: User Registration
Step 1: Start Registration
Command:
/registerBot.sendMessage("Welcome! What’s your name?");
Bot.runCommand("/saveName");
Step 2: Save the Name
Command:
/saveNameUser.setProperty("name", message, "string");
Bot.sendMessage("Hi, " + message + "! How old are you?");
Bot.runCommand("/saveAge");
Step 3: Save the Age
Command:
/saveAgeUser.setProperty("age", message, "integer");
Bot.sendMessage("Registration complete! ✅\nName: " + User.getProperty("name") + "\nAge: " + User.getProperty("age"));
---
▎Example 2: Quiz Workflow
Step 1: Start the Quiz
Command:
/startquizBot.sendMessage("Question 1: What is the capital of France?\n\nA) Paris\nB) Berlin\nC) Madrid");
Bot.runCommand("/checkAnswer1");
Step 2: Check Answer 1
Command:
/checkAnswer1if (message.toLowerCase() == "a" || message.toLowerCase() == "paris") {
User.setProperty("score", 1, "integer");
Bot.sendMessage("✅ Correct! Now for Question 2...");
} else {
User.setProperty("score", 0, "integer");
Bot.sendMessage("❌ Wrong! The correct answer is A) Paris. Next question...");
}
Bot.runCommand("/question2");
Step 3: Ask Question 2
Command:
/question2Bot.sendMessage("Question 2: What is 5 + 3?\n\nA) 6\nB) 8\nC) 10");
Bot.runCommand("/checkAnswer2");
Step 4: Check Answer 2 and Display Results
Command:
/checkAnswer2let score = User.getProperty("score");
if (message.toLowerCase() == "b" || message.toLowerCase() == "8") {
score += 1;
}
Bot.sendMessage("🎉 Quiz Complete! Your score: " + score + "/2");
---
▎Example 3: Multi-Step Order Form
Step 1: Ask for Product
Command:
/orderBot.sendMessage("What product would you like to order?");
Bot.runCommand("/saveProduct");
Step 2: Ask for Quantity
Command:
/saveProductUser.setProperty("product", message, "string");
Bot.sendMessage("How many " + message + "s would you like?");
Bot.runCommand("/confirmOrder");
Step 3: Confirm the Order
Command:
/confirmOrderUser.setProperty("quantity", message, "integer");
let product = User.getProperty("product");
let quantity = User.getProperty("quantity");
Bot.sendMessage("✅ Order placed!\nProduct: " + product + "\nQuantity: " + quantity);
---
▎Assignment for Day 12
1️⃣ Create a Registration Workflow:
Collect the user’s name, email, and age using multiple commands. Display the saved data in the final step.
2️⃣ Build a Quiz Bot:
👍1
Develop a quiz with 3-5 questions, keeping track of the user’s score. Present the final score at the end.
3️⃣ Create an Order Form:
Design an order form that asks the user for a product and quantity, then confirm their order in the final step.
---
Tomorrow, on Day 13, we’ll delve into persistent data storage—learning how to manage user data effectively across sessions for advanced bot functionality. Keep up the fantastic work and continue building amazing bots! 🚀
3️⃣ Create an Order Form:
Design an order form that asks the user for a product and quantity, then confirm their order in the final step.
---
Tomorrow, on Day 13, we’ll delve into persistent data storage—learning how to manage user data effectively across sessions for advanced bot functionality. Keep up the fantastic work and continue building amazing bots! 🚀
❤2👍1
I think that you're not really interested in this 30 Days Bjs Learning Series... 💔
❤2👍2