twitter-api-client

twitter-api-client

Python实现的全面Twitter API开发库

twitter-api-client是一个Python库,实现了Twitter的v1、v2和GraphQL API。该库支持账户自动化、数据抓取、搜索和Spaces音频捕获等功能,可用于构建Twitter应用和数据分析工具。它简化了开发流程,使开发者能更便捷地使用Twitter API。

Twitter API社交媒体数据抓取自动化PythonGithub开源项目

Implementation of X/Twitter v1, v2, and GraphQL APIs

PyPI Version Python Version <img src="https://static.pepy.tech/badge/twitter-api-client"/> <img src="https://static.pepy.tech/badge/twitter-api-client/month"/> GitHub License

Table of Contents

Installation

pip install twitter-api-client -U

Automation

As of Fall 2023 login by username/password is unstable. Using cookies is now recommended.

from twitter.account import Account ## sign-in with credentials email, username, password = ..., ..., ... account = Account(email, username, password) ## or, resume session using cookies # account = Account(cookies={"ct0": ..., "auth_token": ...}) ## or, resume session using cookies (JSON file) # account = Account(cookies='twitter.cookies') account.tweet('test 123') account.untweet(123456) account.retweet(123456) account.unretweet(123456) account.reply('foo', tweet_id=123456) account.quote('bar', tweet_id=123456) account.schedule_tweet('schedule foo', 1681851240) account.unschedule_tweet(123456) account.tweet('hello world', media=[ {'media': 'test.jpg', 'alt': 'some alt text', 'tagged_users': [123]}, {'media': 'test.jpeg', 'alt': 'some alt text', 'tagged_users': [123]}, {'media': 'test.png', 'alt': 'some alt text', 'tagged_users': [123]}, {'media': 'test.jfif', 'alt': 'some alt text', 'tagged_users': [123]}, ]) account.schedule_tweet('foo bar', '2023-04-18 15:42', media=[ {'media': 'test.gif', 'alt': 'some alt text'}, ]) account.schedule_reply('hello world', '2023-04-19 15:42', tweet_id=123456, media=[ {'media': 'test.gif', 'alt': 'some alt text'}, ]) account.dm('my message', [1234], media='test.jpg') account.create_poll('test poll 123', ['hello', 'world', 'foo', 'bar'], 10080) # tweets account.like(123456) account.unlike(123456) account.bookmark(123456) account.unbookmark(123456) account.pin(123456) account.unpin(123456) # users account.follow(1234) account.unfollow(1234) account.mute(1234) account.unmute(1234) account.enable_follower_notifications(1234) account.disable_follower_notifications(1234) account.block(1234) account.unblock(1234) # user profile account.update_profile_image('test.jpg') account.update_profile_banner('test.png') account.update_profile_info(name='Foo Bar', description='test 123', location='Victoria, BC') # topics account.follow_topic(111) account.unfollow_topic(111) # lists account.create_list('My List', 'description of my list', private=False) account.update_list(222, 'My Updated List', 'some updated description', private=False) account.update_list_banner(222, 'test.png') account.delete_list_banner(222) account.add_list_member(222, 1234) account.remove_list_member(222, 1234) account.delete_list(222) account.pin_list(222) account.unpin_list(222) # refresh all pinned lists in this order account.update_pinned_lists([222, 111, 333]) # unpin all lists account.update_pinned_lists([]) # get timelines timeline = account.home_timeline() latest_timeline = account.home_latest_timeline(limit=500) # get bookmarks bookmarks = account.bookmarks() # get DM inbox metadata inbox = account.dm_inbox() # get DMs from all conversations dms = account.dm_history() # get DMs from specific conversations dms = account.dm_history(['123456-789012', '345678-901234']) # search DMs by keyword dms = account.dm_search('test123') # delete entire conversation account.dm_delete(conversation_id='123456-789012') # delete (hide) specific DM account.dm_delete(message_id='123456') # get all scheduled tweets scheduled_tweets = account.scheduled_tweets() # delete a scheduled tweet account.delete_scheduled_tweet(12345678) # get all draft tweets draft_tweets = account.draft_tweets() # delete a draft tweet account.delete_draft_tweet(12345678) # delete all scheduled tweets account.clear_scheduled_tweets() # delete all draft tweets account.clear_draft_tweets() # example configuration account.update_settings({ "address_book_live_sync_enabled": False, "allow_ads_personalization": False, "allow_authenticated_periscope_requests": True, "allow_dm_groups_from": "following", "allow_dms_from": "following", "allow_location_history_personalization": False, "allow_logged_out_device_personalization": False, "allow_media_tagging": "none", "allow_sharing_data_for_third_party_personalization": False, "alt_text_compose_enabled": None, "always_use_https": True, "autoplay_disabled": False, "country_code": "us", "discoverable_by_email": False, "discoverable_by_mobile_phone": False, "display_sensitive_media": False, "dm_quality_filter": "enabled", "dm_receipt_setting": "all_disabled", "geo_enabled": False, "include_alt_text_compose": True, "include_mention_filter": True, "include_nsfw_admin_flag": True, "include_nsfw_user_flag": True, "include_ranked_timeline": True, "language": "en", "mention_filter": "unfiltered", "nsfw_admin": False, "nsfw_user": False, "personalized_trends": True, "protected": False, "ranked_timeline_eligible": None, "ranked_timeline_setting": None, "require_password_login": False, "requires_login_verification": False, "sleep_time": { "enabled": False, "end_time": None, "start_time": None }, "translator_type": "none", "universal_quality_filtering_enabled": "enabled", "use_cookie_personalization": False, }) # example configuration account.update_search_settings({ "optInFiltering": True, # filter nsfw content "optInBlocking": True, # filter blocked accounts }) notifications = account.notifications() account.change_password('old pwd','new pwd')

