Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(new-plugin): truth social #2537

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

Freytes
Copy link
Collaborator

@Freytes Freytes commented Jan 20, 2025

Truth Social Client

A TypeScript client for interacting with Truth Social's API, built on top of the @ai16z/eliza framework for AI-powered social media interactions.

System Overview

This client provides automated interaction capabilities with Truth Social, including:

  • Posting and responding to content
  • Processing mentions and interactions
  • Searching and engaging with relevant content
  • Managing rate limits and API interactions

Core Components

  1. API Layer (api.ts)

    • Handles direct communication with Truth Social's API
    • Manages authentication and rate limiting
    • Provides base methods for posts, likes, reposts, etc.
  2. Base Client (base.ts)

    • Provides foundational client functionality
    • Manages state and caching
    • Handles timeline and post fetching
  3. Post Management (post.ts)

    • Handles post creation and processing
    • Manages periodic posting
    • Processes post actions and interactions
  4. Interactions (interactions.ts)

    • Manages user interactions and responses
    • Handles conversation threading
    • Controls engagement limits and timeouts
  5. Search (search.ts)

    • Implements search functionality
    • Manages topic-based engagement
    • Controls post selection and relevance
  6. Environment (environment.ts)

    • Manages configuration and settings
    • Validates environment variables
    • Sets operational parameters

Supporting Files

  • Types (types.ts): TypeScript interfaces and types
  • Utils (utils.ts): Shared utilities and helper functions
  • Index (index.ts): Main entry point and client initialization

Requirements

Dependencies

  • Node.js 14+
  • TypeScript 4.5+
  • @ai16z/eliza framework
  • axios
  • date-fns
  • zod

Environment Variables

  • TRUTHSOCIAL_DRY_RUN: Boolean, if true, the client will not post or interact with Truth Social
  • TRUTHSOCIAL_USERNAME: String, the username of the Truth Social account
  • TRUTHSOCIAL_PASSWORD: String, the password of the Truth Social account
  • MAX_TRUTH_LENGTH: Number, the maximum length of a post
  • POST_INTERVAL_MIN: Number, the minimum interval between posts in seconds
  • POST_INTERVAL_MAX: Number, the maximum interval between posts in seconds
  • ACTION_INTERVAL: Number, the interval between actions in seconds

Setup

  1. Clone the repository
  2. Install dependencies: npm install
  3. Set environment variables
  4. Run the client: npm start

Architecture

The system follows a layered architecture:

  1. API Layer (Bottom)

    • Raw API communication
    • Rate limiting
    • Authentication
  2. Client Layer

    • Base functionality
    • State management
    • Caching
  3. Feature Layer

    • Post management
    • Interactions
    • Search
    • Content generation
  4. Interface Layer (Top)

    • Client interface
    • Runtime management
    • Configuration

File Dependencies

index.ts
├── environment.ts
├── base.ts
│   └── api.ts
├── post.ts
│   ├── base.ts
│   └── utils.ts
├── interactions.ts
│   ├── base.ts
│   └── utils.ts
└── search.ts
    ├── base.ts
    └── utils.ts
  • api.ts depends on types.ts
  • base.ts depends on types.ts
  • post.ts depends on types.ts
  • interactions.ts depends on types.ts
  • search.ts depends on types.ts
  • environment.ts depends on types.ts
  • utils.ts depends on types.ts
  • index.ts depends on types.ts
  • environment.ts depends on types.ts

Safety Notes

  1. Rate Limiting

    • Built-in rate limit management
    • Configurable intervals
    • Automatic backoff
  2. Content Safety

    • Content filtering
    • Engagement limits
    • Conversation depth control
  3. Error Handling

    • Comprehensive error catching
    • Logging
    • Graceful degradation

Usage Warning

This client includes search and interaction capabilities that should be used responsibly.Be aware of:

  1. Rate limit implications
  2. User privacy considerations
  3. Platform terms of service
  4. Potential account restrictions

