eliza 101

First Twitter Bot

你的第一个Twitter Bot

配置 eliza 环境 (v0.25.9)

git clone https://github.com/elizaOS/eliza.git
cd eliza
git checkout v0.25.9

安装插件

npx elizaos plugins list    # 列出插件(已安装)
npx elizaos plugins install @elizaos-plugins/client-twitter # 安装插件

插件仓库: https://github.com/elizaos-plugins

这个版本的 eliza 弱化了 client 的概念,把 client 统一到了 plugin 里边。

install & build :

node -v
pnpm install
pnpm run build

character 配置

在 character 中配置 llm 的 modelProvider 和 plugins

{
  ...
  "modelProvider": "redpill",
  "plugins": ["@elizaos-plugins/client-twitter"]
  ...
}

twitter 相关的 plugin 有两个:

  • @elizaos-plugins/client-twitter
  • @elizaos-plugins/plugin-twitter 只包含一个发 twitter 的 Action : POST_TWEET

尝试启动 Agent

pnpm run start --character=characters/eliza101.json

这个时候,会报 Env 不存在的错误。

Image

Env 配置选项

1. 基本配置

环境变量描述
TWITTER_USERNAMEtwitter 用户 id
TWITTER_PASSWORD登录密码。如果你是 Gmail 登录过来的,需要单独设置一次。
TWITTER_EMAIL注册邮箱
TWITTER_2FA_SECRET很重要,最好开启配置。

Cookie 模式登录

环境变量浏览器 cookie 名称
TWITTER_COOKIES_AUTH_TOKENauth_token
TWITTER_COOKIES_CT0ct0
TWITTER_COOKIES_GUEST_IDguest_id

从浏览器的 cookie 中获取,当以上的登录方式被 Deny 的时候,可以尝试 Cookie 模式。

配置好以上的选项,就可以登录成功了。

2. 高级配置

自动发 Twitter 配置

环境变量描述默认
POST_INTERVAL_MIN最小分钟数90
POST_INTERVAL_MAX最大分钟数180
POST_IMMEDIATELY启动后立即发送 twitterfalse
ENABLE_TWITTER_POST_GENERATION是否开启自动生成true

bot 自动发 twitter 的间隔介于 POST_INTERVAL_MIN ~ POST_INTERVAL_MAX 分钟之间。 默认在 90 ~ 180 分钟之间随机发 Twitter。

配置逻辑:client-twitter/src/post.ts:#L239

client-twitter/src/post.ts
const generateNewTweetLoop = async () => {
  const lastPost = await this.runtime.cacheManager.get<{
    timestamp: number;
  }>("twitter/" + this.twitterUsername + "/lastPost");
 
  const lastPostTimestamp = lastPost?.timestamp ?? 0;
  const minMinutes = this.client.twitterConfig.POST_INTERVAL_MIN;
  const maxMinutes = this.client.twitterConfig.POST_INTERVAL_MAX;
  const randomMinutes =
    Math.floor(Math.random() * (maxMinutes - minMinutes + 1)) + minMinutes;
  const delay = randomMinutes * 60 * 1000;
 
  if (Date.now() > lastPostTimestamp + delay) {
    await this.generateNewTweet();
  }
 
  setTimeout(() => {
    generateNewTweetLoop(); // Set up next iteration
  }, delay);
 
  elizaLogger.log(`Next tweet scheduled in ${randomMinutes} minutes`);
};

如果你想关闭自动生成 twitter, 可以把 ENABLE_TWITTER_POST_GENERATION 设置为 false.

Twitter 使用的 client 类库是:https://github.com/elizaOS/agent-twitter-client

Twitter 动作响应

环境变量描述默认
TWITTER_POLL_INTERVAL动作检查频率120

每隔一段时间 (默认 2 分钟)拉取需要响应的动作,做出反馈。

动作响应源数据

src/interactions.ts
const mentionCandidates = (
  await this.client.fetchSearchTweets(
    `@${twitterUsername}`,
    20,
    SearchMode.Latest
  )
).tweets;

响应动作分类:

  • at 提及
  • 回复
  • 引用
  • 私信

搜索功能

开启方法:

TWITTER_SEARCH_ENABLE=true # 默认 false

Agent 可以根据 character 中定义的 topics 搜索相关 twitter, 并自动完成交互。

...
"topics": ["eliza","ai16z"],
...

相关代码:

src/search.ts
private engageWithSearchTermsLoop() {
    this.engageWithSearchTerms().then();
    // 生成频率
    const randomMinutes = Math.floor(Math.random() * (120 - 60 + 1)) + 60;
    elizaLogger.log(
        `Next twitter search scheduled in ${randomMinutes} minutes`
    );
    setTimeout(
        () => this.engageWithSearchTermsLoop(),
        randomMinutes * 60 * 1000
    );
}
 
private async engageWithSearchTerms() {
    elizaLogger.log("Engaging with search terms");
    ......
 
    const searchTerm = [...this.runtime.character.topics][
        Math.floor(Math.random() * this.runtime.character.topics.length)
    ];
 
    elizaLogger.log("Fetching search tweets");
    // TODO: we wait 5 seconds here to avoid getting rate limited on startup, but we should queue
    await new Promise((resolve) => setTimeout(resolve, 5000));
    const recentTweets = await this.client.fetchSearchTweets(
        searchTerm,
        20,
        SearchMode.Top
    );
    elizaLogger.log("Search tweets fetched");
}

其他功能

  • space 功能

需要一个 tts 的 api key。

TWITTER_SPACES_ENABLE=false
ELEVENLABS_XI_API_KEY=     # Required for TTS in Spaces
  • discord 许可的 twitter 发送
  1. 生成 twitter 内容发送到一个 discord 的 channel
  2. 用户可以通过或者拒绝发送这条 twitter
  3. 许可的 twitter 内容会自动发送

可能出现的问题

1. 插件安装出现网络连接错误

修改 packages/cli/src/index.js 使用 axios 代替 fetch , 并启动 proxy 配置。

pnpm install axios

替换代码:

async function getPlugins() {
  const resp = await axios.get(
    "https://raw.githubusercontent.com/elizaos-plugins/registry/refs/heads/main/index.json"
  );
  return resp.data;
}

2. 操作过程中可能遇到网络错误

可以在 Agent 测尝试开启全局代理

pnpm install undici # 在 agent 中安装依赖

agent/src/index.ts 中添加全局代理代码:

agent/src/index.ts
import { ProxyAgent, setGlobalDispatcher } from "undici";
const setProxy = () => {
  const proxy = process.env.AGENT_PROXY;
  if (proxy) {
    elizaLogger.info("start agents use proxy : ", proxy);
    const proxyAgent = new ProxyAgent(proxy);
    setGlobalDispatcher(proxyAgent);
  }
};
 
setProxy();

3. 部分日志显示不全

调整日志显示级别

DEFAULT_LOG_LEVEL=log # 默认是 info

全部的日志级别:

const customLevels: Record<string, number> = {
  fatal: 60,
  error: 50,
  warn: 40,
  info: 30,
  log: 29,
  progress: 28,
  success: 27,
  debug: 20,
  trace: 10,
};

4. Twitter 账号被锁

登录 Twitter 时候,太频繁会出现账号被锁的情况,日志如下:

[2025-03-03 09:37:02] ERROR: Login attempt failed: {"errors":[{"code":326,"message":"To protect our users from spam and other malicious activity, this account is temporarily locked. Please log in to https://twitter.com to unlock your account.","sub_error_code":0,"bounce_location":"https://twitter.com/account/access"}]}

登录 Twitter 账号解锁。

视频教程