Scraping

Get all user/tweet data

Two special batch queries scraper.tweets_by_ids and scraper.users_by_ids should be preferred when applicable. These endpoints are more much more efficient and have higher rate limits than their unbatched counterparts. See the table below for a comparison.

EndpointBatch SizeRate Limit
tweets_by_ids~220500 / 15 mins
tweets_by_id150 / 15 mins
users_by_ids~220100 / 15 mins
users_by_id1500 / 15 mins

As of Fall 2023 login by username/password is unstable. Using cookies is now recommended.

from twitter.scraper import Scraper ## sign-in with credentials email, username, password = ..., ..., ... scraper = Scraper(email, username, password) ## or, resume session using cookies # scraper = Scraper(cookies={"ct0": ..., "auth_token": ...}) ## or, resume session using cookies (JSON file) # scraper = Scraper(cookies='twitter.cookies') ## or, initialize guest session (limited endpoints) # from twitter.util import init_session # scraper = Scraper(session=init_session()) # user data users = scraper.users(['foo', 'bar', 'hello', 'world']) users = scraper.users_by_ids([123, 234, 345]) # preferred users = scraper.users_by_id([123, 234, 345]) tweets = scraper.tweets([123, 234, 345]) likes = scraper.likes([123, 234, 345]) tweets_and_replies = scraper.tweets_and_replies([123, 234, 345]) media = scraper.media([123, 234, 345]) following = scraper.following([123, 234, 345]) followers = scraper.followers([123, 234, 345]) scraper.tweet_stats([111111, 222222, 333333]) # get recommended users based on user scraper.recommended_users() scraper.recommended_users([123]) # tweet data tweets = scraper.tweets_by_ids([987, 876, 754]) # preferred tweets = scraper.tweets_by_id([987, 876, 754]) tweet_details = scraper.tweets_details([987, 876, 754]) retweeters = scraper.retweeters([987, 876, 754]) favoriters = scraper.favoriters([987, 876, 754]) scraper.download_media([ 111111, 222222, 333333, 444444, ]) # trends scraper.trends()

Resume Pagination

Pagination is already done by default, however there are circumstances where you may need to resume pagination from a specific cursor. For example, the Followers endpoint only allows for 50 requests every 15 minutes. In this case, we can resume from where we left off by providing a specific cursor value.

from twitter.scraper import Scraper email, username, password = ..., ..., ... scraper = Scraper(email, username, password) user_id = 44196397 cursor = '1767341853908517597|1663601806447476672' # example cursor limit = 100 # arbitrary limit for demonstration follower_subset, last_cursor = scraper.followers([user_id], limit=limit, cursor=cursor) # use last_cursor to resume pagination

Search

from twitter.search import Search email, username, password = ..., ..., ... # default output directory is `data/search_results` if save=True search = Search(email, username, password, save=True, debug=1) res = search.run( limit=37, retries=5, queries=[ { 'category': 'Top', 'query': 'paperswithcode -tensorflow -tf' }, { 'category': 'Latest', 'query': 'test' }, { 'category': 'People', 'query': 'brasil portugal -argentina' }, { 'category': 'Photos', 'query': 'greece' }, { 'category': 'Videos', 'query': 'italy' }, ], )

Search Operators Reference

https://developer.twitter.com/en/docs/twitter-api/v1/rules-and-filtering/search-operators

https://developer.twitter.com/en/docs/twitter-api/tweets/search/integrate/build-a-query

Spaces

Live Audio Capture