Always test with TRUTHSOCIAL_DRY_RUN=true before live deployment.

Summary by CodeRabbit

  • New Features

    • Introduced a comprehensive TypeScript client for interacting with the Truth Social API
    • Added functionality for automated posting, searching, and user interactions
    • Implemented advanced features like conversation tracking and response generation
  • Documentation

    • Created detailed README for the Truth Social Client
    • Added comprehensive TypeScript type definitions for API interactions
  • Configuration

    • Set up ESLint and TypeScript configuration
    • Defined package build and development scripts
  • Core Capabilities

    • User authentication
    • Post creation and management
    • Search functionality
    • User engagement tracking
    • Rate limit handling

Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

📝 Walkthrough

Walkthrough

The pull request introduces a comprehensive Truth Social Client, a TypeScript-based package for interacting with the Truth Social API. The implementation includes modules for API interaction, post management, user engagement, search functionality, and environment configuration. The client provides capabilities for authentication, posting, searching, and managing interactions with robust error handling and rate limiting mechanisms.

Changes

File Change Summary
README.md New comprehensive documentation for Truth Social Client
eslint.config.mjs Added ESLint configuration with imported base settings
package.json Defined package metadata, dependencies, and build scripts
src/api.ts Implemented TruthSocialApi with authentication and interaction methods
src/base.ts Created ClientBase for managing API interactions and post retrieval
src/environment.ts Added configuration validation using Zod schema
src/index.ts Introduced TruthManager and TruthClientInterface
src/interactions.ts Developed TruthInteractionClient for conversation management
src/post.ts Created PostClient for managing posts and interactions
src/search.ts Added TruthSearchClient for search-based engagement
src/types.ts Defined comprehensive TypeScript interfaces
src/utils.ts Implemented utility functions and request queue
tsconfig.json Configured TypeScript compilation settings
tsup.config.ts Set up build configuration for the package

Possibly related PRs

Suggested Labels

Needs Testing, Plugin_new

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 12

🧹 Nitpick comments (11)
packages/client-truth-social/tsup.config.ts (2)

8-8: Remove misleading comment about CommonJS.

The format is correctly set to ESM, but the comment suggests CommonJS targeting.

-    format: ["esm"], // Ensure you're targeting CommonJS
+    format: ["esm"],

3-20: Enable TypeScript declaration files.

