This project has been archived by its maintainers, and is no longer receiving any updates.
tweepy-authlib
Table of Contents
Description
Twitter Web App (Web 版公式クライアント) の内部 API を使い、Tweepy でスクリーンネームとパスワードで認証するためのライブラリです。
スクリーンネーム (ex: @elonmusk) とパスワードを指定して認証し、取得した Cookie などの認証情報で Twitter API v1.1 にアクセスできます。
毎回ログインしていては面倒 & 不審なアクセス扱いされそうなので、Cookie をファイルなどに保存し、次回以降はその Cookie を使ってログインする機能もあります。
Tweepy を利用しているソースコードのうち、認証部分 (tweepy.auth.OAuth1UserHandler) を tweepy_authlib.CookieSessionUserHandler に置き換えるだけで、かんたんに Cookie ベースの認証に変更できます!
認証部分以外は OAuth API のときの実装がそのまま使えるので、ソースコードの変更も最小限に抑えられます。
認証フローは、ブラウザ上で動作する Web 版公式クライアントの API アクセス動作や HTTP リクエストヘッダーを、可能な限りシミュレートしています。
ブラウザから抽出した Web 版公式クライアントのログイン済み Cookie を使うことでも認証が可能です。
Installation
pip install tweepy-authlib
Usage
With JSON
import json
import os
from pathlib import Path
from pprint import pprint
import dotenv
import tweepy
from requests.cookies import RequestsCookieJar
from tweepy_authlib import CookieSessionUserHandler
try:
terminal_size = os.get_terminal_size().columns
except OSError:
terminal_size = 80
# ユーザー名とパスワードを環境変数から取得
dotenv.load_dotenv()
screen_name = os.environ.get('TWITTER_SCREEN_NAME', 'your_screen_name')
password = os.environ.get('TWITTER_PASSWORD', 'your_password')
# 保存した Cookie を使って認証
## 毎回ログインすると不審なログインとして扱われる可能性が高くなるため、
## できるだけ以前認証した際に保存した Cookie を使って認証することを推奨
if Path('cookie.json').exists():
# 保存した Cookie を読み込む
with open('cookie.json') as f:
cookies_dict = json.load(f)
# RequestCookieJar オブジェクトに変換
cookies = RequestsCookieJar()
for key, value in cookies_dict.items():
cookies.set(key, value)
# 読み込んだ RequestCookieJar オブジェクトを CookieSessionUserHandler に渡す
auth_handler = CookieSessionUserHandler(cookies=cookies)
# スクリーンネームとパスワードを指定して認証
else:
# スクリーンネームとパスワードを渡す
## スクリーンネームとパスワードを指定する場合は初期化時に認証のための API リクエストが多数行われるため、完了まで数秒かかる
try:
auth_handler = CookieSessionUserHandler(screen_name=screen_name, password=password)
except tweepy.HTTPException as ex:
# パスワードが間違っているなどの理由で認証に失敗した場合
if len(ex.api_codes) > 0 and len(ex.api_messages) > 0:
error_message = f'Code: {ex.api_codes[0]}, Message: {ex.api_messages[0]}'
else:
error_message = 'Unknown Error'
raise Exception(f'Failed to authenticate with password ({error_message})')
except tweepy.TweepyException as ex:
# 認証フローの途中で予期せぬエラーが発生し、ログインに失敗した
error_message = f'Message: {ex}'
raise Exception(f'Unexpected error occurred while authenticate with password ({error_message})')
# 現在のログインセッションの Cookie を取得
cookies_dict = auth_handler.get_cookies_as_dict()
# Cookie を JSON ファイルに保存
with open('cookie.json', 'w') as f:
json.dump(cookies_dict, f, ensure_ascii=False, indent=4)
# Tweepy で Twitter API v1.1 にアクセス
api = tweepy.API(auth_handler)
print('=' * terminal_size)
print('Logged in user:')
print('-' * terminal_size)
user = api.verify_credentials()
assert user.screen_name == os.environ['TWITTER_SCREEN_NAME']
pprint(user._json)
print('=' * terminal_size)
print('Followers (3 users):')
print('-' * terminal_size)
followers = user.followers(count=3)
for follower in followers:
pprint(follower._json)
print('-' * terminal_size)
print('=' * terminal_size)
print('Home timeline (3 tweets):')
print('-' * terminal_size)
home_timeline = api.home_timeline(count=3)
for status in home_timeline:
pprint(status._json)
print('-' * terminal_size)
print('=' * terminal_size)
# 継続してログインしない場合は明示的にログアウト
## 単に Cookie を消去するだけだと Twitter にセッションが残り続けてしまう
## ログアウト後は、取得した Cookie は再利用できなくなる
# auth_handler.logout()
# os.unlink('cookie.json')
With Pickle
import os
import pickle
from pathlib import Path
from pprint import pprint
import dotenv
import tweepy
from tweepy_authlib import CookieSessionUserHandler
try:
terminal_size = os.get_terminal_size().columns
except OSError:
terminal_size = 80
# ユーザー名とパスワードを環境変数から取得
dotenv.load_dotenv()
screen_name = os.environ.get('TWITTER_SCREEN_NAME', 'your_screen_name')
password = os.environ.get('TWITTER_PASSWORD', 'your_password')
# 保存した Cookie を使って認証
## 毎回ログインすると不審なログインとして扱われる可能性が高くなるため、
## できるだけ以前認証した際に保存した Cookie を使って認証することを推奨
if Path('cookie.pickle').exists():
# 保存した Cookie を読み込む
with open('cookie.pickle', 'rb') as f:
cookies = pickle.load(f)
# 読み込んだ RequestCookieJar オブジェクトを CookieSessionUserHandler に渡す
auth_handler = CookieSessionUserHandler(cookies=cookies)
# スクリーンネームとパスワードを指定して認証
else:
# スクリーンネームとパスワードを渡す
## スクリーンネームとパスワードを指定する場合は初期化時に認証のための API リクエストが多数行われるため、完了まで数秒かかる
try:
auth_handler = CookieSessionUserHandler(screen_name=screen_name, password=password)
except tweepy.HTTPException as ex:
# パスワードが間違っているなどの理由で認証に失敗した場合
if len(ex.api_codes) > 0 and len(ex.api_messages) > 0:
error_message = f'Code: {ex.api_codes[0]}, Message: {ex.api_messages[0]}'
else:
error_message = 'Unknown Error'
raise Exception(f'Failed to authenticate with password ({error_message})')
except tweepy.TweepyException as ex:
# 認証フローの途中で予期せぬエラーが発生し、ログインに失敗した
error_message = f'Message: {ex}'
raise Exception(f'Unexpected error occurred while authenticate with password ({error_message})')
# 現在のログインセッションの Cookie を取得
cookies = auth_handler.get_cookies()
# Cookie を pickle 化して保存
with open('cookie.pickle', 'wb') as f:
pickle.dump(cookies, f)
# Tweepy で Twitter API v1.1 にアクセス
api = tweepy.API(auth_handler)
print('=' * terminal_size)
print('Logged in user:')
print('-' * terminal_size)
user = api.verify_credentials()
assert user.screen_name == os.environ['TWITTER_SCREEN_NAME']
pprint(user._json)
print('=' * terminal_size)
print('Followers (3 users):')
print('-' * terminal_size)
followers = user.followers(count=3)
for follower in followers:
pprint(follower._json)
print('-' * terminal_size)
print('=' * terminal_size)
print('Home timeline (3 tweets):')
print('-' * terminal_size)
home_timeline = api.home_timeline(count=3)
for status in home_timeline:
pprint(status._json)
print('-' * terminal_size)
print('=' * terminal_size)
# 継続してログインしない場合は明示的にログアウト
## 単に Cookie を消去するだけだと Twitter にセッションが残り続けてしまう
## ログアウト後は、取得した Cookie は再利用できなくなる
# auth_handler.logout()
# os.unlink('cookie.pickle')
License
Metadata
Release files for tweepy-authlib 1.7.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| tweepy_authlib-1.7.3.tar.gz | 27.1 kB | Without provenance | Details for tweepy_authlib-1.7.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| tweepy_authlib-1.7.3-py3-none-any.whl | Python 3 | none | any | Details for tweepy_authlib-1.7.3-py3-none-any.whl |
Total release size: 49.5 kB
Release files / tweepy_authlib-1.7.3.tar.gz
| Download URL | tweepy_authlib-1.7.3.tar.gz |
|---|---|
| Size | 27.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ddcbf3de9f33702a0192ce917b71d3105b9bdfc0c8d88e2b1ce02c2348ad894a
|
|
BLAKE2b-256 checksum How to use checksums |
183046d88a690409f5f89f24c8195b28b6e7f5c3788d9b5439171c7179adefa0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Release files / tweepy_authlib-1.7.3-py3-none-any.whl
| Download URL | tweepy_authlib-1.7.3-py3-none-any.whl |
|---|---|
| Size | 22.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2125b6d447244b8ae59f665c718462154c9d2f7844d54f8fd8e7a862400bb4a3
|
|
BLAKE2b-256 checksum How to use checksums |
a6fb38c8ffb819b43e9f4ee6f427a293a70aceeb67790bf11db17c5e72439af7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Security for tweepy-authlib 1.7.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.