smoothretro82

C-bot

Nov 19th, 2025 (edited)
60
0
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.25 KB | None | 0 0
  1. // --- BOT METADATA AND START TIME ---
  2. const START_TIME = Date.now(); // Record the moment the script starts running
  3. const BOT_VERSION = "0.1";
  4. const CREATOR_NAME = "Coinbot Developer";
  5.  
  6. // --- GLOBAL EVENT STATE ---
  7. const EVENT_INTERVAL = 600000; // 10 minutes in milliseconds
  8. const EVENT_DURATION = 300000; // 5 minutes in milliseconds
  9. let eventActive = false;
  10. let eventAmount = 0;
  11. let eventTimeout = null;
  12. let eventStartTime = 0; // Track the exact moment the event started
  13. let lastEventStartTime = START_TIME; // Track the last time the interval successfully triggered (INITIALIZED TO BOT START TIME)
  14.  
  15. // Function to handle the end of the event window if nobody collects the coins
  16. function endEventTimeout() {
  17. eventActive = false;
  18. eventAmount = 0;
  19. eventTimeout = null;
  20. eventStartTime = 0; // Reset start time
  21. w.chat.send("Nobody got the coins in time.");
  22. }
  23.  
  24. // Function to trigger the event manually (called from w.on("msg"))
  25. function triggerEvent() {
  26. eventActive = true;
  27. eventAmount = Math.floor(Math.random() * 301) + 100; // 100 to 400
  28. lastEventStartTime = Date.now(); // Record the current time as the new interval start time
  29. eventStartTime = Date.now(); // Record the exact event start time
  30.  
  31. w.chat.send(
  32. `${eventAmount} coins fell from the sky, !collect them before anybody else.`
  33. );
  34.  
  35. // Set a timer for the event to expire after 5 minutes
  36. eventTimeout = setTimeout(endEventTimeout, EVENT_DURATION);
  37. }
  38.  
  39.  
  40. // Welcome message (fixed event name)
  41. w.on("join", () => {
  42.   w.chat.send("Coinbot Version 0.1 - Type !help for commands");
  43. });
  44.  
  45.  
  46. // Data storage
  47. const balances = {};
  48. // Global statistics object
  49. const globalStats = {
  50. totalSearches: 0,
  51. totalBets: 0,
  52. betsWon: 0,
  53. betsLost: 0,
  54. totalFlips: 0,
  55. flipsWon: 0,
  56. flipsLost: 0,
  57. coinsGiven: 0,
  58. coinsReceived: 0,
  59. coinsTransferred: 0
  60. };
  61. const searchCooldown = {};
  62. const coinflipCooldown = {};
  63.  
  64.  
  65. // Message handler
  66. w.on("msg", (data) => {
  67. const nick = data.nick;
  68. const now = Date.now();
  69.  
  70. // --- EVENT TRIGGER CHECK (Runs on every message regardless of content) ---
  71. // If event is not active AND the required interval has passed, trigger the event
  72. if (!eventActive && (now - lastEventStartTime >= EVENT_INTERVAL)) {
  73. triggerEvent();
  74. }
  75. // -------------------------------------------------------------------------
  76.  
  77.  
  78. // --- !collect: Only processes collection, cannot trigger the event ---
  79. if (data.msg.toLowerCase() === "!collect") {
  80. if (eventActive) {
  81. // 1. Give coins to the first user
  82. if (!balances[nick]) balances[nick] = 0;
  83. balances[nick] += eventAmount;
  84.  
  85. // 2. Clear timeout and set event inactive
  86. clearTimeout(eventTimeout);
  87. eventActive = false;
  88. eventStartTime = 0; // Reset start time after collection
  89.  
  90. // 3. Update global stats
  91. globalStats.coinsGiven += eventAmount;
  92.  
  93. // 4. Send success message
  94. w.chat.send(
  95. `${nick} was the fastest and successfully collected ${eventAmount} coins! New balance: ${balances[nick]}.`
  96. );
  97.  
  98. // Stop processing after collection
  99. return;
  100. } else {
  101. // Event is not active
  102. w.chat.send(`${nick}, there are no fallen coins to collect right now.`);
  103. return;
  104. }
  105. }
  106.  
  107.  
  108. // Exit if message does not start with '!'
  109. if (!data.msg.startsWith("!")) {
  110. return;
  111. }
  112.  
  113.  
  114.   const args = data.msg.slice(1).trim().split(" ");
  115.   const command = args[0];
  116.  
  117.   // --- !help ---
  118.   if (command === "help") {
  119.     w.chat.send(
  120.       `${nick}, Commands: !help, !search, !balance, !bet <amount>, !coinflip <h/t> <amount>, !stats, !leaderboard, !give <nick> <amount>, !info, !uptime, !collect`
  121.     );
  122.     return;
  123.   }
  124.  
  125. // --- !info ---
  126. if (command === "info") {
  127. let eventStatus = '';
  128.  
  129. const formatTime = (ms) => {
  130. const totalSeconds = Math.ceil(Math.max(0, ms) / 1000);
  131. const minutes = Math.floor(totalSeconds / 60);
  132. const seconds = totalSeconds % 60;
  133. return `${minutes}m ${seconds}s`;
  134. };
  135.  
  136. if (eventActive) {
  137. // Calculate remaining time using the known start time and duration
  138. const timeElapsed = now - eventStartTime;
  139. const remainingTimeMs = EVENT_DURATION - timeElapsed;
  140.  
  141. const timeString = formatTime(remainingTimeMs);
  142. eventStatus = ` | Coins Event: ACTIVE (Ends in ${timeString})`;
  143. } else {
  144. // FIX: Calculate time until next event using modulo for full cycle accuracy
  145. const timeElapsedSinceLastStart = now - lastEventStartTime;
  146. // The remaining time is the interval minus the time passed, modulo the interval.
  147. // Adding EVENT_INTERVAL ensures a positive number before the modulo.
  148. const timeToNextEventMs = (EVENT_INTERVAL + lastEventStartTime - now) % EVENT_INTERVAL;
  149.  
  150. const timeString = formatTime(timeToNextEventMs);
  151. eventStatus = ` | Next Coins Event in: ${timeString}`;
  152. }
  153.  
  154. w.chat.send(
  155. `Coinbot Info: Version ${BOT_VERSION} | Creator: ${CREATOR_NAME}${eventStatus}`
  156. );
  157. return;
  158. }
  159.  
  160. // --- !uptime ---
  161. if (command === "uptime") {
  162. const uptimeMs = now - START_TIME;
  163.  
  164. // Calculate time components (seconds, minutes, hours, days)
  165. const seconds = Math.floor(uptimeMs / 1000);
  166. const minutes = Math.floor(seconds / 60);
  167. const hours = Math.floor(minutes / 60);
  168. const days = Math.floor(hours / 24);
  169.  
  170. // Calculate remaining time for display
  171. const displayHours = hours % 24;
  172. const displayMinutes = minutes % 60;
  173. const displaySeconds = seconds % 60;
  174.  
  175. let uptimeString = '';
  176. if (days > 0) uptimeString += `${days}d `;
  177. if (hours > 0) uptimeString += `${displayHours}h `;
  178. if (minutes > 0) uptimeString += `${displayMinutes}m `;
  179. uptimeString += `${displaySeconds}s`; // Always show seconds
  180.  
  181. w.chat.send(
  182. `The bot has been active for: ${uptimeString.trim()}`
  183. );
  184. return;
  185. }
  186.  
  187.  
  188.   // --- !search ---
  189.   if (command === "search") {
  190.    
  191.     if (!searchCooldown[nick] || now - searchCooldown[nick] >= 60000) {
  192.  
  193.       const found = Math.floor(Math.random() * 25) + 1;
  194.  
  195.       if (!balances[nick]) balances[nick] = 0;
  196.       balances[nick] += found;
  197.  
  198.       searchCooldown[nick] = now;
  199.  
  200. // Update Global Stats for !search
  201. globalStats.totalSearches++;
  202. globalStats.coinsGiven += found;
  203.  
  204.       w.chat.send(
  205.         `${nick}, searched the area and found ${found} coins!`
  206.       );
  207.  
  208.     } else {
  209.       const wait = Math.ceil((60000 - (now - searchCooldown[nick])) / 1000);
  210.       w.chat.send(`${nick}, wait ${wait}s before searching again.`);
  211.     }
  212.     return;
  213.   }
  214.  
  215.  
  216.   // --- !balance ---
  217.   if (command === "balance") {
  218.     const bal = balances[nick] || 0;
  219.     w.chat.send(`${nick}, you currently have ${bal} coins.`);
  220.     return;
  221.   }
  222.  
  223.  
  224.   // --- !bet ---
  225.   if (command === "bet") {
  226.     const amount = parseInt(args[1]);
  227.  
  228.     if (isNaN(amount) || amount <= 0) {
  229.       w.chat.send(`${nick}, usage: !bet <amount> (must be a positive number)`);
  230.       return;
  231.     }
  232.  
  233.     if (!balances[nick] || balances[nick] < amount) {
  234.       w.chat.send(`${nick}, you don't have enough coins to bet ${amount}.`);
  235.       return;
  236.     }
  237.  
  238. // Increment total bets before processing win/loss
  239. globalStats.totalBets++;
  240.  
  241.    // 50% win/lose
  242.     const win = Math.random() < 0.5;
  243.  
  244.     if (win) {
  245.       // WIN → user gains the amount they bet
  246.       balances[nick] += amount;
  247.  
  248. // Update Global Stats for bet win
  249. globalStats.betsWon++;
  250. globalStats.coinsGiven += amount;
  251.  
  252.       w.chat.send(
  253.         `${nick}, you won the bet! You gained ${amount} coins! Your new balance is ${balances[nick]}.`
  254.       );
  255.  
  256.     } else {
  257.       // LOSS → user loses the amount they bet
  258.       balances[nick] -= amount;
  259.  
  260. // Update Global Stats for bet loss
  261. globalStats.betsLost++;
  262. globalStats.coinsReceived += amount;
  263.  
  264.       w.chat.send(
  265.         `${nick}, You lost ${amount} coins and now have ${balances[nick]} coins.`
  266.       );
  267.     }
  268.  
  269.     return;
  270.   }
  271.  
  272. // --- !coinflip ---
  273. if (command === "coinflip") {
  274. const COOLDOWN_TIME = 300000; // 5 minutes in milliseconds
  275.  
  276. // 1. Check Cooldown (This correctly calculates and displays the remaining time)
  277. if (coinflipCooldown[nick] && now - coinflipCooldown[nick] < COOLDOWN_TIME) {
  278. const wait = Math.ceil((COOLDOWN_TIME - (now - coinflipCooldown[nick])) / 1000);
  279. w.chat.send(`${nick}, wait ${wait}s before flipping the coin again.`);
  280. return;
  281. }
  282.  
  283. const userGuess = args[1] ? args[1].toLowerCase() : null;
  284. const amount = parseInt(args[2]);
  285. const validGuesses = ["heads", "h", "tails", "t"];
  286.  
  287. // Validation checks
  288. if (!userGuess || !amount || isNaN(amount) || amount <= 0 || !validGuesses.includes(userGuess)) {
  289. w.chat.send(`${nick}, usage: !coinflip <heads/tails or h/t> <amount>`);
  290. return;
  291. }
  292.  
  293. if (!balances[nick] || balances[nick] < amount) {
  294. w.chat.send(`${nick}, you don't have enough coins to bet ${amount}.`);
  295. return;
  296. }
  297.  
  298. // Determine the flip result
  299. const flipResult = Math.random() < 0.5 ? "heads" : "tails";
  300. const isWin = (userGuess === "heads" || userGuess === "h") && flipResult === "heads" ||
  301. (userGuess === "tails" || userGuess === "t") && flipResult === "tails";
  302.  
  303. // Set Cooldown
  304. coinflipCooldown[nick] = now;
  305.  
  306. // Update global stats
  307. globalStats.totalFlips++;
  308.  
  309. if (isWin) {
  310. // WIN: win 4x the amount bet
  311. const winnings = amount * 4;
  312. balances[nick] += winnings;
  313. globalStats.flipsWon++;
  314. globalStats.coinsGiven += winnings;
  315.  
  316. w.chat.send(
  317. `${nick} flipped a ${flipResult}! You won ${winnings} coins! New balance: ${balances[nick]}.`
  318. );
  319. } else {
  320. // LOSS: lose the amount bet
  321. balances[nick] -= amount;
  322. globalStats.flipsLost++;
  323. globalStats.coinsReceived += amount;
  324.  
  325. w.chat.send(
  326. `${nick} flipped a ${flipResult}! You lost ${amount} coins. New balance: ${balances[nick]}.`
  327. );
  328. }
  329.  
  330. return;
  331. }
  332.  
  333.   // --- !stats ---
  334.   if (command === "stats") {
  335. const totalCoins = Object.values(balances).reduce(
  336. (sum, balance) => sum + balance,
  337. 0
  338. );
  339.  
  340. const userCount = Object.keys(balances).length;
  341.  
  342. const betWinRate = globalStats.totalBets > 0
  343. ? ((globalStats.betsWon / globalStats.totalBets) * 100).toFixed(2)
  344. : 'N/A';
  345.  
  346. const flipWinRate = globalStats.totalFlips > 0
  347. ? ((globalStats.flipsWon / globalStats.totalFlips) * 100).toFixed(2)
  348. : 'N/A';
  349.  
  350. // Detailed Stats Output
  351. w.chat.send(
  352. `COIN STATS: ${userCount} users hold ${totalCoins} coins. | Searches: ${globalStats.totalSearches}. | Bets: ${globalStats.totalBets} (W:${globalStats.betsWon} / L:${globalStats.betsLost} | Rate: ${betWinRate}%). | Flips: ${globalStats.totalFlips} (W:${globalStats.flipsWon} / L:${globalStats.flipsLost} | Rate: ${flipWinRate}%). | Economy: Given: ${globalStats.coinsGiven} | Received: ${globalStats.coinsReceived} | Transferred: ${globalStats.coinsTransferred}`
  353. );
  354. return;
  355. }
  356.  
  357.  
  358.   // --- !leaderboard ---
  359.   if (command === "leaderboard") {
  360. // 1. Convert balances object into an array of [nick, balance] pairs
  361. const sortedUsers = Object.entries(balances)
  362. // 2. Sort the array from smallest (a[1]) to biggest (b[1]).
  363. .sort((a, b) => a[1] - b[1]);
  364.  
  365. if (sortedUsers.length === 0) {
  366. w.chat.send(`${nick}, no users have collected any coins yet!`);
  367. return;
  368. }
  369.  
  370. // 3. Format the output string
  371. const leaderboardText = sortedUsers
  372. .reverse()
  373. .map((user, index) => {
  374. const rank = index + 1;
  375. const userNick = user[0];
  376. const coinAmount = user[1];
  377. return `#${rank}: ${userNick} - ${coinAmount} coins`;
  378. })
  379. .join(" | ");
  380.  
  381. w.chat.send(`Leaderboard: ${leaderboardText}`);
  382. return;
  383. }
  384.  
  385.   // --- !give ---
  386.   if (command === "give") {
  387. const recipient = args[1];
  388. const amount = parseInt(args[2]);
  389.  
  390. // Validation checks
  391. if (!recipient || isNaN(amount) || amount <= 0) {
  392. w.chat.send(`${nick}, usage: !give <recipient_nick> <amount>`);
  393. return;
  394. }
  395.  
  396. if (nick === recipient) {
  397. w.chat.send(`${nick}, you cannot give coins to yourself.`);
  398. return;
  399. }
  400.  
  401. if (!balances[nick] || balances[nick] < amount) {
  402. w.chat.send(`${nick}, you only have ${balances[nick] || 0} coins, which is not enough to give ${amount}.`);
  403. return;
  404. }
  405.  
  406. // 1. Deduct from sender
  407. balances[nick] -= amount;
  408.  
  409. // 2. Initialize recipient balance if necessary and add amount
  410. if (!balances[recipient]) {
  411. balances[recipient] = 0;
  412. }
  413. balances[recipient] += amount;
  414.  
  415. // 3. Update Global Stats
  416. globalStats.coinsTransferred += amount;
  417.  
  418. // 4. Send confirmation message
  419. w.chat.send(
  420. `${nick} gave ${amount} coins to ${recipient}! ` +
  421. `(${nick}: ${balances[nick]} coins | ${recipient}: ${balances[recipient]} coins)`
  422. );
  423. return;
  424. }
  425.  
  426. });
Advertisement
Comments
Add Comment
Please, Sign In to add comment