twitter api

1,twurl安装

1.1,安装软件管理包工具,在管理员身份打开的cmd中执行:

@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

 

1.2,choco install ruby

1.3,gem install twurl

1.4,gem install jq 格式化json

 

2,注册twitter开发者账号

https://developer.twitter.com/

3, 使用Restful api

3.1 获取用户最新发布(文档的Tweets下面)

Get Tweet timelines

Filter realtime Tweets standard api for free

Sample realtime Tweets

 


Things every developer should know

 

There are different API families

The standard (free) Twitter APIs consist of REST APIs and Streaming APIs.

The enterprise (paid subscription) APIs include filtered firehose, historical search and engagement APIs for deeper data analytics, listening and other enterprise business applications. 

The premium (pay as you go) APIs consist of reliable and affordable versions of enterprise APIs, allowing your business to grow with your usage.  

Additionally, there are some families of APIs (such as the Ads API) which require applications to be whitelisted in order to make use of them.

The API aims to be a RESTful resource

With the exception of the Streaming API and Account Activity webhooks, the Twitter API endpoints attempt to conform to the design principles of Representational State Transfer (REST). Twitter APIs use the JSON data format for responses (and in some cases, for requests).

The API is HTTP-based (over SSL)

Methods to retrieve data from the Twitter API require a GET request. Methods that submit, change or destroy data require a POST. A DELETE request is also accepted for methods that destroy data. API methods that require a particular HTTP method will return an error if not invoked using the correct style. HTTP Response Codes are meaningful.

Tweet IDs can break Javascript

Use the id_str field instead of id whenever present to stay safe. Web browsers/Javascript interpreters/JSON consumers may munge large integer-based ids, which is why it is recommended to use the string representation. See the documentation on Twitter IDs (snowflake).

There are limits to how many calls and changes can be made in a day

API usage is rate limited, with additional account-based fair use limits on write/create/delete endpoints, to protect Twitter from abuse.

Parameters have certain expectations

Some API methods take optional or requisite parameters. Keep in mind when making requests with parameters:

  • Parameter values should be converted to UTF-8 and URL encoded.
  • The page parameter begins at 1, not 0.

Where noted, some API methods will return different results based on HTTP headers sent by the client. Where the same behavior can be controlled by both a parameter and an HTTP header, the parameter will take precedence.

There are pagination limits

REST API Limit

Clients may access a theoretical maximum of 3,200 statuses via the page and count parameters for the user_timeline REST API methods. Other timeline methods have a theoretical maximum of 800 statuses. Requests for more than the limit will result in a reply with a status code of 200 and an empty result in the format requested. Twitter still maintains a database of all the Tweets sent by a user. However, to ensure performance, this limit is in place on the API calls.

There are Twitter API libraries for almost any language

The community has created numerous Twitter API libraries. If you know of others we haven’t listed, let us know via the developer forums.

### 使用 Twitter API 进行开发 #### 创建开发者账号并获取API密钥 为了使用Twitter API,需要先注册成为Twitter开发者,并创建应用程序来获得必要的认证凭证。这包括消费者密钥(Consumer Key)、消费者秘密(Consumer Secret)、访问令牌(Access Token)以及访问令牌秘密(Access Token Secret)[^2]。 #### 安装库文件 对于Python开发者来说,推荐安装`Tweepy`这个第三方库,它简化了许多与Twitter API交互的过程。可以通过pip命令轻松安装此库: ```bash pip install tweepy ``` 而对于Node.js环境下的开发者,则可以选择`node-twitter-api-v2`作为接口调用工具[^3]。同样地,也可以利用npm来进行包管理器安装操作: ```bash npm install twitter-api-v2 ``` #### 编写代码连接至API 一旦获得了所需的认证信息并且选择了合适的客户端库之后,就可以编写简单的程序来测试是否能成功接入Twitter API了。下面给出一段基于Python (Tweepy) 的例子,展示怎样验证身份并向控制台打印出当前登录用户的名称[^1]: ```python import tweepy consumer_key = "YOUR_CONSUMER_KEY" consumer_secret = "YOUR_CONSUMER_SECRET" access_token = "YOUR_ACCESS_TOKEN" access_token_secret = "YOUR_ACCESS_TOKEN_SECRET" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) try: user = api.verify_credentials() print(f"Connection successful! User name is {user.name}") except Exception as e: print("Error during connection:", str(e)) ``` 同样的逻辑,在JavaScript(Node.js) 中实现如下所示: ```javascript const { TwitterApi } = require('twitter-api-v2'); (async () => { const client = new TwitterApi({ appKey: 'YOUR_CONSUMER_KEY', appSecret: 'YOUR_CONSUMER_SECRET', accessToken: 'YOUR_ACCESS_TOKEN', accessSecret: 'YOUR_ACCESS_TOKEN_SECRET' }); try { const me = await client.v2.me(); console.log(`Connected successfully! Username is ${me.data.username}`); } catch (error) { console.error('Failed to connect:', error); } })(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值