360 Secure SkillHub
360 安全技能中心

X (Twitter) Publisher

基于 Tweepy 的 X(Twitter)发布工具,提供认证校验、单条推文与推文串命令,从环境变量读取 OAuth 1.0a 四项凭证,可发布纯文本、图片或视频内容,并输出含 tweet_id 与 URL 的 JSON 结果;首次运行自动建立虚拟环境安装依赖。

jiangsier-xyz
jiangsier-xyz
热度 50.36
最近更新 2026-07-27 21:32:55
分类:营销依赖:代码执行 / 第三方 API / 读写文件应用场景:社交媒体 / API 集成 / 自动化脚本

安装技能

复制下面的话术发给你的 Agent,它会通过 secure-skills 检索并安装该技能。

执行命令安装此 skill: npx secure-skills-cli add jiangsier-xyz/x-publisher
Metadata
name
X (Twitter) Publisher
description
Publish tweets to X (Twitter) using the official Tweepy library. Supports text-only tweets, tweets with images or videos, and returns detailed publish results including tweet ID and URL. Requires X API credentials (API Key, API Secret, Access Token, Access Token Secret).
env
["X_API_KEY","X_API_SECRET","X_ACCESS_TOKEN","X_ACCESS_TOKEN_SECRET"]

X (Twitter) Tweet Publishing Tool

Publish tweets using the official Tweepy library, supporting text-only, image, video, and other media types.

Features

  • 📝 Text-Only Tweets - Quickly publish text content
  • 🖼️ Image Support - Supports JPG, PNG, GIF, WebP formats (up to 4 images)
  • 🎬 Video Support - Supports MP4, MOV, AVI, WebM formats
  • 📊 Detailed Results - Returns tweet ID, URL, creation time, and more
  • ✅ Auth Verification - Supports verifying API credentials

Prerequisites

1. Dependencies

Python 3.7+ and tweepy are installed automatically: the scripts/x_publisher (and scripts/post_thread) entrypoint wrappers create an isolated virtualenv at <skill_dir>/.venv on first run and install requirements.txt (which pins tweepy) into it. No manual pip install is needed. Override the venv location with SKILL_VENV_DIR=<path>.

2. Get X API Credentials

  1. Visit https://developer.twitter.com/en/portal/dashboard
  2. Create a project and generate API keys
  3. Obtain the following credentials:
    • API Key
    • API Secret
    • Access Token
    • Access Token Secret

3. Configure Environment Variables

The skill reads its credentials only from the environment. Set these four variables before running (in your shell rc, or export them from a .env file):

export X_API_KEY="your-api-key"
export X_API_SECRET="your-api-secret"
export X_ACCESS_TOKEN="your-access-token"
export X_ACCESS_TOKEN_SECRET="your-access-token-secret"

If you keep them in a .env file in the current directory, load it into your environment first, e.g.:

set -a && . ./.env && set +a

Optionally, set X_HTTP_PROXY if the X API is not reachable directly from your environment.

Usage

Verify Authentication

Before first use, verify your credentials:

scripts/x_publisher verify

Example output:

✅ Authentication successful!
👤 Username: @your_username
📛 Display Name: Your Name
👥 Followers: 1,234
📝 Tweets: 5,678

Publish Text-Only Tweet

scripts/x_publisher tweet "Hello, X! This is my first tweet."

Publish Tweet with Images

# Single image
scripts/x_publisher tweet "Check out this photo!" --media /path/to/image.jpg

# Multiple images (up to 4)
scripts/x_publisher tweet "My photo collection:" \
  --media /path/to/photo1.jpg \
  --media /path/to/photo2.png \
  --media /path/to/photo3.gif

Publish Tweet with Video

scripts/x_publisher tweet "Watch this video!" --media /path/to/video.mp4

Publish a Thread

Post a multi-tweet thread in one command. Each tweet is published as a reply to the previous one.

# Thread from positional arguments (one tweet per argument)
scripts/post_thread "First tweet of the thread." "Second tweet." "Third tweet."

# Thread from stdin (one tweet per line)
printf 'First tweet.\nSecond tweet.\nThird tweet.\n' | scripts/post_thread

