Skip to content

Instantly share code, notes, and snippets.

@wokamoto
Last active February 4, 2021 10:27
Show Gist options
  • Save wokamoto/483ba4bc0000fb50fa1a076d98764ac5 to your computer and use it in GitHub Desktop.
Save wokamoto/483ba4bc0000fb50fa1a076d98764ac5 to your computer and use it in GitHub Desktop.
'use strict';
const lastUpdateFileName = './lastupdate.txt';
const feedUrl = 'https://example.com/rss';
const typetalkTopicNum = '__TYPETALK_TOPIC_NUMBER_HERE__';
const typetalkToken = '__TYPETALK_TOKEN_HERE__'
const fs = require('fs');
const FeedParser = require('feedparser');
const https = require('https');
const moment = require('moment');
let lastUpdate = moment('1970-01-01 00:00:00');
let feedDate = moment('1970-01-01 00:00:00');
let feedMeta;
let items = [];
function isExistFile(file) {
try {
fs.statSync(file);
return true
} catch(err) {
if(err.code === 'ENOENT') return false
}
}
if ( isExistFile(lastUpdateFileName) ) {
lastUpdate = moment(fs.readFileSync(lastUpdateFileName, 'utf-8'));
}
// 指定urlにhttpリクエストする
https.get(feedUrl, function(res) {
//レスポンスにフィードパーサをパイプで渡す
res.pipe(new FeedParser({}))
.on('error', function(error) {
console.log('message: HTTP failure while fetching feed');
})
.on('meta', function(meta) {
feedMeta = meta;
})
.on('readable', function() {
var stream = this, item;
// chunkデータを保存する
while (item = stream.read()) {
var pubDate = moment(item.pubDate);
if ( pubDate.isAfter(lastUpdate) ) {
items.push({
title: item.title,
summary: item.summary,
date: pubDate.format('YYYY-MM-DD HH:mm:ss'),
link: item.permalink
});
}
if ( pubDate.isAfter(feedDate) ) {
feedDate = pubDate;
}
}
})
.on('end', function() {
fs.writeFileSync(lastUpdateFileName, feedDate.format('YYYY-MM-DD HH:mm:ss'));
items.forEach( item => {
console.log(`${item.title} (${item.date})`);
let postDataStr = `message=${item.title} (${item.date})\n${item.link}\n\n${item.summary}`;
let options = {
host: 'typetalk.com',
port: 443,
path: `/api/v1/topics/${typetalkTopicNum}`,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postDataStr),
'X-TYPETALK-TOKEN': typetalkToken
}
};
let req = https.request(options, (res) => {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', (chunk) => { console.log('BODY: ' + chunk); });
});
req.on('error', (e) => {
console.log('problem with request: ' + e.message);
});
req.write(postDataStr);
req.end();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment