본문 바로가기
💻 programming

[트위터-티스토리] 트위터 오픈 API 등록하기, 개발자 계정 신청하기, tweepy 실시간 트렌드 가져오기 <3>

by 연구원-A 2022. 12. 29.
반응형

 

티스토리 API를 사용하려고 Access token을 받았던 것처럼

트위터 API를 이용해 실시간 트렌드를 읽어오거나, 트윗-리트윗을 하려면 개발자 계정을 신청해야 한다.

 

1. 개발자 계정 신청하기

개발자 계정이라고해서 특별한 건 아니고, 원래 사용하던 트위터 계정에 개발자 권한을 신청하는 거라 생각하면 된다.

(이미 가입이 되어있어야 한다는 소리)

 

아래 링크로 들어가서 로그인하면 "Create an APP" 버튼을 눌러 개발자 계정에 지원할 수 있다.

https://developer.twitter.com/en/portal/petition/use-case

 

트위터 로그인 / 트위터

휴대폰, 이메일, 사용자 아이디

twitter.com

트위터에서 요청하는 양식에 맞게 작성하고 신청하면 Essential 등급으로 개발자 계정 신청이 완료된다.

별도의 검토나 승인 과정없이 양식에만 맞게 신청하면 개발자 계정을 얻을 수 있다.

 

