Twitter API 사용법 및 유료 멤버십 필요성

Cramming An·2023년 5월 15일
1

Early Risk Detection

목록 보기
4/5
post-thumbnail

Twitter API와 ID를 활용한 Twitter data fetch 방법

Motivation

Twitter ID에 해당하는 Tweet이 필요합니다.

BEARD 데이터는 Twitter ID로 구성이 돼 있습니다.

따라서 BEARD 데이터를 구축하기 위해서 ID를 실제 Tweet으로 바꿔야 합니다.

What to do

Twitter API와 ID를 활용해 Data를 fetch 할 예정입니다.

아래와 같은 단계를 거칠 것 입니다.

  1. 필요한 endpoint 파악
  2. Authentication
  3. fetch code 작성 및 테스트
  4. 데이터 fetch 후 저장

📌 필요한 endpoint 파악

우리가 필요한 endpoint는 Tweets lookup 입니다.

Tweets이란?

Tweet은 Twitter에 개인이 올리는 post를 의미합니다. 다양한 형태의 데이터 타입으로 이루어져 있지만, 우리가 원하는 것은 Text 기반의 Tweet 입니다.

이 때 Tweet은 최대 280 characters를 가질 수 있고, Tweet ID로 specified 됩니다.

그리고 Tweet ID로 Tweet를 얻기 위해선 GET HTTP가 활용됩니다.

해당 endpoint는 다음과 같습니다.

"https://api.twitter.com/2/tweets?{}&{}".format(ids, tweet_fields)

📌 Authentication

다음 중 1개의 authentication이 필요합니다.

📌 fetch code 작성 및 테스트

친절하게도 sample code가 있습니다. [link]

import requests
import os
import json

# To set your enviornment variables in your terminal run the following line:
# export 'BEARER_TOKEN'='<your_bearer_token>'
bearer_token = os.environ.get("BEARER_TOKEN")

def create_url():
    tweet_fields = "tweet.fields=lang,author_id"
    # Tweet fields are adjustable.
    # Options include:
    # attachments, author_id, context_annotations,
    # conversation_id, created_at, entities, geo, id,
    # in_reply_to_user_id, lang, non_public_metrics, organic_metrics,
    # possibly_sensitive, promoted_metrics, public_metrics, referenced_tweets,
    # source, text, and withheld
    ids = "ids=1278747501642657792,1255542774432063488"
    # You can adjust ids to include a single Tweets.
    # Or you can add to up to 100 comma-separated IDs
    url = "https://api.twitter.com/2/tweets?{}&{}".format(ids, tweet_fields)
    return url

def bearer_oauth(r):
    """
    Method required by bearer token authentication.
    """

    r.headers["Authorization"] = f"Bearer {bearer_token}"
    r.headers["User-Agent"] = "v2TweetLookupPython"
    return r

def connect_to_endpoint(url):
    response = requests.request("GET", url, auth=bearer_oauth)
    print(response.status_code)
    if response.status_code != 200:
        raise Exception(
            "Request returned an error: {} {}".format(
                response.status_code, response.text
            )
        )
    return response.json()

def main():
    url = create_url()
    json_response = connect_to_endpoint(url)
    print(json.dumps(json_response, indent=4, sort_keys=True))

if __name__ == "__main__":
    main()

🚨 이슈발생

다음과 같은 에러가 발생했습니다.

Request returned an error: 403 {"client_id":"27087093","detail":"When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.","registration_url":"https://developer.twitter.com/en/docs/projects/overview","title":"Client Forbidden","required_enrollment":"Appropriate Level of API Access","reason":"client-not-enrolled","type":"https://api.twitter.com/2/problems/client-forbidden"}

Project와 attached 된 App을 사용해야 한다는 내용입니다.

https://developer.twitter.com/ 를 보니 Project와 App은 이미 attached가 된 듯 하여 구글링을 해보았습니다.

Twitter developer App을 확인해보았습니다.

구글링 내용처럼 현재 Standalone Apps 이었습니다.

App을 지우고 다시 만들었습니다.

하지만 여전히 Standalone Apps 이고 같은 에러 메시지가 발생합니다.

권한문제?

해결방안으로 2가지 방법을 시도합니다.

  1. tweepy 사용
  2. v2 API 대신 v1.1 API를 활용

Tweepy

우선 Twitter API v1.1 Endpoint 를 활용했습니다.

import tweepy
from utils.const import consumer_key, consumer_key_secret, access_token, access_token_secret, bearer_token

auth = tweepy.OAuth1UserHandler(
    consumer_key, consumer_key_secret, access_token, access_token_secret
)

api = tweepy.API(auth)

public_tweets = api.lookup_statuses([1228393702244134912])
for tweet in public_tweets:
    print(tweet.text)

하지만 다음과 같은 에러가 발생했습니다.

403 Forbidden
453 - You currently have Essential access which includes access to Twitter API v2 endpoints only. If you need access to this endpoint, you’ll need to apply for Elevated access via the Developer Portal. You can learn more here:

https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve

Twitter API v2 endpoints only 이기 때문에 v2 API tweepy 라이브러리를 활용해보겠습니다.

import tweepy
from utils.const import consumer_key, consumer_key_secret, access_token, access_token_secret, bearer_token

client = tweepy.Client(bearer_token=bearer_token, consumer_key=consumer_key, consumer_secret=consumer_key_secret, access_token=access_token, access_token_secret=access_token_secret,)

client.get_tweets([1228393702244134912])

403 Forbidden
When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.

Project와 attached 된 App을 사용해야 한다는 내용이 다시 나타났습니다.

Conclusion

Free 계정에서는 단 3개의 endpoint만 작동이 됩니다.

다음과 같이 create_tweet은 잘 됩니다. ㅎㅎ


다음은 멤버쉽에 따른 접근 권한 endpoint 입니다.

따라서, Basic 멤버십이 있어야 tweet lookup이 가능합니다.

profile
La Dolce Vita🥂

0개의 댓글