### Run Code Before Bot Boot
Source: https://laracord.com/docs/2.x/hooks
Use the `beforeBoot()` method to execute code before the bot starts. This is ideal for initial setup tasks like clearing cache or setting memory limits.
```php
/**
* Actions to run before booting the bot.
*/
public function beforeBoot(): void
{
ini_set('memory_limit', '-1');
cache()->flush();
}
```
--------------------------------
### Install Laracord
Source: https://laracord.com/
Install Laracord using Composer to set up a new Discord bot project.
```bash
composer create-project laracord/laracord my-discord-bot
```
--------------------------------
### Install OpenAI PHP Client
Source: https://laracord.com/docs/2.x/chatgpt
Install the OpenAI client package using Composer. Ensure your API key is added to your `.env` file.
```bash
$ composer require openai-php/client
```
```dotenv
OPENAI_API_KEY=sk-...
```
--------------------------------
### Boot Laracord Bot
Source: https://laracord.com/docs/2.x/installation
Run the 'laracord' command with no arguments to start your bot. If the bot token is not yet in any servers, an invite link will be provided.
```bash
$ php laracord
```
--------------------------------
### Install Livewire using Composer
Source: https://laracord.com/docs/2.x/livewire
Use Composer to add the Livewire package to your project. Ensure you have a Laravel application key generated.
```bash
$ composer require livewire/livewire
```
--------------------------------
### Basic HTTP Client Usage
Source: https://laracord.com/docs/2.x/http-client
Demonstrates basic GET and POST requests using the Http facade. Ensure the Http facade is imported.
```php
console()->log('The Message Create event has fired!');
}
}
```
--------------------------------
### Create a Select Menu with a Route and Placeholder
Source: https://laracord.com/docs/2.x/messages
Configure a select menu to send interactions to a specific route using the `route` parameter. A `placeholder` can be set to guide user selection.
```PHP
$this
->message('What kind of fruit do you like?')
->select([
'Apples',
'Oranges',
'Bananas',
], route: 'selectFruit', placeholder: 'Select a fruit...');
```
--------------------------------
### Set Bot Activity Presence After Boot
Source: https://laracord.com/docs/2.x/hooks
Implement the `afterBoot()` method to run code after the bot has successfully booted and connected to Discord. This example sets the bot's 'Playing' activity.
```php
use Discord\Parts\User\Activity;
/**
* Actions to run after booting the bot.
*/
public function afterBoot(): void
{
$activity = $this->discord()->factory(Activity::class, [
'type' => Activity::TYPE_PLAYING,
'name' => 'with Laracord',
]);
$this->discord()->updatePresence($activity);
}
```
--------------------------------
### Basic Eloquent Model Example
Source: https://laracord.com/docs/2.x/database
A basic example of a generated Eloquent model class. Customize this class to define your model's attributes and relationships.
```php
message('Say hello!')
->button('Hello', fn (Interaction $interaction) => $interaction->respondWithMessage(
$this->message('Well hello to you!')->build(),
ephemeral: true
), emoji: '👋');
```
--------------------------------
### Hide Commands on Bot Boot
Source: https://laracord.com/docs/2.x/configuration
Set the `$showCommands` property to `false` in your `Bot.php` file to prevent the command list from displaying when the bot starts.
```php
/**
* Determine whether to show the commands on boot.
*/
protected bool $showCommands = false;
```
--------------------------------
### Implement Custom Middleware for Commands
Source: https://laracord.com/
Create custom middleware to process commands and interactions before they reach the main command handler. This example prevents a specific command from executing.
```php
isCommand() && $context->command->getName() === 'ping') {
Message::content('Not this time!')->reply($context->source);
return;
}
return $next($context);
}
}
```
--------------------------------
### Livewire Layout with Blade Directives
Source: https://laracord.com/docs/2.x/livewire
Include the `@livewireStyles` and `@livewireScripts` directives in your `app.blade.php` layout. This example also includes Tailwind CSS for styling.
```html
{{ $title ?? 'Laracord' }}
@livewireStyles
{{ $slot }}
@livewireScripts
```
--------------------------------
### Retrieve Cache Item
Source: https://laracord.com/docs/2.x/cache
Retrieve a cached item by its key using the `get()` method.
```php
$cache = cache()->get('key');
```
--------------------------------
### Create a New Service
Source: https://laracord.com/docs/2.x/services
Use the `make:service` command to generate a new service class. The default service logs 'Hello World' to the console every 5 seconds.
```bash
$ php laracord make:service Example
```
--------------------------------
### Create a New Laracord Project
Source: https://laracord.com/docs/2.x/installation
Use Composer's create-project command to set up a new Laracord project. Navigate into the project directory afterwards.
```bash
$ composer create-project laracord/laracord
$ cd laracord
```
--------------------------------
### Create a Simple Select Menu
Source: https://laracord.com/docs/2.x/messages
Use the `select` method with an array of strings to create a basic select menu with predefined options. This is suitable for simple choices.
```PHP
$this
->message('What kind of fruit do you like?')
->select(['Apples', 'Bananas', 'Pineapples']);
```
--------------------------------
### Boot Laracord in Production
Source: https://laracord.com/docs/2.x/deployment
Execute the built PHAR file using PHP 8.1+ on your server. The bot will automatically create a `database.sqlite` file and `cache` folder on its first run if they don't exist.
```bash
php laracord
```
```bash
./laracord
```
--------------------------------
### Write and Read Files with File Facade
Source: https://laracord.com/docs/2.x/filesystem
Use the `File` facade to write content to a file and then read it back. Ensure the path is correctly specified.
```php
discord();
```
--------------------------------
### Build Laracord for Production
Source: https://laracord.com/docs/2.x/deployment
Run this command to bundle your application into a PHAR file for production. The output will be in the `builds/` directory.
```bash
php laracord app:build
```
--------------------------------
### Basic Context Menu Implementation
Source: https://laracord.com/docs/2.x/context-menus
A simple context menu that responds with a message. It defines the menu name, type (message by default), and the `handle` method to process interactions.
```php
respondWithMessage(
$this
->message()
->title('Example Menu')
->content('Hello world!')
->build()
);
}
}
```
--------------------------------
### Create a Model with Migration
Source: https://laracord.com/docs/2.x/database
Generate a new Eloquent model along with its corresponding migration file using the -m option.
```bash
$ php laracord make:model Balance -m
```
--------------------------------
### Create a Hello Slash Command in Laracord
Source: https://laracord.com/
A basic slash command that replies with 'Hello world!' and includes an interactive button. It's designed for quick testing and demonstration.
```php
message('Hello world!')
->button('👋', route: 'wave')
->reply($interaction, ephemeral: true);
}
/**
* The command interaction routes.
*/
public function interactions(): array
{
return [
'wave' => fn (Interaction $interaction) => $this->message('👋')->reply($interaction, ephemeral: true),
];
}
}
```
--------------------------------
### Configure MySQL Database Connection
Source: https://laracord.com/docs/2.x/database
Set DB_CONNECTION to mysql and provide credentials in your .env file to use MySQL instead of the default SQLite.
```env
DB_CONNECTION=mysql
DB_HOST=
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=
```
--------------------------------
### Default Configuration - Services and Events
Source: https://laracord.com/docs/2.x/configuration
Specify additional services to run asynchronously or events to listen for. These are loaded in addition to those automatically registered.
```php
/*
|
| Here you may specify any additional services to run asynchronously
| alongside the Discord bot. These services will be loaded in addition
| to the services automatically loaded from your project.
|*/
'services' => [
//
],
/*
|--------------------------------------------------------------------------
| Additional Events
|--------------------------------------------------------------------------
|
| Here you may specify any additional events to listen for in your
| Discord bot. These events will be registered in addition to the
| events automatically registered from your project.
|*/
'events' => [
//
],
];
```
--------------------------------
### Generate a Migration File
Source: https://laracord.com/docs/2.x/database
Create a new migration file using the make:migration console command. Migrations are stored in the database/migrations directory.
```bash
$ php laracord make:migration create_balances_table
```
--------------------------------
### Write and Read Files with Storage Facade
Source: https://laracord.com/docs/2.x/filesystem
Interact with the bot's configured storage using the `Storage` facade. Files are stored relative to the default storage directory.
```php
[
App\Providers\BotServiceProvider::class,
Livewire\LivewireServiceProvider::class,
],
```
--------------------------------
### Create a New Context Menu
Source: https://laracord.com/docs/2.x/context-menus
Use the `make:menu` Artisan command to generate a new context menu class. This command scaffolds the basic structure for your menu.
```bash
php laracord make:menu ExampleMenu
```
--------------------------------
### Basic Slash Command Structure
Source: https://laracord.com/docs/2.x/slash-commands
A minimal slash command requires a name, description, and a handle method to process interactions. Ensure the command is namespaced correctly.
```php
respondWithMessage(
$this
->message()
->title('Example')
->content('Hello world!')
->build()
);
}
}
```
--------------------------------
### Basic Laracord Command Structure
Source: https://laracord.com/docs/2.x/commands
A generated command class includes properties for name and description, and a `handle` method to define its behavior.
```php
message()
->title('Example')
->content('Hello world!')
->send($message);
}
}
```
--------------------------------
### Add a link button
Source: https://laracord.com/docs/2.x/messages
Create a simple link button with a label and a URL using the `->button()` method.
```php
$this
->message('Hello world!')
->button('Visit Laracord', 'https://laracord.com');
```
--------------------------------
### Create a New Model
Source: https://laracord.com/docs/2.x/database
Use the laracord binary to generate a new Eloquent model. Models are placed in the app/Models directory.
```bash
$ php laracord make:model Balance
```
--------------------------------
### Provide Dynamic Autocomplete Choices with Callback
Source: https://laracord.com/docs/2.x/slash-commands
For dynamic suggestions, use a callback function that receives the interaction and the current input value. This allows you to fetch and filter choices in real-time. The callback should return an array or a collection of choices, limited to 25 items.
```php
use Discord\Parts\Interactions\Interaction;
public function autocomplete(): array
{
return [
'set.channel.id' => fn (Interaction $interaction, mixed $value) => $value
? TicketChannel::where('channel_id', 'like', "%{$value}%")->take(25)->pluck('channel_id')
: TicketChannel::take(25)->pluck('channel_id'),
];
}
```
--------------------------------
### Generate Laravel Application Key
Source: https://laracord.com/docs/2.x/livewire
Generate the application key required by Laravel and Livewire using the `laracord` binary.
```bash
$ php laracord key:generate
```
--------------------------------
### Attach a file by path
Source: https://laracord.com/docs/2.x/messages
Alternatively, attach a file by specifying its path using the `->filePath()` method.
```php
$this
->message('Hello world!')
->filePath('path/to/file');
```
--------------------------------
### ChatGPT Command Implementation
Source: https://laracord.com/docs/2.x/chatgpt
This PHP code implements a Discord command to chat with ChatGPT. It initializes the OpenAI client, handles user messages, trims input, caches conversations for one minute, and interacts with the 'gpt-3.5-turbo' model. Ensure your OpenAI API key is set in `.env`.
```php
';
/**
* The OpenAI API key.
*
* @var string
*/
protected $apiKey = '';
/**
* The OpenAI client instance.
*
* @var \OpenAI\Client
*/
protected $client;
/**
* The OpenAI API key.
*/
protected string $apiKey = '';
/**
* The OpenAI system prompt.
*/
protected string $prompt = 'You only reply with 1-2 sentences at a time as if responding to a chat message.';
/**
* Handle the command.
*
* @param \Discord\Parts\Channel\Message $message
* @param array $args
* @return mixed
*/
public function handle($message, $args)
{
$input = trim(
implode(' ', $args ?? [])
);
if (! $input) {
return $this
->message('You must provide a message.')
->title('Chat')
->error()
->send($message);
}
$message->channel->broadcastTyping()->done(function () use ($message, $input) {
$key = "{$message->channel->id}.chat.responses";
$input = Str::limit($input, 384);
$messages = cache()->get($key, [['role' => 'system', 'content' => $this->prompt]]);
$messages[] = ['role' => 'user', 'content' => $input];
$result = $this->client()->chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => $messages,
]);
$response = $result->choices[0]->message->content;
$messages[] = ['role' => 'assistant', 'content' => $response];
cache()->put($key, $messages, now()->addMinute());
return $this
->message($response)
->send($message);
});
}
/**
* Retrieve the OpenAPI client instance.
*
* @return \OpenAI\Client
*/
protected function client()
{
if ($this->client) {
return $this->client;
}
return $this->client = OpenAI::client($this->apiKey());
}
/**
* Retrieve the OpenAPI API key.
*
* @return string
*/
protected function apiKey()
{
if ($this->apiKey) {
return $this->apiKey;
}
return $this->apiKey = env('OPENAI_API_KEY', $this->apiKey);
}
}
```
--------------------------------
### Define Slash Command Options (Array Format)
Source: https://laracord.com/docs/2.x/slash-commands
Specify command options using a raw array structure for the `$options` property. This format is suitable for simpler option definitions.
```php
use Discord\Parts\Interactions\Command\Option;
/**
* The slash command options.
*
* @var array
*/
protected $options = [
[
'name' => 'message',
'description' => 'Send a message through the bot.',
'type' => Option::STRING,
'required' => true,
],
];
```
--------------------------------
### Create a Select Menu with Custom Options
Source: https://laracord.com/docs/2.x/messages
Customize select menu options by providing an array where keys are option IDs and values are arrays of properties like `label`, `description`, `emoji`, and `default`.
```PHP
$this
->message('What kind of fruit do you like?')
->select([
'apples' => [
'label' => 'Apples',
'description' => 'A tasty red fruit.',
'emoji' => '🍎',
'default' => true,
],
'oranges' => [
'label' => 'Oranges',
'description' => 'A tasty orange fruit.',
'emoji' => '🍊',
],
'bananas' => [
'label' => 'Bananas',
'description' => 'A tasty yellow fruit.',
'emoji' => '🍌',
],
], route: 'selectFruit', placeholder: 'Select a fruit...');
```
--------------------------------
### Default Service Implementation
Source: https://laracord.com/docs/2.x/services
This is the default structure of a generated service. It defines the execution interval and the `handle` method, which contains the core logic.
```php
discord()->getChannel('your-channel-id');
$this
->message()
->content('Hello world.')
->send($channel);
$this->console()->log('Hello world.');
}
}
```
--------------------------------
### Configure Discord Bot Token
Source: https://laracord.com/
Set your Discord bot token in the .env file for authentication.
```dotenv
DISCORD_TOKEN=
```
--------------------------------
### Configure Bot Token
Source: https://laracord.com/docs/2.x/installation
Add your Discord bot token to the .env file. Ensure you have obtained a token from the Discord Developer Portal and enabled necessary intents.
```dotenv
DISCORD_TOKEN=...
```
--------------------------------
### Create Balances Table Migration
Source: https://laracord.com/docs/2.x/database
A migration defining the 'balances' table with columns for discord_id, server_id, amount, and timestamps. The discord_id and server_id are uniquely combined.
```php
id();
$table->string('discord_id');
$table->string('server_id');
$table->integer('amount')->default(0);
$table->unique(['discord_id', 'server_id']);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('balances');
}
};
```
--------------------------------
### Define Slash Command Options (Method Format)
Source: https://laracord.com/docs/2.x/slash-commands
Alternatively, define command options by overriding the `options()` method, allowing for more dynamic option creation using DiscordPHP Option Parts.
```php
/**
* The slash command options.
*
* @return array
*/
public function options()
{
$option = new Option($this->discord());
return [
$option
->setName('message')
->setDescription('Send a message through the bot')
->setType(Option::STRING)
->setRequired(true)
->toArray(),
];
}
```
--------------------------------
### Attach a file by content
Source: https://laracord.com/docs/2.x/messages
Attach a file to your message by providing its raw content and a filename using the `->file()` method.
```php
$this
->message('Hello world!')
->file('Lorem ipsum...', 'lorem.txt');
```
--------------------------------
### Create Different Select Menu Types
Source: https://laracord.com/docs/2.x/messages
Utilize the `type` parameter in the `select` method to create specialized select menus for channels, mentions, roles, or users.
```PHP
$this
->message('Pick a select, any select!')
->select(type: 'channel', route: 'handleChannel')
->select(type: 'mentionable', route: 'handleMentionable')
->select(type: 'role', route: 'handleRole')
->select(type: 'user', route: 'handleUser');
```
--------------------------------
### Set Embed Footer Text and Icon
Source: https://laracord.com/docs/2.x/messages
Add a footer to the embed with text and an optional icon URL using `footerText()` and `footerIcon()`.
```php
$this
->message('Hello world!')
->footerText('Sent by Laracord')
->footerIcon('...');
```
--------------------------------
### Send Basic Message to Channel or User
Source: https://laracord.com/docs/2.x/messages
Use the `message()` method with content and `send()` or `sendTo()` to direct messages to a channel or user ID.
```php
$this
->message('Hello world!')
->send('channel-id');
```
```php
$this
->message('Hello user!')
->sendTo('user-id');
```
--------------------------------
### Basic Message Sending
Source: https://laracord.com/docs/2.x/messages
Demonstrates the fundamental usage of sending a message to a channel or a user.
```APIDOC
## Basic Message Sending
### Description
Sends a simple text message to a specified channel or user.
### Method
```php
$this->message(string $content)
```
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Usage Examples
```php
$this
->message('Hello world!')
->send('channel-id');
$this
->message('Hello user!')
->sendTo('user-id');
```
```
--------------------------------
### Generate Livewire Message Component
Source: https://laracord.com/docs/2.x/livewire
Create a new Livewire component named 'Message' using the `make:livewire` console command.
```bash
$ php laracord make:livewire Message
```
--------------------------------
### Define Route for Livewire Component
Source: https://laracord.com/docs/2.x/livewire
Create a route for the 'Message' Livewire component within your `app/Bot.php` file. It's recommended to protect routes with authentication middleware.
```php
group(function () {
Route::get('/message', Message::class);
});
}
}
```
--------------------------------
### Provide Static Autocomplete Choices
Source: https://laracord.com/docs/2.x/slash-commands
Use a simple array of strings for basic autocomplete options. Laracord automatically generates slugs for these choices.
```php
/**
* Set the autocomplete choices.
*/
public function autocomplete(): array
{
return [
'set.channel.id' => [
'00000',
'11111',
],
];
}
```
--------------------------------
### Create a Ping Command in Laracord
Source: https://laracord.com/
This command responds to 'ping' with 'Pong!' and displays the response time. It also includes an interactive button that triggers another interaction.
```php
message('Ping? Pong!')
->title('Ping')
->field('Response time', $message->timestamp->diffForHumans(null, true))
->button('Laracord Resources', route: 'resources', emoji: '💻', style: Button::STYLE_SECONDARY)
->reply($message);
}
/**
* The command interaction routes.
*/
public function interactions(): array
{
return [
'resources' => fn (Interaction $interaction) => $this
->message('Check out the resources below to learn more about Laracord.')
->title('Laracord Resources')
->buttons([
'Documentation' => 'https://laracord.com',
'GitHub' => 'https://github.com/laracord/laracord',
])
->reply($interaction, ephemeral: true),
];
}
}
```
--------------------------------
### Provide Labeled Autocomplete Choices
Source: https://laracord.com/docs/2.x/slash-commands
To control the displayed label and the actual value sent, use key-value pairs in your autocomplete array. This allows for more user-friendly options.
```php
public function autocomplete(): array
{
return [
'set.channel.id' => [
'General Chat' => '00000',
'Staff Chat' => '11111'
],
];
}
```
--------------------------------
### Send a Message Using an Existing Webhook
Source: https://laracord.com/docs/2.x/messages
Send a message using a pre-existing webhook by providing its URL to the `webhook` method. This requires the bot to have webhook permissions.
```PHP
$this
->message('Hello world')
->webhook('https://discord.com/api/webhooks/...')
->send($channel);
```
--------------------------------
### Generate an Event Handler with Laracord CLI
Source: https://laracord.com/docs/2.x/events
Use the `laracord make:event` command to generate a new event handler class. You will be prompted to select a Discord listener from a searchable list.
```bash
$ php laracord make:event Example
```
--------------------------------
### Access Console Instance via App Container
Source: https://laracord.com/docs/2.x/state
Retrieve the console instance from outside a Laracord-extended class by accessing the bot instance through the application container.
```php
$console = app('bot')->console();
```
--------------------------------
### Retrieve All Slash Command Option Values
Source: https://laracord.com/docs/2.x/slash-commands
To retrieve all flattened option values passed to a command, call the `value()` method without any arguments.
```php
$values = $this->value();
```
--------------------------------
### Send Command Response Directly to User
Source: https://laracord.com/docs/2.x/commands
Modify the `handle` method to use `sendTo($message->author)` to direct the bot's response to the message author instead of the channel.
```php
return $this
->message()
->title('Example')
->content('Hello world!')
->sendTo($message->author);
```
--------------------------------
### Reply to a Message or Interaction
Source: https://laracord.com/docs/2.x/messages
To reply to a user's input, use the `reply()` method, which requires an existing message or interaction context.
```php
$this
->message('Hello to you!')
->reply($message|$interaction);
```
--------------------------------
### Laracord Directory Structure
Source: https://laracord.com/docs/2.x/structure
This tree displays the standard directory structure for a Laracord project, highlighting the placement of Discord commands and console commands.
```tree
.
├── app
│ ├── Commands
│ ├── Console
│ │ └── Commands
│ ├── Events
│ ├── Models
│ ├── Providers
│ │ └── BotServiceProvider.php
│ ├── Services
│ ├── SlashCommands
│ └── Bot.php
├── bootstrap
│ └── app.php
├── config
│ ├── app.php
│ └── discord.php
├── database
│ └── migrations
└── laracord
```
--------------------------------
### Handle Select Menu Interactions
Source: https://laracord.com/docs/2.x/messages
Define an interaction handler for a select menu route. The selected values are available as an array in `$interaction->data->values`.
```PHP
public function interactions(): array
{
return [
'selectFruit' => fn (Interaction $interaction) => $interaction->acknowledge() && dump($interaction->data->values),
];
}
```
--------------------------------
### Access Bot Instance via Getter
Source: https://laracord.com/docs/2.x/state
When inside a class that extends Laracord, use the `bot()` getter to access the bot instance.
```php
$bot = $this->bot();
```
--------------------------------
### Add Bot Admin
Source: https://laracord.com/docs/2.x/installation
Use the 'bot:admin' command to designate a Discord user as an administrator by providing their Discord ID.
```bash
$ php laracord bot:admin
```
--------------------------------
### Create a Timed Task in ReactPHP
Source: https://laracord.com/
Define a timed task to run at a specific interval within the ReactPHP event loop. Set the interval in seconds and whether the task should run eagerly on boot.
```php
message('Hello world!')
->sendTo('453364472304762881');
}
}
```
--------------------------------
### Generate New Command with Laracord CLI
Source: https://laracord.com/docs/2.x/commands
Use the `laracord make:command` Artisan command to generate a new command class file.
```bash
$ php laracord make:command ExampleCommand
```
--------------------------------
### Replying to Messages/Interactions
Source: https://laracord.com/docs/2.x/messages
Shows how to reply to an existing message or interaction, enhancing user experience.
```APIDOC
## Replying to Messages/Interactions
### Description
Replies to a specific message or interaction, maintaining conversational context.
### Method
```php
$this->message(string $content)->reply($message|$interaction)
```
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Usage Examples
```php
$this
->message('Hello to you!')
->reply($message|$interaction);
```
```
--------------------------------
### Set Author Information
Source: https://laracord.com/docs/2.x/messages
Configure the author section of the embed with name, icon, and URL using `authorName()`, `authorIcon()`, and `authorUrl()`.
```php
$this
->message('Hello world!')
->authorName('Laracord')
->authorIcon('...')
->authorUrl('...');
```
--------------------------------
### Register Context Menu to a Specific Guild
Source: https://laracord.com/docs/2.x/context-menus
Set the `$guild` property to a guild ID to restrict the context menu's availability to that specific server.
```php
/**
* The guild the context menu belongs to.
*
* @var string
*/
protected $guild = 'your-guild-id';
```
--------------------------------
### Create Slash Command with Laracord CLI
Source: https://laracord.com/docs/2.x/slash-commands
Use the `laracord make:slash-command` command to generate a new slash command file.
```bash
$ php laracord make:slash-command ExampleCommand
```
--------------------------------
### Add Mentions or Body Content
Source: https://laracord.com/docs/2.x/messages
Use `body()` to include mentions like '@everyone' above the embed, or to send a message without an embed.
```php
$this
->message('Hello world!')
->body('@everyone');
```
```php
$this
->message()
->body('Hello world!');
```
--------------------------------
### Setting Author Information
Source: https://laracord.com/docs/2.x/messages
Configures the author's name, icon, and URL for the embed.
```APIDOC
## Setting Author Information
### Description
Sets the author's name, icon URL, and URL for the embed. By default, Laracord uses the bot's username and avatar.
### Method
```php
$this->message(string $content)->authorName(string $name)
$this->message(string $content)->authorIcon(string $url)
$this->message(string $content)->authorUrl(string $url)
```
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Usage Examples
```php
$this
->message('Hello world!')
->authorName('Laracord')
->authorIcon('...')
->authorUrl('...');
```
```
--------------------------------
### Setting Thumbnail URL
Source: https://laracord.com/docs/2.x/messages
Specifies a URL for a thumbnail image in the embed.
```APIDOC
## Setting Thumbnail URL
### Description
Sets the URL for a thumbnail image that appears to the right of the embed content.
### Method
```php
$this->message(string $content)->thumbnailUrl(string $url)
```
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Usage Examples
```php
$this
->message('Hello world!')
->thumbnailUrl('...');
```
```
--------------------------------
### Retrieve Slash Command Option Values (Dot Notation)
Source: https://laracord.com/docs/2.x/slash-commands
Access nested command option values within the handler using dot notation. The `value()` method safely returns `null` if an option is not found.
```php
use Discord\Parts\Interactions\Command\Option;
protected $options = [
[
'name' => 'set',
'description' => 'Manage the ticket system.',
'type' => Option::SUB_COMMAND_GROUP,
'options' => [
[
'name' => 'channel',
'description' => 'Set the ticket channel.',
'type' => Option::SUB_COMMAND,
'options' => [
[
'name' => 'id',
'description' => 'The channel ID.',
'type' => Option::STRING,
'required' => true,
],
],
],
],
],
];
$id = $this->value('set.channel.id', $default = null);
```
--------------------------------
### Flush All Cache
Source: https://laracord.com/docs/2.x/cache
Remove all items from the cache using the `flush()` method.
```php
cache()->flush();
```
--------------------------------
### Hide Command from Help Output
Source: https://laracord.com/docs/2.x/commands
Set the `$hidden` property to `true` within a command class to prevent it from appearing in the default `!help` command output.
```php
/**
* Indicates whether the command should be displayed in the commands list.
*
* @var bool
*/
protected $hidden = true;
```
--------------------------------
### Set Thumbnail URL
Source: https://laracord.com/docs/2.x/messages
Add a thumbnail image to the right of the embed using the `thumbnailUrl()` method.
```php
$this
->message('Hello world!')
->thumbnailUrl('...');
```
--------------------------------
### Remember Cache Item Forever with Callback
Source: https://laracord.com/docs/2.x/cache
Retrieve a cached item or cache the result of a callback if the item does not exist, using `rememberForever()`.
```php
$remember = cache()->rememberForever('key', fn () => ['hello', 'world']);
```
--------------------------------
### Create Livewire Message Component
Source: https://laracord.com/docs/2.x/livewire
This PHP code defines a Livewire component for sending messages. It uses the HasLaracord trait to access bot functionalities and includes properties for user selection, message content, and a locked list of members. Basic validation and session flashing are implemented for a smooth user experience.
```php
members = collect($this->discord()->users->map(fn ($user) => [
'id' => $user->id,
'username' => $user->username,
]))->keyBy('id');
return view('livewire.message');
}
/**
* Send a message to the selected user.
*
* @return void
*/
public function sendMessage()
{
$this->validate([
'user' => 'required',
'message' => 'required|min:3|max:150',
]);
if (! $this->members->has($this->user)) {
$this->addError('user', 'The selected user does not exist.');
return;
}
$this
->message($this->message)
->sendTo($this->user);
$this->reset('message');
session()->flash('success', 'The message has been sent.');
}
}
```
--------------------------------
### Set Context Menu Type to User
Source: https://laracord.com/docs/2.x/context-menus
Change the `$type` property to `user` to make the context menu appear when right-clicking a user instead of a message.
```php
/**
* The context menu type.
*/
protected string|int $type = 'user';
```
--------------------------------
### Access Console Instance via Getter
Source: https://laracord.com/docs/2.x/state
Use the `console()` getter within a Laracord-extended class to access the console instance for logging or other console-related operations.
```php
$this->console()->log('Hello world!');
```
--------------------------------
### Sending Messages via Service
Source: https://laracord.com/docs/2.x/services
Services can send messages to Discord channels or users. Obtain channel or user instances using the `discord()` instance before sending.
```php
$channel = $this->discord()->getChannel('your-channel-id');
$this
->message()
->content('Hello world.')
->send($channel);
```
```php
$user = $this->discord()->users->get('id', 'a-user-id');
$this
->message()
->content('Hello world.')
->sendTo($user);
```
--------------------------------
### Store Cache Item Forever
Source: https://laracord.com/docs/2.x/cache
Cache a key indefinitely using the `forever()` method.
```php
$forever = cache()->forever('key', 'value');
```
--------------------------------
### Setting Embed Footer Text
Source: https://laracord.com/docs/2.x/messages
Adds text to the footer of the embed.
```APIDOC
## Setting Embed Footer Text
### Description
Sets the text that appears in the footer of the embed.
### Method
```php
$this->message(string $content)->footerText(string $text)
```
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Usage Examples
```php
$this
->message('Hello world!')
->footerText('Sent by Laracord');
```
```
--------------------------------
### Setting Message Title
Source: https://laracord.com/docs/2.x/messages
Configures the title for the message embed.
```APIDOC
## Setting Message Title
### Description
Sets the title for the message embed.
### Method
```php
$this->message(string $content)->title(string $title)
```
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Usage Examples
```php
$this
->message('Hello world!')
->title('Example');
```
```
--------------------------------
### Set Message Color and Type
Source: https://laracord.com/docs/2.x/messages
Override the default embed color using `color()` with a decimal value, or use helper methods like `success()`, `error()`, `warning()`, and `info()`.
```php
$this
->message('Hello world!')
->color('3066993')
->success()
->error()
->warning()
->info();
```
--------------------------------
### Add a link button with a custom emoji
Source: https://laracord.com/docs/2.x/messages
Use custom server emojis for link buttons by providing the emoji name and ID as a string.
```php
$this
->message('Hello world!')
->button('Visit Laracord', 'https://laracord.com', emoji: ':laracord:1204740745286656050');
```
--------------------------------
### Setting Embed Footer Icon
Source: https://laracord.com/docs/2.x/messages
Adds an icon to the footer of the embed.
```APIDOC
## Setting Embed Footer Icon
### Description
Sets the icon URL for the footer of the embed.
### Method
```php
$this->message(string $content)->footerIcon(string $url)
```
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Usage Examples
```php
$this
->message('Hello world!')
->footerIcon('...');
```
```
--------------------------------
### Access Bot Instance via App Container
Source: https://laracord.com/docs/2.x/state
Retrieve the Laracord bot instance globally using the application container. This is useful when not within a Laracord-extended class.
```php
$bot = app('bot');
```
--------------------------------
### Add a group of fields to a message
Source: https://laracord.com/docs/2.x/messages
Use the `->fields()` method to pass an array of fields at once. This is useful for managing multiple fields together.
```php
$this
->message('Hello world!')
->fields([
'Field 1' => 'Value 1',
'Field 2' => 'Value 2',
]);
```