喵星在成功接入Farcaste后,想着也可以接入X (x.com) 。X上的用户还是蛮活跃的,做做运营还是必要的。
问了一轮Gemini,很快就解决了,试了下,也就十数行代码即可接入X,简直不要太简单!说起来X还是蛮开放的,这要搁国内,还不得死死捂住谁也不让接入!
前期准备
在编写代码之前,需要在 X Developer Portal 完成以下步骤:
- 创建项目和应用:获取 API Key、API Key Secret、Access Token 和 Access Token Secret。
- 设置权限:这是最关键的一步。在 App Settings 中,将 User authentication settings 里的权限从 "Read" 改为 "Read and Write",否则你无法发布帖子。
发帖
npm install twitter-api-v2 --save
import { TwitterApi } from 'twitter-api-v2'
// 替换为你的 API 凭证
const client = new TwitterApi({
appKey: 'Your_API_KEY',
appSecret: 'Your_API_KEY_SECRET',
accessToken: 'Your_ACCESS_TOKEN',
accessSecret: 'Your_ACCESS_TOKEN_SECRET',
})
async function postTweet(content) {
try {
const tweet = await client.v2.tweet(content)
console.log('发布成功!帖子 ID:', tweet.data.id) //发布成功!
} catch (error) {
console.error('发布失败:', error)
}
}
postTweet("GM")
// 带图片的帖文
// 1. 上传媒体文件 (使用 v1.1 接口上传)
const mediaId = await client.v1.uploadMedia(filePath)
// 2. 发布带媒体 ID 的帖子 (使用 v2 接口)
await client.v2.tweet({
text: text,
media: { media_ids: [mediaId] }
})
console.log('带图帖子发布成功')
/*
多图发布:media_ids 是一个数组。可以多次调用 uploadMedia,最多将 4 张图片 的 ID 放入该数组中。
视频与 GIF:
如果是 GIF,同样使用 uploadMedia,但数组只能包含这一个 ID。
如果是 视频,建议使用 client.v1.uploadMedia(path, { type: 'longvideo' }),该方法会自动处理分段上传(Chunked Upload),因为视频文件通常较大。
图片描述 (Alt Text):为了无障碍体验,你可以为图片添加描述:
await client.v1.createMediaMetadata(mediaId, { alt_text: { text: '这张图片描述了一只猫' } })
*/
这就行啰!接入X还是挺简单的,快试试吧。

Congratulations @lemooljiang! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)
Your next payout target is 37000 HP.
The unit is Hive Power equivalent because post and comment rewards can be split into HP and HBD
You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word
STOP