Add the dts option to generate TypeScript declaration files for better TypeScript support.

 export default defineConfig({
     entry: ["src/index.ts"],
     outDir: "dist",
     sourcemap: true,
     clean: true,
     format: ["esm"],
+    dts: true,
     external: [
packages/client-truth-social/src/index.ts (1)

35-38: Ensure all components are stopped

In the stop method, only this.post.stop() is called. To prevent resource leaks, ensure that this.interaction and this.search (if initialized) are also stopped.

Apply this diff:

 async stop() {
     await this.post.stop();
+    await this.interaction.stop();
+    if (this.search) {
+        await this.search.stop();
+    }
     // Add other stop logic as needed
 }
packages/client-truth-social/src/environment.ts (1)

4-4: Remove unnecessary process declaration

The declaration of process is unnecessary since it's globally available in Node.js. This could lead to conflicts.

Remove line 4.

packages/client-truth-social/src/utils.ts (1)

44-47: Use consistent logging mechanism

Replace console.error with elizaLogger.error for consistent logging throughout the application.

Apply this diff:

 } catch (error) {
-    console.error("Error sending truth:", error);
+    elizaLogger.error("Error sending truth:", error);
     throw error;
 }

Repeat this change for other instances of console.error.

packages/client-truth-social/src/api.ts (2)

105-108: Improve error logging in authenticate method

The error handling in the authenticate method provides limited information, which may hinder debugging.

Consider logging additional error details, such as error.response.data, to aid in troubleshooting authentication failures.


317-333: Handle exceptions individually when processing target user posts

In the loop for processing target user posts, an exception for one user might prevent processing of subsequent users.

Consider wrapping each user's processing logic in its own try-catch block to ensure that an error with one user does not affect others.

packages/client-truth-social/src/interactions.ts (1)

294-343: Separate error handling in handleTruthInteractions

An error in processing one part (e.g., mentions) may prevent the rest of the method from executing.

Refactor to handle errors for each section independently to ensure full execution of the interaction handling.

packages/client-truth-social/src/types.ts (1)

36-39: Adjust types in hashtags history

In TruthSearchResults, the uses and accounts fields within hashtags.history are typed as string, but they may represent numeric values.

Change the types of uses and accounts to number if they represent counts.

packages/client-truth-social/README.md (2)

107-121: Add language specifier to the file tree code block.

Specify the language for the fenced code block to improve syntax highlighting.

-```
+```txt
🧰 Tools
🪛 Markdownlint (0.37.0)

107-107: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)


123-131: Simplify dependencies section.

The repeated "depends on types.ts" statements can be simplified for better readability.

-api.ts depends on types.ts
-base.ts depends on types.ts
-post.ts depends on types.ts
-interactions.ts depends on types.ts
-search.ts depends on types.ts
-environment.ts depends on types.ts
-utils.ts depends on types.ts
-index.ts depends on types.ts
-environment.ts depends on types.ts
+All modules depend on types.ts:
+- api.ts
+- base.ts
+- post.ts
+- interactions.ts
+- search.ts
+- environment.ts
+- utils.ts
+- index.ts
🧰 Tools
🪛 LanguageTool

[grammar] ~123-~123: This phrase is duplicated. You should probably use “depends on” only once.
Context: ...ts
└── utils.ts


- `api.ts` depends on `types.ts`
- `base.ts` depends on `types.ts`
- `post.ts` depends on `typ...

(PHRASE_REPETITION)

---

[grammar] ~125-~125: This phrase is duplicated. You should probably use “depends on” only once.
Context: ....ts` depends on `types.ts`
- `post.ts` depends on `types.ts`
- `interactions.ts` depends on `types.ts`
- `search.ts` depends on `t...

(PHRASE_REPETITION)

---

[grammar] ~127-~127: This phrase is duplicated. You should probably use “depends on” only once.
Context: ...s` depends on `types.ts`
- `search.ts` depends on `types.ts`
- `environment.ts` depends on `types.ts`
- `utils.ts` depends on `ty...

(PHRASE_REPETITION)

---

[grammar] ~129-~129: This phrase is duplicated. You should probably use “depends on” only once.
Context: ...ts` depends on `types.ts`
- `utils.ts` depends on `types.ts`
- `index.ts` depends on `types.ts`
- `environment.ts` depends ...

(PHRASE_REPETITION)

</details>

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between cfd1f48c3f13a55c8bad632b430e0ddd00fd275c and c06e56f7e8bed4c7a5ff66a1efffd36ab57c5c3f.

</details>

<details>
<summary>📒 Files selected for processing (14)</summary>

* `packages/client-truth-social/README.md` (1 hunks)
* `packages/client-truth-social/eslint.config.mjs` (1 hunks)
* `packages/client-truth-social/package.json` (1 hunks)
* `packages/client-truth-social/src/api.ts` (1 hunks)
* `packages/client-truth-social/src/base.ts` (1 hunks)
* `packages/client-truth-social/src/environment.ts` (1 hunks)
* `packages/client-truth-social/src/index.ts` (1 hunks)
* `packages/client-truth-social/src/interactions.ts` (1 hunks)
* `packages/client-truth-social/src/post.ts` (1 hunks)
* `packages/client-truth-social/src/search.ts` (1 hunks)
* `packages/client-truth-social/src/types.ts` (1 hunks)
* `packages/client-truth-social/src/utils.ts` (1 hunks)
* `packages/client-truth-social/tsconfig.json` (1 hunks)
* `packages/client-truth-social/tsup.config.ts` (1 hunks)

</details>

<details>
<summary>✅ Files skipped from review due to trivial changes (2)</summary>

* packages/client-truth-social/eslint.config.mjs
* packages/client-truth-social/tsconfig.json

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 GitHub Actions: smoke-test</summary>

<details>
<summary>packages/client-truth-social/package.json</summary>

[warning]  Unsupported Node.js engine version. Wanted: 23.3.0, Current: 23.6.0

---

[error]  Missing workspace dependency: @ai16z/eliza is listed as a dependency but not present in the workspace

---

[warning]  Local package.json exists but node_modules is missing. Run package installation

</details>

</details>
<details>
<summary>🪛 LanguageTool</summary>

<details>
<summary>packages/client-truth-social/README.md</summary>

[duplication] ~68-~68: Possible typo: you repeated a word.
Context: ...LENGTH: Number, the maximum length of a post
- POST_INTERVAL_MIN: Number, the minimum inter...

(ENGLISH_WORD_REPEAT_RULE)

---

[uncategorized] ~86-~86: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...ttom)
   - Raw API communication
   - Rate limiting
   - Authentication

