无法访问Twitter上的@handles

时间:2017-02-26 20:10:07

标签: python twitter

我使用以下功能从Twitter上的帐户访问推文。当我输入cs50时,它运行正常,但是当我输入任何像@ cs50这样的句柄时,它都不返回。

def get_user_timeline(screen_name, count=200):
"""Return list of most recent tweets posted by screen_name."""

# ensure count is valid
if count < 1 or count > 200:
    raise RuntimeError("invalid count")

# ensure environment variables are set
if not os.environ.get("API_KEY"):
    raise RuntimeError("API_KEY not set")
if not os.environ.get("API_SECRET"):
    raise RuntimeError("API_SECRET not set")

# get screen_name's most recent tweets
# https://dev.twitter.com/rest/reference/get/users/lookup
# https://dev.twitter.com/rest/reference/get/statuses/user_timeline
# https://github.com/ryanmcgrath/twython/blob/master/twython/endpoints.py
try:
    twitter = Twython(os.environ.get("API_KEY"), os.environ.get("API_SECRET"))
    user = twitter.lookup_user(screen_name=screen_name)
    if user[0]["protected"]:
        return None
    tweets = twitter.get_user_timeline(screen_name=screen_name, count=count)
    return [html.unescape(tweet["text"].replace("\n", " ")) for tweet in tweets]
except TwythonAuthError:
    raise RuntimeError("invalid API_KEY and/or API_SECRET") from None
except TwythonRateLimitError:
    raise RuntimeError("you've hit a rate limit") from None
except TwythonError:
    return None

1 个答案:

答案 0 :(得分:1)

如果@符号是API的问题,您可以在传递之前清理变量,如下所示:

screen_name = screen_name[1:] if screen_name.startswith("@") else screen_name