To reply to a single existing tweet (rather than start a new thread), use the --reply-to flag:

scripts/x_publisher tweet "A reply." --reply-to <tweet_id>

Output

After successful publishing, you will get:

============================================================
✅ Tweet published successfully!
============================================================
📝 Tweet ID: 1234567890123456789
🔗 URL: https://twitter.com/user/status/1234567890123456789
⏰ Created At: 2024-02-03T15:30:45.123456
📄 Preview: Hello, X! This is my first tweet.
============================================================

📋 JSON Output:
{
  "success": true,
  "tweet_id": "1234567890123456789",
  "text": "Hello, X! This is my first tweet.",
  "created_at": "2024-02-03T15:30:45.123456",
  "url": "https://twitter.com/user/status/1234567890123456789"
}

Command Reference

Command Purpose Example
verify Verify authentication scripts/x_publisher verify
tweet Publish a tweet scripts/x_publisher tweet "Hello" --media photo.jpg
(thread) Publish a reply-chained thread scripts/post_thread "First" "Second" "Third"

tweet Command Arguments

Argument Short Description Required
text - Tweet content Yes
--media -m Media file path No

Supported Media Formats

Images

  • JPG/JPEG - Recommended format
  • PNG - Supports transparency
  • GIF - Supports animation
  • WebP - Modern format

Limits:

  • Maximum 4 images
  • Maximum 5MB per image

Videos

  • MP4 - Recommended format
  • MOV - QuickTime format
  • AVI - Common format
  • WebM - Modern format

Limits:

  • Maximum 512MB per video
  • Maximum duration: 2 minutes 20 seconds

Error Handling

Authentication Failure

❌ Authentication failed: Unable to retrieve user information

Solution:

  • Check if API keys and tokens are correct
  • Ensure tokens are not expired
  • Verify network connectivity

Insufficient Permissions

❌ Tweet publishing failed
Error Type: Insufficient permissions
Error Message: You are not allowed to create a Tweet with these settings

Solution:

  • Ensure the app has "Write" permissions
  • Check if you violate X platform rules

Rate Limit Exceeded

❌ Tweet publishing failed
Error Type: Rate limit exceeded
Error Message: Rate limit exceeded

Solution:

  • Wait a few minutes and retry
  • X API rate limit: 300 tweets per 15 minutes

Media Upload Failure

❌ Media file not found: /path/to/image.jpg

Solution:

  • Check if the file path is correct
  • Verify file format is supported
  • Check if file size exceeds the limit

Use Cases

Use Case 1: Automated Publishing

# Publish daily summary
scripts/x_publisher tweet "📊 Today's Market Summary: BTC $43,250 (+2.3%)" 

Use Case 2: Publishing with Images

# Publish screenshots or charts
scripts/x_publisher tweet "📈 Today's chart" --media ~/charts/btc_today.png

Use Case 3: Batch Publishing Script

#!/bin/bash
# publish_news.sh

CONTENT="🚀 Breaking News: ..."
IMAGE="/path/to/news_image.jpg"

scripts/x_publisher tweet "$CONTENT" --media "$IMAGE"

Use Case 4: Integration with Other Tools

import subprocess
import json

result = subprocess.run(
    ['scripts/x_publisher', 'tweet', 'Hello!', '--media', 'photo.jpg'],
    capture_output=True,
    text=True
)

# Parse JSON output
output_lines = result.stdout.split('\n')
for line in output_lines:
    if line.strip().startswith('{'):
        tweet_info = json.loads(line)
        print(f"Tweet ID: {tweet_info['tweet_id']}")
        print(f"URL: {tweet_info['url']}")

API Limits

Limit Type Value Description
Tweet length 280 characters Will be truncated if exceeded
Media count 4 Images and/or videos
Image size 5 MB Per image
Video size 512 MB Per video
Video duration 2 min 20 sec Maximum duration
Publish rate 300/15 min Rate limit

Notes

  1. Credential Security - Do not leak API keys, store them in environment variables
  2. Content Compliance - Follow X platform rules, avoid violating content
  3. Rate Control - Be aware of API rate limits, avoid frequent publishing
  4. Media Copyright - Ensure uploaded media files are copyrighted or authorized

References