Skip to content

MessageManager

Class  ·  Sharkord\Managers\MessageManager

Class MessageManager

Manages message cache interactions, delegating all cache storage and eviction to a Messages collection instance.

Accessible via $sharkord->messages.

// Retrieve a cached message without an API call
$message = $sharkord->messages->getFromCache(609);
// Iterate all cached messages
foreach ($sharkord->messages->collection() as $id => $message) {
echo "{$id}: {$message->content}\n";
}
// Fetch messages from a channel by ID
$sharkord->messages->get(channelId: 12, limit: 25)
->then(function(array $messages) {
foreach ($messages as $message) {
echo "{$message->author->name}: {$message->content}\n";
}
});

MessageManager constructor.

Parameters

ParameterTypeDescription
$sharkordSharkordThe main bot instance.
$maxCacheSize (optional)intMaximum number of messages to hold in memory at once. Passed through to the underlying Messages collection. Defaults to 500.

Retrieves a cached message by ID without hitting the API.

Parameters

ParameterTypeDescription
$id`intstring`

Returns \Message|null — The cached Message model, or null if not found.

Example

$message = $sharkord->messages->getFromCache(609);
if ($message) {
echo $message->content;
}

Returns the underlying Messages collection.

Useful when you want to iterate, count, or array-access the cache directly.

Returns \MessagesCollection

Example

foreach ($sharkord->messages->collection() as $id => $message) {
echo "{$id}: {$message->content}\n";
}
echo count($sharkord->messages->collection());

Returns the number of messages currently held in the cache.

Returns int

Example

echo "Cached messages: " . $sharkord->messages->count() . "\n";

Fetches messages from a channel via the API.

Uses the messages.get RPC. If a targetMessageId is provided the server returns the 20 messages before it plus all newer messages regardless of limit — this enables an efficient index-20 fast path for history traversal. All returned messages are merged into the local cache.

Parameters

ParameterTypeDescription
$channelIdintThe ID of the channel to fetch from.
$limit (optional)intMaximum number of messages to return. Defaults to 50.
$targetMessageId (optional)?intIf set, fetches messages relative to this message ID.

Returns \PromiseInterface — Resolves with an array of Message models, rejects on failure.

Example

// Fetch the latest 50 messages in a channel
$sharkord->messages->get(channelId: 12, limit: 50)
->then(function(array $messages) {
foreach ($messages as $message) {
echo "{$message->author->name}: {$message->content}\n";
}
});
// Fetch messages relative to a known message ID
$sharkord->messages->get(channelId: 12, targetMessageId: 609)
->then(function(array $messages) {
echo "Fetched " . count($messages) . " messages.\n";
});