mrcat44
📎 1 file 2,274 chars
📄
pasted-code-1773034967102.txt
txt 17 lines
▶
The Discord middleman bot is currently crashing during startup with the error “SyntaxError: Unexpected end of input” pointing to the file handlers/ticketHandler.js around line 961. This error means that the JavaScript file ends before the interpreter finishes parsing a block of code. In JavaScript this usually happens when a block is not properly closed. For example, an opening brace { may not have a matching closing brace }, or a function, conditional block, or object definition may be missing its final closing bracket. Because of this, Node.js reaches the end of the file and throws a syntax error since it expects more code to complete the block.

Carefully inspect the entire ticketHandler.js file and verify that every opening brace {, parenthesis (, and bracket [ has a corresponding closing character. Pay special attention to large functions such as setupMessageCollector, createTicketChannel, and any nested if, try/catch, or event listener blocks. These types of structures often cause this error if a closing brace was accidentally deleted while editing the file. Ensure that all collector callbacks, async functions, and conditional statements are properly closed before the end of the file.

Also inspect the bottom section of the file, especially the module.exports block. Sometimes the syntax error occurs because the export object is missing its closing brace or semicolon. The file should end with a properly formatted export statement like:

module.exports = {
    createTicketChannel,
    addUserToTicket,
    sendRoleSelection,
    setupMessageCollector,
    initiatePaymentFlow
};

Ensure that the export object is completely closed and that there are no unfinished functions above it. If any functions appear to continue past the export block, restructure them so that all functions are defined and closed before the export statement.

After fixing the missing bracket or unfinished block, verify that the file compiles without syntax errors and that the bot starts normally. The bot should load configuration, initialize the message collector, and register slash commands without crashing. The goal is to ensure that the entire ticketHandler.js file has balanced brackets and valid JavaScript syntax so Node.js can successfully execute the file.
Kodari AI
KodariMar 9 at 5:43 am 7,559 (v2)

I’ll read the ticketHandler.js file to identify and fix the syntax error causing the crash.

I found the issue! There’s a duplicate function declaration at line 285-286. The sendPriceConfirmation function is declared twice in a row, which breaks the JavaScript parser.

The duplicate function declaration has been removed. The bot should now start without the “Unexpected end of input” syntax error.

mrcat44
📎 1 file 3,562 chars
📄
pasted-code-1773035464095.txt
txt 59 lines
▶
The Discord middleman bot currently initializes the message collector correctly and sets the trade status to "waiting_for_price". The console confirms this with logs such as:

Message collector initialized
Status: waiting_for_price

However, when the seller sends a valid price message such as 0.05 ltc, 10 ltc, or $150, the bot does nothing. This indicates that the message collector is running but the price detection logic inside it is failing. The current implementation likely uses an overly strict regex or conditional logic that prevents valid price messages from being detected.

To fix this properly, rewrite the entire price detection section inside the setupMessageCollector function in handlers/ticketHandler.js with a clean and reliable implementation. The new collector should listen to all non-bot messages in the ticket channel and only process the message if the trade status is "waiting_for_price" and the message author is the seller.

When a message is received, retrieve the trade object using the channel ID from client.trades. If no trade object exists, ignore the message. If the trade status is not "waiting_for_price", ignore the message as well. Next verify that the sender is the seller by comparing message.author.id with trade.sellerId. If the sender is not the seller, ignore the message.

Once the sender is verified, parse the message content to extract a price. The new parser must support flexible formats including:

0.05 ltc
10 ltc
10 LTC
150 usd
150 USD
$150
150$
0.005 btc

Instead of relying on a complex single regex, implement a two-step parser that first extracts the numeric amount and then determines the currency. The numeric amount can be extracted using:

const amountMatch = message.content.match(/(\d+(\.\d+)?)/);

If no numeric value is found, the message should be ignored. If a number is detected, store it as the trade amount.

Next determine the currency. If the message contains $, treat the currency as "usd". Otherwise check if the message contains known currency keywords such as "ltc", "btc", "eth", "usdt", or "usd". If no currency keyword is detected, default to "usd".

After parsing the amount and currency, update the trade object using updateTrade so that the price and currency are saved and the trade status changes to "price_confirmation".

Example:

updateTrade(client, channel.id, {
    price: amount,
    currency: currency,
    status: "price_confirmation"
});

Immediately after updating the trade state, send an embed confirming the detected price. The embed should display something like:

Trade Price Detected
Price: 0.05 LTC
Both participants must confirm the price.

The embed color should follow the dark UI theme used by the bot (for example #1e1e1e). Below the embed include three buttons:

• Buyer Confirm
• Seller Confirm
• Cancel Trade

Both the buyer and seller must confirm the price before the trade proceeds to the payment stage.

Add debug logging inside the collector to verify that messages are being processed correctly. Log the message content, parsed amount, parsed currency, seller ID, and message author ID.

Finally ensure that the message collector is started immediately when the ticket channel is created by calling setupMessageCollector(client, ticketChannel) so the bot can detect price messages as soon as the ticket opens.

After implementing this improved collector logic, when the seller sends messages such as 0.05 ltc, 10 ltc, 150 usd, or $150, the bot should immediately detect the price and send the price confirmation embed so the trade can continue.
Kodari AI
KodariMar 9 at 5:52 am 10,838 (v2)

I’ll fix the price detection logic in the ticket handler by implementing a more reliable message collector with flexible parsing. Let me first read the relevant files to understand the current implementation.

I’ll now rewrite the price detection logic in the message collector to make it more reliable and flexible.

Now I need to fix the bot intents in index.js as it’s missing the required intents to read messages:

Summary:

✅ Fixed the price detection logic with a flexible two-step parser that:

  • First extracts numeric amounts (supports formats like 0.05, 10, 150, 0.005)

  • Then determines currency by checking for $ symbol or keywords (ltc, btc, eth, usdt, usd)

  • Defaults to USD if no currency is specified

✅ Added comprehensive debug logging to track:

  • Message content received

  • Author ID vs Seller ID verification

  • Detected amount and currency

  • Trade update status

✅ Fixed missing Discord intents in index.js by adding:

  • GuildMessages - to receive message events

  • MessageContent - to read message content (privileged intent)

The bot now accepts flexible price formats like:

  • 0.05 ltc

  • 10 LTC

  • $150

  • 150 usd

  • 0.005 btc

⚠️ Important: You must enable the Message Content Intent in the Discord Developer Portal under Bot settings for this to work.

mrcat44
📎 1 file 3,039 chars
📄
pasted-code-1773035847863.txt
txt 53 lines
▶
Loading bot files...
Creating a super duper secure sandbox...
Bot stopped
Sandbox created, starting bot...
added 143 packages, and audited 144 packages in 10s
36 packages are looking for funding
run `npm fund` for details
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: 'discord-trade-middleman@1.0.0',
npm WARN EBADENGINE required: { node: '>=20.0.0' },
npm WARN EBADENGINE current: { node: 'v18.20.4', npm: '9.2.0' }
npm WARN EBADENGINE }
11 vulnerabilities (9 moderate, 2 critical)
To address issues that do not require attention, run:
npm audit fix
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit` for details.
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: 'cheerio@1.2.0',
npm WARN EBADENGINE required: { node: '>=20.18.1' },
npm WARN EBADENGINE current: { node: 'v18.20.4', npm: '9.2.0' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: 'undici@7.22.0',
npm WARN EBADENGINE required: { node: '>=20.18.1' },
npm WARN EBADENGINE current: { node: 'v18.20.4', npm: '9.2.0' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: 'commander@14.0.3',
npm WARN EBADENGINE required: { node: '>=20' },
npm WARN EBADENGINE current: { node: 'v18.20.4', npm: '9.2.0' }
npm WARN EBADENGINE }
✅ Configuration loaded successfully
npm WARN deprecated yaeti@0.0.6: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated whatwg-encoding@3.1.1: Use @exodus/bytes instead for a more spec-conformant and faster implementation
npm WARN deprecated request-promise@4.2.6: request-promise has been deprecated because it extends the now deprecated request package, see https://github.com/request/request/issues/3142
npm WARN deprecated signalr-client@0.0.20: This is no longer active
npm WARN deprecated uuid@3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
❌ Unhandled promise rejection: Error: Used disallowed intents
at WebSocketShard.onClose (/root/node_modules/@discordjs/ws/dist/index.js:1151:18)
at connection.onclose (/root/node_modules/@discordjs/ws/dist/index.js:688:17)
at callListener (/root/node_modules/ws/lib/event-target.js:290:14)
at WebSocket.onClose (/root/node_modules/ws/lib/event-target.js:220:9)
at WebSocket.emit (node:events:517:28)
at WebSocket.emitClose (/root/node_modules/ws/lib/websocket.js:273:10)
at TLSSocket.socketOnClose (/root/node_modules/ws/lib/websocket.js:1346:15)
at TLSSocket.emit (node:events:529:35)
at node:net:351:12
at TCP.done (node:_tls_wrap:657:7)
Bot execution timed out (10 minute limit)
Kodari AI
KodariMar 9 at 5:58 am 16,210 (v2)

I can see the bot is failing due to “Used disallowed intents” error. This means the bot is requesting privileged intents that aren’t enabled in the Discord Developer Portal.

Let me read the current bot files to diagnose and fix this:

Looking at the errors, I can identify two main issues:

  1. “Used disallowed intents” error - The bot is requesting MessageContent intent which is a privileged intent that needs to be enabled in Discord Developer Portal

  2. Wrong event name - The code uses clientReady but should be ready

Let me fix the code issue first:

Now I’ll fix the code issues:


✅ Fixed code issues:

  • Changed clientReady to ready event (correct Discord.js event name)

  • Adjusted Node version requirement from >=20.0.0 to >=18.0.0

⚠️ IMPORTANT - You must enable privileged intents:

The bot needs MESSAGE CONTENT INTENT enabled in Discord Developer Portal:

  1. Select your bot application

  2. Click “Bot” in left sidebar

  3. Scroll to “Privileged Gateway Intents”

  4. Enable “MESSAGE CONTENT INTENT” ✅

  5. Click “Save Changes”

The bot requires this intent because it reads messages in ticket channels to collect:

  • Trade prices

  • Roblox group IDs

  • Roblox usernames

  • Wallet addresses

Without enabling this intent, the bot will continue to crash with “Used disallowed intents” error.

mrcat44
📎 1 file 2,332 chars
📄
pasted-code-1773036199768.txt
txt 23 lines
▶
The Discord middleman bot now correctly detects the trade price and both users can confirm it. However, when the bot moves to the payment stage it fails to generate a payment request and shows the message “Failed to generate payment request. Please contact an administrator.”. This indicates that the payment generation logic inside paymentService.js is failing when calling the NowPayments API.

Inspect the createPaymentRequest function in services/paymentService.js. The function should correctly build a POST request to the NowPayments API endpoint /v1/payment. Ensure the request includes the correct headers and body fields required by the NowPayments API. The request must include the API key in the header x-api-key, and the request body must contain price_amount, price_currency, pay_currency, and a unique order_id.

The current implementation likely fails when the trade price is expressed in USD. When the detected trade price is stored as 5 USD, the bot must convert that into the format required by the API request. The correct request body should look similar to this:

{
  price_amount: 5,
  price_currency: "usd",
  pay_currency: "ltc",
  order_id: "trade_0001",
  order_description: "Discord middleman trade"
}

Make sure the bot extracts the numeric value from the stored trade price and converts it into a number before sending the API request. For example if the stored value is "5 USD" the bot must parse it into 5.

Also ensure the payment currency is valid. If the trade currency is USD, the bot should still set the payment currency to the selected crypto currency such as "ltc" so NowPayments can calculate the correct crypto amount.

Add proper error logging inside the catch block so the bot prints the real API error in the console instead of only showing a generic failure message. For example log error.response?.data if available so developers can see the API response.

Verify that the environment variable NOWPAYMENTS_API_KEY is loaded correctly using process.env.NOWPAYMENTS_API_KEY. If the API key is missing, the bot should log an error stating that the API key is not configured.

After fixing the request structure and parsing logic, the bot should successfully generate a payment request and send an embed containing the payment amount, cryptocurrency type, and payment address for the buyer.
Kodari AI
KodariMar 9 at 6:05 am 17,325 (v2)

I’ll help you fix the payment generation issue in the Discord middleman bot. Let me first read the relevant files to understand the current implementation.

Let me read more files to understand how the payment is initiated and what format the amount is in:

Now I can see the full flow. Let me analyze the issue and fix the payment service:

Issues identified:

  1. No validation that API key exists before making request

  2. The error logging in paymentService.js is good, but the catch block in ticketHandler.js hides the detailed error

  3. Amount parsing looks correct but could be more robust

  4. Need to add validation for the request data

Let me fix the paymentService.js file:

Fixed the payment generation issue with the following improvements:

  1. API Key Validation - Now checks if NOWPAYMENTS_API_KEY exists before making requests and logs clear error if missing

  2. Enhanced Amount Parsing - Properly handles string amounts like “5 USD” by stripping non-numeric characters and validating the result

  3. Detailed Error Logging - Added comprehensive error logging that shows API response status, data, and headers when requests fail

  4. Request Logging - Logs the full payment request data for debugging

  5. Better Error Messages - Provides specific error messages based on whether the issue is with the API response, network, or request format

  6. Data Validation - Validates that the parsed amount is a valid positive number before making the API call

The bot will now show detailed API errors in the console, making it easy to identify issues with the NowPayments API integration.

mrcat44
📎 1 file 3,706 chars
📄
pasted-code-1773036511483.txt
txt 58 lines
▶
Loading bot files...
Creating a super duper secure sandbox...
Sandbox created, starting bot...
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: 'cheerio@1.2.0',
npm WARN EBADENGINE required: { node: '>=20.18.1' },
npm WARN EBADENGINE current: { node: 'v18.20.4', npm: '9.2.0' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: 'undici@7.22.0',
npm WARN EBADENGINE required: { node: '>=20.18.1' },
npm WARN EBADENGINE current: { node: 'v18.20.4', npm: '9.2.0' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: 'commander@14.0.3',
npm WARN EBADENGINE required: { node: '>=20' },
npm WARN EBADENGINE current: { node: 'v18.20.4', npm: '9.2.0' }
npm WARN EBADENGINE }
npm WARN deprecated yaeti@0.0.6: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
npm WARN deprecated whatwg-encoding@3.1.1: Use @exodus/bytes instead for a more spec-conformant and faster implementation
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated request-promise@4.2.6: request-promise has been deprecated because it extends the now deprecated request package, see https://github.com/request/request/issues/3142
npm WARN deprecated signalr-client@0.0.20: This is no longer active
npm WARN deprecated uuid@3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
added 143 packages, and audited 144 packages in 10s
36 packages are looking for funding
run `npm fund` for details
11 vulnerabilities (9 moderate, 2 critical)
To address issues that do not require attention, run:
npm audit fix
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit` for details.
✅ Configuration loaded successfully
✅ Bot is ready! Logged in as test3r4t5#7568
📊 Serving 1 server(s)
🔄 Registering slash commands...
(node:94) DeprecationWarning: The ready event has been renamed to clientReady to distinguish it from the gateway READY event and will only emit under that name in v15. Please use clientReady instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
✅ Slash commands registered successfully
🔧 Message collector initialized for channel 1480446825369440288
📝 Price requested for channel 1480446825369440288 - Status: waiting_for_price, Seller: 1244209834773971005
📩 Message received in 1480446825369440288 from mrcat44: "0.005 ltc"
📊 Trade status: waiting_for_price, Seller: 1244209834773971005, Buyer: 1159132325179838534
📩 Price detection - Message: "0.005 ltc"
📩 Price detection - Author: 1244209834773971005, Seller: 1244209834773971005
✅ Detected amount: 0.005
✅ Detected currency: ltc
✅ Trade updated - Price: 0.005 LTC, Status: price_confirmation
✅ Price confirmation sent for channel 1480446825369440288 - Price: 0.005 LTC
❌ NOWPAYMENTS_API_KEY is not configured in environment variables
❌ Error initiating payment flow: Error: Payment system not configured. Please contact an administrator.
at PaymentService.createPaymentRequest (/root/services/paymentService.js:19:19)
at initiatePaymentFlow (/root/handlers/ticketHandler.js:360:50)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async handlePriceConfirmation (/root/handlers/ticketHandler.js:310:9)
at async Client. (/root/handlers/interactionHandler.js:56:21)
Kodari AI
KodariMar 9 at 6:09 am 12,028 (v2)

I can see your bot is running but failing because the NOWPAYMENTS_API_KEY is not configured. Let me read the relevant files to understand the payment configuration and fix this issue.

I can see the NOWPAYMENTS_API_KEY is actually present in your .env file, but it’s not being loaded properly into the environment. This is likely because dotenv isn’t being initialized early enough or properly. Let me check the main entry point:

I found the issue! The require('dotenv').config() is being called after other modules are loaded, which means paymentConfig.js tries to read process.env.NOWPAYMENTS_API_KEY before the .env file has been loaded.

Fix: Move require('dotenv').config() to the very first line of index.js:

What was happening:

  • The modules were loading and reading process.env.NOWPAYMENTS_API_KEY before dotenv loaded the .env file

  • By moving require('dotenv').config() to the first line, environment variables are loaded before any other code runs

Restart your bot and the payment system should now work correctly with your NOWPayments API key!

mrcat44
📎 1 file 3,605 chars
📄
pasted-code-1773037270947.txt
txt 131 lines
▶
Extend the Discord middleman bot by implementing two advanced administrator commands that allow staff to control trades if something goes wrong. These commands must work with the existing Trade ID system (TRD-0001 format) and must only be executable by users with administrator roles defined in config.json.

The commands to implement are:

/admin cancel 
/admin force-release 

The bot must validate the user's permissions before executing either command. Only users with role IDs listed in config.adminRoleIds should be allowed to use these commands. If a non-admin attempts to run them, the bot must respond with:

❌ You do not have permission to use this command.
Command 1 — Cancel Trade

Implement the command:

/admin cancel TRD-0001

This command allows administrators to immediately cancel a trade if a scam attempt or rule violation is detected.

When executed, the bot must:

Search the stored trades database for the trade matching the given Trade ID.

Retrieve the trade's channelId and fetch the ticket channel.

Update the trade status to:

cancelled_by_admin

Send an embed message in the ticket channel explaining that the trade has been cancelled.

Example embed:

Trade Cancelled by Administrator

Trade ID: TRD-0001
Cancelled By: @AdminUser

Reason: Administrative intervention.

This ticket will now close.

Use a red color theme for the embed.

After sending the message, the bot should wait 10 seconds and then automatically delete the ticket channel.

Also log the action in the console:

ADMIN ACTION: Trade TRD-0001 cancelled by AdminUser
Command 2 — Force Release Trade

Implement the command:

/admin force-release TRD-0001

This command allows administrators to force complete the trade if both parties confirm the trade was successful but the automated system failed.

When executed, the bot must:

Locate the trade using the provided Trade ID.

Retrieve the ticket channel.

Set the trade status to:

completed_by_admin

Send a success embed in the ticket channel.

Example embed:

Trade Completed by Administrator

Trade ID: TRD-0001
Approved By: @AdminUser

The trade has been manually completed by staff.

Use a green embed color.

After this:

• Generate the trade log using the existing tradeLogger.js
• Send the log file to the configured log channel
• Lock the ticket channel (remove send permissions) instead of deleting it immediately

Console log example:

ADMIN ACTION: Trade TRD-0001 force completed by AdminUser
Trade Lookup Logic

These commands must work even if the admin runs them outside the ticket channel. The bot should locate the trade using the stored trade data file (trades.json) by matching:

trade.tradeId === providedTradeId

Once found, the bot should retrieve the corresponding channelId.

Error Handling

If the trade ID does not exist:

❌ Trade ID not found.

If the ticket channel no longer exists:

⚠ Trade found but the ticket channel is missing.
Slash Command Registration

Add these commands during startup in index.js:

/admin cancel tradeid
/admin force-release tradeid
/admin payment tradeid true/false

Ensure they appear only to administrators by setting:

PermissionFlagsBits.Administrator
Additional Safety Requirement

All admin commands must send a hidden confirmation response (ephemeral: true) to the admin who executed them, so the command output does not spam the channel.

Example:

✅ Admin action executed successfully.

✅ After implementing this system, the bot will support:

• Manual payment approval
• Admin trade cancellation
• Forced trade completion
• Trade ID management
• Full moderation control
Kodari AI
KodariMar 9 at 6:22 am 46,984 (v2)

I’ll extend your Discord middleman bot with the two administrator commands. Let me first read the existing files to understand the structure.

I’ll implement the two administrator commands for trade management. Let me create the admin commands handler and update the necessary files.

Now I’ll create the admin commands handler and update the necessary files.

Now I’ll update the remaining files to integrate the admin commands:

✅ Admin commands system implemented successfully!

The bot now supports three powerful administrator commands:

  • /admin cancel <tradeid> - Immediately cancels a trade and deletes the channel after 10 seconds

  • /admin force-release <tradeid> - Manually completes a trade, generates logs, and locks the channel

  • /admin payment <tradeid> <approve> - Manually approves or rejects payment verification

All commands validate admin permissions using config.adminRoleIds and provide ephemeral responses to prevent channel spam.

mrcat44
📎 1 file 2,448 chars
📄
pasted-code-1773038093535.txt
txt 36 lines
▶
The Discord middleman bot successfully retrieves Roblox group information when the seller submits a group ID. The bot correctly shows an embed containing the group name, icon, current owner, and member count. However, the workflow stops after displaying this information. The bot must now implement a group confirmation step before continuing the trade.

After fetching the group information, the bot should send an embed titled "Group Verification" displaying the group details including the group icon, name, current owner username, and member count. Below this embed the bot must include two confirmation buttons:

• Buyer Confirm
• Seller Confirm

Both participants must confirm that the group is correct before the trade continues. Only the buyer and seller involved in the trade should be allowed to click these buttons. If another user tries to click them, the bot should respond with an ephemeral message stating that only trade participants can confirm the group.

When either user confirms, the bot should record the confirmation state inside the trade object using fields such as:

groupBuyerConfirmed: true
groupSellerConfirmed: true

The trade should only proceed once both confirmations are received.

Once both confirmations are completed, the bot should send a new embed titled "Transfer Group Ownership" instructing the seller to transfer the Roblox group to the holding account WeroAutomation. The embed should clearly state:

Seller must transfer the Roblox group ownership to the holding account:

WeroAutomation

Once the ownership is transferred, the bot will automatically detect the change and continue the trade.

After this message, the bot must start a group ownership monitoring system using the Roblox API. The bot should periodically check the group owner every few seconds. When the owner changes to the configured holding account user ID, the bot should detect this automatically and update the trade status.

Once the transfer is detected, the bot should send a success embed saying:

Group Transfer Detected

The Roblox group has been successfully transferred to the holding account.
The trade will now proceed to the final stage.

The trade status should then change to the next stage of the trade workflow.

The bot should also include proper error handling so that if the group owner does not change within a reasonable time limit (for example 30 minutes), the bot notifies both users and alerts administrators.
Kodari can make mistakes. Review important code before using.
Files
config
handlers
services
utils
config.json
index.js
package.json
Code
16 3,104
index.js
require('dotenv').config();

const { Client, GatewayIntentBits, Partials, Collection, REST, Routes, SlashCommandBuilder, PermissionFlagsBits } = require('discord.js');
const { loadConfig } = require('./utils/configLoader');
const { setupInteractionHandler } = require('./handlers/interactionHandler');
const { loadTradeData } = require('./utils/dataManager');

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent
    ],
    partials: [Partials.Channel]
});