2. **Client Lay...

(EN_COMPOUND_ADJECTIVE_INTERNAL)

---

[grammar] ~123-~123: This phrase is duplicated. You should probably use “depends on” only once.
Context: ...ts
    └── utils.ts
  • api.ts depends on types.ts
  • base.ts depends on types.ts
  • post.ts depends on `typ...

(PHRASE_REPETITION)


[grammar] ~125-~125: This phrase is duplicated. You should probably use “depends on” only once.
Context: ....tsdepends ontypes.ts`

  • post.ts depends on types.ts
  • interactions.ts depends on types.ts
  • search.ts depends on `t...

(PHRASE_REPETITION)


[grammar] ~127-~127: This phrase is duplicated. You should probably use “depends on” only once.
Context: ...sdepends ontypes.ts`

  • search.ts depends on types.ts
  • environment.ts depends on types.ts
  • utils.ts depends on `ty...

(PHRASE_REPETITION)


[grammar] ~129-~129: This phrase is duplicated. You should probably use “depends on” only once.
Context: ...tsdepends ontypes.ts`

  • utils.ts depends on types.ts
  • index.ts depends on types.ts
  • environment.ts depends ...

(PHRASE_REPETITION)


[uncategorized] ~135-~135: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ... on types.ts

Safety Notes

  1. Rate Limiting
    • Built-in rate limit management
      ...

(EN_COMPOUND_ADJECTIVE_INTERNAL)

🪛 Markdownlint (0.37.0)
packages/client-truth-social/README.md

107-107: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🪛 Biome (1.9.4)
packages/client-truth-social/src/base.ts

[error] 10-10: Don't use 'BigInt' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'bigint' instead

(lint/complexity/noBannedTypes)

🪛 Gitleaks (8.21.2)
packages/client-truth-social/src/api.ts

14-14: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (4)
packages/client-truth-social/src/utils.ts (1)

106-117: ⚠️ Potential issue

Handle asynchronous iteration correctly

The getUserStatuses method returns an asynchronous iterator. Ensure it's properly handled to avoid missed data or unhandled promises.

Modify the code to correctly await the asynchronous iterator:

 const comments = client.truthApi.getUserStatuses({
     username: currentPost.account.username,
     limit: 1,
     sinceId: currentPost.in_reply_to_id
 });
 
