mattermost-bot/index.php

85 lines
1.8 KiB
PHP

<?php
chdir(__DIR__);
$options = getopt('c:');
$config = parse_ini_file($options['c'] ?? 'config.ini', true);
$debug = (bool) ($config['debug'] ?? false);
$feedUrl = $config['feed']['url'];
$hookUrl = $config['mattermost']['hook_url'];
$cacheFile = $config['cache']['file'];
$template = $config['mattermost']['message_template'];
$cache = [];
$commands = [];
if (file_exists($cacheFile)) {
$cache = json_decode(file_get_contents($cacheFile), true);
if (null === $cache) {
$cache = [];
}
}
$xml = simplexml_load_file($feedUrl);
$entries = array_merge($xml->xpath('//entry'), $xml->xpath('//item'));
foreach ($entries as $entry) {
$title = (string) $entry->title;
$url = null;
foreach ($entry->link as $link) {
if (null !== $url) {
continue;
}
$attributes = $link->attributes();
$content = (string) $link;
$href = (string) ($attributes['href'] ?? '');
$type = (string) ($attributes['type'] ?? '');
if ('' !== $type && 'text/html' !== $type) {
continue;
}
if ('' !== $href) {
$url = $href;
} elseif ('' !== $content) {
$url = $content;
}
}
if (empty($url)) {
continue;
}
$hash = md5($title.$url);
if (!isset($cache[$hash])) {
$cache[$hash] = true;
$json = json_encode([
'text' => sprintf($template, $title, $url),
]);
$commands[] = sprintf(
'curl -i -X POST -H "Content-Type: application/json" -d %s %s',
escapeshellarg($json),
escapeshellarg($hookUrl)
);
}
}
if (!$debug) {
file_put_contents($cacheFile, json_encode($cache));
}
foreach ($commands as $command) {
if ($debug) {
echo $command, "\n";
} else {
shell_exec($command);
}
}