Capture live audio for up to 500 streams per IP

from twitter.scraper import Scraper from twitter.util import init_session session = init_session() # initialize guest session, no login required scraper = Scraper(session=session) rooms = [...] scraper.spaces_live(rooms=rooms) # capture live audio from list of rooms

Live Transcript Capture

Raw transcript chunks

from twitter.scraper import Scraper from twitter.util import init_session session = init_session() # initialize guest session, no login required scraper = Scraper(session=session) # room must be live, i.e. in "Running" state scraper.space_live_transcript('1zqKVPlQNApJB', frequency=2) # word-level live transcript. (dirty, on-the-fly transcription before post-processing)

Processed (final) transcript chunks

from twitter.scraper import Scraper from twitter.util import init_session session = init_session() # initialize guest session, no login required scraper = Scraper(session=session) # room must be live, i.e. in "Running" state scraper.space_live_transcript('1zqKVPlQNApJB', frequency=1) # finalized live transcript. (clean)

Search and Metadata

from twitter.scraper import Scraper from twitter.util import init_session from twitter.constants import SpaceCategory session = init_session() # initialize guest session, no login required scraper = Scraper(session=session) # download audio and chat-log from space spaces = scraper.spaces(rooms=['1eaJbrAPnBVJX', '1eaJbrAlZjjJX'], audio=True, chat=True) # pull metadata only spaces = scraper.spaces(rooms=['1eaJbrAPnBVJX', '1eaJbrAlZjjJX']) # search for spaces in "Upcoming", "Top" and "Live" categories spaces = scraper.spaces(search=[ { 'filter': SpaceCategory.Upcoming, 'query': 'hello' }, { 'filter': SpaceCategory.Top, 'query': 'world' }, { 'filter': SpaceCategory.Live, 'query': 'foo bar' } ])

Automated Solvers

This requires installation of the proton-api-client package

To set up automated email confirmation/verification solvers, add your Proton Mail credentials below as shown. This removes the need to manually solve email challenges via the web app. These credentials can be used in Scraper, Account, and Search constructors.

E.g.

from twitter.account import Account from twitter.util import get_code from proton.client import ProtonMail proton_username, proton_password = ..., ... proton = lambda: get_code(ProtonMail(proton_username, proton_password)) email, username, password = ..., ..., ... account = Account(email, username, password, proton=proton)

Example API Responses

<details> <summary> UserTweetsAndReplies </summary>
{ "entryId": "homeConversation-1648726807301218305-1648801924760711169-1648811419998228480", "sortIndex": "1648811419998228480", "content": { "entryType": "TimelineTimelineModule", "__typename": "TimelineTimelineModule", "items": [ { "entryId": "homeConversation-1648811419998228480-0-tweet-1648726807301218305", "dispensable": true, "item": { "itemContent": { "itemType": "TimelineTweet", "__typename": "TimelineTweet", "tweet_results": { "result": { "__typename": "Tweet", "rest_id": "1648726807301218305", "has_birdwatch_notes": false, "core": { "user_results": { "result": { "__typename": "User", "id": "VXNlcjozMzgzNjYyOQ==", "rest_id": "33836629", "affiliates_highlighted_label": {}, "has_graduated_access": true, "is_blue_verified": true, "profile_image_shape": "Circle", "legacy": { "can_dm": false, "can_media_tag": true, "created_at": "Tue Apr 21 06:49:15 +0000 2009", "default_profile": false, "default_profile_image": false, "description": "Building a kind of JARVIS @ OреոΑӏ. Previously Director of AI @ Tesla, CS231n, PhD @ Stanford. I like to train large deep neural nets 🧠🤖💥", "entities": { "description": { "urls": [] }, "url": { "urls": [ { "display_url": "karpathy.ai", "expanded_url": "https://karpathy.ai", "url": "https://t.co/0EcFthjJXM", "indices": [ 0, 23 ] } ] } }, "fast_followers_count": 0, "favourites_count": 7312, "followers_count": 701921, "friends_count": 809, "has_custom_timelines": true, "is_translator": false, "listed_count": 9207, "location": "Stanford", "media_count": 633, "name": "Andrej Karpathy",

编辑推荐精选

商汤小浣熊

商汤小浣熊

最强AI数据分析助手

小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。

imini AI

imini AI

像人一样思考的AI智能体

imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。

Keevx

Keevx

AI数字人视频创作平台

Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。

即梦AI

即梦AI

一站式AI创作平台

提供 AI 驱动的图片、视频生成及数字人等功能,助力创意创作

扣子-AI办公

扣子-AI办公

AI办公助手,复杂任务高效处理

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
下拉加载更多