PHP code example of more-cores / discord-commands

1. Go to this page and download the library: Download more-cores/discord-commands library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

more-cores / discord-commands example snippets


$message = new WebhookMessage();
$message->setContent($content);

$embed = new Embed();
$embed->setTitle($title);
$embed->setDescription($description);
$embed->setUrl($url);
$embed->setTimestamp($dateTime);
$embed->setColor($color);
$message->addEmbed($embed);

$message->toJson(); // valid json ready to be sent to Discord via a Webhook

$message = new Message();
$message->setContent($content);
$message->addEmbed($embed);


// appends the mention to the previously set content.  Setting the content again overrides mentions
$message->mentionRole($roleId);

$message->isRoleMentioned($roleId);
$message->hasMentions();

use \DiscordCommands\Messages\Message;

$message->setContent('Instead of this channel, go to '.Message::linkChannel(34835835834));

use \DiscordCommands\Messages\Message;
use \DiscordCommands\Messages\GuildNavigation;

$message->setContent('Help find new channels in '.Message::linkInGuild(GuildNavigation::CHANNEL_BROWSER));

use \DiscordCommands\Messages\Message;
use \DiscordCommands\Messages\TimestampFormat;

$message->setContent('The contest runs until '.Message::timestamp(time()+6000));

// You can also customize formatting
$message->setContent('The contest runs until '.Message::timestamp(time()+600, TimestampFormat::SHORT_TIME));

// define an embed author using shorthand
$embed->setAuthor($name);

// and optionally specify specific attributes
$embed->setAuthor($name, $url);

// define an embed author by object
$author = new Author();
$author->setName($name);
$embed->setAuthor($author);

// define an embed video using shorthand
$embed->addField($fieldName, $fieldValue);

// and optionally specify whether it's inline (default to false)
$embed->addField($fieldName, $fieldValue, $inline = true);

// define an embed field by object
$field = new Field();
$field->setName($name);
$field->setValue($value);
$embed->setVideo($field);

$embed->setImageUrl($imageUrl);

$embed->setThumbnailUrl($thumbnailUrl);

// define an embed footer using shorthand
$embed->setFooter($text, $iconUrl);

// and optionally specify  specific attributes
$embed->setFooter($urlToImage, $width, $height);

// define an embed thumbnail by object
$thumbnail = new Thumbnail();
$thumbnail->setText($text);
$thumbnail->setUrl($urlToImage);
$embed->setFooter($thumbnail);

$message->actionRow(new SuccessButton('button-id', 'Approve it'));
$message->actionRow(new DangerButton('button-id', 'Reject it'));
$message->actionRow(new PrimaryButton('button-id', 'Something else'));
$message->actionRow(new SecondaryButton('button-id', 'Something else'));
$message->actionRow(new LinkButton('https://mysite.com', 'My Site'));

$message->addComponent(new StringSelectMenu($menuId, [
    new Option('Option 1', 'option-1'),
    new Option('Option 2', 'option-2'),
]));

$message->addComponent(new RoleSelectMenu($menuId));

$message->addComponent(new MentionableSelectMenu($menuId));

$message->addComponent(new UserSelectMenu($menuId));

$message->addComponent(new ChannelSelectMenu($menuId));

$message->addComponent(new ChannelSelectMenu($menuId, [
    channelTypes: [
        Channel::TYPE_GUILD_TEXT,
        Channel::TYPE_GUILD_VOICE,
    ],
]));

$message->addComponent(new ShortInput($fieldId, 'First Name'));
$message->addComponent(new ParagraphInput($fieldId, 'Dating Profile'));

class MyCommand extends ChatInputCommand
{
    public const NAME = 'my-command';

    public function __construct()
    {
        parent::__construct(
            name: self::NAME,
            description: 'This is executable by the higher ups in the guild',
            availableInDms: false,
            defaultMemberPermissions: [
                Permission::ADMINISTRATOR,
                Permission::MANAGE_GUILD,
            ]
        );
    }
}

$factory = new InteractionTypeFactory();
$interaction = $factory->make($request->json('type'), $request->json());

$verifier = new SignatureVerifier();

if (!$verifier->verify(
    rawBody: file_get_contents('php://input'),
    publicKey: getenv('DISCORD_BOT_PUBLIC_KEY'),
    signature: $_SERVER['HTTP_X_SIGNATURE_ED25519'],
    timestamp: $_SERVER['HTTP_X_SIGNATURE_TIMESTAMP'],
)) {
    return http_response_code(401);
}

// Everything's good, do the rest here

Route::group([
    'prefix' => 'discord',
    'namespace' => 'Api\Discord',
    'middleware' => LaravelDiscordSignatureVerificationMiddleware::class,
], function () {
    Route::post(
        'webhook/command/interactions',
        'CommandInteractionController@userInteracted'
    );
});

    public function userInteracted(
        Request $request,
        InteractionTypeFactory $interactionTypeFactory
    ) {
        $interaction = $interactionTypeFactory->make($request->json('type'), $request->all());

        if ($interaction instanceof Ping) {
            return new Pong();
        }

        // generate other responses based on the inbound interaction
    }

$modal = new ShowModal(
    id: 'something',
    title: "Add new game/software for voting",
);
$modal->actionRow(
    new ShortInput(
        id: 'field-1',
        label: 'My Field',
    )
);
$modal->actionRow(
    new ShortInput(
        id: 'field-2',
        label: 'My Field 2',
    ),
);
return $modal->jsonSerialize();

public function interactions(
    Request $request,
    InteractionTypeFactory $interactionTypeFactory,
    CommandFactory $commandFactory,
) {
    $interaction = $interactionTypeFactory->make($request->json('type'), $request->all());

    if ($interaction instanceof Ping) {
        return new Pong();
    }

    if ($interaction instanceof ModalSubmitted) {
        $command = $commandFactory->makeByModal($interaction->modal()->id());
        return $command->whenSubmitted($interaction, $interaction->modal());
    }

    throw new RuntimeException('Command interaction went unhandled');
}

public function whenSubmitted(
    ModalSubmitted $interaction,
    SubmittedModal $modal,
): CommandResponse {
    Log::info('modal submitted', [
        'modal' => $modal->id(),
        'value' => $modal->fieldValue('field-2'),
    ]);

    return new ReplyWithMessage(
        content: "You're all done!",
        onlyVisibleToCommandIssuer: true,
    );
}