-for await (const comment of comments) {
+for await (const comment of comments) {
     await processThread(comment, depth + 1);
 }

Ensure that the for await...of loop correctly iterates over the asynchronous iterator.

Likely invalid or redundant comment.

packages/client-truth-social/src/search.ts (1)

1-235: Code looks good

The implementation is correct and follows best practices.

packages/client-truth-social/src/api.ts (1)

49-55: Verify rate limit header parsing in checkRateLimit

Ensure that the rate limit headers (x-ratelimit-limit, x-ratelimit-remaining, x-ratelimit-reset) are parsed correctly, accounting for their data types and formats.

packages/client-truth-social/src/interactions.ts (1)

21-46: Ensure placeholders in truthShouldRespondTemplate are correctly replaced

Verify that all placeholders like {{agentName}} and {{truthUserName}} in the truthShouldRespondTemplate are replaced during runtime to prevent template strings from appearing in the final output.

Comment on lines +9 to +19
external: [
"dotenv", // Externalize dotenv to prevent bundling
"fs", // Externalize fs to use Node.js built-in module
"path", // Externalize other built-ins if necessary
"@reflink/reflink",
"@node-llama-cpp",
"https",
"http",
"agentkeepalive",
// Add other modules you want to externalize
],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Add these dependencies to the externals list

external: [
    "dotenv",
    "fs",
    "path",
    "@reflink/reflink",
    "@node-llama-cpp",
    "https",
    "http",
    "agentkeepalive",
    "@ai16z/eliza",
    "glob",
    "zod",
    "whatwg-url",
    // Add other modules you want to externalize
],
🔗 Analysis chain

Complete the external dependencies list.

The comment suggests more externals might be needed. Consider adding other dependencies from your package.json to prevent bundling issues.

Run this script to identify potential external dependencies:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find dependencies in package.json that might need to be externalized
jq -r '.dependencies, .peerDependencies | keys[]' packages/client-truth-social/package.json 2>/dev/null

Length of output: 126

Comment on lines +53 to +56
async stop(runtime: IAgentRuntime) {
elizaLogger.log("Stopping Truth Social client");
// Implement stop logic
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Implement stop logic in TruthClientInterface

The stop method currently only logs a message. Implement the logic to stop the TruthManager instance to ensure all processes are terminated properly.

Add the following:

 async stop(runtime: IAgentRuntime) {
     elizaLogger.log("Stopping Truth Social client");
+    if (this.manager) {
+        await this.manager.stop();
+    }
 }

Ensure that manager is accessible within TruthClientInterface.

Committable suggestion skipped: line range outside the PR's diff.


elizaLogger.log("Truth Social client started");

const manager = new TruthManager(runtime, this.enableSearch);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix undefined 'enableSearch' property

At line 47, this.enableSearch is used but not defined in TruthClientInterface. This will cause a runtime error.

Apply this diff to define enableSearch:

 export const TruthClientInterface: Client = {
+    enableSearch: boolean, // Add this property
     async start(runtime: IAgentRuntime) {

Alternatively, pass enableSearch as a parameter to the start method.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +9 to +34
TRUTHSOCIAL_DRY_RUN: z
.string()
.transform((val) => val.toLowerCase() === "true"),
TRUTHSOCIAL_USERNAME: z.string().min(1, "Truth Social username is required"),
TRUTHSOCIAL_PASSWORD: z.string().min(1, "Truth Social password is required"),
MAX_TRUTH_LENGTH: z
.string()
.pipe(z.coerce.number().min(0).int())
.default(DEFAULT_MAX_TRUTH_LENGTH.toString()),
POST_INTERVAL_MIN: z
.string()
.pipe(z.coerce.number().min(0).int())
.default("90"),
POST_INTERVAL_MAX: z
.string()
.pipe(z.coerce.number().min(0).int())
.default("180"),
ACTION_INTERVAL: z
.string()
.pipe(z.coerce.number().min(0).int())
.default("300000"), // 5 minutes
ENABLE_ACTION_PROCESSING: z
.string()
.transform((val) => val.toLowerCase() === "true")
.default("true"),
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Correct default value placement in Zod schema

The default() method should be called before transformations to ensure defaults are applied when the environment variable is undefined.

Apply this diff:

 TRUTHSOCIAL_DRY_RUN: z
-    .string()
+    .string().default("false")
     .transform((val) => val.toLowerCase() === "true"),

Make similar adjustments for other fields with defaults.

Committable suggestion skipped: line range outside the PR's diff.

public truthApi: TruthSocialApi;
public profile: any;
public requestQueue: RequestQueue;
public lastCheckedPostId: BigInt = BigInt(0);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use 'bigint' instead of 'BigInt' for consistency

In TypeScript, the lowercase 'bigint' should be used as the type annotation.

Apply this diff to fix the issue:

- public lastCheckedPostId: BigInt = BigInt(0);
+ public lastCheckedPostId: bigint = BigInt(0);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public lastCheckedPostId: BigInt = BigInt(0);
public lastCheckedPostId: bigint = BigInt(0);
🧰 Tools
🪛 Biome (1.9.4)

[error] 10-10: Don't use 'BigInt' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'bigint' instead

(lint/complexity/noBannedTypes)

Comment on lines +161 to +197
private async trackUserEngagement(
username: string,
interactionType: string,
points: number = 1
): Promise<void> {
const engagement = this.userEngagementCache.get(username) || {
interactions: 0,
lastInteraction: new Date(),
interactionTypes: new Set<string>()
};

if (Date.now() - engagement.lastInteraction.getTime() > this.ENGAGEMENT_WINDOW) {
engagement.interactions = 0;
engagement.interactionTypes.clear();
}

engagement.interactions += points;
engagement.lastInteraction = new Date();
engagement.interactionTypes.add(interactionType);
this.userEngagementCache.set(username, engagement);

// Check if we should follow based on diverse engagement
if (engagement.interactions >= this.ENGAGEMENT_THRESHOLD &&
engagement.interactionTypes.size >= 2) {
try {
const profile = await this.lookupUser(username);
const alreadyFollowing = await this.checkIfFollowing(profile.id);

if (!alreadyFollowing) {
await this.followUser(profile.id);
elizaLogger.log(`Following ${username} after ${engagement.interactions} points across ${engagement.interactionTypes.size} types`);
}
} catch (error) {
elizaLogger.error(`Error following ${username}:`, error);
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Address potential concurrency issues with userEngagementCache

The userEngagementCache is modified in asynchronous contexts, which could lead to race conditions.

Ensure thread safety when updating shared data structures in asynchronous code. Synchronize access or redesign to prevent concurrent modifications.

Comment on lines +106 to +111
if (timeSinceLastInteraction > this.conversationTimeout) {
elizaLogger.log(`Conversation ${threadId} timed out after ${timeSinceLastInteraction/1000/60} minutes`);
this.conversationDepths.delete(threadId);
this.conversationTimeouts.delete(threadId);
return true; // Allow new conversation to start
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Clarify return value logic in shouldContinueConversation

Returning true after a conversation times out may unintentionally allow continuation of expired conversations.

Consider returning false when the conversation has timed out to prevent further replies in the same thread.

Comment on lines +1 to +24
{
"name": "@ai16z/client-truth",
"version": "0.1.5-alpha.5",
"description": "Truth Social client integration for AI16Z agents",
"main": "dist/index.js",
"type": "module",
"types": "dist/index.d.ts",
"dependencies": {
"@ai16z/eliza": "workspace:*",
"glob": "11.0.0",
"zod": "3.23.8"
},
"devDependencies": {
"tsup": "8.3.5"
},
"scripts": {
"build": "tsup --format esm --dts",
"dev": "tsup --format esm --dts --watch",
"lint": "eslint . --fix"
},
"peerDependencies": {
"whatwg-url": "7.1.0"
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add engines field to specify Node.js version requirements.

Add Node.js version constraints to prevent version mismatches like the current warning (wanted 23.3.0, got 23.6.0).

{
    "name": "@ai16z/client-truth",
+   "engines": {
+     "node": "^23.3.0"
+   },
    ...
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{
"name": "@ai16z/client-truth",
"version": "0.1.5-alpha.5",
"description": "Truth Social client integration for AI16Z agents",
"main": "dist/index.js",
"type": "module",
"types": "dist/index.d.ts",
"dependencies": {
"@ai16z/eliza": "workspace:*",
"glob": "11.0.0",
"zod": "3.23.8"
},
"devDependencies": {
"tsup": "8.3.5"
},
"scripts": {
"build": "tsup --format esm --dts",
"dev": "tsup --format esm --dts --watch",
"lint": "eslint . --fix"
},
"peerDependencies": {
"whatwg-url": "7.1.0"
}
}
{
"name": "@ai16z/client-truth",
"engines": {
"node": "^23.3.0"
},
"version": "0.1.5-alpha.5",
"description": "Truth Social client integration for AI16Z agents",
"main": "dist/index.js",
"type": "module",
"types": "dist/index.d.ts",
"dependencies": {
"@ai16z/eliza": "workspace:*",
"glob": "11.0.0",
"zod": "3.23.8"
},
"devDependencies": {
"tsup": "8.3.5"
},
"scripts": {
"build": "tsup --format esm --dts",
"dev": "tsup --format esm --dts --watch",
"lint": "eslint . --fix"
},
"peerDependencies": {
"whatwg-url": "7.1.0"
}
}
🧰 Tools
🪛 GitHub Actions: smoke-test

[warning] Unsupported Node.js engine version. Wanted: 23.3.0, Current: 23.6.0


[error] Missing workspace dependency: @ai16z/eliza is listed as a dependency but not present in the workspace


[warning] Local package.json exists but node_modules is missing. Run package installation

Comment on lines +8 to +12
"dependencies": {
"@ai16z/eliza": "workspace:*",
"glob": "11.0.0",
"zod": "3.23.8"
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Potential issue

Missing @ai16z/eliza package in workspace

The workspace configuration is correct, but the @ai16z/eliza package doesn't exist in the workspace. Either:

  • Add the missing package to the workspace
  • Remove the dependency if it's no longer needed
  • Update the reference if the package name has changed
🔗 Analysis chain

Fix workspace dependency configuration.

The pipeline is failing due to missing @ai16z/eliza workspace dependency. Ensure the workspace is properly configured and the dependency is available.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check workspace configuration
cat pnpm-workspace.yaml || cat package.json | jq '.workspaces'

Length of output: 114


Script:

#!/bin/bash
# Check if @ai16z/eliza package exists
fd --type directory "eliza" packages/

Length of output: 64


Script:

#!/bin/bash
# Search for package.json files containing eliza
fd package.json packages/ --exec grep -l "eliza" {} \;

Length of output: 2025


Script:

#!/bin/bash
# Search for package.json files containing @ai16z/eliza as package name
fd package.json packages/ --exec jq -r 'select(.name == "@ai16z/eliza") | .name' {} \;

Length of output: 91

🧰 Tools
🪛 GitHub Actions: smoke-test

[warning] Unsupported Node.js engine version. Wanted: 23.3.0, Current: 23.6.0


[error] Missing workspace dependency: @ai16z/eliza is listed as a dependency but not present in the workspace


[warning] Local package.json exists but node_modules is missing. Run package installation

Comment on lines +56 to +58
- Node.js 14+
- TypeScript 4.5+
- @ai16z/eliza framework
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Update Node.js version requirement.

The Node.js version requirement (14+) conflicts with the package.json engine requirement (^23.3.0).

-Node.js 14+
+Node.js 23.3+
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- Node.js 14+
- TypeScript 4.5+
- @ai16z/eliza framework
- Node.js 23.3+
- TypeScript 4.5+
- @ai16z/eliza framework

@wtfsayo wtfsayo changed the title Truth Social feat(new-plugin): truth social Jan 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant