2017-09-22 187 views
1

正如問題所述,我想檢查一下twitter用戶ID列表的狀態。我有大約20k的推特用戶。我能夠獲得大約一半的時間表。其他人可能已被暫停,停用或有0條推文。我發現這個腳本在線,據說可以檢查twitter用戶的狀態。這裏是腳本(https://github.com/dbrgn/Twitter-User-Checker/blob/master/checkuser.py): `我想檢查一下twitter用戶ID列表的狀態

#!/usr/bin/env python2 

# Twitter User Checker 
# Author: Danilo Bargen 
# License: GPLv3 

import sys 
import tweepy 
import urllib2 
try: 
    import json 
except ImportError: 
    import simplejson as json 
from datetime import datetime 

auth = tweepy.AppAuthHandler("xxx", "xxxx") 

api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) 

if (not api): 
    print ("Can't Authenticate") 
    sys.exit(-1) 

# Continue with rest of code 


try: 
    user = sys.argv[1] 
except IndexError: 
    print 'Usage: checkuser.py [username]' 
    sys.exit(-1) 

url = 'https://api.twitter.com/1.1/users/show.json?id=%s' % user 

try: 
    request = urllib2.urlopen(url) 
    status = request.code 
    data = request.read() 
except urllib2.HTTPError, e: 
    status = e.code 
    data = e.read() 

data = json.loads(data) 

print data 

if status == 403: 
    print "helloooooooo" 
# if 'suspended' in data['error']: 
#  print 'User %s has been suspended' % user 
# else: 
#  print 'Unknown response' 
elif status == 404: 
    print 'User %s not found' % user 
elif status == 200: 
    days_active = (datetime.now() - datetime.strptime(data['created_at'], 
        '%a %b %d %H:%M:%S +0000 %Y')).days 
    print 'User %s is active and has posted %s tweets in %s days' % \ 
      (user, data['statuses_count'], days_active) 
else: 
    print 'Unknown response' 

