最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

discord - DiscordJS Slash Command using fetch not returning response or any errors - Stack Overflow

programmeradmin5浏览0评论

I'm using Discord.js and am using NodeJS v22.14.0

I have a slash command called work which calls a remote PHP script and sends the userID value using POST. When the command is run in Discord I get the following : 'The application did not respond'

If I call the script directly in the browser it returns a successful response with data No errors in the PHP error_log file either

Any help with this would be great, its been stressing me out for days and I know its a stupid issue causing it

Here is the DiscordJS command

client.on('interactionCreate', async (interaction) => {
    if (!interaction.isCommand()) return;

    const { commandName, options, channelId, user } = interaction;

  if (commandName === 'work') {
    const userid = interaction.user.id;
    const response  = await fetch('.php',
            {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ userid }),
            });
            const result = await response.json();
            if (response.ok && result.success === true) 
            { 
                 return interaction.reply({content: `${result.message}`, ephemeral: true});
            } else {
                 interaction.reply('Failed');
            }
    }
});

If I access the PHP script via the browser it returns data successfully

PHP Script ( trimmed )

<?php
header('Content-Type: application/json');
$data = json_decode(file_get_contents("php://input"));
$userid = $data->userid;
$int = rand(2, 13);
$amount = ($int > 7) ? rand(360, 694) : rand(82, 340);

$earned = "**You earned $$amount**";
$made = "**You made $$amount**";
$work = [
    "You helped an old lady carry her groceries \n $earned",
    "Your boss was shocked to see you at work \n $earned",
    "After a $int hour shift as an Uber driver \n $earned",
    "Your wife pays you to tidy up the garage \n $earned",
    "You spent $int hours delivering food \n $earned",
    "You spot a bargain in a charity shop & sell it on ebay \n $made",
    "Insurance company pays out your claim \n $earned",
    "Made a cool profit trading the stock market \n $made",
    "Your crypto portfolio value shows a nice profit \n $made",
    "You sell your kidney on Craigslist \n $earned",
    "Garage sale was a success  \n $made"
];

$i = rand(0, 10);
$res = $work[$i];
echo json_encode(['success' => true, 'message' => "$res"]);
?>
{"success":true,"message":"Garage sale was a success  \n **You made $282**"}

I'm using Discord.js and am using NodeJS v22.14.0

I have a slash command called work which calls a remote PHP script and sends the userID value using POST. When the command is run in Discord I get the following : 'The application did not respond'

If I call the script directly in the browser it returns a successful response with data No errors in the PHP error_log file either

Any help with this would be great, its been stressing me out for days and I know its a stupid issue causing it

Here is the DiscordJS command

client.on('interactionCreate', async (interaction) => {
    if (!interaction.isCommand()) return;

    const { commandName, options, channelId, user } = interaction;

  if (commandName === 'work') {
    const userid = interaction.user.id;
    const response  = await fetch('https://example/script.php',
            {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ userid }),
            });
            const result = await response.json();
            if (response.ok && result.success === true) 
            { 
                 return interaction.reply({content: `${result.message}`, ephemeral: true});
            } else {
                 interaction.reply('Failed');
            }
    }
});

If I access the PHP script via the browser it returns data successfully

PHP Script ( trimmed )

<?php
header('Content-Type: application/json');
$data = json_decode(file_get_contents("php://input"));
$userid = $data->userid;
$int = rand(2, 13);
$amount = ($int > 7) ? rand(360, 694) : rand(82, 340);

$earned = "**You earned $$amount**";
$made = "**You made $$amount**";
$work = [
    "You helped an old lady carry her groceries \n $earned",
    "Your boss was shocked to see you at work \n $earned",
    "After a $int hour shift as an Uber driver \n $earned",
    "Your wife pays you to tidy up the garage \n $earned",
    "You spent $int hours delivering food \n $earned",
    "You spot a bargain in a charity shop & sell it on ebay \n $made",
    "Insurance company pays out your claim \n $earned",
    "Made a cool profit trading the stock market \n $made",
    "Your crypto portfolio value shows a nice profit \n $made",
    "You sell your kidney on Craigslist \n $earned",
    "Garage sale was a success  \n $made"
];

$i = rand(0, 10);
$res = $work[$i];
echo json_encode(['success' => true, 'message' => "$res"]);
?>
{"success":true,"message":"Garage sale was a success  \n **You made $282**"}
Share Improve this question asked 8 hours ago ChrisYatesChrisYates 496 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

discord requires a response within 3 seconds. maybe you have a solution: use interaction.deferReply() to save more time!!

example:

client.on('interactionCreate', async (interaction) => {
    if (!interaction.isCommand()) return;

    if (interactionmandName === 'work') {
        await interaction.deferReply({ ephemeral: true });

        try {
            const userid = interaction.user.id;
            const response = await fetch('https://example/script.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ userid }),
            });

            const result = await response.json();
            if (response.ok && result.success) { 
                return interaction.editReply({ content: result.message });
            } else {
                return interaction.editReply('Failed');
            }
        } catch (error) {
            console.error(error);
            return interaction.editReply('error during command execution');
        }
    }
});
发布评论

评论列表(0)

  1. 暂无评论