Essential 등급 신청하는 방법은 해당 블로그 참고 (https://limitt.tistory.com/145)

 

cf. 트위터 API 접속 제한 등급

구글링하다보니 뭔가 미묘하게 달라서 찾아보니 트위터 API v2가 공개되었다고 한다.

트위터 실시간 트렌드 결과를 가져오려면 Elevated 등급이 되어야 한다.

 

사실 twitter API를 사용하다가 아래와 같은 에러가 발생해서 알게되었다.

Does your app have Essential Access, or Elevated Access? You will need elevated access to use the V1.1 API which is probably what the Google Script is using. – Andy Piper
  Essential Elevated Elevated+
(coming soon)
Academic Research
Getting access Sign up Apply for additional access within the developer portal Need more?
Sign up for our waitlist
Apply for additional access
Price Free Free Free
Access to Twitter API v2 ✔️ ✔️ ✔️
Access to standard v1.1 ✔️ (Limited access - only media endpoints) ✔️ ✔️
Access to premium v1.1 ✔️ ✔️
Access to enterprise ✔️ ✔️
Project limits 1 Project 1 Project 1 Project
App limits 1 App per Project 3 Apps per Project 1 App per Project
Tweet caps Retrieve up to 500k Tweets per month Retrieve up to 2 million Tweets per month Retrieve up to 10 million Tweets per month
Filtered stream rule limit 5 rules 25 rules 1000 rules
Filtered stream rule length 512 characters 512 characters 1024 characters
Filtered stream POST rules rate limit 25 requests per 15 minutes 50 requests per 15 minutes 100 requests per 15 minutes
Search Tweets query length 512 characters 512 characters 1024 characters
Access to full-archive search Tweets ✔️
Access to full-archive Tweet counts ✔️
Access to advanced filter operators ✔️
Option to manage a team in the developer portal ✔️ (Requires an organization type account)
Access to the Ads API ✔️ (Requires additional application) ✔️ (Requires additional application)
Authentication methods OAuth 2.0 with PKCE

App only
OAuth 2.0 with PKCE

OAuth 1.0a

App only
OAuth 2.0 with PKCE

OAuth 1.0a

App only

 

2. Elevated 등급 요청하기

tweepy.API(auth).available_trends() 처럼 몇몇 API는 Essential 계정에서는 접근할 수가 없다.

해당 API를 사용하기 위해서는 Elevated 등급을 다시 요청해야하는데,

Elevated 등급부터는 심사/승인 과정을 거친다.

 

How will you use the Twitter API or Twitter Data?
트위터 API 또는 트위터 데이터를 어떻게 사용할 것입니까?

 

Are you planning to analyze Twitter data?
트위터 데이터를 분석할 예정입니까?

 

Will your App use Tweet, Retweet, Like, Follow, or Direct Message functionality?
당신의 애플리케이션은 트윗, 리트윗, 마음에 들어요, 팔로우, 또는 쪽지 기능을 사용할 예정입니까?

 

Do you plan to display Tweets or aggregate data about Twitter content outside Twitter?
트위터 외부에서 트윗을 표시하거나 트위터에 관한 데이터를 집계할 예정입니까?

 

Will your product, service, or analysis make Twitter content or derived information available to a government entity?
당신의 제품, 서비스, 혹은 분석을 통해 트위터 콘텐츠 또는 그로부터 유래된 정보를 정부 단체에 제공할 것입니까?

 

위 설문에 대해 각각 영어로 응답하면 신청이 끝난다.

심사는 굉-장히 빠르게 (몇 시간만에) 진행되고, 대답이 모호한 부분은 메일로 다시 질문이 온다.

Hello,
Thanks for your interest in building on Twitter!
To finish our review of your application, please reply to the following questions:
What’s your key use case or business purpose for using the Twitter APIs? Do you intend to analyze Tweets, Twitter users, or their content? If yes, how will you run this analysis?Will your use case involve Tweeting, Retweeting, or liking content? If yes, how will you interact with the Twitter accounts? Will you display Twitter content outside of Twitter? If yes, how and where will you display the content? Will Twitter content be displayed at row level or aggregated?
We appreciate your help! 
 
Thanks, 
Twitter

구글 번역도 하고 적당히 찾아서 답변하면,,

Hello,
Thank you for the information. I have answered your questions.
The core use case, intent, or business purpose for your use of the Twitter APIs.
 * I just consider a simple project to introduce daily/weekly/monthly Twitter's trending topics on my site.
   * First, I will get the trends of South Korea via Twitter API
   * Then, we make content regarding the keywords of the trending topics
   * Then, we finally post the content to my site by using blog's APIs
If you intend to analyze Tweets, Twitter users, or their content, please share details about the analyses you plan to conduct, and the methods or techniques.
 * First, we just gather the daily keywords of trending topics (user's trends and preferences) through the Twitter API.
 * Then, we will try to find a reason why these topics became hot topics by searching the keyword in Wiki page.
If your use involves Tweeting, Retweeting, or liking content, share how you will interact with Twitter users or their content.
 * No, we don't have a plan to tweet, retweet, likes.
If you’ll display Twitter content off of Twitter, please explain how, and where, Tweets and Twitter content will be displayed to users of your product or service, including whether Tweets and Twitter content will be displayed at row level, or aggregated.
* I plan to display the analysis of South Korea's trending topics on my site including keywords (title), explanations, and the number of tweets about the topics at the row level.
Thank you.

 

Elevated Access Approved 되었다는 메일이 온다.

 

3. 실시간 트렌드 가져오기

트위터 API를 쉽게 호출해주는 python 라이브러리인 tweepy를 사용했다.

 

pip를 이용해서 간단히 설치할 수 있고

https://docs.tweepy.org/ko/latest/install.html

pip3 install tweepy

 

아래 python 스크립트를 호출해서 5000건 이상 트윗-리트윗된 키워드를 얻을 수 있다.

import tweepy
# import keys

class TwitterManager:
    def __init__(self):
        self.__twitter_consumer_key = '본인의 consumer key'
        self.__twitter_consumer_secret = '본인의 consumer secret'
        self.__twitter_access_token = '본인의 access token'
        self.__twitter_access_secret = '본인의 access secret'

    def initialize(self):
        auth = tweepy.OAuthHandler( self.__twitter_consumer_key,
                                    self.__twitter_consumer_secret)
        auth.set_access_token(  self.__twitter_access_token,
                                self.__twitter_access_secret)
        self.__api = tweepy.API(auth)

    def run(self):
        pass

    def get_trending_topics(self):
        trends_available = self.__api.available_trends()
        print(f"Number of Trends availables: {len(trends_available)}")
        rj_trends = self.__api.get_place_trends(id =1132599) # WOEID of Seoul; 1132599
        trends = []
        for trend in rj_trends[0]['trends']:
            if trend['tweet_volume'] is not None and trend['tweet_volume'] > 5000:
                trends.append((trend['name'], trend['tweet_volume']))

        trends.sort(key=lambda x:-x[1])
        print(trends)
        return trends
        
twt = TwitterManager()
twt.initialize()
twt.get_trending_topics()

 

오늘 (2022-12-29) 대한민국의 실시간 트렌드 중에서 5000건 이상 게시된 키워드는

자카르타, #HAPPYVDAY, 경인고속도로 3가지이다.

Number of Trends availables: 467
v[('자카르타', 53576), ('#HAPPYVDAY', 35018), ('경인고속도로', 12843)]

 

2022.12.13 - [programming] - [트위터-티스토리] 트위터 실시간 트렌드를 티스토리에 자동으로 포스트하기 <1>

2022.12.21 - [programming] - [트위터-티스토리] 티스토리 오픈 API 등록하기, Access token 발급받기, 카테고리 목록 가져오기 <2>

 

 

 

 

반응형

댓글