X Plugin
X Plugin (formerly Twitter) enables agents to interact with the X platform, allowing for searching, posting, and analyzing content on X.
Features
- Post Tweets: Create and publish tweets programmatically
- Search Tweets: Find tweets using keywords, hashtags, or other criteria
- User Profiles: Retrieve and analyze user profile information
- Tool Integration: Execute X-related operations using Astreus's tool system
- API Authentication: Seamless connection to X API using credentials
Installation
Install the X Plugin along with Astreus:
npm install @astreus-ai/astreus @astreus-ai/x-plugin
Authentication
To use the X Plugin, you'll need X (Twitter) API credentials:
- Apply for X Developer access at developer.twitter.com
- Create a new project and app in the X Developer portal
- Generate API keys, access tokens, and client credentials
- Add these credentials to your environment variables
Required environment variables:
X_API_KEY=your-x-api-key
X_API_SECRET_KEY=your-x-api-secret
X_ACCESS_TOKEN=your-x-access-token
X_ACCESS_TOKEN_SECRET=your-x-access-token-secret
X_CLIENT_ID=your-x-client-id
X_CLIENT_SECRET=your-x-client-secret
Basic Usage
Create an agent with the X Plugin:
import { createAgent, createMemory, createProvider, createDatabase, PluginManager } from '@astreus-ai/astreus';
import { XPlugin } from '@astreus-ai/x-plugin';
async function main() {
// Initialize Astreus components
const db = await createDatabase();
const memory = await createMemory({ database: db, tableName: 'memories' });
const provider = createProvider({ type: 'openai', model: 'gpt-4o-mini' });
// Initialize X Plugin
const xPlugin = new XPlugin({
apiKey: process.env.X_API_KEY,
apiSecret: process.env.X_API_SECRET_KEY,
accessToken: process.env.X_ACCESS_TOKEN,
accessSecret: process.env.X_ACCESS_TOKEN_SECRET
});
await xPlugin.init();
// Create a plugin manager and add the X plugin
const pluginManager = new PluginManager({
name: 'social-plugins',
tools: xPlugin.getTools()
});
// Create an agent
const agent = await createAgent({
name: 'Social Media Agent',
description: 'An assistant that can interact with X',
provider: provider,
memory: memory,
plugins: [pluginManager],
systemPrompt: `You are a helpful assistant that can interact with X (formerly Twitter).
Help the user search, post, and analyze content on X.`
});
// Your agent is now ready to interact with X
const response = await agent.chat("Find the latest tweets about #AI");
console.log(response);
}
main();
Available Tools
The X Plugin provides several tools for interacting with the X platform:
Post Tweet
// Post a tweet using the agent
const response = await agent.execute('x_send_tweet', {
text: "Hello world from Astreus X Plugin! #AI #MachineLearning"
});
console.log(`Tweet posted with ID: ${response.id}`);
Search Tweets
// Search for tweets
const response = await agent.execute('x_search_tweets', {
query: "#machinelearning",
limit: 10
});
console.log(`Found ${response.tweets.length} tweets`);
Get User Profile
// Retrieve a user profile
const response = await agent.execute('x_get_profile', {
username: "OpenAI"
});
console.log(`User: ${response.name} (@${response.username})`);
X Plugin Starter Project
The Astreus X Plugin Starter provides a ready-to-use template for building applications with the X Plugin:
- Clone the starter repository:
git clone https://github.com/astreus-ai/astreus-starter.git
cd astreus-starter
- Install dependencies:
npm install
- Set up your environment variables:
cp .env.example .env
-
Edit the
.env
file and add your X API credentials and OpenAI API key. -
Run the example:
npm run dev
Error Handling
The X Plugin includes robust error handling:
try {
const response = await agent.execute('x_send_tweet', {
text: "Hello world from Astreus X Plugin! #AI #MachineLearning"
});
if (response.success) {
console.log(`Tweet posted successfully with ID: ${response.id}`);
} else {
console.warn("Tweet posting failed");
if (response.error) {
console.error(`Error: ${response.error}`);
}
}
} catch (error) {
console.error("Error executing tool:", error);
}
Advanced Usage
Scheduled Tweets
Create a system to post tweets on a schedule:
import { createAgent, createMemory, createProvider, createDatabase } from '@astreus-ai/astreus';
import { XPlugin } from '@astreus-ai/x-plugin';
import cron from 'node-cron';
async function main() {
// Initialize Astreus and X Plugin components
const db = await createDatabase();
const memory = await createMemory({ database: db, tableName: 'memories' });
const provider = createProvider({ type: 'openai', model: 'gpt-4o-mini' });
const xPlugin = new XPlugin();
await xPlugin.init();
const agent = await createAgent({
name: 'Scheduled Twitter Bot',
provider: provider,
memory: memory,
database: db
});
// Add plugin tools to agent
xPlugin.getTools().forEach(tool => agent.addTool(tool));
// Schedule tweets every day at 9:00 AM
cron.schedule('0 9 * * *', async () => {
// Generate tweet content (could use the agent to generate content)
const tweetText = `Daily AI update: ${new Date().toLocaleDateString()}`;
// Post the tweet
try {
const response = await agent.execute('x_send_tweet', {
text: tweetText
});
console.log(`Daily tweet posted with ID: ${response.id}`);
} catch (error) {
console.error('Failed to post daily tweet:', error);
}
});
console.log('Scheduled tweet system started');
}
main();
Monitoring Keywords
Set up a system to monitor X for specific keywords:
import { createAgent, createMemory, createProvider, createDatabase } from '@astreus-ai/astreus';
import { XPlugin } from '@astreus-ai/x-plugin';
async function monitorKeywords(keywords, interval = 60000) {
// Initialize components
const db = await createDatabase();
const memory = await createMemory({ database: db, tableName: 'monitoring' });
const provider = createProvider({ type: 'openai', model: 'gpt-3.5-turbo' });
const xPlugin = new XPlugin();
await xPlugin.init();
const agent = await createAgent({
name: 'X Monitoring Agent',
provider: provider,
memory: memory,
database: db
});
// Add plugin tools to agent
xPlugin.getTools().forEach(tool => agent.addTool(tool));
// Monitoring loop
setInterval(async () => {
for (const keyword of keywords) {
try {
// Search for tweets
const response = await agent.execute('x_search_tweets', {
query: keyword,
limit: 10
});
if (response.success && response.tweets?.length > 0) {
console.log(`Found ${response.tweets.length} tweets containing "${keyword}"`);
// Process the tweets (analyze sentiment, categorize, etc.)
}
} catch (error) {
console.error(`Error monitoring keyword "${keyword}":`, error);
}
}
}, interval);
console.log(`Monitoring started for keywords: ${keywords.join(', ')}`);
}
// Start monitoring
monitorKeywords(['#artificialintelligence', '#machinelearning', 'large language models']);
How is this guide?