`

我收到以下錯誤: File "twitter_status_checker.py", line 16, in <module> auth = tweepy.AppAuthHandler("xxx", "xxxx") File "/Users/aloush/anaconda/lib/python2.7/site-packages/tweepy/auth.py", line 170, in __init__ 'but got %s instead' % data.get('token_type')) tweepy.error.TweepError: Expected token_type to equal "bearer", but got None instead

誰能幫我修正這個錯誤,以及允許腳本檢查每次運行的用戶列表而不是一個用戶。

這裏是HTTP狀態代碼,我想檢查的列表:https://dev.twitter.com/overview/api/response-codes

謝謝。

回答

1

看來你沒有驗證twitter。對於最新版本(3.5),tweepy使用OAuthHander進行身份驗證。請檢查如何使用Tweepy。而且您使用的鏈接腳本是逐個檢查帳戶,這可能非常緩慢。

要檢查大集Twitter賬戶通過Tweepy的地位,特別是如果你想知道爲什麼它是無效的(例如,未找到,暫停),你需要注意以下幾點。:

  1. 應該使用哪個API?

Twitter提供了兩個相關的API,一個是user/show,另一個是user/lookup。前者返回一個指定用戶的配置文件,而後者返回最多100個用戶的配置文件。相應tweepy API是API.get_userAPI.lookup_users(我找不到它的文檔中,但它確實在代碼中存在)。當然,你應該使用第二個。但是,當存在一些非活動用戶時,只有這些活動的API返回lookup_users。這意味着您必須致電get_user API才能獲取非活動帳戶的詳細原因。

  1. 如何確定用戶的狀態?

當然,您應該注意Twitter提供的response code。但是,在使用tweepy而不是HTTP錯誤代碼時,您應該更多關注錯誤消息。以下是一些常見情況:

  • 如果配置文件被成功提取,它是一個活動用戶;
  • 否則,我們可以檢查錯誤代碼:
    • 50找不到用戶。
    • 63用戶已經暫停。
    • ...也許關於用戶更多的代碼解釋

對於tweepy,當個人資料無法取得,一個TweepyError提高。 TweepyError.message [0]是來自twitter API的錯誤消息。

好的,這是邏輯處理

(1)將較大的塊的用戶進入的100尺寸的片; (2)對於這些片段中的每一片,do(3)和(4);

(3)致電lookup_users,返回的用戶將被視爲活動用戶,其餘用戶將被視爲非活動用戶;

(4)調用get_user爲每個非活動用戶獲取詳細的原因。

這裏是你的示例代碼:

import logging 

import tweepy 

logger = logging.getLogger(__name__) 


def to_bulk(a, size=100): 
    """Transform a list into list of list. Each element of the new list is a 
    list with size=100 (except the last one). 
    """ 
    r = [] 
    qt, rm = divmod(len(a), size) 
    i = -1 
    for i in range(qt): 
     r.append(a[i * size:(i + 1) * size]) 
    if rm != 0: 
     r.append(a[(i + 1) * size:]) 
    return r 


def fast_check(api, uids): 
    """ Fast check the status of specified accounts. 
    Parameters 
    --------------- 
     api: tweepy API instance 
     uids: account ids 

    Returns 
    ---------- 
    Tuple (active_uids, inactive_uids). 
     `active_uids` is a list of active users and 
     `inactive_uids` is a list of inactive uids, 
      either supended or deactivated. 
    """ 
    try: 
     users = api.lookup_users(user_ids=uids, 
           include_entities=False) 
     active_uids = [u.id for u in users] 
     inactive_uids = list(set(uids) - set(active_uids)) 
     return active_uids, inactive_uids 
    except tweepy.TweepError as e: 
     if e[0]['code'] == 50 or e[0]['code'] == 63: 
      logger.error('None of the users is valid: %s', e) 
      return [], inactive_uids 
     else: 
      # Unexpected error 
      raise 


def check_inactive(api, uids): 
    """ Check inactive account, one by one. 
    Parameters 
    --------------- 
    uids : list 
     A list of inactive account 

    Returns 
    ---------- 
     Yield tuple (uid, reason). Where `uid` is the account id, 
     and `reason` is a string. 
    """ 
    for uid in uids: 
     try: 
      u = api.get_user(user_id=uid) 
      logger.warning('This user %r should be inactive', uid) 
      yield (u, dict(code=-1, message='OK')) 
     except tweepy.TweepyError as e: 
      yield (uid, e[0][0]) 


def check_one_block(api, uids): 
    """Check the status of user for one block (<100). """ 
    active_uids, inactive_uids = fast_check(api, uids) 
    inactive_users_status = list(check_inactive(api, inactive_uids)) 
    return active_uids, inactive_users_status 


def check_status(api, large_uids): 
    """Check the status of users for any size of users. """ 
    active_uids = [] 
    inactive_users_status = [] 
    for uids in to_bulk(large_uids, size=100): 
     au, iu = check_one_block(api, uids) 
     active_uids += au 
     inactive_users_status += iu 
    return active_uids, inactive_users_status 


def main(twitter_crendient, large_uids): 
    """ The main function to call check_status. """ 
    # First prepare tweepy API 
    auth = tweepy.OAuthHandler(twitter_crendient['consumer_key'], 
           twitter_crendient['consumer_secret']) 
    auth.set_access_token(twitter_crendient['access_token'], 
          twitter_crendient['access_token_secret']) 
    api = tweepy.API(auth, wait_on_rate_limit=True) 
    # Then, call check_status 
    active_uids, inactive_user_status = check_status(api, large_uids) 

由於缺乏數據的,我從來沒有對代碼進行測試。可能有錯誤,你應該照顧他們。

希望這是有幫助的。

+0

謝謝@rojeeer。我只有興趣知道X中的用戶x是否活動,如果不是爲什麼?是否暫停,停用等? 您上面寫的代碼不會返回錯誤的類型。例如,我通過用戶的此列表:' 的uid = [ '858379747549749249', '862798674891608064', '869677035291127808', '823878900413583363', '863111039986135040', '851767792521146368', '849779141734002688', '753953185857933312', '863051428805398529' ,'847459130017067008','1694924514']',並且只有其中兩個返回,因爲它們是活動的。 – Aloush87