Skip to content

Instantly share code, notes, and snippets.

@book000
Last active August 8, 2020 01:01
Show Gist options
  • Save book000/6be20056cc982fad2072df3816488a84 to your computer and use it in GitHub Desktop.
Save book000/6be20056cc982fad2072df3816488a84 to your computer and use it in GitHub Desktop.
ハミダシクリエイティブの新着ニュースをWebhookを通じてDiscordに通知する。
<?php
function sendDiscordWebhook($message)
{
$url = "<DISCORD WEBHOOK URL>";
$data = [
"content" => $message
];
$header = array(
"Content-Type: application/json",
"Content-Length: ".strlen(json_encode($data)),
"User-Agent: DiscordBot (http://example.com, v0.0.1)"
);
$context = array(
"http" => array(
"method" => "POST",
"header" => implode("\r\n", $header),
"content" => json_encode($data)
)
);
$context = stream_context_create($context);
file_get_contents($url, false, $context);
}
$rss_url = "http://madosoft.net/hamidashi/wp-json/wp/v2/posts?categories=3";
$str = file_get_contents($rss_url);
$json = json_decode($str, true);
if (file_exists(__DIR__ . "/hamikuri_readed.json")) {
$readed = json_decode(file_get_contents(__DIR__ . "/hamikuri_readed.json"), true);
} else {
$readed = [];
}
foreach ($json as $article) {
$id = $article["id"];
$article_link = $article["link"];
$title = $article["title"]["rendered"];
$content = $article["content"]["rendered"];
if (in_array($id, $readed)) {
continue;
}
preg_match_all("/<a href=\"(.+?)\".*>(.+?)<\/a>/", $content, $m, PREG_SET_ORDER);
$link_id = 1;
$links = [];
foreach ($m as $a_tag) {
$tag = $a_tag[0];
$link = $a_tag[1];
$text = $a_tag[2];
$text = trim($text);
if (in_array($link, $links)) {
$_link_id = array_search($link, $links);
$content = str_replace($tag, " " . $text . " [*" . $_link_id . "] ", $content);
continue;
}
$content = str_replace($tag, " " . $text . "[*" . $link_id . "] ", $content);
$links[$link_id] = $link;
$link_id++;
}
$content = strip_tags($content);
$content = trim($content);
$content .= "\n\n";
foreach ($links as $link_id => $link) {
$content .= "*" . $link_id . ": " . $link . "\n";
}
echo "[$id] $title```$content```$article_link\n";
sendDiscordWebhook(":new:__**$title**__```$content```$article_link");
$readed[] = $id;
}
file_put_contents(__DIR__ . "/hamikuri_readed.json", json_encode($readed));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment