-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #10873 from hicommonwealth/tim/twitter-poller
- Loading branch information
Showing
20 changed files
with
404 additions
and
4 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import { TwitterCursor } from '@hicommonwealth/schemas'; | ||
import Sequelize from 'sequelize'; | ||
import { z } from 'zod'; | ||
import { ModelInstance } from './types'; | ||
|
||
export type TwitterCursorAttributes = z.infer<typeof TwitterCursor>; | ||
|
||
export type TwitterCursorInstance = ModelInstance<TwitterCursorAttributes>; | ||
|
||
export default ( | ||
sequelize: Sequelize.Sequelize, | ||
): Sequelize.ModelStatic<TwitterCursorInstance> => | ||
sequelize.define<TwitterCursorInstance>( | ||
'TwitterCursor', | ||
{ | ||
bot_name: { | ||
type: Sequelize.STRING, | ||
primaryKey: true, | ||
}, | ||
last_polled_timestamp: { | ||
type: Sequelize.BIGINT, | ||
allowNull: false, | ||
}, | ||
}, | ||
{ | ||
timestamps: false, | ||
tableName: 'TwitterCursors', | ||
}, | ||
); |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import { TwitterBotName } from '@hicommonwealth/shared'; | ||
import { z } from 'zod'; | ||
|
||
export const TwitterCursor = z.object({ | ||
bot_name: z.nativeEnum(TwitterBotName), | ||
last_polled_timestamp: z.number(), | ||
}); |
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './twitter'; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import { z } from 'zod'; | ||
|
||
export const Tweet = z.object({ | ||
id: z.string(), | ||
author_id: z.string(), | ||
username: z.string(), | ||
created_at: z.string(), | ||
text: z.string().describe('The first 280 characters of the tweet'), | ||
note_tweet: z | ||
.string() | ||
.optional() | ||
.describe('The full tweet text including anything above 280 characters'), | ||
conversation_id: z.string().optional(), | ||
reply_settings: z | ||
.enum([ | ||
'everyone', | ||
'mentionedUsers', | ||
'following', | ||
'other', | ||
'subscribers', | ||
'verified', | ||
]) | ||
.optional(), | ||
}); | ||
|
||
export const TwitterMentionsTimeline = z.object({ | ||
data: z.array(Tweet), | ||
errors: z.array( | ||
z.object({ | ||
title: z.string(), | ||
type: z.string(), | ||
detail: z.string().optional(), | ||
status: z.number().optional(), | ||
}), | ||
), | ||
meta: z | ||
.object({ | ||
next_token: z.string().optional(), | ||
}) | ||
.optional(), | ||
}); |
This file contains 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
This file contains 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
This file contains 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
21 changes: 21 additions & 0 deletions
21
packages/commonwealth/server/migrations/20250207060647-add-twitter-cursors.js
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
'use strict'; | ||
|
||
/** @type {import('sequelize-cli').Migration} */ | ||
module.exports = { | ||
async up(queryInterface, Sequelize) { | ||
return queryInterface.createTable('TwitterCursors', { | ||
bot_name: { | ||
type: Sequelize.STRING, | ||
primaryKey: true, | ||
}, | ||
last_polled_timestamp: { | ||
type: Sequelize.BIGINT, | ||
allowNull: false, | ||
}, | ||
}); | ||
}, | ||
|
||
async down(queryInterface, Sequelize) { | ||
return queryInterface.dropTable('TwitterCursors'); | ||
}, | ||
}; |
This file contains 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
94 changes: 94 additions & 0 deletions
94
packages/commonwealth/server/workers/twitterWorker/pollTwitter.ts
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
import { logger } from '@hicommonwealth/core'; | ||
import { Tweet, TwitterMentionsTimeline } from '@hicommonwealth/schemas'; | ||
import fetch from 'node-fetch'; | ||
import z from 'zod'; | ||
import { TwitterBotConfig } from './utils'; | ||
|
||
const log = logger(import.meta); | ||
|
||
async function getFromTwitter({ | ||
twitterBotConfig, | ||
url, | ||
queryParams, | ||
}: { | ||
twitterBotConfig: TwitterBotConfig; | ||
url: string; | ||
queryParams: Record<string, string | Date | number>; | ||
}): Promise<{ jsonBody: Record<string, unknown>; requestsRemaining: number }> { | ||
const parsedQueryParams: Record<string, string> = Object.fromEntries( | ||
Object.entries(queryParams).map(([key, value]) => [ | ||
key, | ||
value instanceof Date ? value.toISOString() : value.toString(), | ||
]), | ||
); | ||
|
||
const queryString = new URLSearchParams(parsedQueryParams).toString(); | ||
const fullUrl = `${url}?${queryString}`; | ||
|
||
const response = await fetch(fullUrl, { | ||
method: 'GET', | ||
headers: { | ||
Authorization: `Bearer ${twitterBotConfig.bearerToken}`, | ||
'Content-Type': 'application/json', | ||
}, | ||
}); | ||
|
||
if (!response.ok) { | ||
throw new Error( | ||
`Request failed with status ${response.status}: ${response.statusText}`, | ||
); | ||
} | ||
|
||
return { | ||
jsonBody: await response.json(), | ||
requestsRemaining: Number(response.headers.get('x-rate-limit-remaining')), | ||
}; | ||
} | ||
|
||
// https://docs.x.com/x-api/posts/user-mention-timeline-by-user-id | ||
export async function getMentions({ | ||
twitterBotConfig, | ||
startTime, | ||
endTime, | ||
}: { | ||
twitterBotConfig: TwitterBotConfig; | ||
startTime: Date; | ||
endTime: Date; | ||
}): Promise<{ mentions: z.infer<typeof Tweet>[]; endTime: Date }> { | ||
const allMentions: z.infer<typeof Tweet>[] = []; | ||
let paginationToken: string | undefined; | ||
let requestsRemaining: number; | ||
do { | ||
const res = await getFromTwitter({ | ||
twitterBotConfig, | ||
url: `https://api.x.com/2/users/${twitterBotConfig.twitterUserId}/mentions`, | ||
queryParams: { | ||
start_time: startTime, | ||
end_time: endTime, | ||
}, | ||
}); | ||
const parsedRes = TwitterMentionsTimeline.parse(res.jsonBody); | ||
paginationToken = parsedRes.meta?.next_token; | ||
requestsRemaining = res.requestsRemaining; | ||
|
||
for (const error of parsedRes.errors) { | ||
log.error( | ||
'Error occurred polling for Twitter mentions', | ||
new Error(JSON.stringify(error)), | ||
{ | ||
botName: twitterBotConfig.name, | ||
}, | ||
); | ||
} | ||
allMentions.push(...parsedRes.data); | ||
} while (paginationToken && requestsRemaining > 0); | ||
|
||
if (paginationToken && requestsRemaining === 0 && allMentions.length > 0) { | ||
return { | ||
mentions: allMentions, | ||
endTime: new Date(allMentions.at(-1)!.created_at), | ||
}; | ||
} | ||
|
||
return { mentions: allMentions, endTime }; | ||
} |
Oops, something went wrong.