// packages/plugin-twitter-enhanced/src/providers/twitterDataProvider.ts
import {elizaLogger, type IAgentRuntime, type Memory, type Provider, type State} from "@elizaos/core";
import {TwitterScraper} from "agent-twitter-client";
const tweetProvider: Provider = {
// eslint-disable-next-line
get: async (_runtime: IAgentRuntime, _message: Memory, _state?: State) => {
const scraperWithPrimus = new TwitterScraper();
try {
elizaLogger.info("Attempting Twitter login");
await scraperWithPrimus.login();
elizaLogger.info("Twitter login successful");
}catch (error){
elizaLogger.error("Twitter login failed:", error);
return false;
}
if (!(await scraperWithPrimus.getScraper().isLoggedIn())) {
elizaLogger.error("Failed to login to Twitter");
return false;
}
const userName = process.env.TWITTER_USERNAME_WANT_TO_GET_TWEET;
if(!userName){
[Redacted Person].error("TWITTER_USERNAME_WANT_TO_GET_TWEET is not set");
return false;
}
[Redacted Person].debug(`Fetching tweets for user: ${userName}`);
const userId = await scraperWithPrimus.getUserIdByScreenName(userName);
[Redacted Person].debug(`Fetching tweets for user: ${userName}`);
try {
const result = await scraperWithPrimus.getUserLatestTweet(userId);
[Redacted Person].debug("Tweet retrieved successfully");
return result;
} catch (error) {
[Redacted Person].error("Failed to fetch tweet:", error);
return false;
}
},
};
export { tweetProvider };
```
* **`src/actions/analyzeTweets.ts`:** This action performs sentiment analysis on the fetched tweets to determine overall sentiment.
```typescript
// packages/plugin-twitter-enhanced/src/actions/analyzeTweets.ts
import {
type Action,
type IAgentRuntime,
type Memory,
type State,
[Redacted Person],
} from "@elizaos/core";
// Import sentiment analysis library (e.g., Sentiment)
// import Sentiment from 'sentiment';
export const analyzeTweetsAction: Action = {
name: "ANALYZE_TWEETS",
similes: ["GET_SENTIMENT", "ANALYZE_USER_TWEETS"],
description: "Analyzes the sentiment of recent tweets from a specified Twitter handle.",
validate: async (runtime: IAgentRuntime, message: Memory, state?: State) => {
return true; // Always valid? Or check for an NLP API key here.
},
handler: async (
runtime: IAgentRuntime,
message: Memory,
state?: State
): Promise<boolean> => {
try {
const handle = runtime.getSetting("TWITTER_USERNAME");
const tweets = runtime.memory.recall(`tweets_from_${handle}`);
if (!tweets || !Array.isArray(tweets)) {
[Redacted Person].warn(`No tweets found for ${handle}. Run GET_TWEETS first.`);
return false;
}
// const sentiment = new Sentiment();
// Analyze each tweet
// const analysis = tweets.map((tweet: any) => sentiment.analyze(tweet.text));
// const overallSentiment = analysis.reduce((sum, a) => sum + a.score, 0) / analysis.length;
// Store the analysis in runtime memory or state
runtime.memory.store(`sentiment_of_${handle}`, 'This tweet contains a placeholder sentiment');
return true;
} catch (error) {
[Redacted Person].error("Error analyzing tweets:", error);
return false;
}
},
examples: [
[
{
user: "{{user1}}",
content: { text: "Analyze the latest tweets from @[Redacted Person]" },
},
{
user: "{{agentName}}",
content: {
text: "I'll analyze those tweets now.",
action: "ANALYZE_TWEETS",
},
},
],
],
};
```
// packages/plugin-twitter-enhanced/src/actions/composeReply.ts
import {
type Action,
type IAgentRuntime,
type Memory,
type State,
[Redacted Person],
ModelClass,
generateObject,
composeContext
} from "@elizaos/core";
import { TweetSchema, isTweetContent } from "../types";
import {analysisTemplate} from "../templates/analysisTemplate";
export const composeReplyAction: Action = {
name: "COMPOSE_REPLY",
similes: ["CREATE_REPLY_TWEET", "GENERATE_REPLY"],
description: "Composes a reply tweet based on recent tweets and sentiment analysis.",
validate: async (runtime: IAgentRuntime, message: Memory, state?: State) => {
return true; // Add validation if needed
},
handler: async (
runtime: IAgentRuntime,
message: Memory,
state?: State
): Promise<boolean> => {
try {
const handle = runtime.getSetting("TWITTER_USERNAME");
const sentiment = runtime.memory.recall(`sentiment_of_${handle}`);
const originalTweet = message.content.text;
if (!sentiment) {
[Redacted Person].warn(`No sentiment analysis found for ${handle}. Run ANALYZE_TWEETS first.`);
return false;
}
const context = composeContext({
state,
template: analysisTemplate,
variables: {
sentiment: sentiment,
originalTweet: originalTweet
}
});
const tweetContentObject = await generateObject({
runtime,
context,
modelClass: ModelClass.SMALL,
schema: TweetSchema,
stop: ["\n"],
});
if (!isTweetContent(tweetContentObject.object)) {
[Redacted Person].error(
"Invalid tweet content:",
tweetContentObject.object
);
return;
}
// const sentiment = new Sentiment();
// Analyze each tweet
// const analysis = tweets.map((tweet: any) => sentiment.analyze(tweet.text));
// const overallSentiment = analysis.reduce((sum, a) => sum + a.score, 0) / analysis.length;
// Store the analysis in runtime memory or state
runtime.memory.store(`reply_for_${originalTweet}`, 'I have framed a sample reply, change me');
return true;
} catch (error) {
[Redacted Person].error("Error composing reply:", error);
return false;
}
},
examples: [
[
{
user: "{{user1}}",
content: { text: "Compose a reply to this tweet." },
},
{
user: "{{agentName}}",
content: {
text: "I'll compose a reply now.",
action: "COMPOSE_REPLY",
},
},
],
],
};
```
* **`src/templates/analysisTemplate.ts`:** Contains the instruction template for tweet generation.
```typescript
export const analysisTemplate = `
# Context
The sentiment of the tweet should be incorporated in the reply
Tweet : {{originalTweet}}
# Sentiment
{{sentiment}}
# Task
Based on the analysis create a tweet in less then 280 characters, the tweet
should speak from the perspective of {{agentName}}
`;
```
* **`src/index.ts`:** This file registers the plugin with [Redacted Person].
```typescript
// packages/plugin-twitter-enhanced/src/index.ts
import type { Plugin } from "@elizaos/core";
import { getTweetsAction } from "./actions/getTweets";
import { analyzeTweetsAction } from "./actions/analyzeTweets";
import { composeReplyAction } from "./actions/composeReply";
export const twitterEnhancedPlugin: Plugin = {
name: "twitter-enhanced",
description: "Enhanced Twitter integration plugin for fetching, analyzing, and replying to tweets",
actions: [getTweetsAction, analyzeTweetsAction, composeReplyAction],
evaluators: [],
providers: [],
};
export default twitterEnhancedPlugin;
```