feat(x): optional X API v2 recent search in listen mode

- config/social.example.json + loadSocialConfig; social.json gitignored.
- fetchXAsArticles merges tweets with RSS before keyword filter.
- x:test / npm run x:test probes queries + bearer token.

Made-with: Cursor
This commit is contained in:
David Santos committed 2026-03-24 21:41:35 +00:00
1 parent d31e158b84
commit 560ad9716f
8 files changed
+224 -5

No files matched your search

+1
View File
@@ -4,4 +4,5 @@ logs/
*.log
config/sites/*.json
!config/sites/example.json
config/social.json
.DS_Store
+8 -1
View File
@@ -29,6 +29,7 @@ node src/index.js write "FC Porto match result"
| `npm run verify:deploy -- <url>` | Smoke-test `GET /health` (expects `listen` mode); needs `curl` + `node` |
| `npm run wp:test` | `GET /wp-json/wp/v2/users/me` — validates **every** `config/sites/*.json` (excl. example), or `WP_*` env if no site files |
| `npm run rss:test` | Probe each RSS URL in `config/sources.json` (3 attempts, backoff); stdout `{ "ok", "feeds" }`; exit 1 if any feed fails |
| `npm run x:test` | X API v2 **recent search** for each `x.queries[]` in `config/social.json`; needs `TWITTER_BEARER_TOKEN` |
| `npm run ops:check` | **`rss:test` always**; **`wp:test` only** if `config/sites/*.json` (≠ example) or `WP_URL`+`WP_USER`+`WP_PASSWORD` |
| `npm start` | Same as `write` |
| `npm run dev` | Auto-restart with nodemon |
@@ -50,11 +51,13 @@ RSS Feeds / News Sites
**Listener / auto mode:**
```
src/listener/rss-listener.js — cron-based RSS polling
src/listener/rss-listener.js — cron-based RSS polling (+ optional X recent search)
↓
detectTopics() → generateArticle() → publishToWordPress()
```
**X (Twitter) — optional:** copy `config/social.example.json` → `config/social.json`, set `TWITTER_BEARER_TOKEN` in `.env`. In `listen` mode, tweets are merged with RSS before keyword filtering. Uses [X API v2 recent search](https://developer.twitter.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent) (plan limits apply).
## Configuration
### Sources (`config/sources.json`)
@@ -62,6 +65,9 @@ Edit to add/remove RSS feeds, keywords, and trusted domains.
`npm run rss:test` walks every `rss[]` entry with the same retry logic as the crawler; stdout is `{ "ok": boolean, "feeds": [ { "ok", "name", "url", "item_count", "error" } ] }`.
Default URLs are chosen for stability; publishers change endpoints often — if probes fail, swap the entry for a working RSS URL and re-run `rss:test`.
### Social — X (`config/social.json`, gitignored)
Copy `config/social.example.json` → `config/social.json`. Define `x.queries` (recent-search strings, max 512 chars each per X rules) and optional `max_results_per_query` (10–100). Requires `TWITTER_BEARER_TOKEN`. Run `npm run x:test` to validate credentials and queries.
### Sites (`config/sites/*.json`)
One JSON file per WordPress target site. Copy `config/sites/example.json`.
Credentials come from your vault — never commit real passwords.
@@ -97,6 +103,7 @@ Credentials come from your vault — never commit real passwords.
| `RSS_TIMEOUT_MS` | Per-feed HTTP timeout for `rss-parser` (default 10000, max 120000) |
| `RSS_FETCH_CONCURRENCY` | Parallel RSS fetches in `fetchAllFeeds` (default 3, max 20) |
| `SCRAPER_TIMEOUT_MS` | Article scrape timeout (default 12000, max 120000) |
| `TWITTER_BEARER_TOKEN` | X API v2 bearer (optional; required when using `social.json` + listen mode) |
## Article output format
+8
View File
@@ -0,0 +1,8 @@
{
"x": {
"queries": [
"(FC Porto OR Benfica OR Sporting) (football OR futebol) -is:retweet lang:pt"
],
"max_results_per_query": 10
}
}
+1
View File
@@ -12,6 +12,7 @@
"verify:deploy": "bash tools/verify-deploy.sh",
"wp:test": "node src/index.js wp:test",
"rss:test": "node src/index.js rss:test",
"x:test": "node src/index.js x:test",
"ops:check": "bash tools/ops-check.sh",
"test": "node --test src/**/*.test.js"
},
+12 -1
View File
@@ -51,4 +51,15 @@ function loadDefaultSiteConfig() {
};
}
module.exports = { loadSources, loadSiteConfigs, loadDefaultSiteConfig };
/**
* Optional X (Twitter) recent-search queries — copy social.example.json → social.json.
*/
function loadSocialConfig() {
const social_path = path.join(ROOT, 'config', 'social.json');
if (!fs.existsSync(social_path)) {
return { x: { queries: [], max_results_per_query: 10 } };
}
return JSON.parse(fs.readFileSync(social_path, 'utf8'));
}
module.exports = { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadSocialConfig };
+165
View File
@@ -0,0 +1,165 @@
'use strict';
const axios = require('axios');
const logger = require('../logger');
const X_SEARCH_URL = 'https://api.twitter.com/2/tweets/search/recent';
const DEFAULT_UA = 'ai-news-writer/0.1 (+https://bitreport.pt)';
function maxResultsClamped(raw) {
const n = parseInt(raw ?? 10, 10);
if (!Number.isFinite(n)) {
return 10;
}
return Math.min(100, Math.max(10, n));
}
/**
* @param {string} bearer
* @param {string} query
* @param {number} max_results
* @returns {Promise<object[]>} tweet objects from X API v2
*/
async function searchRecentRaw(bearer, query, max_results) {
const url = new URL(X_SEARCH_URL);
url.searchParams.set('query', query);
url.searchParams.set('max_results', String(max_results));
url.searchParams.set('tweet.fields', 'created_at,author_id');
const response = await axios.get(url.toString(), {
timeout: 20000,
headers: {
Authorization: `Bearer ${bearer}`,
'User-Agent': process.env.HTTP_USER_AGENT || DEFAULT_UA,
},
validateStatus: () => true,
});
if (response.status === 429) {
throw new Error('rate limited (429)');
}
if (response.status !== 200) {
const detail =
response.data?.errors?.[0]?.detail ||
response.data?.errors?.[0]?.message ||
response.data?.title ||
response.statusText ||
'unknown error';
throw new Error(`HTTP ${response.status}: ${detail}`);
}
return Array.isArray(response.data?.data) ? response.data.data : [];
}
function tweetToArticle(tweet, query) {
const id = tweet.id;
const text = tweet.text || '';
const created = tweet.created_at ? new Date(tweet.created_at).toISOString() : new Date().toISOString();
const title = text.length > 120 ? `${text.slice(0, 117)}...` : text;
return {
source: 'x',
source_url: query,
category: 'social',
lang: 'und',
title,
link: `https://twitter.com/i/web/status/${id}`,
summary: text,
content: '',
published_at: created,
guid: `x:${id}`,
};
}
/**
* Optional X (Twitter) recent search → same article shape as RSS.
* Requires TWITTER_BEARER_TOKEN and config/social.json (copy from social.example.json).
*
* @param {object} social_config
* @returns {Promise<object[]>}
*/
async function fetchXAsArticles(social_config) {
const bearer = (process.env.TWITTER_BEARER_TOKEN || '').trim();
const queries = social_config?.x?.queries;
if (!bearer) {
logger.debug('X: TWITTER_BEARER_TOKEN not set — skipping social fetch');
return [];
}
if (!Array.isArray(queries) || queries.length === 0) {
return [];
}
const max_results = maxResultsClamped(social_config?.x?.max_results_per_query);
const articles = [];
for (let i = 0; i < queries.length; i++) {
const query = queries[i];
if (!query || typeof query !== 'string') {
continue;
}
try {
const tweets = await searchRecentRaw(bearer, query, max_results);
for (const tweet of tweets) {
articles.push(tweetToArticle(tweet, query));
}
} catch (err) {
logger.warn(`X search failed [${query.slice(0, 80)}]: ${err.message}`);
}
if (i < queries.length - 1) {
await new Promise((resolve) => setTimeout(resolve, 1100));
}
}
if (articles.length > 0) {
logger.info(`X: normalized ${articles.length} tweets from ${queries.length} queries`);
}
return articles;
}
/**
* Structured probe for CLI (x:test).
* @param {object} social_config
* @returns {Promise<{ ok: boolean, queries: object[], total_tweets: number }>}
*/
async function probeXQueries(social_config) {
const bearer = (process.env.TWITTER_BEARER_TOKEN || '').trim();
const queries = social_config?.x?.queries || [];
if (queries.length === 0) {
return {
ok: false,
queries: [],
total_tweets: 0,
error: 'No x.queries — copy config/social.example.json to config/social.json',
};
}
if (!bearer) {
return { ok: false, queries: [], total_tweets: 0, error: 'TWITTER_BEARER_TOKEN is not set' };
}
const max_results = maxResultsClamped(social_config?.x?.max_results_per_query);
const rows = [];
let total = 0;
for (let i = 0; i < queries.length; i++) {
const query = queries[i];
if (!query || typeof query !== 'string') {
rows.push({ query: String(query), ok: false, count: 0, error: 'invalid query' });
continue;
}
try {
const tweets = await searchRecentRaw(bearer, query, max_results);
total += tweets.length;
rows.push({ query, ok: true, count: tweets.length, error: null });
} catch (err) {
rows.push({ query, ok: false, count: 0, error: err.message });
}
if (i < queries.length - 1) {
await new Promise((resolve) => setTimeout(resolve, 1100));
}
}
return { ok: rows.every((r) => r.ok), queries: rows, total_tweets: total };
}
module.exports = { fetchXAsArticles, probeXQueries };
+17 -1
View File
@@ -9,7 +9,8 @@ const { generateArticle, detectTopics } = require('./writer/ai');
const { publishToWordPress, testConnection } = require('./publisher/wordpress');
const { startRSSListener } = require('./listener/rss-listener');
const { startStatusServer } = require('./http/status-server');
const { loadSources, loadSiteConfigs, loadDefaultSiteConfig } = require('./config/loader');
const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadSocialConfig } = require('./config/loader');
const { probeXQueries } = require('./crawler/x');
const fs = require('fs');
const path = require('path');
@@ -71,6 +72,17 @@ async function runManualWrite(topic) {
return article;
}
async function runXTest() {
const social = loadSocialConfig();
const result = await probeXQueries(social);
if (result.error) {
logger.error(`x:test — ${result.error}`);
process.exit(1);
}
console.log(JSON.stringify({ ok: result.ok, total_tweets: result.total_tweets, queries: result.queries }));
process.exit(result.ok ? 0 : 1);
}
async function runRssTest() {
const sources_config = loadSources();
const feeds = sources_config.rss || [];
@@ -220,12 +232,16 @@ async function main() {
} else if (command === 'rss:test') {
await runRssTest();
process.exit(0);
} else if (command === 'x:test') {
await runXTest();
process.exit(0);
} else {
console.log('Usage:');
console.log(' node src/index.js write [topic] — write one article (exits)');
console.log(' node src/index.js listen — RSS listener + HTTP on HOST:PORT (/, /health)');
console.log(' node src/index.js wp:test — verify WP REST + application password (exits)');
console.log(' node src/index.js rss:test — probe all RSS feeds in sources.json (exits)');
console.log(' node src/index.js x:test — probe X API v2 recent search (needs social.json + TWITTER_BEARER_TOKEN)');
process.exit(1);
}
}
+12 -2
View File
@@ -2,6 +2,8 @@
const cron = require('node-cron');
const { fetchAllFeeds, filterByKeywords } = require('../crawler/rss');
const { fetchXAsArticles } = require('../crawler/x');
const { loadSocialConfig } = require('../config/loader');
const logger = require('../logger');
let _last_seen_guids = new Set();
@@ -21,8 +23,16 @@ function startRSSListener(sources, cron_expr, on_new_articles) {
const task = cron.schedule(schedule, async () => {
try {
const all_articles = await fetchAllFeeds(sources);
const filtered = filterByKeywords(all_articles, sources.keywords);
const articles_rss = await fetchAllFeeds(sources);
let articles_x = [];
try {
articles_x = await fetchXAsArticles(loadSocialConfig());
} catch (err) {
logger.warn(`X listener aggregate error: ${err.message}`);
}
const merged = [...articles_rss, ...articles_x];
merged.sort((a, b) => new Date(b.published_at) - new Date(a.published_at));
const filtered = filterByKeywords(merged, sources.keywords);
const new_articles = filtered.filter((a) => !_last_seen_guids.has(a.guid));