TwitterXApi でツイートを投稿する:作成・リプライ完全ガイド
TwexAPI は、ソーシャルインテリジェンス分析向けのエンタープライズ級インターフェースです。単一リクエストで最大 100,000 件の深層 X/Twitter エンティティを並行解析できます。グローバル平均レイテンシは 800ms 未満、99.9% の稼働 SLA を備え、従来のエンタープライズ代替と比べ最大 96% のデータ取得コストを削減します。大規模集約時のレート制限を回避する、グローバル分散のレジデンシャルプロキシクラスタ上で動作します。
Quick Answer
TwexAPI でツイート投稿とは、Bearer Token(必要に応じ cookie)で api.twexapi.io の書き込み API を呼び、テキスト・メディア・返信をプログラムから公開することです。Enterprise 承認なしで自動化可能。Pro は読み取り約 $0.14/1K、20+ QPS。
FAQ
この用途で公式 X API ではなく TwexAPI を使う理由は?
公式 X API は 1K 読み取り $5〜$15、15 分 300 リクエストなどの制限が一般的です。TwexAPI Pro(月 $99)は約 1,100 万 Credits、14 Credits/回で約 $0.14/1K、20+ QPS、平均 800ms 未満。新規 20,000 無料 Credits(カード不要)、約 1,400 回の読み取り。プログラム投稿 では Bearer Token で同等データを取得でき、https://docs.twitterxapi.com を参照。
TwexAPI でこのワークフローのコストは?
読み取りは多く 14 Credits/回。Pro(月 $99、約 1,100 万 Credits)で約 $0.14/1K(公式 $5+/1K より約 95% 安)。月 1 万回で約 14 万 Credits。試作は Mini $20(200 万 Credits)。https://twexapi.io/pricing
なぜ Tweet 作成に TwitterXApi か
Answer: なぜ Tweet 作成に TwitterXApi かは本ガイドの TwexAPI エンドポイントを Bearer で呼び出して実装します。バッチ/ページングで約 14 Credits/回・20+ QPS です。
TwitterXApi の Create a Tweet or Reply エンドポイントは、X 公式 API に比べ次の利点があります:
- シンプルな認証:複雑な OAuth 不要、Bearer token のみ
- コスト効率:API 呼び出し 1 回 $0.01
- 豊富な機能:メディア、スケジュール、リプライ、コミュニティ投稿
- レート制限の煩わしさなし:X 公式 API の厳しい制限を回避
- 容易な統合:任意の言語で使える REST API
次の用途に最適です:
- SNS 管理:複数アカウントへのスケジュール投稿
- Twitter ボット:自動返信とエンゲージメント
- コンテンツ自動化:ブログ、ニュース、更新の自動共有
- カスタマーサービス:プログラムからの返信
- マーケティング:プロモーションと告知のスケジュール
API 概要
Answer: API 概要は本ガイドの TwexAPI エンドポイントを Bearer で呼び出して実装します。バッチ/ページングで約 14 Credits/回・20+ QPS です。
エンドポイントは https://api.twitterxapi.com/twitter/tweets/create への POST です。Bearer token 認証が必要で、ツイートをカスタマイズする各種パラメータを受け付けます。
主な機能
- ツイート作成:テキストとメディアで新規投稿
- リプライ機能:既存ツイートへの返信
- メディア対応:URL で画像を添付
- スケジュール:将来の投稿を予約
- コミュニティ投稿:特定コミュニティへ投稿
- Cookie 対応:認証 cookie で機能拡張
リクエストパラメータ
公式ドキュメントに基づく:
- tweet_content(string、必須):ツイート本文
- media_url(string、任意):添付画像 URL
- reply_tweet_id(string、任意):返信先ツイート ID
- schedule(string、任意):スケジュール用 ISO タイムスタンプ
- cookie(string、任意):機能拡張用認証 cookie
- community_name(string、任意):投稿先コミュニティ名
レスポンス構造
成功レスポンス(HTTP 200)は次を返します:
- code:ステータスコード(200 は成功)
- msg:成功メッセージ
- data:tweet_id、user_id、確認コードを含むオブジェクト
基本的なツイート作成例
Answer: 基本的なツイート作成例とは、この事例で api.twexapi.io の TwexAPI Bearer API を使う手順を指します(読み取り約 14 Credits/回、Pro で約 $0.14/1K、20+ QPS)。公式の $5〜$15/1K や 15 分 300 回制限より運用しやすいです。
まず、異なる方法でのシンプルな投稿例から始めます。
例 1:基本 cURL リクエスト
cURL でシンプルなツイートを投稿する方法:
curl --request POST \\
--url https://api.twitterxapi.com/twitter/tweets/create \\
--header 'Authorization: Bearer <your_token>' \\
--header 'Content-Type: application/json' \\
--data '{
"tweet_content": "Hello, world! This is my first automated tweet using TwitterXApi! 🚀"
}'期待されるレスポンス:
{
"code": 200,
"msg": "success",
"data": {
"tweet_id": "1234567890123456789",
"user_id": "1234567890",
"code": 200
}
}例 2:Python ツイート作成
ツイート投稿用 Python スクリプト:
1import requests
2import json
3
4def post_tweet(content, token):
5 """
6 Post a tweet using TwitterXApi
7 """
8 url = "https://api.twitterxapi.com/twitter/tweets/create"
9
10 headers = {
11 "Authorization": f"Bearer {token}",
12 "Content-Type": "application/json"
13 }
14
15 payload = {
16 "tweet_content": content
17 }
18
19 response = requests.post(url, headers=headers, data=json.dumps(payload))
20
21 if response.status_code == 200:
22 data = response.json()
23 print(f"Tweet posted successfully!")
24 print(f"Tweet ID: {data['data']['tweet_id']}")
25 print(f"User ID: {data['data']['user_id']}")
26 return data['data']['tweet_id']
27 else:
28 print(f"Error posting tweet: {response.status_code}")
29 print(response.text)
30 return None
31
32# Example usage
33TOKEN = "<your_bearer_token>"
34tweet_content = "Just posted this tweet programmatically using TwitterXApi! 🔥 #automation"
35
36tweet_id = post_tweet(tweet_content, TOKEN)高度なツイート作成機能
Answer: 高度なツイート作成機能とは、この事例で api.twexapi.io の TwexAPI Bearer API を使う手順を指します(読み取り約 14 Credits/回、Pro で約 $0.14/1K、20+ QPS)。公式の $5〜$15/1K や 15 分 300 回制限より運用しやすいです。
次に、このエンドポイントの高度な機能を見ていきます。
ツイートリプライの作成
リプライには reply_tweet_id パラメータを含めます:
1def post_reply(content, reply_to_tweet_id, token):
2 """
3 Post a reply to an existing tweet
4 """
5 url = "https://api.twitterxapi.com/twitter/tweets/create"
6
7 headers = {
8 "Authorization": f"Bearer {token}",
9 "Content-Type": "application/json"
10 }
11
12 payload = {
13 "tweet_content": content,
14 "reply_tweet_id": reply_to_tweet_id
15 }
16
17 response = requests.post(url, headers=headers, data=json.dumps(payload))
18
19 if response.status_code == 200:
20 data = response.json()
21 print(f"Reply posted successfully!")
22 print(f"Reply Tweet ID: {data['data']['tweet_id']}")
23 return data['data']['tweet_id']
24 else:
25 print(f"Error posting reply: {response.status_code}")
26 print(response.text)
27 return None
28
29# Example usage
30reply_content = "Thanks for sharing this! Really insightful content. 👍"
31original_tweet_id = "1234567890123456789"
32
33reply_id = post_reply(reply_content, original_tweet_id, TOKEN)メディア付きツイート投稿
media URL を指定してツイートに画像を添付:
1def post_tweet_with_media(content, media_url, token):
2 """
3 Post a tweet with an attached image
4 """
5 url = "https://api.twitterxapi.com/twitter/tweets/create"
6
7 headers = {
8 "Authorization": f"Bearer {token}",
9 "Content-Type": "application/json"
10 }
11
12 payload = {
13 "tweet_content": content,
14 "media_url": media_url
15 }
16
17 response = requests.post(url, headers=headers, data=json.dumps(payload))
18
19 if response.status_code == 200:
20 data = response.json()
21 print(f"Tweet with media posted successfully!")
22 print(f"Tweet ID: {data['data']['tweet_id']}")
23 return data['data']['tweet_id']
24 else:
25 print(f"Error posting tweet with media: {response.status_code}")
26 print(response.text)
27 return None
28
29# Example usage
30content = "Check out this amazing view! 🌅 #photography #nature"
31image_url = "https://example.com/beautiful-sunset.jpg"
32
33tweet_id = post_tweet_with_media(content, image_url, TOKEN)ツイートのスケジュール
ISO タイムスタンプで将来の投稿をスケジュール:
1from datetime import datetime, timedelta
2
3def schedule_tweet(content, schedule_time, token):
4 """
5 Schedule a tweet for future posting
6 """
7 url = "https://api.twitterxapi.com/twitter/tweets/create"
8
9 headers = {
10 "Authorization": f"Bearer {token}",
11 "Content-Type": "application/json"
12 }
13
14 # Convert datetime to ISO format
15 if isinstance(schedule_time, datetime):
16 schedule_iso = schedule_time.strftime("%Y-%m-%dT%H:%M:%SZ")
17 else:
18 schedule_iso = schedule_time
19
20 payload = {
21 "tweet_content": content,
22 "schedule": schedule_iso
23 }
24
25 response = requests.post(url, headers=headers, data=json.dumps(payload))
26
27 if response.status_code == 200:
28 data = response.json()
29 print(f"Tweet scheduled successfully for {schedule_iso}!")
30 print(f"Scheduled Tweet ID: {data['data']['tweet_id']}")
31 return data['data']['tweet_id']
32 else:
33 print(f"Error scheduling tweet: {response.status_code}")
34 print(response.text)
35 return None
36
37# Example usage - schedule tweet for tomorrow at 9 AM
38tomorrow_9am = datetime.now() + timedelta(days=1)
39tomorrow_9am = tomorrow_9am.replace(hour=9, minute=0, second=0, microsecond=0)
40
41content = "Good morning everyone! Starting the day with some inspiration. ☀️ #MondayMotivation"
42schedule_tweet(content, tomorrow_9am, TOKEN)ツイート管理システムの構築
Answer: ツイート管理システムの構築とは、この事例で api.twexapi.io の TwexAPI Bearer API を使う手順を指します(読み取り約 14 Credits/回、Pro で約 $0.14/1K、20+ QPS)。公式の $5〜$15/1K や 15 分 300 回制限より運用しやすいです。
全機能を統合したツイート管理システムの包括例:
1import requests
2import json
3import time
4from datetime import datetime, timedelta
5from typing import Optional, Dict, Any
6
7class TwitterXApiClient:
8 def __init__(self, bearer_token: str):
9 self.bearer_token = bearer_token
10 self.base_url = "https://api.twitterxapi.com/twitter/tweets/create"
11 self.headers = {
12 "Authorization": f"Bearer {bearer_token}",
13 "Content-Type": "application/json"
14 }
15
16 def post_tweet(
17 self,
18 content: str,
19 media_url: Optional[str] = None,
20 reply_to: Optional[str] = None,
21 schedule: Optional[datetime] = None,
22 community: Optional[str] = None,
23 cookie: Optional[str] = None
24 ) -> Optional[Dict[str, Any]]:
25 """
26 Post a tweet with all available options
27 """
28 payload = {"tweet_content": content}
29
30 if media_url:
31 payload["media_url"] = media_url
32 if reply_to:
33 payload["reply_tweet_id"] = reply_to
34 if schedule:
35 payload["schedule"] = schedule.strftime("%Y-%m-%dT%H:%M:%SZ")
36 if community:
37 payload["community_name"] = community
38 if cookie:
39 payload["cookie"] = cookie
40
41 try:
42 response = requests.post(
43 self.base_url,
44 headers=self.headers,
45 data=json.dumps(payload),
46 timeout=30
47 )
48
49 if response.status_code == 200:
50 return response.json()
51 else:
52 print(f"Error: {response.status_code} - {response.text}")
53 return None
54
55 except requests.exceptions.RequestException as e:
56 print(f"Request failed: {e}")
57 return None
58
59 def post_thread(self, tweets: list) -> list:
60 """
61 Post a thread of tweets
62 """
63 thread_ids = []
64 previous_tweet_id = None
65
66 for i, tweet_content in enumerate(tweets):
67 if i == 0:
68 # First tweet in thread
69 result = self.post_tweet(tweet_content)
70 else:
71 # Reply to previous tweet
72 result = self.post_tweet(tweet_content, reply_to=previous_tweet_id)
73
74 if result and result.get('data'):
75 tweet_id = result['data']['tweet_id']
76 thread_ids.append(tweet_id)
77 previous_tweet_id = tweet_id
78 print(f"Posted tweet {i+1}/{len(tweets)}: {tweet_id}")
79
80 # Add delay between tweets to avoid rate limiting
81 if i < len(tweets) - 1:
82 time.sleep(2)
83 else:
84 print(f"Failed to post tweet {i+1}")
85 break
86
87 return thread_ids
88
89 def schedule_content_series(self, content_schedule: list):
90 """
91 Schedule a series of tweets with specific times
92 """
93 scheduled_tweets = []
94
95 for content, schedule_time in content_schedule:
96 result = self.post_tweet(content, schedule=schedule_time)
97 if result:
98 scheduled_tweets.append({
99 'tweet_id': result['data']['tweet_id'],
100 'content': content,
101 'scheduled_for': schedule_time
102 })
103 print(f"Scheduled: {content[:50]}... for {schedule_time}")
104
105 return scheduled_tweets
106
107# Example usage
108client = TwitterXApiClient("<your_bearer_token>")
109
110# Post a simple tweet
111simple_tweet = client.post_tweet("Hello from my automated system! 🤖")
112
113# Post a tweet with media
114media_tweet = client.post_tweet(
115 "Check out this awesome chart! 📊",
116 media_url="https://example.com/chart.png"
117)
118
119# Post a thread
120thread_content = [
121 "🧵 Thread: Let me explain how to use TwitterXApi effectively (1/4)",
122 "First, you need to get your Bearer token from the dashboard. This is your authentication key. (2/4)",
123 "Then, you can use any programming language to make HTTP requests to the API endpoints. (3/4)",
124 "The possibilities are endless - bots, scheduling, analytics, and more! Happy coding! 🚀 (4/4)"
125]
126
127thread_ids = client.post_thread(thread_content)
128
129# Schedule content for the week
130now = datetime.now()
131weekly_schedule = [
132 ("Monday motivation! Let's make this week amazing! 💪", now + timedelta(days=1, hours=9)),
133 ("Wednesday wisdom: Consistency beats perfection every time. 🎯", now + timedelta(days=3, hours=12)),
134 ("Friday feels! What are your weekend plans? 🎉", now + timedelta(days=5, hours=17))
135]
136
137scheduled = client.schedule_content_series(weekly_schedule)Twitter ボット例
Answer: Twitter ボット例とは、この事例で api.twexapi.io の TwexAPI Bearer API を使う手順を指します(読み取り約 14 Credits/回、Pro で約 $0.14/1K、20+ QPS)。公式の $5〜$15/1K や 15 分 300 回制限より運用しやすいです。
メンションに応答する Twitter ボットの実践例:
1import requests
2import json
3import time
4import random
5
6class TwitterBot:
7 def __init__(self, bearer_token):
8 self.client = TwitterXApiClient(bearer_token)
9 self.responses = {
10 "greeting": [
11 "Hello! Thanks for reaching out! 👋",
12 "Hi there! How can I help you today? 😊",
13 "Hey! Great to hear from you! ✨"
14 ],
15 "thanks": [
16 "You're very welcome! 🙏",
17 "Happy to help! Feel free to reach out anytime! 😊",
18 "My pleasure! Have a great day! ☀️"
19 ],
20 "question": [
21 "That's a great question! Let me think about that... 🤔",
22 "Interesting point! I'd love to discuss this further. 💭",
23 "Thanks for asking! This is definitely worth exploring. 🔍"
24 ]
25 }
26
27 def get_random_response(self, category):
28 """Get a random response from a category"""
29 return random.choice(self.responses[category])
30
31 def determine_response_type(self, tweet_text):
32 """Determine what type of response to send based on tweet content"""
33 text_lower = tweet_text.lower()
34
35 if any(word in text_lower for word in ["hello", "hi", "hey", "good morning"]):
36 return "greeting"
37 elif any(word in text_lower for word in ["thank", "thanks", "thx"]):
38 return "thanks"
39 elif any(word in text_lower for word in ["?", "how", "what", "why", "when"]):
40 return "question"
41 else:
42 return "greeting" # Default
43
44 def respond_to_mention(self, tweet_id, tweet_text, username):
45 """Generate and post a response to a mention"""
46 response_type = self.determine_response_type(tweet_text)
47 response_text = self.get_random_response(response_type)
48
49 # Add username to response
50 full_response = f"@{username} {response_text}"
51
52 # Post reply
53 result = self.client.post_tweet(full_response, reply_to=tweet_id)
54
55 if result:
56 print(f"Replied to @{username}: {full_response}")
57 return result['data']['tweet_id']
58 else:
59 print(f"Failed to reply to @{username}")
60 return None
61
62 def post_daily_content(self):
63 """Post daily automated content"""
64 daily_posts = [
65 "Good morning! Starting the day with positive energy! ☀️ #MondayMotivation",
66 "Tuesday tip: Small consistent actions lead to big results! 💪 #TuesdayTip",
67 "Wednesday wisdom: Progress over perfection, always! 🎯 #WednesdayWisdom",
68 "Thursday thoughts: What are you grateful for today? 🙏 #ThursdayThoughts",
69 "Friday feels! Celebrating the wins, big and small! 🎉 #FridayFeels"
70 ]
71
72 # Get current day of week (0=Monday, 4=Friday)
73 today = datetime.now().weekday()
74
75 if today < 5: # Only post on weekdays
76 post_content = daily_posts[today]
77 result = self.client.post_tweet(post_content)
78
79 if result:
80 print(f"Posted daily content: {post_content}")
81 return result['data']['tweet_id']
82
83 return None
84
85# Example usage
86bot = TwitterBot("<your_bearer_token>")
87
88# Simulate responding to mentions (in a real bot, you'd get these from search API)
89mentions = [
90 {"tweet_id": "123", "text": "Hello bot!", "username": "user1"},
91 {"tweet_id": "124", "text": "Thanks for the info!", "username": "user2"},
92 {"tweet_id": "125", "text": "How does this work?", "username": "user3"}
93]
94
95for mention in mentions:
96 bot.respond_to_mention(
97 mention["tweet_id"],
98 mention["text"],
99 mention["username"]
100 )
101 time.sleep(1) # Rate limiting
102
103# Post daily content
104bot.post_daily_content()ベストプラクティスとヒント
Answer: ベストプラクティスとヒントとは、この事例で api.twexapi.io の TwexAPI Bearer API を使う手順を指します(読み取り約 14 Credits/回、Pro で約 $0.14/1K、20+ QPS)。公式の $5〜$15/1K や 15 分 300 回制限より運用しやすいです。
コンテンツガイドライン
- 文字数制限内:Twitter の文字数に収める
- 魅力的なコンテンツ:絵文字、ハッシュタグ、メンションを適切に
- レート制限を尊重:API 呼び出し間に遅延を入れる
- 量より質:スパムではなく価値あるコンテンツに集中
技術的ベストプラクティス
1import requests
2import json
3import time
4from datetime import datetime
5import logging
6
7# Set up logging
8logging.basicConfig(level=logging.INFO)
9logger = logging.getLogger(__name__)
10
11class BestPracticesTwitterClient:
12 def __init__(self, bearer_token):
13 self.bearer_token = bearer_token
14 self.base_url = "https://api.twitterxapi.com/twitter/tweets/create"
15 self.headers = {
16 "Authorization": f"Bearer {bearer_token}",
17 "Content-Type": "application/json"
18 }
19 self.last_request_time = 0
20 self.min_request_interval = 1 # Minimum 1 second between requests
21
22 def validate_content(self, content):
23 """Validate tweet content before posting"""
24 if not content or not content.strip():
25 raise ValueError("Tweet content cannot be empty")
26
27 if len(content) > 280:
28 raise ValueError(f"Tweet too long: {len(content)} characters (max 280)")
29
30 return True
31
32 def rate_limit_delay(self):
33 """Implement rate limiting"""
34 time_since_last = time.time() - self.last_request_time
35 if time_since_last < self.min_request_interval:
36 sleep_time = self.min_request_interval - time_since_last
37 logger.info(f"Rate limiting: sleeping for {sleep_time:.2f} seconds")
38 time.sleep(sleep_time)
39
40 def post_tweet_safely(self, content, **kwargs):
41 """Post tweet with validation and error handling"""
42 try:
43 # Validate content
44 self.validate_content(content)
45
46 # Rate limiting
47 self.rate_limit_delay()
48
49 # Prepare payload
50 payload = {"tweet_content": content}
51 payload.update(kwargs)
52
53 # Make request
54 response = requests.post(
55 self.base_url,
56 headers=self.headers,
57 data=json.dumps(payload),
58 timeout=30
59 )
60
61 self.last_request_time = time.time()
62
63 if response.status_code == 200:
64 data = response.json()
65 logger.info(f"Tweet posted successfully: {data['data']['tweet_id']}")
66 return data
67 else:
68 logger.error(f"API error: {response.status_code} - {response.text}")
69 return None
70
71 except ValueError as e:
72 logger.error(f"Validation error: {e}")
73 return None
74 except requests.exceptions.RequestException as e:
75 logger.error(f"Request error: {e}")
76 return None
77 except Exception as e:
78 logger.error(f"Unexpected error: {e}")
79 return None
80
81 def bulk_post_with_delays(self, tweets, delay_seconds=5):
82 """Post multiple tweets with proper delays"""
83 results = []
84
85 for i, tweet_content in enumerate(tweets):
86 logger.info(f"Posting tweet {i+1}/{len(tweets)}")
87
88 result = self.post_tweet_safely(tweet_content)
89 results.append(result)
90
91 # Add delay between posts (except for the last one)
92 if i < len(tweets) - 1:
93 logger.info(f"Waiting {delay_seconds} seconds before next tweet...")
94 time.sleep(delay_seconds)
95
96 return results
97
98# Example usage
99safe_client = BestPracticesTwitterClient("<your_bearer_token>")
100
101# Safe single tweet
102result = safe_client.post_tweet_safely(
103 "This tweet was posted using best practices! ✅ #coding #automation"
104)
105
106# Safe bulk posting
107bulk_tweets = [
108 "Tweet 1: Introduction to our new series! 🧵",
109 "Tweet 2: First tip - always validate your input! ✅",
110 "Tweet 3: Second tip - implement rate limiting! ⏱️",
111 "Tweet 4: Third tip - handle errors gracefully! 🛡️",
112 "Tweet 5: Thanks for following along! 🙏"
113]
114
115bulk_results = safe_client.bulk_post_with_delays(bulk_tweets, delay_seconds=3)エラーハンドリング
1def robust_tweet_post(content, token, max_retries=3):
2 """
3 Post tweet with retry logic and comprehensive error handling
4 """
5 for attempt in range(max_retries):
6 try:
7 url = "https://api.twitterxapi.com/twitter/tweets/create"
8 headers = {
9 "Authorization": f"Bearer {token}",
10 "Content-Type": "application/json"
11 }
12 payload = {"tweet_content": content}
13
14 response = requests.post(
15 url,
16 headers=headers,
17 data=json.dumps(payload),
18 timeout=30
19 )
20
21 if response.status_code == 200:
22 data = response.json()
23 logger.info(f"Tweet posted successfully on attempt {attempt + 1}")
24 return data
25 elif response.status_code == 429:
26 logger.warning("Rate limit hit, waiting 60 seconds...")
27 time.sleep(60)
28 elif response.status_code == 422:
29 logger.error(f"Validation error: {response.text}")
30 return None # Don't retry validation errors
31 else:
32 logger.warning(f"HTTP {response.status_code}: {response.text}")
33
34 except requests.exceptions.Timeout:
35 logger.warning(f"Timeout on attempt {attempt + 1}")
36 except requests.exceptions.RequestException as e:
37 logger.warning(f"Request failed on attempt {attempt + 1}: {e}")
38 except Exception as e:
39 logger.error(f"Unexpected error on attempt {attempt + 1}: {e}")
40
41 # Wait before retry (except on last attempt)
42 if attempt < max_retries - 1:
43 wait_time = 2 ** attempt # Exponential backoff
44 logger.info(f"Waiting {wait_time} seconds before retry...")
45 time.sleep(wait_time)
46
47 logger.error(f"Failed to post tweet after {max_retries} attempts")
48 return Noneユースケースと応用
Answer: ユースケースと応用とは、この事例で api.twexapi.io の TwexAPI Bearer API を使う手順を指します(読み取り約 14 Credits/回、Pro で約 $0.14/1K、20+ QPS)。公式の $5〜$15/1K や 15 分 300 回制限より運用しやすいです。
ソーシャルメディア管理
1class SocialMediaManager:
2 def __init__(self, bearer_token):
3 self.client = TwitterXApiClient(bearer_token)
4 self.scheduled_posts = []
5 self.posted_content = []
6
7 def create_content_calendar(self, start_date, days=7):
8 """Create a week's worth of scheduled content"""
9 content_templates = [
10 "Monday Motivation: {motivation_quote} 💪 #MondayMotivation",
11 "Tech Tuesday: {tech_tip} 🔧 #TechTuesday",
12 "Wednesday Wisdom: {wisdom_quote} 🧠 #WednesdayWisdom",
13 "Throwback Thursday: {throwback_content} 📸 #ThrowbackThursday",
14 "Feature Friday: {feature_highlight} ⭐ #FeatureFriday"
15 ]
16
17 for day in range(days):
18 post_date = start_date + timedelta(days=day)
19 day_of_week = post_date.weekday()
20
21 if day_of_week < 5: # Weekdays only
22 template = content_templates[day_of_week]
23 # In real implementation, you'd fill these from a content database
24 content = template.format(
25 motivation_quote="Success is the sum of small efforts!",
26 tech_tip="Always backup your code!",
27 wisdom_quote="Learn from yesterday, live for today.",
28 throwback_content="Remember our first product launch?",
29 feature_highlight="Check out our new API endpoint!"
30 )
31
32 self.scheduled_posts.append({
33 'content': content,
34 'schedule_time': post_date.replace(hour=9, minute=0),
35 'status': 'scheduled'
36 })
37
38 return self.scheduled_posts
39
40 def execute_scheduled_posts(self):
41 """Execute all scheduled posts that are due"""
42 now = datetime.now()
43 executed = []
44
45 for post in self.scheduled_posts:
46 if (post['status'] == 'scheduled' and
47 post['schedule_time'] <= now):
48
49 result = self.client.post_tweet(post['content'])
50 if result:
51 post['status'] = 'posted'
52 post['tweet_id'] = result['data']['tweet_id']
53 executed.append(post)
54 self.posted_content.append(post)
55
56 return executed
57
58# Example usage
59manager = SocialMediaManager("<your_bearer_token>")
60calendar = manager.create_content_calendar(datetime.now(), days=7)
61print(f"Created {len(calendar)} scheduled posts")
62
63# Execute due posts
64executed = manager.execute_scheduled_posts()
65print(f"Executed {len(executed)} posts")カスタマーサービスボット
1class CustomerServiceBot:
2 def __init__(self, bearer_token):
3 self.client = TwitterXApiClient(bearer_token)
4 self.auto_responses = {
5 'support': "Thanks for reaching out! Our support team will get back to you within 24 hours. For urgent issues, please DM us! 🆘",
6 'compliment': "Thank you so much for the kind words! We really appreciate your support! 🙏 ❤️",
7 'feature_request': "Thanks for the suggestion! We've noted your feature request and will consider it for future updates! 💡",
8 'bug_report': "We appreciate you reporting this issue! Our technical team is investigating. We'll keep you updated! 🔧"
9 }
10
11 def classify_tweet(self, tweet_text):
12 """Classify tweet to determine appropriate response"""
13 text_lower = tweet_text.lower()
14
15 if any(word in text_lower for word in ['help', 'support', 'issue', 'problem']):
16 return 'support'
17 elif any(word in text_lower for word in ['love', 'great', 'awesome', 'amazing']):
18 return 'compliment'
19 elif any(word in text_lower for word in ['feature', 'request', 'suggestion', 'could you add']):
20 return 'feature_request'
21 elif any(word in text_lower for word in ['bug', 'error', 'broken', 'not working']):
22 return 'bug_report'
23 else:
24 return 'support' # Default
25
26 def respond_to_customer(self, tweet_id, tweet_text, customer_username):
27 """Generate appropriate response to customer tweet"""
28 classification = self.classify_tweet(tweet_text)
29 response_template = self.auto_responses[classification]
30
31 # Personalize response
32 response = f"@{customer_username} {response_template}"
33
34 # Post reply
35 result = self.client.post_tweet(response, reply_to=tweet_id)
36
37 if result:
38 print(f"Responded to {customer_username} ({classification}): {response}")
39 return result['data']['tweet_id']
40
41 return None
42
43# Example usage
44cs_bot = CustomerServiceBot("<your_bearer_token>")
45
46# Simulate customer interactions
47customer_tweets = [
48 {"id": "1001", "text": "I'm having trouble with login", "username": "customer1"},
49 {"id": "1002", "text": "Your app is amazing! Love it!", "username": "customer2"},
50 {"id": "1003", "text": "Could you add dark mode?", "username": "customer3"},
51 {"id": "1004", "text": "Found a bug in the payment system", "username": "customer4"}
52]
53
54for tweet in customer_tweets:
55 cs_bot.respond_to_customer(tweet["id"], tweet["text"], tweet["username"])
56 time.sleep(2) # Rate limitingまとめ
TwitterXApi の Create a Tweet or Reply エンドポイントは、Twitter プレゼンスの自動化と高度な SNS アプリ構築に強力なツールです。ブランドアカウント管理、CS ボット、コンテンツ自動化——いずれにも必要な柔軟性と信頼性を提供します。
主な利点:
- 実装が簡単:明確なドキュメント付き REST API
- 機能が豊富:リプライ、メディア、スケジュール、コミュニティ
- コスト効率:1 回 $0.01、任意の規模に対応
- 信頼性:複雑な認証や厳しいレート制限なし
はじめに
- TwitterXApi.com で登録し Bearer token を取得
- シンプルに基本投稿から開始
- メディア、スケジュール、リプライを段階的に追加
- エラー処理とレート制限のベストプラクティスを実装
- より複雑な自動化へスケール
次のステップ
- 他の TwitterXApi エンドポイントで包括的な自動化
- Webhook でリアルタイム通知
- コンテンツ管理ダッシュボードの構築
- 分析とパフォーマンス追跡の実装を検討
可能性は無限大!今日から Twitter 自動化を構築し、SNS 管理を変えましょう。
詳細は API ドキュメント と X のコミュニティをご覧ください。
免責事項:本記事は 2025 年 7 月時点の TwitterXApi ドキュメントに基づきます。API は変更される可能性があるため、常に公式ドキュメントを参照してください。教育目的のみ。投稿時はプラットフォーム規約と適用法令を遵守してください。