log > TumblrのRSSを書き換えて元のURLへリンクする
TumblrのRSSを書き換えて元のURLへリンクする
書いた。tumblr/tumblr.phpを使用した。
- Tumblrにアプリを登録
- API Consoleで、API Keyを取得
composer require tumblr/tumblr
- 以下のコード+定数の設定ファイルを書いて、デプロイ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Filter | |
{ | |
private $default_remove_tags = [ | |
'炎上' | |
]; | |
private $default_remove_titles = [ | |
'2ch', | |
'w', | |
'速' | |
]; | |
public function isRemoveTitle ($title, $remove_titles = null) | |
{ | |
if ($remove_titles === null) { | |
$remove_titles = $this->default_remove_titles; | |
} | |
foreach ($remove_titles as $r_title) { | |
$result = preg_match('/'.$r_title.'/isu', $title); | |
if (boolval($result)) { | |
return true; | |
} | |
} | |
} | |
public function isRemoveTag ($tags, $remove_tags = null) | |
{ | |
if ($remove_tags === null) { | |
$remove_tags = $this->default_remove_tags; | |
} | |
foreach ($remove_tags as $r_tag) { | |
foreach ($tags as $tag) { | |
$result = preg_match('/'.$r_tag.'/isu', $tag); | |
if (boolval($result)) { | |
return true; | |
} | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require 'vendor/autoload.php'; | |
require 'config.php'; | |
require 'filter.php'; | |
// Authenticate via API Key | |
$client = new Tumblr\API\Client(TUMBLR_API_KEY); | |
// Make the request | |
$response = $client->getBlogPosts(BLOG_URL, array('type' => 'link')); | |
$posts = $response->posts; | |
$xml_str = <<< XML_STR | |
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"> | |
<channel> | |
<description>BLOG_DESCRIPTION</description> | |
<title>BLOG_TITLE</title> | |
<generator>Tumblr (3.0; @BLOG_TITLE)</generator> | |
<link>http://BLOG_URL/</link> | |
</channel> | |
</rss> | |
XML_STR; | |
$xml = new SimpleXmlElement($xml_str); | |
$filter = new Filter(); | |
foreach ($posts as $post) { | |
if ($filter->isRemoveTitle($post->title) || $filter->isRemoveTag($post->tags)) { | |
continue; | |
} | |
$item = $xml->channel->addChild('item'); | |
$item->addChild('title', $post->title); | |
$item->addChild('description', $post->description); | |
$item->addChild('link', $post->url); | |
$item->addChild('guid', $post->url); | |
$item->addChild('pubDate', $post->date); | |
foreach ($post->tags as $tag) { | |
$item->addChild('category', $tag); | |
} | |
} | |
header("Content-type: text/xml;charset=utf-8"); | |
echo $xml->asXML(); |
Tumblrにbotがリンクを投稿しているので、それを読んでいる。だが、そのサイトのRSSをTwitterに流したら”xxxx.tumblr.com”のURLがツイートされた。昔は元のURLも含まれていた気がしたのだが、気のせいだったかもしれない。いずれにしても元のURLでツイートしないと気まずいので、RSSを書き換えて、IFTTTで連携することにした。