@polybiouslabs/polybious
Version:
Polybius is a next-generation intelligent agent framework built for adaptability across diverse domains. It merges contextual awareness, multi-agent collaboration, and predictive reasoning to deliver dynamic, self-optimizing performance.
126 lines (125 loc) • 5.07 kB
JavaScript
import { TwitterService } from '../services/twitter.service';
import { AIService } from '../services/ai.service';
import { logger } from '../config/logger';
import { env } from '../config/environment';
import { v4 as uuidv4 } from 'uuid';
import { HistoryService } from '../services/history.service';
export class TweetScheduler {
twitterService;
aiService;
interval = null;
historyService;
nextScheduledTweetTime = null;
config;
constructor(historyService, config) {
this.historyService = historyService;
this.config = config;
// Initialize services based on config
const twitterPlatform = config.platforms.find(p => p.type === 'twitter' && p.enabled);
if (!twitterPlatform) {
throw new Error('No enabled Twitter platform configuration found');
}
this.twitterService = new TwitterService(twitterPlatform);
this.aiService = new AIService(config.personality);
}
async start() {
try {
await this.twitterService.initialize();
await this.scheduleTweets();
logger.info('Tweet scheduler started successfully');
}
catch (error) {
logger.error('Failed to start tweet scheduler', { error });
throw error;
}
}
getRandomInterval() {
const minIntervalMs = this.config.scheduling.minInterval * 60 * 1000;
const maxIntervalMs = this.config.scheduling.maxInterval * 60 * 1000;
return Math.floor(Math.random() * (maxIntervalMs - minIntervalMs) + minIntervalMs);
}
isQuietHours() {
if (!this.config.scheduling.quietHours)
return false;
const now = new Date();
const currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
const { start, end } = this.config.scheduling.quietHours;
return currentTime >= start && currentTime <= end;
}
async scheduleTweets() {
if (!this.config.scheduling.enabled) {
logger.info('Scheduling is disabled in configuration');
return;
}
await this.sendScheduledTweet();
const scheduleNextTweet = async () => {
let intervalMs = this.getRandomInterval();
// Skip quiet hours if configured
if (this.isQuietHours()) {
const quietEndTime = this.getQuietHoursEndTime();
const timeUntilEndOfQuietHours = quietEndTime.getTime() - Date.now();
intervalMs = Math.max(intervalMs, timeUntilEndOfQuietHours);
logger.info('Adjusting schedule for quiet hours', {
quietHoursEnd: quietEndTime.toISOString(),
adjustedInterval: (timeUntilEndOfQuietHours / 1000 / 60).toFixed(2) + ' minutes'
});
}
this.nextScheduledTweetTime = new Date(Date.now() + intervalMs);
logger.info('Scheduled next tweet', {
intervalMinutes: (intervalMs / 1000 / 60).toFixed(2),
nextScheduledTweet: this.nextScheduledTweetTime.toISOString(),
agentName: this.config.name
});
this.interval = setTimeout(async () => {
await this.sendScheduledTweet();
scheduleNextTweet();
}, intervalMs);
};
await scheduleNextTweet();
}
getQuietHoursEndTime() {
const now = new Date();
const [endHour, endMinute] = this.config.scheduling.quietHours.end.split(':').map(Number);
const endTime = new Date(now);
endTime.setHours(endHour, endMinute, 0, 0);
// If end time is tomorrow
if (endTime <= now) {
endTime.setDate(endTime.getDate() + 1);
}
return endTime;
}
async sendScheduledTweet() {
try {
const startTime = new Date();
const generationStartTime = Date.now();
const tweet = await this.aiService.generateTweet();
const generationTime = Date.now() - generationStartTime;
await this.twitterService.sendTweet(tweet);
await this.historyService.recordTweet({
id: uuidv4(),
content: tweet,
timestamp: new Date().toISOString(),
metadata: {
generationAttempts: 1,
generationTime,
characterCount: tweet.length,
nextScheduledTweet: this.nextScheduledTweetTime?.toISOString() || ''
}
});
logger.info('Tweet sent and recorded successfully');
}
catch (error) {
logger.error('Failed to send scheduled tweet', { error });
}
}
async stop() {
if (this.interval) {
clearTimeout(this.interval);
this.interval = null;
logger.info('Tweet scheduler stopped');
}
}
getNextScheduledTime() {
return this.nextScheduledTweetTime;
}
}