Files
rocket-chat-php-scripts/koozali-channel-message.php
2025-09-02 14:27:20 +02:00

74 lines
2.1 KiB
PHP

<?php
// https://github.com/alekseykuleshov/rocket-chat
/**
* Send a message to a public channel
*/
use Dotenv\Dotenv;
require 'vendor/autoload.php';
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
$dotenv->required(['SERVER_HOST', 'SERVER_USER', 'SERVER_PASS']);
$server = $_SERVER['SERVER_HOST'];
$user = $_SERVER['SERVER_USER'];
$pass = $_SERVER['SERVER_PASS'];
// Firstly, init
\ATDev\RocketChat\Chat::setUrl($server); // No trailing / on the https://host.domain
// Now, login
$result = \ATDev\RocketChat\Chat::login($user, $pass);
if (!$result) {
// Log the error
$error = \ATDev\RocketChat\Chat::getError();
// And out
} else {
// Do something
$myText = "OK - upgraded to 7.9.3 after a few wriggles with docker";
// All Rooms are converted to hyphenated
$channelID = "smestuff";
$channelID = strtolower($channelID);
$myUserId = $result->getUserId();
$listing = \ATDev\RocketChat\Channels\Channel::listing();
if (!$listing) {
// Log the error
$error = \ATDev\RocketChat\Channels\Channel::getError();
// Bail and logout
} else {
foreach ($listing as $channel) {
$mychannel = strtolower($channel->getName());
//echo $channel->getName() . "<br>";
//$myRoomId = $channel->getRoomId();
echo "my channel $mychannel - ChannelId $channelID \n";
if ($mychannel == $channelID) {
// Send a message
$myChannelId = $channel->getChannelId();
echo "ID = $myChannelId\n";
$message = new \ATDev\RocketChat\Messages\Message();
// Always a Message->RoomID - use either group or channelID from above
$message->setRoomId($myChannelId);
$message->setText($myText);
$messageresult = $message->postMessage();
if (!$messageresult) {
// Log the error
$error = $message->getError();
}
}
}
$result = \ATDev\RocketChat\Chat::logout();
}
// Never logged in or has logged out
}