client.config = loadConfig();
client.trades = new Collection();
client.tradeCounter = 0;

client.once('ready', async () => {
    console.log(`✅ Bot is ready! Logged in as ${client.user.tag}`);
    console.log(`📊 Serving ${client.guilds.cache.size} server(s)`);

    loadTradeData(client);

    await registerSlashCommands(client);

    client.user.setActivity('trades', { type: 3 });
});

async function registerSlashCommands(client) {
    const commands = [
        new SlashCommandBuilder()
            .setName('sendpanel')
            .setDescription('Send the trade panel to the configured channel')
            .setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
        new SlashCommandBuilder()
            .setName('adduser')
            .setDescription('Add a user to the current trade ticket')
            .addStringOption(option =>
                option.setName('userid')
                    .setDescription('The Discord User ID to add')
                    .setRequired(true)),
        new SlashCommandBuilder()
            .setName('submitgroup')
            .setDescription('Submit the Roblox group ID for the trade')
            .addStringOption(option =>
                option.setName('groupid')
                    .setDescription('The Roblox Group ID')
                    .setRequired(true)),
        new SlashCommandBuilder()
            .setName('admin')
            .setDescription('Administrator trade management commands')
            .setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
            .addSubcommand(subcommand =>
                subcommand
                    .setName('cancel')
                    .setDescription('Cancel a trade immediately')
                    .addStringOption(option =>
                        option.setName('tradeid')
                            .setDescription('Trade ID (e.g., TRD-0001)')
                            .setRequired(true)))
            .addSubcommand(subcommand =>
                subcommand
                    .setName('force-release')
                    .setDescription('Force complete a trade')
                    .addStringOption(option =>
                        option.setName('tradeid')
                            .setDescription('Trade ID (e.g., TRD-0001)')
                            .setRequired(true)))
            .addSubcommand(subcommand =>
                subcommand
                    .setName('payment')
                    .setDescription('Manually approve or reject payment')
                    .addStringOption(option =>
                        option.setName('tradeid')
                            .setDescription('Trade ID (e.g., TRD-0001)')
                            .setRequired(true))
                    .addBooleanOption(option =>
                        option.setName('approve')
                            .setDescription('Approve (true) or Reject (false)')
                            .setRequired(true)))
    ].map(command => command.toJSON());

    const rest = new REST().setToken(process.env.DISCORD_TOKEN);

    try {
        console.log('🔄 Registering slash commands...');
        
        for (const guild of client.guilds.cache.values()) {
            await rest.put(
                Routes.applicationGuildCommands(client.user.id, guild.id),
                { body: commands }
            );
        }
        
        console.log('✅ Slash commands registered successfully');
    } catch (error) {
        console.error('❌ Error registering slash commands:', error);
    }
}

setupInteractionHandler(client);

client.on('error', error => {
    console.error('❌ Discord client error:', error);
});

process.on('unhandledRejection', error => {
    console.error('❌ Unhandled promise rejection:', error);
});

client.login(process.env.DISCORD_TOKEN);