Showing preview only (556K chars total). Download the full file or copy to clipboard to get everything.
Repository: xdevplatform/Twitter-API-v2-sample-code
Branch: main
Commit: 99992dd773dd
Files: 236
Total size: 499.2 KB
Directory structure:
gitextract_8ed01k13/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.md
│ │ └── config.yml
│ └── workflows/
│ └── cla.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── LICENSE
├── README.md
├── api-index.json
├── java/
│ ├── README.md
│ ├── posts/
│ │ ├── FullArchiveSearchDemo.java
│ │ ├── FullArchiveTweetCountsDemo.java
│ │ ├── QuoteTweetsDemo.java
│ │ ├── RecentSearchDemo.java
│ │ ├── RecentTweetCountsDemo.java
│ │ ├── SearchRecent.java
│ │ └── TweetsDemo.java
│ ├── spaces/
│ │ ├── SearchSpacesDemo.java
│ │ └── SpacesLookupDemo.java
│ ├── streams/
│ │ ├── FilteredStreamDemo.java
│ │ └── SampledStream.java
│ ├── timelines/
│ │ ├── UserMentionsDemo.java
│ │ ├── UserTweetsDemo.java
│ │ └── reverse-chron-home-timeline-java-sdk.java
│ ├── usage/
│ │ └── UsageTweetsDemo.java
│ └── users/
│ ├── FollowersLookupDemo.java
│ ├── FollowingLookupDemo.java
│ ├── Lookup.java
│ └── UsersDemo.java
├── javascript/
│ ├── README.md
│ ├── compliance/
│ │ ├── create_jobs.js
│ │ ├── download_results.js
│ │ ├── get_jobs.js
│ │ ├── get_jobs_by_id.js
│ │ └── upload_ids.js
│ ├── lists/
│ │ ├── add_member.js
│ │ ├── create_list.js
│ │ ├── delete_list.js
│ │ ├── get_list_by_id.js
│ │ ├── get_list_followers.js
│ │ ├── get_list_members.js
│ │ ├── get_list_posts.js
│ │ ├── remove_member.js
│ │ └── update_list.js
│ ├── posts/
│ │ ├── create_post.js
│ │ ├── delete_post.js
│ │ ├── get_liking_users.js
│ │ ├── get_post_counts_all.js
│ │ ├── get_post_counts_recent.js
│ │ ├── get_posts_by_ids.js
│ │ ├── get_posts_by_ids_user_context.js
│ │ ├── get_quoted_posts.js
│ │ ├── get_reposted_by.js
│ │ ├── search_all.js
│ │ └── search_recent.js
│ ├── spaces/
│ │ ├── get_spaces_by_ids.js
│ │ └── search_spaces.js
│ ├── streams/
│ │ ├── stream_posts_filtered.js
│ │ └── stream_posts_sample.js
│ ├── usage/
│ │ └── get_usage.js
│ └── users/
│ ├── block/
│ │ └── get_blocking.js
│ ├── bookmark/
│ │ ├── create_bookmark.js
│ │ ├── delete_bookmark.js
│ │ └── get_bookmarks.js
│ ├── follow/
│ │ ├── get_followers.js
│ │ ├── get_followers_paginated.js
│ │ └── get_following_paginated.js
│ ├── get_users_by_usernames.js
│ ├── get_users_by_usernames_user_context.js
│ ├── get_users_me.js
│ ├── like/
│ │ ├── get_liked_posts.js
│ │ ├── like_post.js
│ │ └── unlike_post.js
│ ├── lists/
│ │ ├── follow_list.js
│ │ ├── get_followed_lists.js
│ │ ├── get_list_memberships.js
│ │ ├── get_owned_lists.js
│ │ ├── pin_list.js
│ │ ├── unfollow_list.js
│ │ └── unpin_list.js
│ ├── mute/
│ │ ├── get_muting.js
│ │ ├── mute_user.js
│ │ └── unmute_user.js
│ ├── repost/
│ │ ├── repost_post.js
│ │ └── unrepost_post.js
│ └── timeline/
│ ├── get_home_timeline.js
│ ├── get_mentions.js
│ ├── get_posts.js
│ └── get_posts_paginated.js
├── llms.txt
├── python/
│ ├── README.md
│ ├── activity/
│ │ ├── create_subscription.py
│ │ ├── delete_subscription.py
│ │ ├── list_subscriptions.py
│ │ ├── stream_events.py
│ │ └── update_subscription.py
│ ├── compliance/
│ │ ├── create_jobs.py
│ │ ├── download_results.py
│ │ ├── get_jobs.py
│ │ ├── get_jobs_by_id.py
│ │ └── upload_ids.py
│ ├── direct_messages/
│ │ ├── get_events_by_conversation.py
│ │ ├── get_one_to_one_conversation_events.py
│ │ ├── get_user_conversation_events.py
│ │ ├── post_dm_to_conversation.py
│ │ ├── post_group_conversation_dm.py
│ │ └── post_one_to_one_dm.py
│ ├── lists/
│ │ ├── add_member.py
│ │ ├── create_list.py
│ │ ├── delete_list.py
│ │ ├── get_list_by_id.py
│ │ ├── get_list_followers.py
│ │ ├── get_list_members.py
│ │ ├── get_list_posts.py
│ │ ├── remove_member.py
│ │ └── update_list.py
│ ├── media/
│ │ ├── media_upload_v2.py
│ │ └── upload.py
│ ├── posts/
│ │ ├── create_post.py
│ │ ├── delete_post.py
│ │ ├── get_liking_users.py
│ │ ├── get_post_by_id.py
│ │ ├── get_post_counts_all.py
│ │ ├── get_post_counts_recent.py
│ │ ├── get_posts_by_ids.py
│ │ ├── get_quoted_posts.py
│ │ ├── get_reposted_by.py
│ │ ├── hide_reply.py
│ │ ├── search_all.py
│ │ └── search_recent.py
│ ├── requirements.txt
│ ├── spaces/
│ │ ├── get_spaces_by_ids.py
│ │ └── search_spaces.py
│ ├── streams/
│ │ ├── stream_posts_filtered.py
│ │ └── stream_posts_sample.py
│ ├── usage/
│ │ └── get_usage.py
│ ├── users/
│ │ ├── block/
│ │ │ └── get_blocking.py
│ │ ├── bookmark/
│ │ │ ├── create_bookmark.py
│ │ │ ├── delete_bookmark.py
│ │ │ └── get_bookmarks.py
│ │ ├── follow/
│ │ │ ├── follow_user.py
│ │ │ ├── get_followers.py
│ │ │ ├── get_following.py
│ │ │ └── unfollow_user.py
│ │ ├── get_users_by_usernames.py
│ │ ├── get_users_by_usernames_user_context.py
│ │ ├── get_users_me.py
│ │ ├── like/
│ │ │ ├── get_liked_posts.py
│ │ │ ├── like_post.py
│ │ │ └── unlike_post.py
│ │ ├── lists/
│ │ │ ├── follow_list.py
│ │ │ ├── get_followed_lists.py
│ │ │ ├── get_list_memberships.py
│ │ │ ├── get_owned_lists.py
│ │ │ ├── get_pinned_lists.py
│ │ │ ├── pin_list.py
│ │ │ ├── unfollow_list.py
│ │ │ └── unpin_list.py
│ │ ├── mute/
│ │ │ ├── get_muting.py
│ │ │ ├── mute_user.py
│ │ │ └── unmute_user.py
│ │ ├── repost/
│ │ │ ├── get_reposts_of_me.py
│ │ │ ├── repost_post.py
│ │ │ └── unrepost_post.py
│ │ └── timeline/
│ │ ├── get_home_timeline.py
│ │ ├── get_mentions.py
│ │ └── get_posts.py
│ └── webhooks/
│ ├── delete_webhook.py
│ ├── list_webhooks.py
│ ├── register_webhook.py
│ ├── validate_webhook.py
│ └── webhook_server.py
├── r/
│ ├── posts/
│ │ ├── full-archive-search.r
│ │ ├── full_archive_tweet_counts.r
│ │ ├── recent-search.r
│ │ └── recent_tweet_counts.r
│ └── users/
│ └── get_users_with_bearer_token.r
└── ruby/
├── Gemfile
├── README.md
├── bookmarks/
│ └── bookmarks_lookup.rb
├── lists/
│ ├── List-Tweets.rb
│ ├── Pinned-List.rb
│ ├── add_member.rb
│ ├── create_a_list.rb
│ ├── delete_a_list.rb
│ ├── follow_list.rb
│ ├── list-followers-lookup.rb
│ ├── list-lookup-by-id.rb
│ ├── list-member-lookup.rb
│ ├── lookup.rb
│ ├── pin_list.rb
│ ├── remove_member.rb
│ ├── unfollow_list.rb
│ ├── unpin_list.rb
│ ├── update_a_list.rb
│ ├── user-list-followed.rb
│ ├── user-list-memberships.rb
│ └── user-owned-list-lookup.rb
├── posts/
│ ├── create_tweet.rb
│ ├── delete_tweet.rb
│ ├── full-archive-search.rb
│ ├── full_archive_tweet_counts.rb
│ ├── get_tweets_with_bearer_token.rb
│ ├── get_tweets_with_user_context.rb
│ ├── like_a_tweet.rb
│ ├── liked_tweets.rb
│ ├── liking_users.rb
│ ├── lookup.rb
│ ├── quote_tweets.rb
│ ├── recent_search.rb
│ ├── recent_tweet_counts.rb
│ ├── retweet_a_tweet.rb
│ ├── retweeted_by.rb
│ ├── search_recent.rb
│ ├── undo_a_retweet.rb
│ └── unlike_a_tweet.rb
├── spaces/
│ ├── search_spaces.rb
│ └── spaces_lookup.rb
├── streams/
│ ├── filtered_stream.rb
│ └── sampled_stream.rb
├── timelines/
│ ├── reverse-chron-home-timeline.rb
│ ├── user-mentions.rb
│ ├── user-tweets.rb
│ └── user_posts.rb
└── users/
├── block_a_user.rb
├── followers-lookup.rb
├── followers.rb
├── following-lookup.rb
├── get_users_me_with_user_context.rb
├── get_users_with_bearer_token.rb
├── get_users_with_user_context.rb
├── lookup.rb
├── lookup_blocks.rb
├── lookup_mutes.rb
├── mute_a_user.rb
├── unblock_a_user.rb
└── unmute_a_user.rb
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve this code
title: ''
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
**Expected behavior**
A clear and concise description of what you expected to happen.
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
- name: Question about the API? Ask in the Twitter Developer Community
url: https://twittercommunity.com/c/twitter-api/twitter-api-v2/
about: For general API functionality questions, please ask in the developer forums.
================================================
FILE: .github/workflows/cla.yml
================================================
name: "CLA Assistant"
on:
issue_comment:
types: [created]
pull_request_target:
types: [opened,closed,synchronize]
jobs:
CLAssistant:
runs-on: ubuntu-latest
steps:
- name: "CLA Assistant"
if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target'
# Alpha Release
uses: cla-assistant/github-action@v2.0.2-alpha
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PERSONAL_ACCESS_TOKEN : ${{ secrets.CLA_PAT }}
with:
remote-organization-name: twitter
remote-repository-name: .github-private
path-to-signatures: 'cla/signatures.json'
path-to-document: 'https://gist.github.com/twitter-service/a1ad5818c024dc4265f8b60e6d043f26'
custom-allsigned-prcomment: 'All Contributors have signed the CLA. If the commit check is not passing, a maintainer must go the Checks tab of this PR and rerun the GitHub Action.'
branch: 'main'
================================================
FILE: .gitignore
================================================
*.gem
*.rbc
/.config
/coverage/
/InstalledFiles
/pkg/
/spec/reports/
/spec/examples.txt
/test/tmp/
/test/version_tmp/
/tmp/
.DS_Store
node_modules/
package-lock.json
package.json
yarn.lock
../node_modules/
../package.json
../yarn.lock
# Used by dotenv library to load environment variables.
# .env
# Ignore Byebug command history file.
.byebug_history
## Specific to RubyMotion:
.dat*
.repl_history
build/
*.bridgesupport
build-iPhoneOS/
build-iPhoneSimulator/
## Specific to RubyMotion (use of CocoaPods):
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
#
# vendor/Pods/
## Documentation cache and generated files:
/.yardoc/
/_yardoc/
/doc/
/rdoc/
## Environment normalization:
/.bundle/
/vendor/bundle
/lib/bundler/man/
# for a library or gem, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# Gemfile.lock
# .ruby-version
# .ruby-gemset
# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
.rvmrc
# Used by RuboCop. Remote config files pulled in from inherit_from directive.
# .rubocop-https?--*
================================================
FILE: CODE_OF_CONDUCT.md
================================================
We feel that a welcoming community is important and we ask that you follow Twitter's
[Open Source Code of Conduct](https://github.com/twitter/code-of-conduct/blob/master/code-of-conduct.md)
in all interactions with the community.
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2020 @TwitterDev
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# X API v2 Sample Code
[](https://developer.x.com/en/docs/twitter-api)
Working code samples for the **X API v2** in Python, JavaScript, Ruby, Java, and R.
## 📁 Repository Structure
```
├── python/ # 65 Python examples
├── javascript/ # 59 JavaScript examples
├── ruby/ # 58 Ruby examples
├── java/ # 19 Java examples
├── r/ # 5 R examples
├── llms.txt # LLM-friendly documentation
└── api-index.json # Machine-readable endpoint catalog
```
## 🚀 Quick Start
### 1. Get API Credentials
Sign up at the [X Developer Portal](https://developer.x.com/en/portal/dashboard).
### 2. Set Environment Variables
**For read-only operations (search, lookup):**
```bash
export BEARER_TOKEN='your_bearer_token'
```
**For user actions (post, like, repost, bookmark, etc.):**
```bash
export CLIENT_ID='your_client_id'
export CLIENT_SECRET='your_client_secret'
```
**For OAuth 1.0a (legacy endpoints):**
```bash
export CONSUMER_KEY='your_consumer_key'
export CONSUMER_SECRET='your_consumer_secret'
```
### 3. Run an Example
```bash
# Python
cd python && pip install -r requirements.txt
python posts/search_recent.py
# JavaScript
cd javascript
node posts/search_recent.js
# Ruby
cd ruby && bundle install
ruby posts/search_recent.rb
# Java
cd java
javac -cp ".:lib/*" posts/RecentSearchDemo.java
java -cp ".:lib/*" RecentSearchDemo
```
## 📚 Examples by Category
| Category | Python | JavaScript | Ruby | Java | R |
|----------|--------|------------|------|------|---|
| Posts (search, create, delete, likes, reposts) | ✅ | ✅ | ✅ | ✅ | ✅ |
| Users (lookup, followers, following, blocks, mutes) | ✅ | ✅ | ✅ | ✅ | ✅ |
| Timelines (user, mentions, home) | ✅ | ✅ | ✅ | ✅ | |
| Streams (filtered, sampled) | ✅ | ✅ | ✅ | ✅ | |
| Lists (lookup, manage, members, follow) | ✅ | ✅ | ✅ | | |
| Spaces (lookup, search) | ✅ | ✅ | ✅ | ✅ | |
| Bookmarks | ✅ | ✅ | ✅ | | |
| Direct Messages | ✅ | | | | |
| Media Upload | ✅ | | | | |
| Compliance | ✅ | ✅ | | | |
| Usage | ✅ | ✅ | | ✅ | |
## 🔐 Authentication
| Type | Use Case | Env Vars |
|------|----------|----------|
| Bearer Token | Read-only (search, lookup) | `BEARER_TOKEN` |
| OAuth 2.0 PKCE | User actions (post, like, repost, bookmark, mute, etc.) | `CLIENT_ID`, `CLIENT_SECRET` |
| OAuth 1.0a | Legacy endpoints (if applicable) | `CONSUMER_KEY`, `CONSUMER_SECRET` |
## 🤖 For LLMs
- **`llms.txt`** - Context file for AI assistants
- **`api-index.json`** - Machine-readable endpoint catalog
## 🔗 Resources
- [X API Documentation](https://developer.x.com/en/docs/twitter-api)
- [Developer Portal](https://developer.x.com/en/portal/dashboard)
## 📄 License
Apache 2.0
================================================
FILE: api-index.json
================================================
{
"name": "X API v2 Sample Code",
"version": "2.0",
"base_url": "https://api.x.com/2",
"languages": ["python", "javascript", "ruby", "java"],
"endpoints": [
{
"name": "Create Post",
"path": "/tweets",
"method": "POST",
"auth": ["oauth1", "oauth2-user"],
"folder": "posts",
"files": {
"python": "create_post.py",
"javascript": "create_post.js"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets"
},
{
"name": "Delete Post",
"path": "/tweets/:id",
"method": "DELETE",
"auth": ["oauth1", "oauth2-user"],
"folder": "posts",
"files": {
"python": "delete_post.py",
"javascript": "delete_post.js"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/delete-tweets-id"
},
{
"name": "Post Lookup",
"path": "/tweets",
"method": "GET",
"auth": ["bearer", "oauth1", "oauth2-user"],
"folder": "posts",
"files": {
"python": "lookup.py",
"javascript": "lookup.js",
"ruby": "lookup.rb"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets"
},
{
"name": "Recent Search",
"path": "/tweets/search/recent",
"method": "GET",
"auth": ["bearer", "oauth2-user"],
"folder": "posts",
"files": {
"python": "search_recent.py",
"javascript": "search_recent.js",
"ruby": "search_recent.rb",
"java": "SearchRecent.java"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent"
},
{
"name": "Full Archive Search",
"path": "/tweets/search/all",
"method": "GET",
"auth": ["bearer"],
"folder": "posts",
"files": {
"python": "search_full_archive.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-all",
"note": "Requires Academic Research access"
},
{
"name": "Recent Post Counts",
"path": "/tweets/counts/recent",
"method": "GET",
"auth": ["bearer"],
"folder": "posts",
"files": {
"python": "counts_recent.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/counts/api-reference/get-tweets-counts-recent"
},
{
"name": "Quote Posts",
"path": "/tweets/:id/quote_tweets",
"method": "GET",
"auth": ["bearer", "oauth2-user"],
"folder": "posts",
"files": {
"python": "quote_posts.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/quote-tweets/api-reference/get-tweets-id-quote_tweets"
},
{
"name": "Repost",
"path": "/users/:id/retweets",
"method": "POST",
"auth": ["oauth1", "oauth2-user"],
"folder": "posts",
"files": {
"python": "repost.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/post-users-id-retweets"
},
{
"name": "Undo Repost",
"path": "/users/:id/retweets/:source_tweet_id",
"method": "DELETE",
"auth": ["oauth1", "oauth2-user"],
"folder": "posts",
"files": {
"python": "undo_repost.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/delete-users-id-retweets-tweet_id"
},
{
"name": "Reposted By",
"path": "/tweets/:id/retweeted_by",
"method": "GET",
"auth": ["bearer", "oauth2-user"],
"folder": "posts",
"files": {
"python": "reposted_by.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/get-tweets-id-retweeted_by"
},
{
"name": "Like Post",
"path": "/users/:id/likes",
"method": "POST",
"auth": ["oauth1", "oauth2-user"],
"folder": "posts",
"files": {
"python": "like.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/post-users-id-likes"
},
{
"name": "Unlike Post",
"path": "/users/:id/likes/:tweet_id",
"method": "DELETE",
"auth": ["oauth1", "oauth2-user"],
"folder": "posts",
"files": {
"python": "unlike.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/delete-users-id-likes-tweet_id"
},
{
"name": "Liking Users",
"path": "/tweets/:id/liking_users",
"method": "GET",
"auth": ["bearer", "oauth2-user"],
"folder": "posts",
"files": {
"python": "liking_users.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/get-tweets-id-liking_users"
},
{
"name": "Liked Posts",
"path": "/users/:id/liked_tweets",
"method": "GET",
"auth": ["bearer", "oauth2-user"],
"folder": "posts",
"files": {
"python": "liked_posts.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/get-users-id-liked_tweets"
},
{
"name": "User Lookup",
"path": "/users/by",
"method": "GET",
"auth": ["bearer", "oauth1", "oauth2-user"],
"folder": "users",
"files": {
"python": "lookup.py",
"javascript": "lookup.js",
"ruby": "lookup.rb",
"java": "Lookup.java"
},
"docs": "https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-by"
},
{
"name": "Authenticated User (Me)",
"path": "/users/me",
"method": "GET",
"auth": ["oauth1", "oauth2-user"],
"folder": "users",
"files": {
"python": "me.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-me"
},
{
"name": "User Followers",
"path": "/users/:id/followers",
"method": "GET",
"auth": ["bearer", "oauth2-user"],
"folder": "users",
"files": {
"python": "followers.py",
"javascript": "followers.js",
"ruby": "followers.rb"
},
"docs": "https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/get-users-id-followers"
},
{
"name": "User Following",
"path": "/users/:id/following",
"method": "GET",
"auth": ["bearer", "oauth2-user"],
"folder": "users",
"files": {
"python": "following.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/get-users-id-following"
},
{
"name": "Block User",
"path": "/users/:id/blocking",
"method": "POST",
"auth": ["oauth1", "oauth2-user"],
"folder": "users",
"files": {
"python": "block.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/users/blocks/api-reference/post-users-user_id-blocking"
},
{
"name": "Unblock User",
"path": "/users/:source_user_id/blocking/:target_user_id",
"method": "DELETE",
"auth": ["oauth1", "oauth2-user"],
"folder": "users",
"files": {
"python": "unblock.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/users/blocks/api-reference/delete-users-user_id-blocking"
},
{
"name": "Blocked Users",
"path": "/users/:id/blocking",
"method": "GET",
"auth": ["oauth1", "oauth2-user"],
"folder": "users",
"files": {
"python": "blocked.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/users/blocks/api-reference/get-users-blocking"
},
{
"name": "Mute User",
"path": "/users/:id/muting",
"method": "POST",
"auth": ["oauth1", "oauth2-user"],
"folder": "users",
"files": {
"python": "mute.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/post-users-user_id-muting"
},
{
"name": "Unmute User",
"path": "/users/:source_user_id/muting/:target_user_id",
"method": "DELETE",
"auth": ["oauth1", "oauth2-user"],
"folder": "users",
"files": {
"python": "unmute.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/delete-users-user_id-muting"
},
{
"name": "Muted Users",
"path": "/users/:id/muting",
"method": "GET",
"auth": ["oauth1", "oauth2-user"],
"folder": "users",
"files": {
"python": "muted.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/get-users-muting"
},
{
"name": "User Posts Timeline",
"path": "/users/:id/tweets",
"method": "GET",
"auth": ["bearer", "oauth2-user"],
"folder": "timelines",
"files": {
"python": "user_posts.py",
"javascript": "user_posts.js",
"ruby": "user_posts.rb"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-tweets"
},
{
"name": "User Mentions Timeline",
"path": "/users/:id/mentions",
"method": "GET",
"auth": ["bearer", "oauth2-user"],
"folder": "timelines",
"files": {
"python": "user_mentions.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-mentions"
},
{
"name": "Home Timeline",
"path": "/users/:id/reverse_chronological_timeline",
"method": "GET",
"auth": ["oauth1", "oauth2-user"],
"folder": "timelines",
"files": {
"python": "home_timeline.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-reverse-chronological-timeline"
},
{
"name": "Filtered Stream",
"path": "/tweets/search/stream",
"method": "GET",
"auth": ["bearer"],
"folder": "streams",
"files": {
"python": "filtered_stream.py",
"javascript": "filtered_stream.js"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/filtered-stream/api-reference/get-tweets-search-stream"
},
{
"name": "Sampled Stream",
"path": "/tweets/sample/stream",
"method": "GET",
"auth": ["bearer"],
"folder": "streams",
"files": {
"python": "sampled_stream.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/volume-streams/api-reference/get-tweets-sample-stream"
},
{
"name": "Bookmarks Lookup",
"path": "/users/:id/bookmarks",
"method": "GET",
"auth": ["oauth2-user"],
"folder": "bookmarks",
"files": {
"python": "lookup.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/get-users-id-bookmarks"
},
{
"name": "Create Bookmark",
"path": "/users/:id/bookmarks",
"method": "POST",
"auth": ["oauth2-user"],
"folder": "bookmarks",
"files": {
"python": "create.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/post-users-id-bookmarks"
},
{
"name": "Delete Bookmark",
"path": "/users/:id/bookmarks/:tweet_id",
"method": "DELETE",
"auth": ["oauth2-user"],
"folder": "bookmarks",
"files": {
"python": "delete.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/delete-users-id-bookmarks-tweet_id"
},
{
"name": "Spaces Lookup",
"path": "/spaces",
"method": "GET",
"auth": ["bearer", "oauth2-user"],
"folder": "spaces",
"files": {
"python": "lookup.py",
"javascript": "lookup.js"
},
"docs": "https://developer.x.com/en/docs/twitter-api/spaces/lookup/api-reference/get-spaces"
},
{
"name": "Spaces Search",
"path": "/spaces/search",
"method": "GET",
"auth": ["bearer", "oauth2-user"],
"folder": "spaces",
"files": {
"python": "search.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/spaces/search/api-reference/get-spaces-search"
},
{
"name": "List Lookup",
"path": "/lists/:id",
"method": "GET",
"auth": ["bearer", "oauth2-user"],
"folder": "lists",
"files": {
"python": "lookup.py",
"javascript": "lookup.js",
"ruby": "lookup.rb"
},
"docs": "https://developer.x.com/en/docs/twitter-api/lists/list-lookup/api-reference/get-lists-id"
},
{
"name": "Create List",
"path": "/lists",
"method": "POST",
"auth": ["oauth1", "oauth2-user"],
"folder": "lists",
"files": {
"python": "create.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/post-lists"
},
{
"name": "Delete List",
"path": "/lists/:id",
"method": "DELETE",
"auth": ["oauth1", "oauth2-user"],
"folder": "lists",
"files": {
"python": "delete.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/delete-lists-id"
},
{
"name": "DM Events Lookup",
"path": "/dm_events",
"method": "GET",
"auth": ["oauth1", "oauth2-user"],
"folder": "direct_messages",
"files": {
"python": "lookup.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-events"
},
{
"name": "Send DM",
"path": "/dm_conversations/with/:participant_id/messages",
"method": "POST",
"auth": ["oauth1", "oauth2-user"],
"folder": "direct_messages",
"files": {
"python": "send.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations-with-participant_id-messages"
},
{
"name": "Create Compliance Job",
"path": "/compliance/jobs",
"method": "POST",
"auth": ["bearer"],
"folder": "compliance",
"files": {
"python": "create_job.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/post-compliance-jobs"
},
{
"name": "Get Compliance Jobs",
"path": "/compliance/jobs",
"method": "GET",
"auth": ["bearer"],
"folder": "compliance",
"files": {
"python": "get_jobs.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/get-compliance-jobs"
},
{
"name": "API Usage",
"path": "/usage/tweets",
"method": "GET",
"auth": ["bearer"],
"folder": "usage",
"files": {
"python": "get_usage.py"
},
"docs": "https://developer.x.com/en/docs/twitter-api/usage/api-reference/get-usage-tweets"
}
]
}
================================================
FILE: java/README.md
================================================
# X API v2 - Java Examples
Working Java code samples for the X (formerly Twitter) API v2.
## Setup
### 1. Install Java 11+
```bash
java --version
```
### 2. Add dependencies
Using Maven, add to your `pom.xml`:
```xml
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.1</version>
</dependency>
</dependencies>
```
### 3. Set environment variables
**For read-only operations (search, lookup):**
```bash
export BEARER_TOKEN='your_bearer_token'
```
**For user actions (post, like, repost, bookmark, etc.):**
```bash
export CLIENT_ID='your_client_id'
export CLIENT_SECRET='your_client_secret'
```
**Note:** Most user action examples require OAuth 2.0 authentication with `CLIENT_ID` and `CLIENT_SECRET`. Read-only examples (search, lookup) only require `BEARER_TOKEN`.
## Examples by Category
### Posts
- `posts/FullArchiveSearchDemo.java` - Full archive search demo
- `posts/FullArchiveTweetCountsDemo.java` - Full archive tweet counts demo
- `posts/QuoteTweetsDemo.java` - Get posts that quote a post
- `posts/RecentSearchDemo.java` - Recent search demo (last 7 days)
- `posts/RecentTweetCountsDemo.java` - Recent tweet counts demo
- `posts/SearchRecent.java` - Recent search (last 7 days)
- `posts/TweetsDemo.java` - Look up posts by ID
### Users
- `users/FollowersLookupDemo.java` - Get user's followers
- `users/FollowingLookupDemo.java` - Get users a user is following
- `users/Lookup.java` - Look up users by username
- `users/UsersDemo.java` - Users lookup demo
### Timelines
- `timelines/reverse-chron-home-timeline-java-sdk.java` - Get home timeline (reverse chronological)
- `timelines/UserMentionsDemo.java` - Get user mentions timeline
- `timelines/UserTweetsDemo.java` - Get user's posts timeline
### Streams
- `streams/FilteredStreamDemo.java` - Filtered stream with rules
- `streams/SampledStream.java` - Sampled stream
### Spaces
- `spaces/SearchSpacesDemo.java` - Search for Spaces
- `spaces/SpacesLookupDemo.java` - Look up Spaces by ID
### Usage
- `usage/UsageTweetsDemo.java` - Get API usage information
## Building and Running
### Compile
```bash
# Compile a single file
javac -cp ".:lib/*" posts/SearchRecent.java
# Or compile all files
find . -name "*.java" -exec javac -cp ".:lib/*" {} \;
```
### Run
```bash
# Run a single example
java -cp ".:lib/*" posts.SearchRecent
# Or with package structure
java -cp ".:lib/*" posts/RecentSearchDemo
```
## More Information
- [X API Documentation](https://developer.x.com/en/docs/twitter-api)
- [X Developer Portal](https://developer.x.com/en/portal/dashboard)
================================================
FILE: java/posts/FullArchiveSearchDemo.java
================================================
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/*
* Sample code to demonstrate the use of the Full archive search endpoint
* */
public class FullArchiveSearchDemo {
// To set your enviornment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
//Replace the search term with a term of your choice
String response = search("from:TwitterDev OR from:SnowBotDev OR from:DailyNASA", bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the full-archive search endpoint with a the search term passed to it as a query parameter
* */
private static String search(String searchString, String bearerToken) throws IOException, URISyntaxException {
String searchResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/search/all");
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("query", searchString));
uriBuilder.addParameters(queryParameters);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
searchResponse = EntityUtils.toString(entity, "UTF-8");
}
return searchResponse;
}
}
================================================
FILE: java/posts/FullArchiveTweetCountsDemo.java
================================================
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/*
* Sample code to demonstrate the use of the Full-archive Tweet counts endpoint
* */
public class FullArchiveTweetCountsDemo {
// To set your enviornment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
//Replace the search term with a term of your choice
String response = getTweetCounts("from:TwitterDev", bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the full-archive Tweet counts endpoint with a the search term passed to it as a query parameter
* */
private static String getTweetCounts(String searchString, String bearerToken) throws IOException, URISyntaxException {
String searchResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/counts/all");
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("query", searchString));
queryParameters.add(new BasicNameValuePair("granularity", "day"));
queryParameters.add(new BasicNameValuePair("start_time", "2021-01-01T00:00:00Z"));
uriBuilder.addParameters(queryParameters);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
searchResponse = EntityUtils.toString(entity, "UTF-8");
}
return searchResponse;
}
}
================================================
FILE: java/posts/QuoteTweetsDemo.java
================================================
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
/*
* Sample code to demonstrate the use of the v2 Quote Tweets endpoint
* */
public class QuoteTweetsDemo {
// To set your environment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
final String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
//Replace with Tweet ID below
String response = getTweets(20, bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the v2 Quote Tweets endpoint by Tweet ID
* */
private static String getTweets(int tweetId, String bearerToken) throws IOException, URISyntaxException {
String tweetResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder(String.format("https://api.x.com/2/tweets/%s/quote_tweets", tweetId));
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("tweet.fields", "created_at"));
uriBuilder.addParameters(queryParameters);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
tweetResponse = EntityUtils.toString(entity, "UTF-8");
}
return tweetResponse;
}
}
================================================
FILE: java/posts/RecentSearchDemo.java
================================================
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/*
* Sample code to demonstrate the use of the Recent search endpoint
* */
public class RecentSearchDemo {
// To set your enviornment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
//Replace the search term with a term of your choice
String response = search("from:TwitterDev OR from:SnowBotDev OR from:DailyNASA", bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting you bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the recent search endpoint with a the search term passed to it as a query parameter
* */
private static String search(String searchString, String bearerToken) throws IOException, URISyntaxException {
String searchResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/search/recent");
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("query", searchString));
uriBuilder.addParameters(queryParameters);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
searchResponse = EntityUtils.toString(entity, "UTF-8");
}
return searchResponse;
}
}
================================================
FILE: java/posts/RecentTweetCountsDemo.java
================================================
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/*
* Sample code to demonstrate the use of the Recent Tweet counts endpoint
* */
public class RecentTweetCountsDemo {
// To set your enviornment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
//Replace the search term with a term of your choice
String response = getTweetCounts("from:TwitterDev", bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting you bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the recent Tweet counts endpoint with a the search term passed to it as a query parameter
* */
private static String getTweetCounts(String searchString, String bearerToken) throws IOException, URISyntaxException {
String searchResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/counts/recent");
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("query", searchString));
queryParameters.add(new BasicNameValuePair("granularity", "day"));
uriBuilder.addParameters(queryParameters);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
searchResponse = EntityUtils.toString(entity, "UTF-8");
}
return searchResponse;
}
}
================================================
FILE: java/posts/SearchRecent.java
================================================
/**
* Recent Search - X API v2
*
* Endpoint: GET https://api.x.com/2/tweets/search/recent
* Docs: https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent
*
* Authentication: Bearer Token (App-only)
* Required env vars: BEARER_TOKEN
*
* Dependencies: org.apache.httpcomponents:httpclient, com.google.code.gson:gson
*/
import java.io.IOException;
import java.net.URISyntaxException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class SearchRecent {
public static void main(String[] args) throws IOException, URISyntaxException {
String bearerToken = System.getenv("BEARER_TOKEN");
if (bearerToken == null) {
System.err.println("BEARER_TOKEN environment variable not set");
System.exit(1);
}
String response = search("from:XDevelopers -is:retweet", bearerToken);
System.out.println(response);
}
private static String search(String query, String bearerToken) throws IOException, URISyntaxException {
String searchUrl = "https://api.x.com/2/tweets/search/recent";
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder(searchUrl);
uriBuilder.addParameter("query", query);
uriBuilder.addParameter("tweet.fields", "author_id,created_at");
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", "Bearer " + bearerToken);
httpGet.setHeader("User-Agent", "v2RecentSearchJava");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, "UTF-8");
} else {
return "No response";
}
}
}
================================================
FILE: java/posts/TweetsDemo.java
================================================
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
/*
* Sample code to demonstrate the use of the v2 Tweets endpoint
* */
public class TweetsDemo {
// To set your enviornment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
//Replace comma separated ids with Tweets Ids of your choice
String response = getTweets("1138505981460193280,1261326399320715264", bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting you bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the v2 Tweets endpoint with ids as query parameter
* */
private static String getTweets(String ids, String bearerToken) throws IOException, URISyntaxException {
String tweetResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets");
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("ids", ids));
queryParameters.add(new BasicNameValuePair("tweet.fields", "created_at"));
uriBuilder.addParameters(queryParameters);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
tweetResponse = EntityUtils.toString(entity, "UTF-8");
}
return tweetResponse;
}
}
================================================
FILE: java/spaces/SearchSpacesDemo.java
================================================
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/*
* Sample code to demonstrate the use of the Spaces lookup endpoint
* */
public class SpacesLookupDemo {
// To set your enviornment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
//Replace SPACE_ID with the ID of a Space
String response = getSpaceById("SPACE_ID", bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the Spaces lookup endpoint with the ID passed to it as a query parameter
* */
private static String getSpaceById(String spaceId, String bearerToken) throws IOException, URISyntaxException {
String searchResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/spaces");
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("ids", spaceId));
uriBuilder.addParameters(queryParameters);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("User-Agent", "v2SpacesLookupJava");
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
searchResponse = EntityUtils.toString(entity, "UTF-8");
}
return searchResponse;
}
}
================================================
FILE: java/spaces/SpacesLookupDemo.java
================================================
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/*
* Sample code to demonstrate the use of the Spaces lookup endpoint
* */
public class SpacesLookupDemo {
// To set your enviornment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
//Replace SPACE_ID with the ID of a Space
String response = getSpaceById("SPACE_ID", bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the Spaces lookup endpoint with the ID passed to it as a query parameter
* */
private static String getSpaceById(String spaceId, String bearerToken) throws IOException, URISyntaxException {
String searchResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/spaces");
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("ids", spaceId));
uriBuilder.addParameters(queryParameters);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("User-Agent", "v2SpacesLookupJava");
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
searchResponse = EntityUtils.toString(entity, "UTF-8");
}
return searchResponse;
}
}
================================================
FILE: java/streams/FilteredStreamDemo.java
================================================
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.*;
import java.net.URISyntaxException;
import java.util.*;
/*
* Sample code to demonstrate the use of the Filtered Stream endpoint
* */
public class FilteredStreamDemo {
// To set your enviornment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
Map<String, String> rules = new HashMap<>();
rules.put("cats has:images", "cat images");
rules.put("dogs has:images", "dog images");
setupRules(bearerToken, rules);
connectStream(bearerToken);
} else {
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the filtered stream endpoint and streams Tweets from it
* */
private static void connectStream(String bearerToken) throws IOException, URISyntaxException {
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/search/stream");
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
BufferedReader reader = new BufferedReader(new InputStreamReader((entity.getContent())));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
}
}
/*
* Helper method to setup rules before streaming data
* */
private static void setupRules(String bearerToken, Map<String, String> rules) throws IOException, URISyntaxException {
List<String> existingRules = getRules(bearerToken);
if (existingRules.size() > 0) {
deleteRules(bearerToken, existingRules);
}
createRules(bearerToken, rules);
}
/*
* Helper method to create rules for filtering
* */
private static void createRules(String bearerToken, Map<String, String> rules) throws URISyntaxException, IOException {
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/search/stream/rules");
HttpPost httpPost = new HttpPost(uriBuilder.build());
httpPost.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpPost.setHeader("content-type", "application/json");
StringEntity body = new StringEntity(getFormattedString("{\"add\": [%s]}", rules));
httpPost.setEntity(body);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
System.out.println(EntityUtils.toString(entity, "UTF-8"));
}
}
/*
* Helper method to get existing rules
* */
private static List<String> getRules(String bearerToken) throws URISyntaxException, IOException {
List<String> rules = new ArrayList<>();
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/search/stream/rules");
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("content-type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
JSONObject json = new JSONObject(EntityUtils.toString(entity, "UTF-8"));
if (json.length() > 1) {
JSONArray array = (JSONArray) json.get("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = (JSONObject) array.get(i);
rules.add(jsonObject.getString("id"));
}
}
}
return rules;
}
/*
* Helper method to delete rules
* */
private static void deleteRules(String bearerToken, List<String> existingRules) throws URISyntaxException, IOException {
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/search/stream/rules");
HttpPost httpPost = new HttpPost(uriBuilder.build());
httpPost.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpPost.setHeader("content-type", "application/json");
StringEntity body = new StringEntity(getFormattedString("{ \"delete\": { \"ids\": [%s]}}", existingRules));
httpPost.setEntity(body);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
System.out.println(EntityUtils.toString(entity, "UTF-8"));
}
}
private static String getFormattedString(String string, List<String> ids) {
StringBuilder sb = new StringBuilder();
if (ids.size() == 1) {
return String.format(string, "\"" + ids.get(0) + "\"");
} else {
for (String id : ids) {
sb.append("\"" + id + "\"" + ",");
}
String result = sb.toString();
return String.format(string, result.substring(0, result.length() - 1));
}
}
private static String getFormattedString(String string, Map<String, String> rules) {
StringBuilder sb = new StringBuilder();
if (rules.size() == 1) {
String key = rules.keySet().iterator().next();
return String.format(string, "{\"value\": \"" + key + "\", \"tag\": \"" + rules.get(key) + "\"}");
} else {
for (Map.Entry<String, String> entry : rules.entrySet()) {
String value = entry.getKey();
String tag = entry.getValue();
sb.append("{\"value\": \"" + value + "\", \"tag\": \"" + tag + "\"}" + ",");
}
String result = sb.toString();
return String.format(string, result.substring(0, result.length() - 1));
}
}
}
================================================
FILE: java/streams/SampledStream.java
================================================
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
/*
* Sample code to demonstrate the use of the Sampled Stream endpoint
* */
public class SampledStreamDemo {
// To set your enviornment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
connectStream(bearerToken);
} else {
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the sample stream endpoint and streams Tweets from it
* */
private static void connectStream(String bearerToken) throws IOException, URISyntaxException {
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/sample/stream");
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
BufferedReader reader = new BufferedReader(new InputStreamReader((entity.getContent())));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
}
}
}
================================================
FILE: java/timelines/UserMentionsDemo.java
================================================
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
/*
* Sample code to demonstrate the use of the v2 User Mentions timeline endpoint
* */
public class UserMentionsDemo {
// To set your environment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
final String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
//Replace with user ID below
String response = getTweets("2244994945", bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the v2 User Mentions timeline endpoint by user ID
* */
private static String getTweets(String userId, String bearerToken) throws IOException, URISyntaxException {
String tweetResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder(String.format("https://api.x.com/2/users/%s/mentions", userId));
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("tweet.fields", "created_at"));
uriBuilder.addParameters(queryParameters);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
tweetResponse = EntityUtils.toString(entity, "UTF-8");
}
return tweetResponse;
}
}
================================================
FILE: java/timelines/UserTweetsDemo.java
================================================
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
/*
* Sample code to demonstrate the use of the v2 User Tweet timeline endpoint
* */
public class UserTweetsDemo {
// To set your environment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
final String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
// Replace with user ID below
String response = getTweets("2244994945", bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the v2 User Tweet timeline endpoint by user ID
* */
private static String getTweets(String userId, String bearerToken) throws IOException, URISyntaxException {
String tweetResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder(String.format("https://api.x.com/2/users/%s/tweets", userId));
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("tweet.fields", "created_at"));
uriBuilder.addParameters(queryParameters);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
tweetResponse = EntityUtils.toString(entity, "UTF-8");
}
return tweetResponse;
}
}
================================================
FILE: java/timelines/reverse-chron-home-timeline-java-sdk.java
================================================
package com.twitter.clientlib.auth;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.pkce.PKCE;
import com.github.scribejava.core.pkce.PKCECodeChallengeMethod;
import com.twitter.clientlib.TwitterCredentialsBearer;
import com.twitter.clientlib.ApiClient;
import com.twitter.clientlib.ApiException;
import com.twitter.clientlib.Configuration;
import com.twitter.clientlib.auth.*;
import com.twitter.clientlib.model.*;
import com.twitter.clientlib.TwitterCredentialsOAuth2;
import com.twitter.clientlib.api.TwitterApi;
import com.twitter.clientlib.api.BookmarksApi;
import java.util.List;
import java.util.Set;
import java.util.Arrays;
import java.util.HashSet;
import java.time.OffsetDateTime;
import org.json.*;
/**
* This is an example of getting an OAuth2 access token and using it to call an API.
* It's expected to set TWITTER_OAUTH2_CLIENT_ID & TWITTER_OAUTH2_CLIENT_SECRET in TwitterCredentialsOAuth2
*
* Example steps:
* 1. Getting the App Authorization URL.
* 2. User should click the URL and authorize it.
* 3. After receiving the access token, setting the values into TwitterCredentialsOAuth2.
* 4. Call the API.
*/
public class OAuth20GetAccessToken {
public static void main(String[] args) {
OAuth20GetAccessToken example = new OAuth20GetAccessToken();
TwitterCredentialsOAuth2 credentials = new TwitterCredentialsOAuth2("REPLACE-WITH-CLIENT-ID",
"REPLACE-WITH-CLIENT-SECRET",
null,
null);
OAuth2AccessToken accessToken = example.getAccessToken(credentials);
if (accessToken == null) {
return;
}
// Setting the access & refresh tokens into TwitterCredentialsOAuth2
credentials.setTwitterOauth2AccessToken(accessToken.getAccessToken());
credentials.setTwitterOauth2RefreshToken(accessToken.getRefreshToken());
example.callApi(credentials);
}
public OAuth2AccessToken getAccessToken(TwitterCredentialsOAuth2 credentials) {
TwitterOAuth20Service service = new TwitterOAuth20Service(
credentials.getTwitterOauth2ClientId(),
credentials.getTwitterOAuth2ClientSecret(),
"https://www.example.com/oauth",
"offline.access tweet.read users.read");
OAuth2AccessToken accessToken = null;
try {
final Scanner in = new Scanner(System.in, "UTF-8");
System.out.println("Fetching the Authorization URL...");
final String secretState = "state";
PKCE pkce = new PKCE();
pkce.setCodeChallenge("challenge");
pkce.setCodeChallengeMethod(PKCECodeChallengeMethod.PLAIN);
pkce.setCodeVerifier("challenge");
String authorizationUrl = service.getAuthorizationUrl(pkce, secretState);
System.out.println("Go to the Authorization URL and authorize your App:\n" +
authorizationUrl + "\nAfter that paste the authorization code here\n>>");
final String code = in.nextLine();
System.out.println("\nTrading the Authorization Code for an Access Token...");
accessToken = service.getAccessToken(pkce, code);
System.out.println("Access token: " + accessToken.getAccessToken());
System.out.println("Refresh token: " + accessToken.getRefreshToken());
} catch (Exception e) {
System.err.println("Error while getting the access token:\n " + e);
e.printStackTrace();
}
return accessToken;
}
public void callApi(TwitterCredentialsOAuth2 credentials) {
TwitterApi apiInstance = new TwitterApi();
apiInstance.setTwitterCredentials(credentials);
// Set the params values
String sinceId = "791775337160081409"; // String | The minimum Tweet ID to be included in the result set. This parameter takes precedence over start_time if both are specified.
String untilId = "1346889436626259968"; // String | The maximum Tweet ID to be included in the result set. This parameter takes precedence over end_time if both are specified.
Integer maxResults = 56; // Integer | The maximum number of results
String paginationToken = "paginationToken_example"; // String | This parameter is used to get the next 'page' of results.
OffsetDateTime startTime = OffsetDateTime.parse("2021-02-01T18:40:40.000Z"); // OffsetDateTime | YYYY-MM-DDTHH:mm:ssZ. The earliest UTC timestamp from which the Tweets will be provided. The since_id parameter takes precedence if it is also specified.
OffsetDateTime endTime = OffsetDateTime.parse("2021-02-14T18:40:40.000Z"); // OffsetDateTime | YYYY-MM-DDTHH:mm:ssZ. The latest UTC timestamp to which the Tweets will be provided. The until_id parameter takes precedence if it is also specified.
Set<String> expansions = new HashSet<>(Arrays.asList()); // Set<String> | A comma separated list of fields to expand.
Set<String> tweetFields = new HashSet<>(Arrays.asList()); // Set<String> | A comma separated list of Tweet fields to display.
Set<String> userFields = new HashSet<>(Arrays.asList()); // Set<String> | A comma separated list of User fields to display.
Set<String> mediaFields = new HashSet<>(Arrays.asList()); // Set<String> | A comma separated list of Media fields to display.
Set<String> placeFields = new HashSet<>(Arrays.asList()); // Set<String> | A comma separated list of Place fields to display.
Set<String> pollFields = new HashSet<>(Arrays.asList()); // Set<String> | A comma separated list of Poll fields to display.
try {
//Gets the authorized user ID and parses it into an JSON object
SingleUserLookupResponse userData = apiInstance.users().findMyUser(null, null, null);
String jsonString = userData.getData().toJson();
JSONObject obj = new JSONObject(jsonString);
String userId = obj.getString("id");
//Passes the parsed ID into the userIdTimeline request
GenericTweetsTimelineResponse result = apiInstance.tweets().usersIdTimeline(userId, sinceId, untilId, maxResults, null, paginationToken, startTime, endTime, expansions, tweetFields, userFields, mediaFields, placeFields, pollFields);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UsersApi#usersIdTimeline");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
================================================
FILE: java/usage/UsageTweetsDemo.java
================================================
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
/*
* Sample code to demonstrate the use of the v2 Usage Tweets endpoint
* */
public class UsageTweetsDemo {
// To set your enviornment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
String response = getUsageTweets(bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting you bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the v2 Usage Tweets endpoint
* */
private static String getUsageTweets(String bearerToken) throws IOException, URISyntaxException {
String usageTweetsResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/usage/tweets");
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
usageTweetsResponse = EntityUtils.toString(entity, "UTF-8");
}
return usageTweetsResponse;
}
}
================================================
FILE: java/users/FollowersLookupDemo.java
================================================
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
/*
* Sample code to demonstrate the use of the v2 followers lookup endpoint
* */
public class FollowersLookupDemo {
// To set your environment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
final String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
// Replace with user ID below
String response = getFollowers("2244994945", bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the v2 followers lookup endpoint by user ID
* */
private static String getFollowers(String userId, String bearerToken) throws IOException, URISyntaxException {
String tweetResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder(String.format("https://api.x.com/2/users/%s/followers", userId));
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("user.fields", "created_at"));
uriBuilder.addParameters(queryParameters);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
tweetResponse = EntityUtils.toString(entity, "UTF-8");
}
return tweetResponse;
}
}
================================================
FILE: java/users/FollowingLookupDemo.java
================================================
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
/*
* Sample code to demonstrate the use of the v2 following lookup endpoint
* */
public class FollowingLookupDemo {
// To set your environment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
final String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
// Replace with user ID below
String response = getFollowing("2244994945", bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the v2 following lookup endpoint
* */
private static String getFollowing(String userId, String bearerToken) throws IOException, URISyntaxException {
String tweetResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder(String.format("https://api.x.com/2/users/%s/following", userId));
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("user.fields", "created_at"));
uriBuilder.addParameters(queryParameters);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
tweetResponse = EntityUtils.toString(entity, "UTF-8");
}
return tweetResponse;
}
}
================================================
FILE: java/users/Lookup.java
================================================
/**
* User Lookup - X API v2
*
* Endpoint: GET https://api.x.com/2/users/by
* Docs: https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-by
*
* Authentication: Bearer Token (App-only)
* Required env vars: BEARER_TOKEN
*
* Dependencies: org.apache.httpcomponents:httpclient, com.google.code.gson:gson
*/
import java.io.IOException;
import java.net.URISyntaxException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class Lookup {
public static void main(String[] args) throws IOException, URISyntaxException {
String bearerToken = System.getenv("BEARER_TOKEN");
if (bearerToken == null) {
System.err.println("BEARER_TOKEN environment variable not set");
System.exit(1);
}
String response = lookupUsers("XDevelopers,X", bearerToken);
System.out.println(response);
}
private static String lookupUsers(String usernames, String bearerToken) throws IOException, URISyntaxException {
String userLookupUrl = "https://api.x.com/2/users/by";
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder(userLookupUrl);
uriBuilder.addParameter("usernames", usernames);
uriBuilder.addParameter("user.fields", "created_at,description,public_metrics");
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", "Bearer " + bearerToken);
httpGet.setHeader("User-Agent", "v2UserLookupJava");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, "UTF-8");
} else {
return "No response";
}
}
}
================================================
FILE: java/users/UsersDemo.java
================================================
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
/*
* Sample code to demonstrate the use of the v2 Users endpoint
* */
public class UsersDemo {
// To set your enviornment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'
public static void main(String args[]) throws IOException, URISyntaxException {
String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
//Replace comma separated usernames with usernames of your choice
String response = getUsers("TwitterDev,TwitterEng", bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting you bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}
/*
* This method calls the v2 Users endpoint with usernames as query parameter
* */
private static String getUsers(String usernames, String bearerToken) throws IOException, URISyntaxException {
String userResponse = null;
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/users/by");
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("usernames", usernames));
queryParameters.add(new BasicNameValuePair("user.fields", "created_at,description,pinned_tweet_id"));
uriBuilder.addParameters(queryParameters);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
userResponse = EntityUtils.toString(entity, "UTF-8");
}
return userResponse;
}
}
================================================
FILE: javascript/README.md
================================================
# X API v2 - JavaScript (Node.js) Examples
Working JavaScript code samples for the X (formerly Twitter) API v2.
## Setup
### 1. Install Node.js 14+
```bash
node --version
```
### 2. Install dependencies
No package.json is required. Examples use Node.js built-in modules or standard libraries.
### 3. Set environment variables
**For read-only operations (search, lookup):**
```bash
export BEARER_TOKEN='your_bearer_token'
```
**For user actions (post, like, repost, bookmark, mute, etc.):**
```bash
export CLIENT_ID='your_client_id'
export CLIENT_SECRET='your_client_secret'
```
**Note:** Most user action examples (create post, like, repost, bookmark, mute, block, etc.) require OAuth 2.0 authentication with `CLIENT_ID` and `CLIENT_SECRET`. Read-only examples (search, lookup) only require `BEARER_TOKEN`.
## Examples by Category
### Posts
- `posts/create_post.js` - Create a new post (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `posts/delete_post.js` - Delete a post (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `posts/get_liking_users.js` - Get users who liked a post (requires `CLIENT_ID`, `CLIENT_SECRET` for user context)
- `posts/get_post_counts_all.js` - Get post counts (full archive)
- `posts/get_post_counts_recent.js` - Get post counts (recent)
- `posts/get_posts_by_ids.js` - Look up posts by ID (bearer token)
- `posts/get_posts_by_ids_user_context.js` - Look up posts by ID (user context) (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `posts/get_quoted_posts.js` - Get posts that quote a post
- `posts/get_reposted_by.js` - Get users who reposted a post
- `posts/search_all.js` - Full archive search
- `posts/search_recent.js` - Recent search (last 7 days)
### Users
- `users/get_users_by_usernames.js` - Look up users by username (bearer token)
- `users/get_users_by_usernames_user_context.js` - Look up users by username (user context) (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `users/get_users_me.js` - Get authenticated user (me) (requires `CLIENT_ID`, `CLIENT_SECRET`)
#### User Actions - Block
- `users/block/get_blocking.js` - Get users blocked by a user (requires `CLIENT_ID`, `CLIENT_SECRET`)
#### User Actions - Bookmark
- `users/bookmark/create_bookmark.js` - Create a bookmark (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `users/bookmark/delete_bookmark.js` - Delete a bookmark (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `users/bookmark/get_bookmarks.js` - Get user's bookmarks (requires `CLIENT_ID`, `CLIENT_SECRET`)
#### User Actions - Follow
- `users/follow/get_followers.js` - Get user's followers
- `users/follow/get_followers_paginated.js` - Get user's followers (paginated)
- `users/follow/get_following_paginated.js` - Get users a user is following (paginated)
#### User Actions - Like
- `users/like/get_liked_posts.js` - Get posts liked by a user (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `users/like/like_post.js` - Like a post (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `users/like/unlike_post.js` - Unlike a post (requires `CLIENT_ID`, `CLIENT_SECRET`)
#### User Actions - Lists
- `users/lists/follow_list.js` - Follow a list (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `users/lists/get_followed_lists.js` - Get lists followed by a user
- `users/lists/get_list_memberships.js` - Get list memberships
- `users/lists/get_owned_lists.js` - Get lists owned by a user
- `users/lists/pin_list.js` - Pin a list (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `users/lists/unfollow_list.js` - Unfollow a list (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `users/lists/unpin_list.js` - Unpin a list (requires `CLIENT_ID`, `CLIENT_SECRET`)
#### User Actions - Mute
- `users/mute/get_muting.js` - Get users muted by a user (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `users/mute/mute_user.js` - Mute a user (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `users/mute/unmute_user.js` - Unmute a user (requires `CLIENT_ID`, `CLIENT_SECRET`)
#### User Actions - Repost
- `users/repost/repost_post.js` - Repost a post (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `users/repost/unrepost_post.js` - Undo a repost (requires `CLIENT_ID`, `CLIENT_SECRET`)
#### User Actions - Timeline
- `users/timeline/get_home_timeline.js` - Get home timeline (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `users/timeline/get_mentions.js` - Get user mentions timeline
- `users/timeline/get_posts.js` - Get user's posts timeline
- `users/timeline/get_posts_paginated.js` - Get user's posts timeline (paginated)
### Timelines
- See `users/timeline/` directory for timeline examples
### Streams
- `streams/stream_posts_filtered.js` - Filtered stream with rules
- `streams/stream_posts_sample.js` - Sampled stream
### Lists
- `lists/add_member.js` - Add member to a list (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `lists/create_list.js` - Create a new list (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `lists/delete_list.js` - Delete a list (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `lists/get_list_by_id.js` - Get list by ID
- `lists/get_list_followers.js` - Get list followers
- `lists/get_list_members.js` - Get list members
- `lists/get_list_posts.js` - Get posts from a list
- `lists/remove_member.js` - Remove member from a list (requires `CLIENT_ID`, `CLIENT_SECRET`)
- `lists/update_list.js` - Update a list (requires `CLIENT_ID`, `CLIENT_SECRET`)
### Spaces
- `spaces/get_spaces_by_ids.js` - Look up Spaces by ID
- `spaces/search_spaces.js` - Search for Spaces
### Compliance
- `compliance/create_jobs.js` - Create compliance job
- `compliance/download_results.js` - Download compliance results
- `compliance/get_jobs_by_id.js` - Get compliance job by ID
- `compliance/get_jobs.js` - Get compliance jobs
- `compliance/upload_ids.js` - Upload IDs for compliance
### Usage
- `usage/get_usage.js` - Get API usage information
## Running Examples
```bash
# Make sure environment variables are set
node posts/search_recent.js
```
## More Information
- [X API Documentation](https://developer.x.com/en/docs/twitter-api)
- [X Developer Portal](https://developer.x.com/en/portal/dashboard)
================================================
FILE: javascript/compliance/create_jobs.js
================================================
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
// For User Compliance Job, replace type value with users instead of tweets
// Also replace the name value with your desired job name
const data = {
type: "tweets",
name: 'my_batch_compliance_job'
};
(async () => {
try {
// Make request
const response = await client.compliance.createJobs(data);
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/compliance/download_results.js
================================================
// Replace with your job download_url
downloadUrl = ''
async function getRequest() {
const res = await fetch(downloadUrl, {
headers: {
'Accept-Encoding': 'gzip, deflate, br'
}
})
if (res.ok) {
return await res.text();
} else {
throw new Error('Unsuccessful request');
}
}
(async () => {
try {
// Make request
const response = await getRequest();
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/compliance/get_jobs.js
================================================
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
// For User Compliance job, replace the value for type with users
const params = {
type: "tweets"
};
(async () => {
try {
// Make request
const response = await client.compliance.getJobs(params);
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/compliance/get_jobs_by_id.js
================================================
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
// Replace with your job ID
const jobId = '';
(async () => {
try {
// Make request
const response = await client.compliance.getJobsById(jobId);
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/compliance/upload_ids.js
================================================
const fs = require('fs');
// Replace with your job download_url
const uploadUrl = '';
// Replace with your file path that contains the list of Post IDs or User IDs, one ID per line
const filePath = '/path/to/file';
async function getRequest() {
const readStream = fs.createReadStream(filePath);
const fileBuffer = await new Promise((resolve, reject) => {
const chunks = [];
readStream.on('data', chunk => chunks.push(chunk));
readStream.on('end', () => resolve(Buffer.concat(chunks)));
readStream.on('error', reject);
});
const res = await fetch(uploadUrl, {
method: 'PUT',
body: fileBuffer,
headers: {
"Content-Type": "text/plain"
}
});
if (res.ok) {
return res.status;
} else {
throw new Error('Unsuccessful request');
}
}
(async () => {
try {
// Make request
const response = await getRequest();
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/lists/add_member.js
================================================
// Add member to a list using OAuth 2.0 to authorize the user
// https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/quick-start
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// Be sure to replace your-list-id with your own list ID or one of an authenticated user
const listId = "your-list-id";
// Be sure to replace user-id-to-add with the user id you wish to add.
// You can find a user ID by using the user lookup endpoint
const userId = "user-id-to-add";
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'list.read', 'list.write', 'offline.access']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log("Please go here and authorize:", authUrl);
// Input callback URL from terminal
const redirectCallback = await input("Paste the redirected callback URL here: ");
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK
const response = await client.lists.addMember(listId, { body: { user_id: userId } });
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/lists/create_list.js
================================================
// Create a new list using OAuth 2.0 to authorize the user
// https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/quick-start
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// Be sure to add replace name-of-list with the name you wish to call the list.
// description and private keys are optional
const data = {
name: "name-of-list",
description: "description-of-list",
private: false,
};
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'list.read', 'list.write', 'offline.access']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log("Please go here and authorize:", authUrl);
// Input callback URL from terminal
const redirectCallback = await input("Paste the redirected callback URL here: ");
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK
const response = await client.lists.create({ body: data });
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/lists/delete_list.js
================================================
// Delete an existing list the authenticated user owns - using OAuth 2.0 to authorize the user
// https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/quick-start
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// Be sure to add replace the your-list-id with the id of the list you wish to delete.
const targetListId = "your-list-id";
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'list.read', 'list.write', 'offline.access']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log("Please go here and authorize:", authUrl);
// Input callback URL from terminal
const redirectCallback = await input("Paste the redirected callback URL here: ");
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK
const response = await client.lists.delete(targetListId);
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/lists/get_list_by_id.js
================================================
/**
* List Lookup - X API v2
*
* Endpoint: GET https://api.x.com/2/lists/:id
* Docs: https://developer.x.com/en/docs/twitter-api/lists/list-lookup/api-reference/get-lists-id
*
* Authentication: Bearer Token (App-only) or OAuth (User Context)
* Required env vars: BEARER_TOKEN
*/
const { Client } = require('@xdevplatform/xdk');
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
// Replace with the list ID you want to look up
const listId = "84839422";
(async () => {
try {
const response = await client.lists.getById(listId, {
listFields: ['created_at', 'follower_count', 'member_count', 'owner_id', 'description']
});
console.dir(response, { depth: null });
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/lists/get_list_followers.js
================================================
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
const id = "list-id";
(async () => {
try {
// These are the parameters for the API request
// by default, only the User ID and name are returned
const response = await client.lists.getFollowers(id, {
userFields: ['pinned_tweet_id', 'created_at'], // Edit optional query parameters here
expansions: ['pinned_tweet_id'], // expansions is used to include the Post object
tweetFields: ['created_at'] // Edit optional query parameters here
});
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/lists/get_list_members.js
================================================
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
const id = "list-id";
(async () => {
try {
// These are the parameters for the API request
// by default, only the User ID and name are returned
const response = await client.lists.getMembers(id, {
userFields: ['pinned_tweet_id', 'created_at'], // Edit optional query parameters here
expansions: ['pinned_tweet_id'], // expansions is used to include the Post object
tweetFields: ['created_at'] // Edit optional query parameters here
});
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/lists/get_list_posts.js
================================================
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
const id = "list-id";
(async () => {
try {
// These are the parameters for the API request
// by default, only the Post ID and text are returned
const response = await client.lists.getPosts(id, {
tweetFields: ['lang', 'author_id'], // Edit optional query parameters here
expansions: ['author_id'], // expansions is used to include the user object
userFields: ['created_at'] // Edit optional query parameters here
});
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/lists/remove_member.js
================================================
// Remove member from a list using OAuth 2.0 to authorize the user
// https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/quick-start
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// Be sure to replace your-list-id with your own list ID or one of an authenticated user
const listId = "your-list-id";
// Be sure to replace user-id-to-remove with the user id you wish to remove.
// You can find a user ID by using the user lookup endpoint
const userId = "user-id-to-remove";
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'list.read', 'list.write', 'offline.access']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log("Please go here and authorize:", authUrl);
// Input callback URL from terminal
const redirectCallback = await input("Paste the redirected callback URL here: ");
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK
const response = await client.lists.removeMemberByUserId(listId, userId);
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/lists/update_list.js
================================================
// Update the metadata of an existing list the authenticated user owns - using OAuth 2.0 to authorize the user
// https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/quick-start
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// Be sure to add replace update-name-of-list with the name you wish to call the list.
// name, description and private are all optional
const data = {
name: "update-name-of-list",
description: "update-description-of-list",
private: false,
};
// Be sure to add replace the your-list-id with the list id of the list you wish to update.
const targetListId = "your-list-id";
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'list.read', 'list.write', 'offline.access']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log("Please go here and authorize:", authUrl);
// Input callback URL from terminal
const redirectCallback = await input("Paste the redirected callback URL here: ");
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK
const response = await client.lists.update(targetListId, { body: data });
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/posts/create_post.js
================================================
/**
* Create Post - X API v2
*
* Endpoint: POST https://api.x.com/2/posts
* Docs: https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets
*
* Authentication: OAuth 2.0 (User Context)
* Required env vars: CLIENT_ID, CLIENT_SECRET
*/
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// The text content of the post. You can also add parameters for polls,
// quote posts, reply settings, and more.
const data = {
text: "Hello world!"
};
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'tweet.write', 'offline.access']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log('Please go here and authorize:', authUrl);
// Input callback URL from terminal
const redirectCallback = await input('Paste the redirected callback URL here: ');
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK
const response = await client.posts.create(data);
console.dir(response, { depth: null });
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/posts/delete_post.js
================================================
/**
* Delete Post - X API v2
*
* Endpoint: DELETE https://api.x.com/2/posts/:id
* Docs: https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/delete-tweets-id
*
* Authentication: OAuth 2.0 (User Context)
* Required env vars: CLIENT_ID, CLIENT_SECRET
*/
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// Replace with the post ID you want to delete
const postId = "post-id-to-delete";
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'tweet.write','offline.access']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log('Please go here and authorize:', authUrl);
// Input callback URL from terminal
const redirectCallback = await input('Paste the redirected callback URL here: ');
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK
const response = await client.posts.delete(postId);
console.dir(response, { depth: null });
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/posts/get_liking_users.js
================================================
// Get liking users for a post using OAuth 2.0 to authorize the user
// https://developer.twitter.com/en/docs/twitter-api/tweets/likes/api-reference/get-tweets-id-liking_users
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// You can replace the ID given with the Post ID you wish to get liking users for.
// You can find an ID by using the Post lookup endpoint
const id = "1354143047324299264";
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'like.read', 'offline.access']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log("Please go here and authorize:", authUrl);
// Input callback URL from terminal
const redirectCallback = await input("Paste the redirected callback URL here: ");
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// These are the parameters for the API request
// by default, only the Post ID and text are returned
const response = await client.posts.getLikingUsers(id, {
tweetFields: ['lang', 'author_id'], // Edit optional query parameters here
userFields: ['created_at'] // Edit optional query parameters here
});
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/posts/get_post_counts_all.js
================================================
// Search for public posts across the whole Twitter archive
// https://developer.twitter.com/en/docs/twitter-api/tweets/search/quick-start/full-archive-search
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
(async () => {
try {
// Edit query parameters below and specify a search query
// optional params: start_time,end_time,since_id,until_id,next_token,granularity
const response = await client.posts.getCountsAll('from:xdevelopers', {
granularity: 'day',
startTime: '2021-01-01T00:00:00Z'
});
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/posts/get_post_counts_recent.js
================================================
// Search for posts within the past seven days
// https://developer.twitter.com/en/docs/twitter-api/tweets/search/quick-start/recent-search
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
(async () => {
try {
// Edit query parameters below and specify a search query
// optional params: start_time,end_time,since_id,until_id,next_token,granularity
const response = await client.posts.getCountsRecent('from:xdevelopers', {
granularity: 'day'
});
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/posts/get_posts_by_ids.js
================================================
/**
* Post Lookup - X API v2
*
* Endpoint: GET https://api.x.com/2/posts
* Docs: https://developer.x.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets
*
* Authentication: Bearer Token (App-only) or OAuth (User Context)
* Required env vars: BEARER_TOKEN
*/
const { Client } = require('@xdevplatform/xdk');
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
// These are the parameters for the API request
// specify Post IDs to fetch, and any additional fields that are required
// by default, only the Post ID and text are returned
const postIDs = ['1278747501642657792', '1275828087666679809']; // Edit the Post IDs to look up
(async () => {
try {
// Post IDs to look up (comma-separated, up to 100)
const response = await client.posts.getByIds(postIDs, {
tweetFields: ['created_at', 'author_id', 'lang', 'source', 'public_metrics'],
userFields: ['created_at'],
expansions: ['author_id']
});
console.dir(response, { depth: null });
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/posts/get_posts_by_ids_user_context.js
================================================
// Get Post objects by ID, using user authentication
// https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/quick-start
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// These are the parameters for the API request
// specify Post IDs to fetch, and any additional fields that are required
// by default, only the Post ID and text are returned
const postIDs = ['1278747501642657792', '1275828087666679809']; // Edit the Post IDs to look up
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'offline.access']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log('Please go here and authorize:', authUrl);
// Input callback URL from terminal
const redirectCallback = await input('Paste the redirected callback URL here: ');
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK
const response = await client.posts.getByIds(postIDs, {
tweetFields: ['lang', 'author_id'],
userFields: ['created_at']
});
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/posts/get_quoted_posts.js
================================================
// Get Quote Posts by Post ID
// https://developer.twitter.com/en/docs/twitter-api/tweets/quote-tweets-lookup/quick-start
const { Client, PostPaginator } = require('@xdevplatform/xdk');
const postId = '1980412193624785337';
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const bearerToken = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: bearerToken });
const getQuotePosts = async () => {
console.log("Retrieving quote posts...");
// Use paginator for automatic pagination
const quotePosts = new PostPaginator(
async (token) => {
const res = await client.posts.getQuoted(postId, {
maxResults: 100,
paginationToken: token,
tweetFields: ['created_at']
});
return {
data: res.data ?? [],
meta: res.meta,
includes: res.includes,
errors: res.errors
};
}
);
// Fetch all pages
await quotePosts.fetchNext();
while (!quotePosts.done) {
await quotePosts.fetchNext();
}
console.dir(quotePosts.posts, {
depth: null
});
console.log(`Got ${quotePosts.posts.length} quote posts for Post ID ${postId}!`);
}
getQuotePosts().catch(err => {
console.error('Error:', err);
process.exit(-1);
});
================================================
FILE: javascript/posts/get_reposted_by.js
================================================
// Get Reposted By (Users who reposted) by Post ID
// https://developer.twitter.com/en/docs/twitter-api/tweets/retweets/api-reference/get-tweets-id-retweeted_by
const { Client, UserPaginator } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const bearerToken = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: bearerToken });
// You can replace the ID given with the Post ID you wish to lookup reposting users for
// You can find an ID by using the Post lookup endpoint
const postId = "1980412193624785337";
const getRepostedBy = async () => {
console.log("Retrieving users who reposted...");
// Use paginator for automatic pagination
const repostedBy = new UserPaginator(
async (token) => {
const res = await client.posts.getRepostedBy(postId, {
maxResults: 100,
paginationToken: token,
tweetFields: ['lang', 'author_id'],
userFields: ['created_at']
});
return {
data: res.data ?? [],
meta: res.meta,
includes: res.includes,
errors: res.errors
};
}
);
// Fetch all pages
await repostedBy.fetchNext();
while (!repostedBy.done) {
await repostedBy.fetchNext();
}
console.dir(repostedBy.users, {
depth: null
});
console.log(`Got ${repostedBy.users.length} users who reposted Post ID ${postId}!`);
}
getRepostedBy().catch(err => {
console.error('Error:', err);
process.exit(-1);
});
================================================
FILE: javascript/posts/search_all.js
================================================
// Search for public posts across the whole Twitter archive
// https://developer.twitter.com/en/docs/twitter-api/tweets/search/quick-start/full-archive-search
const { Client, PostPaginator } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const bearerToken = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: bearerToken });
const query = 'from:xdevelopers';
const searchAll = async () => {
console.log("Searching full archive...");
// Use paginator for automatic pagination
const searchResults = new PostPaginator(
async (token) => {
const res = await client.posts.searchAll(query, {
maxResults: 100,
nextToken: token,
tweetFields: ['author_id']
});
return {
data: res.data ?? [],
meta: res.meta,
includes: res.includes,
errors: res.errors
};
}
);
// Fetch all pages
await searchResults.fetchNext();
while (!searchResults.done) {
await searchResults.fetchNext();
}
console.dir(searchResults.posts, {
depth: null
});
console.log(`Got ${searchResults.posts.length} posts for query: ${query}`);
}
searchAll().catch(err => {
console.error('Error:', err);
process.exit(-1);
});
================================================
FILE: javascript/posts/search_recent.js
================================================
/**
* Recent Search - X API v2
*
* Endpoint: GET https://api.x.com/2/posts/search/recent
* Docs: https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent
*
* Authentication: Bearer Token (App-only)
* Required env vars: BEARER_TOKEN
*
* Note: Returns posts from the last 7 days.
* This example demonstrates automatic pagination using PostPaginator
* to fetch all pages of results.
*/
const { Client, PostPaginator } = require('@xdevplatform/xdk');
const bearerToken = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: bearerToken });
const query = 'from:x -is:retweet';
const searchRecent = async () => {
console.log("Searching recent posts...");
// Use paginator for automatic pagination
const searchResults = new PostPaginator(
async (token) => {
const res = await client.posts.searchRecent(query, {
maxResults: 100,
nextToken: token,
tweetFields: ['author_id', 'created_at']
});
return {
data: res.data ?? [],
meta: res.meta,
includes: res.includes,
errors: res.errors
};
}
);
// Fetch all pages
await searchResults.fetchNext();
while (!searchResults.done) {
await searchResults.fetchNext();
}
console.dir(searchResults.posts, {
depth: null
});
console.log(`Got ${searchResults.posts.length} posts for query: ${query}`);
}
searchRecent().catch(err => {
console.error('Error:', err);
process.exit(-1);
});
================================================
FILE: javascript/spaces/get_spaces_by_ids.js
================================================
/**
* Spaces Lookup - X API v2
*
* Endpoint: GET https://api.x.com/2/spaces
* Docs: https://developer.x.com/en/docs/twitter-api/spaces/lookup/api-reference/get-spaces
*
* Authentication: Bearer Token (App-only) or OAuth (User Context)
* Required env vars: BEARER_TOKEN
*/
const { Client } = require('@xdevplatform/xdk');
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
const spaceIds = ['1DXxyRYNejbKM'];
(async () => {
try {
// Replace with Space IDs you want to look up
const response = await client.spaces.getByIds(spaceIds, {
spaceFields: ['host_ids', 'created_at', 'creator_id', 'participant_count', 'title', 'state']
});
console.dir(response, { depth: null });
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/spaces/search_spaces.js
================================================
// Lookup Spaces by ID
// https://developer.twitter.com/en/docs/twitter-api/spaces/lookup
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
const query = 'NBA';
(async () => {
try {
// Edit query parameters below and specify a search query
// optional params: host_ids,conversation_controls,created_at,creator_id,id,invited_user_ids,is_ticketed,lang,media_key,participants,scheduled_start,speaker_ids,started_at,state,title,updated_at
const response = await client.spaces.search(query, {
spaceFields: ['title', 'created_at'],
expansions: ['creator_id']
});
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/streams/stream_posts_filtered.js
================================================
// Open a realtime stream of posts, filtered according to rules
// https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/quick-start
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
// this sets up two rules - the value is the search terms to match on, and the tag is an identifier that
// will be applied to the posts returned to show which rule they matched
// with a standard project with Basic Access, you can add up to 25 concurrent rules to your stream, and
// each rule can be up to 512 characters long
// Edit rules as desired below
const rules = [{
value: 'dog has:images -is:retweet',
tag: 'dog pictures'
},
{
value: 'cat has:images -grumpy',
tag: 'cat pictures'
},
];
(async () => {
try {
// Gets the complete list of rules currently applied to the stream
const currentRules = await client.stream.getRules();
// Delete all rules. Comment the line below if you want to keep your existing rules.
if (currentRules.data && currentRules.data.length > 0) {
const ids = currentRules.data.map(rule => rule.id);
await client.stream.updateRules({ delete: { ids: ids } });
}
// Add rules to the stream. Comment the line below if you don't want to add new rules.
await client.stream.updateRules({ add: rules });
// Listen to the stream
const stream = await client.stream.posts({
tweetFields: ['id', 'text', 'created_at']
});
stream.on('data', (event) => {
// event is the parsed JSON line (data/includes/matching_rules)
console.log('New data:', event);
});
stream.on('error', (e) => {
console.error('Stream error:', e);
if (e.detail === "This stream is currently at the maximum allowed connection limit.") {
console.log(e.detail);
process.exit(1);
}
});
stream.on('keepAlive', () => {
// heartbeat event - keep alive signal received
});
stream.on('close', () => {
console.log('Stream closed');
});
} catch (e) {
console.error(e);
process.exit(1);
}
})();
================================================
FILE: javascript/streams/stream_posts_sample.js
================================================
// Open a live stream of roughly 1% random sample of publicly available posts
// https://developer.twitter.com/en/docs/twitter-api/tweets/volume-streams/quick-start
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
(async () => {
try {
// 1% sampled public posts
const stream = await client.stream.postsSample({
tweetFields: ['id', 'text', 'created_at']
});
// Listen to events
stream.on('data', (event) => {
// event is the parsed JSON line (data/includes/matching_rules)
console.log('New data:', event);
});
stream.on('error', (e) => {
console.error('Stream error:', e);
if (e.status === 401) {
console.log('Unauthorized');
process.exit(1);
} else if (e.detail === "This stream is currently at the maximum allowed connection limit.") {
console.log(e.detail);
process.exit(1);
}
});
stream.on('keepAlive', () => {
// heartbeat event - keep alive signal received
});
stream.on('close', () => {
console.log('Stream closed');
});
} catch (e) {
console.error('Error:', e);
process.exit(1);
}
})();
================================================
FILE: javascript/usage/get_usage.js
================================================
// Get Posts Usage
// https://developer.twitter.com/en/docs/twitter-api/usage/tweets
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
(async () => {
try {
// Make request
const response = await client.usage.get();
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/users/block/get_blocking.js
================================================
// Block a user, using user authentication
// https://developer.twitter.com/en/docs/twitter-api/users/blocks/quick-start
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// Be sure to replace your-user-id with your own user ID or one of an authenticated user
// You can find a user ID by using the user lookup endpoint
const userId = "your-user-id";
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'tweet.write', 'offline.access', 'block.read']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log('Please go here and authorize:', authUrl);
// Input callback URL from terminal
const redirectCallback = await input('Paste the redirected callback URL here: ');
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK
const response = await client.users.getBlocking(userId);
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/users/bookmark/create_bookmark.js
================================================
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
//Helper function to parse callback
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
//Helper terminal input function
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
// Include the ID of the Post you wish to bookmark
const tweetId = "post-id"; // Replace with the ID of the Post you wish to bookmark
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'bookmark.write']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const STATE = "my-state";
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(STATE);
console.log(`Please go here and authorize:`, authUrl);
//Input users callback url in terminal
const redirectCallback = await input("Paste the redirected callback here: ");
//Parse callback
const { state, code } = getQueryStringParams(redirectCallback);
if (state !== STATE) {
console.log("State isn't matching");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
//Get the user ID
const meResponse = await client.users.getMe();
const userId = meResponse.data?.id;
if (!userId) {
throw new Error('Could not get user ID');
}
//Makes api call
const postBookmark = await client.users.createBookmark(userId, { tweet_id: tweetId });
console.dir(postBookmark, {
depth: null,
});
process.exit();
} catch (error) {
console.log(error);
process.exit(-1);
}
})();
================================================
FILE: javascript/users/bookmark/delete_bookmark.js
================================================
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
//Helper function to parse callback
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
//Helper terminal input function
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
// Include the ID of the Post you wish to unbookmark
const tweetId = "1996314591996129694";
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'bookmark.write']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const STATE = "my-state";
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(STATE);
console.log(`Please go here and authorize:`, authUrl);
//Input users callback url in terminal
const redirectCallback = await input("Paste the redirected callback here: ");
//Parse callback
const { state, code } = getQueryStringParams(redirectCallback);
if (state !== STATE) {
console.log("State isn't matching");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
//Get the user ID
const meResponse = await client.users.getMe();
const userId = meResponse.data?.id;
if (!userId) {
throw new Error('Could not get user ID');
}
//Makes api call
const deleteBookmark = await client.users.deleteBookmark(userId, tweetId);
console.dir(deleteBookmark, {
depth: null,
});
process.exit();
} catch (error) {
console.log(error);
process.exit(-1);
}
})();
================================================
FILE: javascript/users/bookmark/get_bookmarks.js
================================================
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
//Helper function to parse callback
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
//Helper terminal input function
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
// Optional parameters for additional payload data
const params = {
expansions: ['author_id'],
userFields: ['username', 'created_at'],
tweetFields: ['geo', 'entities', 'context_annotations']
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'bookmark.read']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const STATE = "my-state";
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(STATE);
console.log(`Please go here and authorize:`, authUrl);
//Input users callback url in terminal
const redirectCallback = await input("Paste the redirected callback here: ");
//Parse callback
const { state, code } = getQueryStringParams(redirectCallback);
if (state !== STATE) {
console.log("State isn't matching");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
//Get the user ID
const meResponse = await client.users.getMe();
const userId = meResponse.data?.id;
if (!userId) {
throw new Error('Could not get user ID');
}
//Makes api call
const getBookmark = await client.users.getBookmarks(userId, params);
console.dir(getBookmark, {
depth: null,
});
process.exit();
} catch (error) {
console.log(error);
process.exit(-1);
}
})();
================================================
FILE: javascript/users/follow/get_followers.js
================================================
// Fetch the followers of a user account, by ID
// https://developer.twitter.com/en/docs/twitter-api/users/follows/quick-start
const { Client, UserPaginator } = require('@xdevplatform/xdk');
// this is the ID for @XDevelopers
const userId = '2244994945';
const bearerToken = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: bearerToken });
const getFollowers = async () => {
console.log("Retrieving followers...");
// Use paginator for automatic pagination
const followers = new UserPaginator(
async (token) => {
const res = await client.users.getFollowers(userId, {
maxResults: 1000,
paginationToken: token,
userFields: ['created_at']
});
return {
data: res.data ?? [],
meta: res.meta,
includes: res.includes,
errors: res.errors
};
}
);
// Fetch all pages
await followers.fetchNext();
while (!followers.done) {
await followers.fetchNext();
}
console.log(followers.users);
console.log(`Got ${followers.users.length} users.`);
}
getFollowers().catch(err => {
console.error('Error:', err);
process.exit(-1);
});
================================================
FILE: javascript/users/follow/get_followers_paginated.js
================================================
/**
* User Followers Lookup (Paginated) - X API v2
*
* Endpoint: GET https://api.x.com/2/users/:id/followers
* Docs: https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/get-users-id-followers
*
* Authentication: Bearer Token (App-only) or OAuth (User Context)
* Required env vars: BEARER_TOKEN
*
* This example demonstrates automatic pagination using UserPaginator
* to fetch all pages of results. For a simple single-request example,
* see followers_lookup.js
*/
const { Client, UserPaginator } = require('@xdevplatform/xdk');
// this is the ID for @XDevelopers
const userId = '2244994945';
const bearerToken = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: bearerToken });
const getFollowers = async () => {
console.log("Retrieving followers...");
// Use paginator for automatic pagination
const followers = new UserPaginator(
async (token) => {
const res = await client.users.getFollowers(userId, {
maxResults: 1000,
paginationToken: token,
userFields: ['created_at']
});
return {
data: res.data ?? [],
meta: res.meta,
includes: res.includes,
errors: res.errors
};
}
);
// Fetch all pages
await followers.fetchNext();
while (!followers.done) {
await followers.fetchNext();
}
console.log(followers.users);
console.log(`Got ${followers.users.length} users.`);
}
getFollowers().catch(err => {
console.error('Error:', err);
process.exit(-1);
});
================================================
FILE: javascript/users/follow/get_following_paginated.js
================================================
/**
* User Following Lookup (Paginated) - X API v2
*
* Endpoint: GET https://api.x.com/2/users/:id/following
* Docs: https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/get-users-id-following
*
* Authentication: Bearer Token (App-only) or OAuth (User Context)
* Required env vars: BEARER_TOKEN
*
* This example demonstrates automatic pagination using UserPaginator
* to fetch all pages of results.
*/
const { Client, UserPaginator } = require('@xdevplatform/xdk');
// this is the ID for @XDevelopers
const userId = '2244994945';
const bearerToken = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: bearerToken });
const getFollowing = async () => {
console.log("Retrieving users this user is following...");
// Use paginator for automatic pagination
const following = new UserPaginator(
async (token) => {
const res = await client.users.getFollowing(userId, {
maxResults: 1000,
paginationToken: token,
userFields: ['created_at']
});
return {
data: res.data ?? [],
meta: res.meta,
includes: res.includes,
errors: res.errors
};
}
);
// Fetch all pages
await following.fetchNext();
while (!following.done) {
await following.fetchNext();
}
console.log(following.users);
console.log(`Got ${following.users.length} users.`);
}
getFollowing().catch(err => {
console.error('Error:', err);
process.exit(-1);
});
================================================
FILE: javascript/users/get_users_by_usernames.js
================================================
/**
* User Lookup - X API v2
*
* Endpoint: GET https://api.x.com/2/users/by
* Docs: https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-by
*
* Authentication: Bearer Token (App-only) or OAuth (User Context)
* Required env vars: BEARER_TOKEN
*/
const { Client } = require('@xdevplatform/xdk');
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
const usernames = ['XDevelopers', 'X'];
(async () => {
try {
// Usernames to look up (up to 100)
const response = await client.users.getByUsernames(usernames, {
userFields: ['created_at', 'description', 'public_metrics'],
expansions: ['pinned_tweet_id']
});
console.dir(response, { depth: null });
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/users/get_users_by_usernames_user_context.js
================================================
// Get User objects by username, using user authentication
// https://developer.twitter.com/en/docs/twitter-api/users/lookup/quick-start
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// These are the parameters for the API request
// specify usernames to fetch, and any additional fields that are required
// by default, only the User ID, name and username are returned
const usernames = ['XDevelopers', 'X']; // Edit usernames to look up
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'offline.access']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log('Please go here and authorize:', authUrl);
// Input callback URL from terminal
const redirectCallback = await input('Paste the redirected callback URL here: ');
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK
const response = await client.users.getByUsernames(usernames, {
userFields: ['created_at', 'description'],
expansions: ['pinned_tweet_id']
});
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/users/get_users_me.js
================================================
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'offline.access']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log('Please go here and authorize:', authUrl);
// Input callback URL from terminal
const redirectCallback = await input('Paste the redirected callback URL here: ');
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK - get authenticated user
const response = await client.users.getMe({
userFields: ['created_at', 'description'],
expansions: ['pinned_tweet_id']
});
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/users/like/get_liked_posts.js
================================================
// Get Liked Posts by User ID using OAuth 2.0 to authorize the user
// https://developer.twitter.com/en/docs/twitter-api/tweets/likes/api-reference/get-users-id-liked_tweets
const {
Client,
OAuth2,
PostPaginator,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// You can replace the ID given with the User ID you wish to get liked posts for.
// You can find a user ID by using the user lookup endpoint
const userId = "your-user-id";
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'like.read', 'offline.access']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log("Please go here and authorize:", authUrl);
// Input callback URL from terminal
const redirectCallback = await input("Paste the redirected callback URL here: ");
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
console.log("Retrieving liked posts...");
// Use paginator for automatic pagination
const likedPosts = new PostPaginator(
async (token) => {
const res = await client.users.getLikedPosts(userId, {
maxResults: 100,
paginationToken: token,
tweetFields: ['lang', 'author_id'],
userFields: ['created_at']
});
return {
data: res.data ?? [],
meta: res.meta,
includes: res.includes,
errors: res.errors
};
}
);
// Fetch all pages
await likedPosts.fetchNext();
while (!likedPosts.done) {
await likedPosts.fetchNext();
}
console.dir(likedPosts.posts, {
depth: null
});
console.log(`Got ${likedPosts.posts.length} liked posts for user ID ${userId}!`);
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/users/like/like_post.js
================================================
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// Be sure to replace your-user-id with your own user ID or one of an authenticating user
// You can find a user ID by using the user lookup endpoint
const userId = "your-user-id";
// You can replace Post ID given with the Post ID you wish to like.
// You can find a Post ID by using the Post lookup endpoint
const postId = "1354143047324299264";
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'tweet.write', 'offline.access', 'like.write']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log('Please go here and authorize:', authUrl);
// Input callback URL from terminal
const redirectCallback = await input('Paste the redirected callback URL here: ');
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK
const response = await client.users.likePost(userId, {body: {tweet_id: postId}});
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/users/like/unlike_post.js
================================================
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// Be sure to replace your-user-id with your own user ID or one of an authenticating user
// You can find a user ID by using the user lookup endpoint
const userId = "your-user-id";
// You can replace Post ID given with the Post ID you wish to unlike.
// You can find a Post ID by using the Post lookup endpoint
const postId = "1354143047324299264";
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'tweet.write', 'offline.access', 'like.write']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log('Please go here and authorize:', authUrl);
// Input callback URL from terminal
const redirectCallback = await input('Paste the redirected callback URL here: ');
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK
const response = await client.users.unlikePost(userId, postId);
console.dir(response, {
depth: null
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/users/lists/follow_list.js
================================================
// Follow a list using OAuth 2.0 to authorize the user
// https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/quick-start
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// Be sure to replace your-user-id with your own user ID or one of an authenticated user
// You can find a user ID by using the user lookup endpoint
const userId = "your-user-id";
// Be sure to add replace list-id-to-follow with the list id you wish to follow.
const listId = "list-id-to-follow";
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
(async () => {
try {
// Configure OAuth 2.0
const oauth2Config = {
clientId: clientId,
clientSecret: clientSecret,
redirectUri: 'https://example.com',
scope: ['tweet.read', 'users.read', 'list.read', 'list.write', 'offline.access']
};
const oauth2 = new OAuth2(oauth2Config);
// Generate PKCE parameters
const state = 'example-state';
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
oauth2.setPkceParameters(codeVerifier, codeChallenge);
// Get authorization URL
const authUrl = await oauth2.getAuthorizationUrl(state);
console.log("Please go here and authorize:", authUrl);
// Input callback URL from terminal
const redirectCallback = await input("Paste the redirected callback URL here: ");
// Parse callback
const { state: returnedState, code } = getQueryStringParams(redirectCallback);
if (returnedState !== state) {
console.log("State doesn't match");
process.exit(-1);
}
// Exchange code for tokens
const tokens = await oauth2.exchangeCode(code, codeVerifier);
// Create client with access token
const client = new Client({
accessToken: tokens.access_token
});
// Make the request using SDK
const response = await client.users.followList(userId, {body: {list_id: listId}});
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/users/lists/get_followed_lists.js
================================================
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
const id = "user-id";
(async () => {
try {
// These are the parameters for the API request
// by default, only the List ID and name are returned
const response = await client.users.getFollowedLists(id, {
listFields: ['owner_id'], // Edit optional query parameters here
expansions: ['owner_id'], // expansions is used to include the user object
userFields: ['created_at', 'verified'] // Edit optional query parameters here
});
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/users/lists/get_list_memberships.js
================================================
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
const id = "user-id";
(async () => {
try {
// These are the parameters for the API request
// by default, only the List ID and name are returned
const response = await client.users.getListMemberships(id, {
listFields: ['owner_id'], // Edit optional query parameters here
expansions: ['owner_id'], // expansions is used to include the user object
userFields: ['created_at', 'verified'] // Edit optional query parameters here
});
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/users/lists/get_owned_lists.js
================================================
const { Client } = require('@xdevplatform/xdk');
// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
const client = new Client({ bearerToken: token });
const id = "user-id";
(async () => {
try {
// These are the parameters for the API request
// by default, only the List ID and name are returned
const response = await client.users.getOwnedLists(id, {
listFields: ['owner_id'], // Edit optional query parameters here
expansions: ['owner_id'], // expansions is used to include the user object
userFields: ['created_at', 'verified'] // Edit optional query parameters here
});
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
================================================
FILE: javascript/users/lists/pin_list.js
================================================
// Pin a list using OAuth 2.0 to authorize the user
// https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/quick-start
const {
Client,
OAuth2,
generateCodeVerifier,
generateCodeChallenge
} = require('@xdevplatform/xdk');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
// The code below sets the client ID and client secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENT_SECRET='YOUR-CLIENT-SECRET'
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
// Be sure to replace your-user-id with your own user ID or one of an authenticated user
// You can find a user ID by using the user lookup endpoint
const userId = "your-user-id";
// Be sure to add replace list-id-to-pin with the list id you wish to pin.
const listId = "list-id-to-pin";
async function input(prompt) {
return new Promise((resolve) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// Helper function to parse callback URL
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
gitextract_8ed01k13/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.md
│ │ └── config.yml
│ └── workflows/
│ └── cla.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── LICENSE
├── README.md
├── api-index.json
├── java/
│ ├── README.md
│ ├── posts/
│ │ ├── FullArchiveSearchDemo.java
│ │ ├── FullArchiveTweetCountsDemo.java
│ │ ├── QuoteTweetsDemo.java
│ │ ├── RecentSearchDemo.java
│ │ ├── RecentTweetCountsDemo.java
│ │ ├── SearchRecent.java
│ │ └── TweetsDemo.java
│ ├── spaces/
│ │ ├── SearchSpacesDemo.java
│ │ └── SpacesLookupDemo.java
│ ├── streams/
│ │ ├── FilteredStreamDemo.java
│ │ └── SampledStream.java
│ ├── timelines/
│ │ ├── UserMentionsDemo.java
│ │ ├── UserTweetsDemo.java
│ │ └── reverse-chron-home-timeline-java-sdk.java
│ ├── usage/
│ │ └── UsageTweetsDemo.java
│ └── users/
│ ├── FollowersLookupDemo.java
│ ├── FollowingLookupDemo.java
│ ├── Lookup.java
│ └── UsersDemo.java
├── javascript/
│ ├── README.md
│ ├── compliance/
│ │ ├── create_jobs.js
│ │ ├── download_results.js
│ │ ├── get_jobs.js
│ │ ├── get_jobs_by_id.js
│ │ └── upload_ids.js
│ ├── lists/
│ │ ├── add_member.js
│ │ ├── create_list.js
│ │ ├── delete_list.js
│ │ ├── get_list_by_id.js
│ │ ├── get_list_followers.js
│ │ ├── get_list_members.js
│ │ ├── get_list_posts.js
│ │ ├── remove_member.js
│ │ └── update_list.js
│ ├── posts/
│ │ ├── create_post.js
│ │ ├── delete_post.js
│ │ ├── get_liking_users.js
│ │ ├── get_post_counts_all.js
│ │ ├── get_post_counts_recent.js
│ │ ├── get_posts_by_ids.js
│ │ ├── get_posts_by_ids_user_context.js
│ │ ├── get_quoted_posts.js
│ │ ├── get_reposted_by.js
│ │ ├── search_all.js
│ │ └── search_recent.js
│ ├── spaces/
│ │ ├── get_spaces_by_ids.js
│ │ └── search_spaces.js
│ ├── streams/
│ │ ├── stream_posts_filtered.js
│ │ └── stream_posts_sample.js
│ ├── usage/
│ │ └── get_usage.js
│ └── users/
│ ├── block/
│ │ └── get_blocking.js
│ ├── bookmark/
│ │ ├── create_bookmark.js
│ │ ├── delete_bookmark.js
│ │ └── get_bookmarks.js
│ ├── follow/
│ │ ├── get_followers.js
│ │ ├── get_followers_paginated.js
│ │ └── get_following_paginated.js
│ ├── get_users_by_usernames.js
│ ├── get_users_by_usernames_user_context.js
│ ├── get_users_me.js
│ ├── like/
│ │ ├── get_liked_posts.js
│ │ ├── like_post.js
│ │ └── unlike_post.js
│ ├── lists/
│ │ ├── follow_list.js
│ │ ├── get_followed_lists.js
│ │ ├── get_list_memberships.js
│ │ ├── get_owned_lists.js
│ │ ├── pin_list.js
│ │ ├── unfollow_list.js
│ │ └── unpin_list.js
│ ├── mute/
│ │ ├── get_muting.js
│ │ ├── mute_user.js
│ │ └── unmute_user.js
│ ├── repost/
│ │ ├── repost_post.js
│ │ └── unrepost_post.js
│ └── timeline/
│ ├── get_home_timeline.js
│ ├── get_mentions.js
│ ├── get_posts.js
│ └── get_posts_paginated.js
├── llms.txt
├── python/
│ ├── README.md
│ ├── activity/
│ │ ├── create_subscription.py
│ │ ├── delete_subscription.py
│ │ ├── list_subscriptions.py
│ │ ├── stream_events.py
│ │ └── update_subscription.py
│ ├── compliance/
│ │ ├── create_jobs.py
│ │ ├── download_results.py
│ │ ├── get_jobs.py
│ │ ├── get_jobs_by_id.py
│ │ └── upload_ids.py
│ ├── direct_messages/
│ │ ├── get_events_by_conversation.py
│ │ ├── get_one_to_one_conversation_events.py
│ │ ├── get_user_conversation_events.py
│ │ ├── post_dm_to_conversation.py
│ │ ├── post_group_conversation_dm.py
│ │ └── post_one_to_one_dm.py
│ ├── lists/
│ │ ├── add_member.py
│ │ ├── create_list.py
│ │ ├── delete_list.py
│ │ ├── get_list_by_id.py
│ │ ├── get_list_followers.py
│ │ ├── get_list_members.py
│ │ ├── get_list_posts.py
│ │ ├── remove_member.py
│ │ └── update_list.py
│ ├── media/
│ │ ├── media_upload_v2.py
│ │ └── upload.py
│ ├── posts/
│ │ ├── create_post.py
│ │ ├── delete_post.py
│ │ ├── get_liking_users.py
│ │ ├── get_post_by_id.py
│ │ ├── get_post_counts_all.py
│ │ ├── get_post_counts_recent.py
│ │ ├── get_posts_by_ids.py
│ │ ├── get_quoted_posts.py
│ │ ├── get_reposted_by.py
│ │ ├── hide_reply.py
│ │ ├── search_all.py
│ │ └── search_recent.py
│ ├── requirements.txt
│ ├── spaces/
│ │ ├── get_spaces_by_ids.py
│ │ └── search_spaces.py
│ ├── streams/
│ │ ├── stream_posts_filtered.py
│ │ └── stream_posts_sample.py
│ ├── usage/
│ │ └── get_usage.py
│ ├── users/
│ │ ├── block/
│ │ │ └── get_blocking.py
│ │ ├── bookmark/
│ │ │ ├── create_bookmark.py
│ │ │ ├── delete_bookmark.py
│ │ │ └── get_bookmarks.py
│ │ ├── follow/
│ │ │ ├── follow_user.py
│ │ │ ├── get_followers.py
│ │ │ ├── get_following.py
│ │ │ └── unfollow_user.py
│ │ ├── get_users_by_usernames.py
│ │ ├── get_users_by_usernames_user_context.py
│ │ ├── get_users_me.py
│ │ ├── like/
│ │ │ ├── get_liked_posts.py
│ │ │ ├── like_post.py
│ │ │ └── unlike_post.py
│ │ ├── lists/
│ │ │ ├── follow_list.py
│ │ │ ├── get_followed_lists.py
│ │ │ ├── get_list_memberships.py
│ │ │ ├── get_owned_lists.py
│ │ │ ├── get_pinned_lists.py
│ │ │ ├── pin_list.py
│ │ │ ├── unfollow_list.py
│ │ │ └── unpin_list.py
│ │ ├── mute/
│ │ │ ├── get_muting.py
│ │ │ ├── mute_user.py
│ │ │ └── unmute_user.py
│ │ ├── repost/
│ │ │ ├── get_reposts_of_me.py
│ │ │ ├── repost_post.py
│ │ │ └── unrepost_post.py
│ │ └── timeline/
│ │ ├── get_home_timeline.py
│ │ ├── get_mentions.py
│ │ └── get_posts.py
│ └── webhooks/
│ ├── delete_webhook.py
│ ├── list_webhooks.py
│ ├── register_webhook.py
│ ├── validate_webhook.py
│ └── webhook_server.py
├── r/
│ ├── posts/
│ │ ├── full-archive-search.r
│ │ ├── full_archive_tweet_counts.r
│ │ ├── recent-search.r
│ │ └── recent_tweet_counts.r
│ └── users/
│ └── get_users_with_bearer_token.r
└── ruby/
├── Gemfile
├── README.md
├── bookmarks/
│ └── bookmarks_lookup.rb
├── lists/
│ ├── List-Tweets.rb
│ ├── Pinned-List.rb
│ ├── add_member.rb
│ ├── create_a_list.rb
│ ├── delete_a_list.rb
│ ├── follow_list.rb
│ ├── list-followers-lookup.rb
│ ├── list-lookup-by-id.rb
│ ├── list-member-lookup.rb
│ ├── lookup.rb
│ ├── pin_list.rb
│ ├── remove_member.rb
│ ├── unfollow_list.rb
│ ├── unpin_list.rb
│ ├── update_a_list.rb
│ ├── user-list-followed.rb
│ ├── user-list-memberships.rb
│ └── user-owned-list-lookup.rb
├── posts/
│ ├── create_tweet.rb
│ ├── delete_tweet.rb
│ ├── full-archive-search.rb
│ ├── full_archive_tweet_counts.rb
│ ├── get_tweets_with_bearer_token.rb
│ ├── get_tweets_with_user_context.rb
│ ├── like_a_tweet.rb
│ ├── liked_tweets.rb
│ ├── liking_users.rb
│ ├── lookup.rb
│ ├── quote_tweets.rb
│ ├── recent_search.rb
│ ├── recent_tweet_counts.rb
│ ├── retweet_a_tweet.rb
│ ├── retweeted_by.rb
│ ├── search_recent.rb
│ ├── undo_a_retweet.rb
│ └── unlike_a_tweet.rb
├── spaces/
│ ├── search_spaces.rb
│ └── spaces_lookup.rb
├── streams/
│ ├── filtered_stream.rb
│ └── sampled_stream.rb
├── timelines/
│ ├── reverse-chron-home-timeline.rb
│ ├── user-mentions.rb
│ ├── user-tweets.rb
│ └── user_posts.rb
└── users/
├── block_a_user.rb
├── followers-lookup.rb
├── followers.rb
├── following-lookup.rb
├── get_users_me_with_user_context.rb
├── get_users_with_bearer_token.rb
├── get_users_with_user_context.rb
├── lookup.rb
├── lookup_blocks.rb
├── lookup_mutes.rb
├── mute_a_user.rb
├── unblock_a_user.rb
└── unmute_a_user.rb
SYMBOL INDEX (330 symbols across 187 files)
FILE: java/posts/FullArchiveSearchDemo.java
class FullArchiveSearchDemo (line 20) | public class FullArchiveSearchDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method search (line 39) | private static String search(String searchString, String bearerToken) ...
FILE: java/posts/FullArchiveTweetCountsDemo.java
class FullArchiveTweetCountsDemo (line 20) | public class FullArchiveTweetCountsDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method getTweetCounts (line 39) | private static String getTweetCounts(String searchString, String beare...
FILE: java/posts/QuoteTweetsDemo.java
class QuoteTweetsDemo (line 20) | public class QuoteTweetsDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method getTweets (line 39) | private static String getTweets(int tweetId, String bearerToken) throw...
FILE: java/posts/RecentSearchDemo.java
class RecentSearchDemo (line 20) | public class RecentSearchDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method search (line 39) | private static String search(String searchString, String bearerToken) ...
FILE: java/posts/RecentTweetCountsDemo.java
class RecentTweetCountsDemo (line 20) | public class RecentTweetCountsDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method getTweetCounts (line 39) | private static String getTweetCounts(String searchString, String beare...
FILE: java/posts/SearchRecent.java
class SearchRecent (line 25) | public class SearchRecent {
method main (line 27) | public static void main(String[] args) throws IOException, URISyntaxEx...
method search (line 39) | private static String search(String query, String bearerToken) throws ...
FILE: java/posts/TweetsDemo.java
class TweetsDemo (line 20) | public class TweetsDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method getTweets (line 39) | private static String getTweets(String ids, String bearerToken) throws...
FILE: java/spaces/SearchSpacesDemo.java
class SpacesLookupDemo (line 20) | public class SpacesLookupDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method getSpaceById (line 39) | private static String getSpaceById(String spaceId, String bearerToken)...
FILE: java/spaces/SpacesLookupDemo.java
class SpacesLookupDemo (line 20) | public class SpacesLookupDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method getSpaceById (line 39) | private static String getSpaceById(String spaceId, String bearerToken)...
FILE: java/streams/FilteredStreamDemo.java
class FilteredStreamDemo (line 22) | public class FilteredStreamDemo {
method main (line 26) | public static void main(String args[]) throws IOException, URISyntaxEx...
method connectStream (line 42) | private static void connectStream(String bearerToken) throws IOExcepti...
method setupRules (line 70) | private static void setupRules(String bearerToken, Map<String, String>...
method createRules (line 81) | private static void createRules(String bearerToken, Map<String, String...
method getRules (line 104) | private static List<String> getRules(String bearerToken) throws URISyn...
method deleteRules (line 134) | private static void deleteRules(String bearerToken, List<String> exist...
method getFormattedString (line 154) | private static String getFormattedString(String string, List<String> i...
method getFormattedString (line 167) | private static String getFormattedString(String string, Map<String, St...
FILE: java/streams/SampledStream.java
class SampledStreamDemo (line 18) | public class SampledStreamDemo {
method main (line 23) | public static void main(String args[]) throws IOException, URISyntaxEx...
method connectStream (line 36) | private static void connectStream(String bearerToken) throws IOExcepti...
FILE: java/timelines/UserMentionsDemo.java
class UserMentionsDemo (line 20) | public class UserMentionsDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method getTweets (line 39) | private static String getTweets(String userId, String bearerToken) thr...
FILE: java/timelines/UserTweetsDemo.java
class UserTweetsDemo (line 20) | public class UserTweetsDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method getTweets (line 39) | private static String getTweets(String userId, String bearerToken) thr...
FILE: java/timelines/reverse-chron-home-timeline-java-sdk.java
class OAuth20GetAccessToken (line 40) | public class OAuth20GetAccessToken {
method main (line 42) | public static void main(String[] args) {
method getAccessToken (line 60) | public OAuth2AccessToken getAccessToken(TwitterCredentialsOAuth2 crede...
method callApi (line 94) | public void callApi(TwitterCredentialsOAuth2 credentials) {
FILE: java/usage/UsageTweetsDemo.java
class UsageTweetsDemo (line 20) | public class UsageTweetsDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method getUsageTweets (line 38) | private static String getUsageTweets(String bearerToken) throws IOExce...
FILE: java/users/FollowersLookupDemo.java
class FollowersLookupDemo (line 20) | public class FollowersLookupDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method getFollowers (line 39) | private static String getFollowers(String userId, String bearerToken) ...
FILE: java/users/FollowingLookupDemo.java
class FollowingLookupDemo (line 20) | public class FollowingLookupDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method getFollowing (line 39) | private static String getFollowing(String userId, String bearerToken) ...
FILE: java/users/Lookup.java
class Lookup (line 25) | public class Lookup {
method main (line 27) | public static void main(String[] args) throws IOException, URISyntaxEx...
method lookupUsers (line 39) | private static String lookupUsers(String usernames, String bearerToken...
FILE: java/users/UsersDemo.java
class UsersDemo (line 20) | public class UsersDemo {
method main (line 25) | public static void main(String args[]) throws IOException, URISyntaxEx...
method getUsers (line 39) | private static String getUsers(String usernames, String bearerToken) t...
FILE: javascript/compliance/download_results.js
function getRequest (line 4) | async function getRequest() {
FILE: javascript/compliance/upload_ids.js
function getRequest (line 9) | async function getRequest() {
FILE: javascript/lists/add_member.js
function input (line 29) | async function input(prompt) {
FILE: javascript/lists/create_list.js
function input (line 30) | async function input(prompt) {
FILE: javascript/lists/delete_list.js
function input (line 25) | async function input(prompt) {
FILE: javascript/lists/remove_member.js
function input (line 29) | async function input(prompt) {
FILE: javascript/lists/update_list.js
function input (line 33) | async function input(prompt) {
FILE: javascript/posts/create_post.js
function input (line 32) | async function input(prompt) {
FILE: javascript/posts/delete_post.js
function input (line 29) | async function input(prompt) {
FILE: javascript/posts/get_liking_users.js
function input (line 26) | async function input(prompt) {
FILE: javascript/posts/get_posts_by_ids_user_context.js
function input (line 28) | async function input(prompt) {
FILE: javascript/users/block/get_blocking.js
function input (line 26) | async function input(prompt) {
FILE: javascript/users/bookmark/create_bookmark.js
function input (line 29) | async function input(prompt) {
constant CLIENT_ID (line 42) | const CLIENT_ID = process.env.CLIENT_ID;
constant CLIENT_SECRET (line 43) | const CLIENT_SECRET = process.env.CLIENT_SECRET;
FILE: javascript/users/bookmark/delete_bookmark.js
function input (line 29) | async function input(prompt) {
constant CLIENT_ID (line 42) | const CLIENT_ID = process.env.CLIENT_ID;
constant CLIENT_SECRET (line 43) | const CLIENT_SECRET = process.env.CLIENT_SECRET;
FILE: javascript/users/bookmark/get_bookmarks.js
function input (line 29) | async function input(prompt) {
constant CLIENT_ID (line 42) | const CLIENT_ID = process.env.CLIENT_ID;
constant CLIENT_SECRET (line 43) | const CLIENT_SECRET = process.env.CLIENT_SECRET;
FILE: javascript/users/get_users_by_usernames_user_context.js
function input (line 28) | async function input(prompt) {
FILE: javascript/users/get_users_me.js
function input (line 20) | async function input(prompt) {
FILE: javascript/users/like/get_liked_posts.js
function input (line 28) | async function input(prompt) {
FILE: javascript/users/like/like_post.js
function input (line 28) | async function input(prompt) {
FILE: javascript/users/like/unlike_post.js
function input (line 28) | async function input(prompt) {
FILE: javascript/users/lists/follow_list.js
function input (line 29) | async function input(prompt) {
FILE: javascript/users/lists/pin_list.js
function input (line 29) | async function input(prompt) {
FILE: javascript/users/lists/unfollow_list.js
function input (line 29) | async function input(prompt) {
FILE: javascript/users/lists/unpin_list.js
function input (line 29) | async function input(prompt) {
FILE: javascript/users/mute/get_muting.js
function input (line 26) | async function input(prompt) {
FILE: javascript/users/mute/mute_user.js
function input (line 30) | async function input(prompt) {
FILE: javascript/users/mute/unmute_user.js
function input (line 29) | async function input(prompt) {
FILE: javascript/users/repost/repost_post.js
function input (line 28) | async function input(prompt) {
FILE: javascript/users/repost/unrepost_post.js
function input (line 28) | async function input(prompt) {
FILE: javascript/users/timeline/get_home_timeline.js
function input (line 26) | async function input(prompt) {
FILE: python/activity/create_subscription.py
function main (line 41) | def main():
FILE: python/activity/delete_subscription.py
function main (line 26) | def main():
FILE: python/activity/list_subscriptions.py
function main (line 21) | def main():
FILE: python/activity/stream_events.py
function main (line 25) | def main():
FILE: python/activity/update_subscription.py
function main (line 29) | def main():
FILE: python/compliance/create_jobs.py
function main (line 22) | def main():
FILE: python/compliance/download_results.py
function main (line 16) | def main():
FILE: python/compliance/get_jobs.py
function main (line 21) | def main():
FILE: python/compliance/get_jobs_by_id.py
function main (line 21) | def main():
FILE: python/compliance/upload_ids.py
function main (line 20) | def main():
FILE: python/direct_messages/get_events_by_conversation.py
function main (line 35) | def main():
FILE: python/direct_messages/get_one_to_one_conversation_events.py
function main (line 35) | def main():
FILE: python/direct_messages/get_user_conversation_events.py
function main (line 32) | def main():
FILE: python/direct_messages/post_dm_to_conversation.py
function main (line 35) | def main():
FILE: python/direct_messages/post_group_conversation_dm.py
function main (line 35) | def main():
FILE: python/direct_messages/post_one_to_one_dm.py
function main (line 35) | def main():
FILE: python/lists/add_member.py
function main (line 35) | def main():
FILE: python/lists/create_list.py
function main (line 37) | def main():
FILE: python/lists/delete_list.py
function main (line 33) | def main():
FILE: python/lists/get_list_by_id.py
function main (line 24) | def main():
FILE: python/lists/get_list_followers.py
function main (line 25) | def main():
FILE: python/lists/get_list_members.py
function main (line 21) | def main():
FILE: python/lists/get_list_posts.py
function main (line 21) | def main():
FILE: python/lists/remove_member.py
function main (line 36) | def main():
FILE: python/lists/update_list.py
function main (line 41) | def main():
FILE: python/media/media_upload_v2.py
class VideoPost (line 65) | class VideoPost(object):
method __init__ (line 67) | def __init__(self, file_name):
method upload_init (line 74) | def upload_init(self):
method upload_append (line 94) | def upload_append(self):
method upload_finalize (line 130) | def upload_finalize(self):
method check_status (line 147) | def check_status(self):
method post (line 179) | def post(self):
FILE: python/media/upload.py
function main (line 35) | def main():
FILE: python/posts/create_post.py
function main (line 33) | def main():
FILE: python/posts/delete_post.py
function main (line 33) | def main():
FILE: python/posts/get_liking_users.py
function main (line 34) | def main():
FILE: python/posts/get_post_by_id.py
function main (line 21) | def main():
FILE: python/posts/get_post_counts_all.py
function main (line 22) | def main():
FILE: python/posts/get_post_counts_recent.py
function main (line 22) | def main():
FILE: python/posts/get_posts_by_ids.py
function main (line 22) | def main():
FILE: python/posts/get_quoted_posts.py
function main (line 21) | def main():
FILE: python/posts/get_reposted_by.py
function main (line 22) | def main():
FILE: python/posts/hide_reply.py
function main (line 36) | def main():
FILE: python/posts/search_all.py
function main (line 24) | def main():
FILE: python/posts/search_recent.py
function main (line 24) | def main():
FILE: python/spaces/get_spaces_by_ids.py
function main (line 22) | def main():
FILE: python/spaces/search_spaces.py
function main (line 21) | def main():
FILE: python/streams/stream_posts_filtered.py
function get_rules (line 20) | def get_rules():
function delete_all_rules (line 29) | def delete_all_rules(rules):
function set_rules (line 42) | def set_rules():
function get_stream (line 56) | def get_stream():
function main (line 72) | def main():
FILE: python/streams/stream_posts_sample.py
function main (line 20) | def main():
FILE: python/usage/get_usage.py
function main (line 20) | def main():
FILE: python/users/block/get_blocking.py
function main (line 30) | def main():
FILE: python/users/bookmark/create_bookmark.py
function main (line 32) | def main():
FILE: python/users/bookmark/delete_bookmark.py
function main (line 32) | def main():
FILE: python/users/bookmark/get_bookmarks.py
function main (line 29) | def main():
FILE: python/users/follow/follow_user.py
function main (line 33) | def main():
FILE: python/users/follow/get_followers.py
function main (line 21) | def main():
FILE: python/users/follow/get_following.py
function main (line 21) | def main():
FILE: python/users/follow/unfollow_user.py
function main (line 33) | def main():
FILE: python/users/get_users_by_usernames.py
function main (line 21) | def main():
FILE: python/users/get_users_by_usernames_user_context.py
function main (line 32) | def main():
FILE: python/users/get_users_me.py
function main (line 29) | def main():
FILE: python/users/like/get_liked_posts.py
function main (line 29) | def main():
FILE: python/users/like/like_post.py
function main (line 33) | def main():
FILE: python/users/like/unlike_post.py
function main (line 33) | def main():
FILE: python/users/lists/follow_list.py
function main (line 36) | def main():
FILE: python/users/lists/get_followed_lists.py
function main (line 21) | def main():
FILE: python/users/lists/get_list_memberships.py
function main (line 21) | def main():
FILE: python/users/lists/get_owned_lists.py
function main (line 21) | def main():
FILE: python/users/lists/get_pinned_lists.py
function main (line 33) | def main():
FILE: python/users/lists/pin_list.py
function main (line 36) | def main():
FILE: python/users/lists/unfollow_list.py
function main (line 36) | def main():
FILE: python/users/lists/unpin_list.py
function main (line 36) | def main():
FILE: python/users/mute/get_muting.py
function main (line 30) | def main():
FILE: python/users/mute/mute_user.py
function main (line 36) | def main():
FILE: python/users/mute/unmute_user.py
function main (line 37) | def main():
FILE: python/users/repost/get_reposts_of_me.py
function main (line 31) | def main():
FILE: python/users/repost/repost_post.py
function main (line 33) | def main():
FILE: python/users/repost/unrepost_post.py
function main (line 33) | def main():
FILE: python/users/timeline/get_home_timeline.py
function main (line 29) | def main():
FILE: python/users/timeline/get_mentions.py
function main (line 21) | def main():
FILE: python/users/timeline/get_posts.py
function main (line 21) | def main():
FILE: python/webhooks/delete_webhook.py
function main (line 25) | def main():
FILE: python/webhooks/list_webhooks.py
function main (line 21) | def main():
FILE: python/webhooks/register_webhook.py
function main (line 27) | def main():
FILE: python/webhooks/validate_webhook.py
function main (line 27) | def main():
FILE: python/webhooks/webhook_server.py
function webhook_request (line 49) | def webhook_request():
function main (line 90) | def main():
FILE: ruby/bookmarks/bookmarks_lookup.rb
function users_me (line 70) | def users_me(url, token_response)
function bookmarked_tweets (line 94) | def bookmarked_tweets(bookmarks_url, token_response)
FILE: ruby/lists/List-Tweets.rb
function list_tweets (line 27) | def list_tweets(url, bearer_token, params)
FILE: ruby/lists/Pinned-List.rb
function get_request_token (line 31) | def get_request_token(consumer)
function get_user_authorization (line 38) | def get_user_authorization(request_token)
function obtain_access_token (line 46) | def obtain_access_token(consumer, request_token, pin)
function pin_list (line 59) | def pin_list(url, oauth_params)
FILE: ruby/lists/add_member.rb
function get_request_token (line 26) | def get_request_token(consumer)
function get_user_authorization (line 33) | def get_user_authorization(request_token)
function obtain_access_token (line 41) | def obtain_access_token(consumer, request_token, pin)
function add_member (line 54) | def add_member(url, oauth_params)
FILE: ruby/lists/create_a_list.rb
function get_request_token (line 28) | def get_request_token(consumer)
function get_user_authorization (line 35) | def get_user_authorization(request_token)
function obtain_access_token (line 43) | def obtain_access_token(consumer, request_token, pin)
function create_list (line 56) | def create_list(url, oauth_params)
FILE: ruby/lists/delete_a_list.rb
function get_request_token (line 26) | def get_request_token(consumer)
function get_user_authorization (line 33) | def get_user_authorization(request_token)
function obtain_access_token (line 41) | def obtain_access_token(consumer, request_token, pin)
function delete_list (line 54) | def delete_list(url, oauth_params)
FILE: ruby/lists/follow_list.rb
function get_request_token (line 27) | def get_request_token(consumer)
function get_user_authorization (line 34) | def get_user_authorization(request_token)
function obtain_access_token (line 42) | def obtain_access_token(consumer, request_token, pin)
function follow_list (line 55) | def follow_list(url, oauth_params)
FILE: ruby/lists/list-followers-lookup.rb
function lists (line 24) | def lists(url, bearer_token, params)
FILE: ruby/lists/list-lookup-by-id.rb
function lists (line 23) | def lists(url, bearer_token, params)
FILE: ruby/lists/list-member-lookup.rb
function lists (line 24) | def lists(url, bearer_token, params)
FILE: ruby/lists/lookup.rb
function lookup_list (line 22) | def lookup_list(url, bearer_token, query_params)
FILE: ruby/lists/pin_list.rb
function get_request_token (line 27) | def get_request_token(consumer)
function get_user_authorization (line 34) | def get_user_authorization(request_token)
function obtain_access_token (line 42) | def obtain_access_token(consumer, request_token, pin)
function pin_list (line 55) | def pin_list(url, oauth_params)
FILE: ruby/lists/remove_member.rb
function get_request_token (line 26) | def get_request_token(consumer)
function get_user_authorization (line 33) | def get_user_authorization(request_token)
function obtain_access_token (line 41) | def obtain_access_token(consumer, request_token, pin)
function remove_member (line 54) | def remove_member(url, oauth_params)
FILE: ruby/lists/unfollow_list.rb
function get_request_token (line 28) | def get_request_token(consumer)
function get_user_authorization (line 35) | def get_user_authorization(request_token)
function obtain_access_token (line 43) | def obtain_access_token(consumer, request_token, pin)
function unfollow_list (line 56) | def unfollow_list(url, oauth_params)
FILE: ruby/lists/unpin_list.rb
function get_request_token (line 28) | def get_request_token(consumer)
function get_user_authorization (line 35) | def get_user_authorization(request_token)
function obtain_access_token (line 43) | def obtain_access_token(consumer, request_token, pin)
function unpin_list (line 56) | def unpin_list(url, oauth_params)
FILE: ruby/lists/update_a_list.rb
function get_request_token (line 31) | def get_request_token(consumer)
function get_user_authorization (line 38) | def get_user_authorization(request_token)
function obtain_access_token (line 46) | def obtain_access_token(consumer, request_token, pin)
function update_list (line 59) | def update_list(url, oauth_params)
FILE: ruby/lists/user-list-followed.rb
function lists (line 23) | def lists(url, bearer_token, params)
FILE: ruby/lists/user-list-memberships.rb
function lists (line 23) | def lists(url, bearer_token, params)
FILE: ruby/lists/user-owned-list-lookup.rb
function lists (line 23) | def lists(url, bearer_token, params)
FILE: ruby/posts/create_tweet.rb
function get_request_token (line 24) | def get_request_token(consumer)
function get_user_authorization (line 31) | def get_user_authorization(request_token)
function obtain_access_token (line 39) | def obtain_access_token(consumer, request_token, pin)
function create_tweet (line 52) | def create_tweet(url, oauth_params)
FILE: ruby/posts/delete_tweet.rb
function get_request_token (line 23) | def get_request_token(consumer)
function get_user_authorization (line 30) | def get_user_authorization(request_token)
function obtain_access_token (line 38) | def obtain_access_token(consumer, request_token, pin)
function delete_tweet (line 51) | def delete_tweet(url, oauth_params)
FILE: ruby/posts/full-archive-search.rb
function search_tweets (line 32) | def search_tweets(url, bearer_token, query_params)
FILE: ruby/posts/full_archive_tweet_counts.rb
function get_tweet_counts (line 25) | def get_tweet_counts(url, bearer_token, query_params)
FILE: ruby/posts/get_tweets_with_bearer_token.rb
function tweet_lookup (line 28) | def tweet_lookup(url, bearer_token, params)
FILE: ruby/posts/get_tweets_with_user_context.rb
function get_request_token (line 38) | def get_request_token(consumer)
function get_user_authorization (line 45) | def get_user_authorization(request_token)
function obtain_access_token (line 53) | def obtain_access_token(consumer, request_token, pin)
function tweet_lookup (line 65) | def tweet_lookup(url, oauth_params, query_params)
FILE: ruby/posts/like_a_tweet.rb
function get_request_token (line 28) | def get_request_token(consumer)
function get_user_authorization (line 35) | def get_user_authorization(request_token)
function obtain_access_token (line 43) | def obtain_access_token(consumer, request_token, pin)
function user_like (line 56) | def user_like(url, oauth_params)
FILE: ruby/posts/liked_tweets.rb
function liked_tweets (line 28) | def liked_tweets(url, bearer_token, params)
FILE: ruby/posts/liking_users.rb
function liking_users (line 26) | def liking_users(url, bearer_token, params)
FILE: ruby/posts/lookup.rb
function lookup_posts (line 23) | def lookup_posts(url, bearer_token, query_params)
FILE: ruby/posts/quote_tweets.rb
function get_quote_tweets (line 25) | def get_quote_tweets(url, bearer_token, query_params)
FILE: ruby/posts/recent_search.rb
function search_tweets (line 32) | def search_tweets(url, bearer_token, query_params)
FILE: ruby/posts/recent_tweet_counts.rb
function get_tweet_counts (line 24) | def get_tweet_counts(url, bearer_token, query_params)
FILE: ruby/posts/retweet_a_tweet.rb
function get_request_token (line 28) | def get_request_token(consumer)
function get_user_authorization (line 35) | def get_user_authorization(request_token)
function obtain_access_token (line 43) | def obtain_access_token(consumer, request_token, pin)
function user_retweet (line 56) | def user_retweet(url, oauth_params)
FILE: ruby/posts/retweeted_by.rb
function retweeted_by_users (line 26) | def retweeted_by_users(url, bearer_token, params)
FILE: ruby/posts/search_recent.rb
function search_posts (line 30) | def search_posts(url, bearer_token, query_params)
FILE: ruby/posts/undo_a_retweet.rb
function get_request_token (line 31) | def get_request_token(consumer)
function get_user_authorization (line 38) | def get_user_authorization(request_token)
function obtain_access_token (line 46) | def obtain_access_token(consumer, request_token, pin)
function user_unretweet (line 59) | def user_unretweet(url, oauth_params)
FILE: ruby/posts/unlike_a_tweet.rb
function get_request_token (line 31) | def get_request_token(consumer)
function get_user_authorization (line 38) | def get_user_authorization(request_token)
function obtain_access_token (line 46) | def obtain_access_token(consumer, request_token, pin)
function tweet_unlike (line 59) | def tweet_unlike(url, oauth_params)
FILE: ruby/spaces/search_spaces.rb
function get_space (line 25) | def get_space(url, bearer_token, query_params)
FILE: ruby/spaces/spaces_lookup.rb
function get_space (line 25) | def get_space(url, bearer_token, query_params)
FILE: ruby/streams/filtered_stream.rb
function get_all_rules (line 33) | def get_all_rules
function set_rules (line 49) | def set_rules(rules)
function delete_all_rules (line 70) | def delete_all_rules(rules)
function setup_rules (line 95) | def setup_rules
function stream_connect (line 114) | def stream_connect(params)
FILE: ruby/streams/sampled_stream.rb
function stream_connect (line 24) | def stream_connect(url, bearer_token, params)
FILE: ruby/timelines/reverse-chron-home-timeline.rb
function users_me (line 69) | def users_me(url, token_response)
function reverse_chron_timeline (line 94) | def reverse_chron_timeline(url, token_response)
FILE: ruby/timelines/user-mentions.rb
function get_user_mentions (line 30) | def get_user_mentions(url, bearer_token, query_params)
FILE: ruby/timelines/user-tweets.rb
function get_user_tweets (line 36) | def get_user_tweets(url, bearer_token, query_params)
FILE: ruby/timelines/user_posts.rb
function get_user_posts (line 23) | def get_user_posts(url, bearer_token, query_params)
FILE: ruby/users/block_a_user.rb
function get_request_token (line 28) | def get_request_token(consumer)
function get_user_authorization (line 35) | def get_user_authorization(request_token)
function obtain_access_token (line 43) | def obtain_access_token(consumer, request_token, pin)
function user_block (line 56) | def user_block(url, oauth_params)
FILE: ruby/users/followers-lookup.rb
function get_followers (line 21) | def get_followers(url, bearer_token, query_params)
FILE: ruby/users/followers.rb
function get_followers (line 23) | def get_followers(url, bearer_token, query_params)
FILE: ruby/users/following-lookup.rb
function get_following (line 21) | def get_following(url, bearer_token, query_params)
FILE: ruby/users/get_users_me_with_user_context.rb
function get_request_token (line 19) | def get_request_token(consumer)
function get_user_authorization (line 26) | def get_user_authorization(request_token)
function obtain_access_token (line 34) | def obtain_access_token(consumer, request_token, pin)
function user_lookup (line 54) | def user_lookup(url, oauth_params, query_params)
FILE: ruby/users/get_users_with_bearer_token.rb
function user_lookup (line 27) | def user_lookup(url, bearer_token, params)
FILE: ruby/users/get_users_with_user_context.rb
function get_request_token (line 26) | def get_request_token(consumer)
function get_user_authorization (line 33) | def get_user_authorization(request_token)
function obtain_access_token (line 41) | def obtain_access_token(consumer, request_token, pin)
function user_lookup (line 62) | def user_lookup(url, oauth_params, query_params)
FILE: ruby/users/lookup.rb
function lookup_users (line 22) | def lookup_users(url, bearer_token, query_params)
FILE: ruby/users/lookup_blocks.rb
function get_request_token (line 25) | def get_request_token(consumer)
function get_user_authorization (line 32) | def get_user_authorization(request_token)
function obtain_access_token (line 40) | def obtain_access_token(consumer, request_token, pin)
function user_block (line 53) | def user_block(url, oauth_params)
FILE: ruby/users/lookup_mutes.rb
function get_request_token (line 25) | def get_request_token(consumer)
function get_user_authorization (line 32) | def get_user_authorization(request_token)
function obtain_access_token (line 40) | def obtain_access_token(consumer, request_token, pin)
function users_muted (line 53) | def users_muted(url, oauth_params)
FILE: ruby/users/mute_a_user.rb
function get_request_token (line 27) | def get_request_token(consumer)
function get_user_authorization (line 34) | def get_user_authorization(request_token)
function obtain_access_token (line 42) | def obtain_access_token(consumer, request_token, pin)
function user_mute (line 55) | def user_mute(url, oauth_params)
FILE: ruby/users/unblock_a_user.rb
function get_request_token (line 31) | def get_request_token(consumer)
function get_user_authorization (line 38) | def get_user_authorization(request_token)
function obtain_access_token (line 46) | def obtain_access_token(consumer, request_token, pin)
function user_unblock (line 59) | def user_unblock(url, oauth_params)
FILE: ruby/users/unmute_a_user.rb
function get_request_token (line 29) | def get_request_token(consumer)
function get_user_authorization (line 36) | def get_user_authorization(request_token)
function obtain_access_token (line 44) | def obtain_access_token(consumer, request_token, pin)
function user_unmute (line 57) | def user_unmute(url, oauth_params)
Condensed preview — 236 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (549K chars).
[
{
"path": ".github/ISSUE_TEMPLATE/bug_report.md",
"chars": 396,
"preview": "---\nname: Bug report\nabout: Create a report to help us improve this code\ntitle: ''\nlabels: bug\nassignees: ''\n\n---\n\n**Des"
},
{
"path": ".github/ISSUE_TEMPLATE/config.yml",
"chars": 272,
"preview": "blank_issues_enabled: false\ncontact_links:\n - name: Question about the API? Ask in the Twitter Developer Community\n "
},
{
"path": ".github/workflows/cla.yml",
"chars": 1083,
"preview": "name: \"CLA Assistant\"\non:\n issue_comment:\n types: [created]\n pull_request_target:\n types: [opened,closed,synchro"
},
{
"path": ".gitignore",
"chars": 1316,
"preview": "*.gem\n*.rbc\n/.config\n/coverage/\n/InstalledFiles\n/pkg/\n/spec/reports/\n/spec/examples.txt\n/test/tmp/\n/test/version_tmp/\n/t"
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 230,
"preview": "We feel that a welcoming community is important and we ask that you follow Twitter's\n[Open Source Code of Conduct](https"
},
{
"path": "LICENSE",
"chars": 11341,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 2779,
"preview": "# X API v2 Sample Code\n\n["
},
{
"path": "api-index.json",
"chars": 15229,
"preview": "{\n \"name\": \"X API v2 Sample Code\",\n \"version\": \"2.0\",\n \"base_url\": \"https://api.x.com/2\",\n \"languages\": [\"python\", \""
},
{
"path": "java/README.md",
"chars": 2807,
"preview": "# X API v2 - Java Examples\n\nWorking Java code samples for the X (formerly Twitter) API v2.\n\n## Setup\n\n### 1. Install Jav"
},
{
"path": "java/posts/FullArchiveSearchDemo.java",
"chars": 2536,
"preview": "import java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.ArrayList;\n\nimport org.apache.http.Http"
},
{
"path": "java/posts/FullArchiveTweetCountsDemo.java",
"chars": 2690,
"preview": "import java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.ArrayList;\n\nimport org.apache.http.Http"
},
{
"path": "java/posts/QuoteTweetsDemo.java",
"chars": 2439,
"preview": "import org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.NameValuePair;\nimport org"
},
{
"path": "java/posts/RecentSearchDemo.java",
"chars": 2521,
"preview": "import java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.ArrayList;\n\nimport org.apache.http.Http"
},
{
"path": "java/posts/RecentTweetCountsDemo.java",
"chars": 2588,
"preview": "import java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.ArrayList;\n\nimport org.apache.http.Http"
},
{
"path": "java/posts/SearchRecent.java",
"chars": 2339,
"preview": "/**\n * Recent Search - X API v2\n * \n * Endpoint: GET https://api.x.com/2/tweets/search/recent\n * Docs: https://developer"
},
{
"path": "java/posts/TweetsDemo.java",
"chars": 2520,
"preview": "import org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.NameValuePair;\nimport org"
},
{
"path": "java/spaces/SearchSpacesDemo.java",
"chars": 2501,
"preview": "import java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.ArrayList;\n\nimport org.apache.http.Http"
},
{
"path": "java/spaces/SpacesLookupDemo.java",
"chars": 2501,
"preview": "import java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.ArrayList;\n\nimport org.apache.http.Http"
},
{
"path": "java/streams/FilteredStreamDemo.java",
"chars": 7057,
"preview": "import org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport"
},
{
"path": "java/streams/SampledStream.java",
"chars": 2077,
"preview": "import org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport"
},
{
"path": "java/timelines/UserMentionsDemo.java",
"chars": 2464,
"preview": "import org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.NameValuePair;\nimport org"
},
{
"path": "java/timelines/UserTweetsDemo.java",
"chars": 2455,
"preview": "import org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.NameValuePair;\nimport org"
},
{
"path": "java/timelines/reverse-chron-home-timeline-java-sdk.java",
"chars": 6452,
"preview": "package com.twitter.clientlib.auth;\n\nimport java.util.HashSet;\nimport java.util.Scanner;\nimport java.util.Set;\n\nimport c"
},
{
"path": "java/usage/UsageTweetsDemo.java",
"chars": 2146,
"preview": "import org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.NameValuePair;\nimport org"
},
{
"path": "java/users/FollowersLookupDemo.java",
"chars": 2462,
"preview": "import org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.NameValuePair;\nimport org"
},
{
"path": "java/users/FollowingLookupDemo.java",
"chars": 2451,
"preview": "import org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.NameValuePair;\nimport org"
},
{
"path": "java/users/Lookup.java",
"chars": 2323,
"preview": "/**\n * User Lookup - X API v2\n * \n * Endpoint: GET https://api.x.com/2/users/by\n * Docs: https://developer.x.com/en/docs"
},
{
"path": "java/users/UsersDemo.java",
"chars": 2553,
"preview": "import org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.NameValuePair;\nimport org"
},
{
"path": "javascript/README.md",
"chars": 5976,
"preview": "# X API v2 - JavaScript (Node.js) Examples\n\nWorking JavaScript code samples for the X (formerly Twitter) API v2.\n\n## Set"
},
{
"path": "javascript/compliance/create_jobs.js",
"chars": 852,
"preview": "const { Client } = require('@xdevplatform/xdk');\n\n// The code below sets the bearer token from your environment variable"
},
{
"path": "javascript/compliance/download_results.js",
"chars": 602,
"preview": "// Replace with your job download_url\ndownloadUrl = ''\n\nasync function getRequest() {\n const res = await fetch(downlo"
},
{
"path": "javascript/compliance/get_jobs.js",
"chars": 748,
"preview": "const { Client } = require('@xdevplatform/xdk');\n\n// The code below sets the bearer token from your environment variable"
},
{
"path": "javascript/compliance/get_jobs_by_id.js",
"chars": 692,
"preview": "const { Client } = require('@xdevplatform/xdk');\n\n// The code below sets the bearer token from your environment variable"
},
{
"path": "javascript/compliance/upload_ids.js",
"chars": 1117,
"preview": "const fs = require('fs');\n\n// Replace with your job download_url\nconst uploadUrl = '';\n\n// Replace with your file path t"
},
{
"path": "javascript/lists/add_member.js",
"chars": 3151,
"preview": "// Add member to a list using OAuth 2.0 to authorize the user\n// https://developer.twitter.com/en/docs/twitter-api/lists"
},
{
"path": "javascript/lists/create_list.js",
"chars": 3060,
"preview": "// Create a new list using OAuth 2.0 to authorize the user\n// https://developer.twitter.com/en/docs/twitter-api/lists/ma"
},
{
"path": "javascript/lists/delete_list.js",
"chars": 2995,
"preview": "// Delete an existing list the authenticated user owns - using OAuth 2.0 to authorize the user\n// https://developer.twit"
},
{
"path": "javascript/lists/get_list_by_id.js",
"chars": 864,
"preview": "/**\n * List Lookup - X API v2\n * \n * Endpoint: GET https://api.x.com/2/lists/:id\n * Docs: https://developer.x.com/en/doc"
},
{
"path": "javascript/lists/get_list_followers.js",
"chars": 971,
"preview": "const { Client } = require('@xdevplatform/xdk');\n\n// The code below sets the bearer token from your environment variable"
},
{
"path": "javascript/lists/get_list_members.js",
"chars": 969,
"preview": "const { Client } = require('@xdevplatform/xdk');\n\n// The code below sets the bearer token from your environment variable"
},
{
"path": "javascript/lists/get_list_posts.js",
"chars": 950,
"preview": "const { Client } = require('@xdevplatform/xdk');\n\n// The code below sets the bearer token from your environment variable"
},
{
"path": "javascript/lists/remove_member.js",
"chars": 3153,
"preview": "// Remove member from a list using OAuth 2.0 to authorize the user\n// https://developer.twitter.com/en/docs/twitter-api/"
},
{
"path": "javascript/lists/update_list.js",
"chars": 3282,
"preview": "// Update the metadata of an existing list the authenticated user owns - using OAuth 2.0 to authorize the user\n// https:"
},
{
"path": "javascript/posts/create_post.js",
"chars": 2824,
"preview": "/**\n * Create Post - X API v2\n * \n * Endpoint: POST https://api.x.com/2/posts\n * Docs: https://developer.x.com/en/docs/t"
},
{
"path": "javascript/posts/delete_post.js",
"chars": 2764,
"preview": "/**\n * Delete Post - X API v2\n * \n * Endpoint: DELETE https://api.x.com/2/posts/:id\n * Docs: https://developer.x.com/en/"
},
{
"path": "javascript/posts/get_liking_users.js",
"chars": 3268,
"preview": "// Get liking users for a post using OAuth 2.0 to authorize the user\n// https://developer.twitter.com/en/docs/twitter-ap"
},
{
"path": "javascript/posts/get_post_counts_all.js",
"chars": 1035,
"preview": "// Search for public posts across the whole Twitter archive\n// https://developer.twitter.com/en/docs/twitter-api/tweets/"
},
{
"path": "javascript/posts/get_post_counts_recent.js",
"chars": 974,
"preview": "// Search for posts within the past seven days\n// https://developer.twitter.com/en/docs/twitter-api/tweets/search/quick-"
},
{
"path": "javascript/posts/get_posts_by_ids.js",
"chars": 1182,
"preview": "/**\n * Post Lookup - X API v2\n * \n * Endpoint: GET https://api.x.com/2/posts\n * Docs: https://developer.x.com/en/docs/tw"
},
{
"path": "javascript/posts/get_posts_by_ids_user_context.js",
"chars": 3156,
"preview": "// Get Post objects by ID, using user authentication\n// https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/"
},
{
"path": "javascript/posts/get_quoted_posts.js",
"chars": 1514,
"preview": "// Get Quote Posts by Post ID\n// https://developer.twitter.com/en/docs/twitter-api/tweets/quote-tweets-lookup/quick-star"
},
{
"path": "javascript/posts/get_reposted_by.js",
"chars": 1762,
"preview": "// Get Reposted By (Users who reposted) by Post ID\n// https://developer.twitter.com/en/docs/twitter-api/tweets/retweets/"
},
{
"path": "javascript/posts/search_all.js",
"chars": 1539,
"preview": "// Search for public posts across the whole Twitter archive\n// https://developer.twitter.com/en/docs/twitter-api/tweets/"
},
{
"path": "javascript/posts/search_recent.js",
"chars": 1636,
"preview": "/**\n * Recent Search - X API v2\n * \n * Endpoint: GET https://api.x.com/2/posts/search/recent\n * Docs: https://developer."
},
{
"path": "javascript/spaces/get_spaces_by_ids.js",
"chars": 881,
"preview": "/**\n * Spaces Lookup - X API v2\n * \n * Endpoint: GET https://api.x.com/2/spaces\n * Docs: https://developer.x.com/en/docs"
},
{
"path": "javascript/spaces/search_spaces.js",
"chars": 1096,
"preview": "// Lookup Spaces by ID\n// https://developer.twitter.com/en/docs/twitter-api/spaces/lookup\n\nconst { Client } = require('@"
},
{
"path": "javascript/streams/stream_posts_filtered.js",
"chars": 2552,
"preview": "// Open a realtime stream of posts, filtered according to rules\n// https://developer.twitter.com/en/docs/twitter-api/twe"
},
{
"path": "javascript/streams/stream_posts_sample.js",
"chars": 1447,
"preview": "// Open a live stream of roughly 1% random sample of publicly available posts\n// https://developer.twitter.com/en/docs/t"
},
{
"path": "javascript/usage/get_usage.js",
"chars": 714,
"preview": "// Get Posts Usage\n// https://developer.twitter.com/en/docs/twitter-api/usage/tweets\n\nconst { Client } = require('@xdevp"
},
{
"path": "javascript/users/block/get_blocking.js",
"chars": 2992,
"preview": "// Block a user, using user authentication\n// https://developer.twitter.com/en/docs/twitter-api/users/blocks/quick-start"
},
{
"path": "javascript/users/bookmark/create_bookmark.js",
"chars": 3020,
"preview": "const { \n Client, \n OAuth2,\n generateCodeVerifier,\n generateCodeChallenge\n} = require('@xdevplatform/xdk');\n\nconst r"
},
{
"path": "javascript/users/bookmark/delete_bookmark.js",
"chars": 2968,
"preview": "const { \n Client, \n OAuth2,\n generateCodeVerifier,\n generateCodeChallenge\n} = require('@xdevplatform/xdk');\n\nconst r"
},
{
"path": "javascript/users/bookmark/get_bookmarks.js",
"chars": 3066,
"preview": "const { \n Client, \n OAuth2,\n generateCodeVerifier,\n generateCodeChallenge\n} = require('@xdevplatform/xdk');\n\nconst r"
},
{
"path": "javascript/users/follow/get_followers.js",
"chars": 1271,
"preview": "// Fetch the followers of a user account, by ID\n// https://developer.twitter.com/en/docs/twitter-api/users/follows/quick"
},
{
"path": "javascript/users/follow/get_followers_paginated.js",
"chars": 1644,
"preview": "/**\n * User Followers Lookup (Paginated) - X API v2\n * \n * Endpoint: GET https://api.x.com/2/users/:id/followers\n * Docs"
},
{
"path": "javascript/users/follow/get_following_paginated.js",
"chars": 1595,
"preview": "/**\n * User Following Lookup (Paginated) - X API v2\n * \n * Endpoint: GET https://api.x.com/2/users/:id/following\n * Docs"
},
{
"path": "javascript/users/get_users_by_usernames.js",
"chars": 893,
"preview": "/**\n * User Lookup - X API v2\n * \n * Endpoint: GET https://api.x.com/2/users/by\n * Docs: https://developer.x.com/en/docs"
},
{
"path": "javascript/users/get_users_by_usernames_user_context.js",
"chars": 3164,
"preview": "// Get User objects by username, using user authentication\n// https://developer.twitter.com/en/docs/twitter-api/users/lo"
},
{
"path": "javascript/users/get_users_me.js",
"chars": 2774,
"preview": "const { \n Client, \n OAuth2,\n generateCodeVerifier,\n generateCodeChallenge\n} = require('@xdevplatform/xdk');\n\nconst r"
},
{
"path": "javascript/users/like/get_liked_posts.js",
"chars": 3793,
"preview": "// Get Liked Posts by User ID using OAuth 2.0 to authorize the user\n// https://developer.twitter.com/en/docs/twitter-api"
},
{
"path": "javascript/users/like/like_post.js",
"chars": 3065,
"preview": "const { \n Client, \n OAuth2,\n generateCodeVerifier,\n generateCodeChallenge\n} = require('@xdevplatform/xdk');\n\nconst r"
},
{
"path": "javascript/users/like/unlike_post.js",
"chars": 3049,
"preview": "const { \n Client, \n OAuth2,\n generateCodeVerifier,\n generateCodeChallenge\n} = require('@xdevplatform/xdk');\n\nconst r"
},
{
"path": "javascript/users/lists/follow_list.js",
"chars": 3154,
"preview": "// Follow a list using OAuth 2.0 to authorize the user\n// https://developer.twitter.com/en/docs/twitter-api/lists/manage"
},
{
"path": "javascript/users/lists/get_followed_lists.js",
"chars": 958,
"preview": "const { Client } = require('@xdevplatform/xdk');\n\n// The code below sets the bearer token from your environment variable"
},
{
"path": "javascript/users/lists/get_list_memberships.js",
"chars": 960,
"preview": "const { Client } = require('@xdevplatform/xdk');\n\n// The code below sets the bearer token from your environment variable"
},
{
"path": "javascript/users/lists/get_owned_lists.js",
"chars": 955,
"preview": "const { Client } = require('@xdevplatform/xdk');\n\n// The code below sets the bearer token from your environment variable"
},
{
"path": "javascript/users/lists/pin_list.js",
"chars": 3131,
"preview": "// Pin a list using OAuth 2.0 to authorize the user\n// https://developer.twitter.com/en/docs/twitter-api/lists/manage-li"
},
{
"path": "javascript/users/lists/unfollow_list.js",
"chars": 3141,
"preview": "// Unfollow a list using OAuth 2.0 to authorize the user\n// https://developer.twitter.com/en/docs/twitter-api/lists/mana"
},
{
"path": "javascript/users/lists/unpin_list.js",
"chars": 3126,
"preview": "// Unpin a list using OAuth 2.0 to authorize the user\n// https://developer.twitter.com/en/docs/twitter-api/lists/manage-"
},
{
"path": "javascript/users/mute/get_muting.js",
"chars": 2996,
"preview": "// Retrieve accounts muted by authenticated user\n// https://developer.twitter.com/en/docs/twitter-api/users/mutes/quick-"
},
{
"path": "javascript/users/mute/mute_user.js",
"chars": 3199,
"preview": "// mute a user, using user authentication\n// https://developer.twitter.com/en/docs/twitter-api/users/mutes/quick-start\nc"
},
{
"path": "javascript/users/mute/unmute_user.js",
"chars": 3125,
"preview": "// Unmute a user, using user authentication\nconst { \n Client, \n OAuth2,\n generateCodeVerifier,\n generateCodeChalleng"
},
{
"path": "javascript/users/repost/repost_post.js",
"chars": 3061,
"preview": "const { \n Client, \n OAuth2,\n generateCodeVerifier,\n generateCodeChallenge\n} = require('@xdevplatform/xdk');\n\nconst r"
},
{
"path": "javascript/users/repost/unrepost_post.js",
"chars": 3059,
"preview": "const { \n Client, \n OAuth2,\n generateCodeVerifier,\n generateCodeChallenge\n} = require('@xdevplatform/xdk');\n\nconst r"
},
{
"path": "javascript/users/timeline/get_home_timeline.js",
"chars": 3015,
"preview": "// Get reverse chronological home timeline\n// https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/api-ref"
},
{
"path": "javascript/users/timeline/get_mentions.js",
"chars": 1547,
"preview": "// Get User mentions timeline by user ID\n// https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/quick-sta"
},
{
"path": "javascript/users/timeline/get_posts.js",
"chars": 997,
"preview": "/**\n * User Posts Timeline - X API v2\n * \n * Endpoint: GET https://api.x.com/2/users/:id/posts\n * Docs: https://develope"
},
{
"path": "javascript/users/timeline/get_posts_paginated.js",
"chars": 2204,
"preview": "/**\n * User Posts Timeline (Paginated) - X API v2\n * \n * Endpoint: GET https://api.x.com/2/users/:id/posts\n * Docs: http"
},
{
"path": "llms.txt",
"chars": 4719,
"preview": "# X API v2 Sample Code Repository\n\n> This file provides context for LLMs (Large Language Models) to understand and navig"
},
{
"path": "python/README.md",
"chars": 6426,
"preview": "# X API v2 - Python Examples\n\nWorking Python examples for the X API v2.\n\n## Setup\n\n```bash\npip install -r requirements.t"
},
{
"path": "python/activity/create_subscription.py",
"chars": 1861,
"preview": "\"\"\"\nCreate Activity Subscription - X API v2\n========================================\nEndpoint: POST https://api.x.com/2/"
},
{
"path": "python/activity/delete_subscription.py",
"chars": 1016,
"preview": "\"\"\"\nDelete Activity Subscription - X API v2\n========================================\nEndpoint: DELETE https://api.x.com/"
},
{
"path": "python/activity/list_subscriptions.py",
"chars": 904,
"preview": "\"\"\"\nList Activity Subscriptions - X API v2\n=======================================\nEndpoint: GET https://api.x.com/2/act"
},
{
"path": "python/activity/stream_events.py",
"chars": 1308,
"preview": "\"\"\"\nActivity Stream - X API v2\n==========================\nEndpoint: GET https://api.x.com/2/activity/stream\nDocs: https:"
},
{
"path": "python/activity/update_subscription.py",
"chars": 1199,
"preview": "\"\"\"\nUpdate Activity Subscription - X API v2\n========================================\nEndpoint: PUT https://api.x.com/2/a"
},
{
"path": "python/compliance/create_jobs.py",
"chars": 826,
"preview": "\"\"\"\nCreate Compliance Job - X API v2\n================================\nEndpoint: POST https://api.x.com/2/compliance/jobs"
},
{
"path": "python/compliance/download_results.py",
"chars": 870,
"preview": "\"\"\"\nDownload Compliance Results - X API v2\n======================================\nEndpoint: GET <download_url> (provided"
},
{
"path": "python/compliance/get_jobs.py",
"chars": 673,
"preview": "\"\"\"\nGet Compliance Jobs - X API v2\n==============================\nEndpoint: GET https://api.x.com/2/compliance/jobs\nDocs"
},
{
"path": "python/compliance/get_jobs_by_id.py",
"chars": 673,
"preview": "\"\"\"\nGet Compliance Job by ID - X API v2\n===================================\nEndpoint: GET https://api.x.com/2/compliance"
},
{
"path": "python/compliance/upload_ids.py",
"chars": 1023,
"preview": "\"\"\"\nUpload IDs for Compliance Job - X API v2\n========================================\nEndpoint: PUT <upload_url> (provid"
},
{
"path": "python/direct_messages/get_events_by_conversation.py",
"chars": 2784,
"preview": "\"\"\"\nGet Events by Conversation ID - X API v2\n=========================================\nEndpoint: GET https://api.x.com/2"
},
{
"path": "python/direct_messages/get_one_to_one_conversation_events.py",
"chars": 2888,
"preview": "\"\"\"\nGet One-to-One Conversation Events - X API v2\n=============================================\nEndpoint: GET https://ap"
},
{
"path": "python/direct_messages/get_user_conversation_events.py",
"chars": 2825,
"preview": "\"\"\"\nGet User Conversation Events - X API v2\n=======================================\nEndpoint: GET https://api.x.com/2/dm"
},
{
"path": "python/direct_messages/post_dm_to_conversation.py",
"chars": 2372,
"preview": "\"\"\"\nPost DM to Conversation - X API v2\n===================================\nEndpoint: POST https://api.x.com/2/dm_convers"
},
{
"path": "python/direct_messages/post_group_conversation_dm.py",
"chars": 2452,
"preview": "\"\"\"\nPost Group Conversation Direct Message - X API v2\n=================================================\nEndpoint: POST h"
},
{
"path": "python/direct_messages/post_one_to_one_dm.py",
"chars": 2341,
"preview": "\"\"\"\nPost One-to-One Direct Message - X API v2\n==========================================\nEndpoint: POST https://api.x.co"
},
{
"path": "python/lists/add_member.py",
"chars": 2218,
"preview": "\"\"\"\nAdd List Member - X API v2\n==========================\nEndpoint: POST https://api.x.com/2/lists/:id/members\nDocs: htt"
},
{
"path": "python/lists/create_list.py",
"chars": 2149,
"preview": "\"\"\"\nCreate List - X API v2\n======================\nEndpoint: POST https://api.x.com/2/lists\nDocs: https://developer.x.com"
},
{
"path": "python/lists/delete_list.py",
"chars": 2105,
"preview": "\"\"\"\nDelete List - X API v2\n======================\nEndpoint: DELETE https://api.x.com/2/lists/:id\nDocs: https://developer"
},
{
"path": "python/lists/get_list_by_id.py",
"chars": 1027,
"preview": "\"\"\"\nList Lookup by ID - X API v2\n=============================\nEndpoint: GET https://api.x.com/2/lists/:id\nDocs: https:/"
},
{
"path": "python/lists/get_list_followers.py",
"chars": 1710,
"preview": "\"\"\"\nList Followers Lookup - X API v2\n=================================\nEndpoint: GET https://api.x.com/2/lists/:id/follo"
},
{
"path": "python/lists/get_list_members.py",
"chars": 1534,
"preview": "\"\"\"\nList Members Lookup - X API v2\n==============================\nEndpoint: GET https://api.x.com/2/lists/:id/members\nDo"
},
{
"path": "python/lists/get_list_posts.py",
"chars": 1585,
"preview": "\"\"\"\nList Tweets - X API v2\n======================\nEndpoint: GET https://api.x.com/2/lists/:id/tweets\nDocs: https://devel"
},
{
"path": "python/lists/remove_member.py",
"chars": 2289,
"preview": "\"\"\"\nRemove List Member - X API v2\n==============================\nEndpoint: DELETE https://api.x.com/2/lists/:id/members/"
},
{
"path": "python/lists/update_list.py",
"chars": 2354,
"preview": "\"\"\"\nUpdate List - X API v2\n======================\nEndpoint: PUT https://api.x.com/2/lists/:id\nDocs: https://developer.x."
},
{
"path": "python/media/media_upload_v2.py",
"chars": 5791,
"preview": "\"\"\"\nMedia Upload v2 (Video) - X API v2\n===================================\nEndpoint: POST https://api.x.com/2/media/uplo"
},
{
"path": "python/media/upload.py",
"chars": 2565,
"preview": "\"\"\"\nMedia Upload - X API v2\n=======================\nEndpoint: POST https://upload.x.com/1.1/media/upload.json\nDocs: http"
},
{
"path": "python/posts/create_post.py",
"chars": 2165,
"preview": "\"\"\"\nCreate Tweet - X API v2\n=======================\nEndpoint: POST https://api.x.com/2/tweets\nDocs: https://developer.x."
},
{
"path": "python/posts/delete_post.py",
"chars": 2111,
"preview": "\"\"\"\nDelete Tweet - X API v2\n=======================\nEndpoint: DELETE https://api.x.com/2/tweets/:id\nDocs: https://develo"
},
{
"path": "python/posts/get_liking_users.py",
"chars": 2888,
"preview": "\"\"\"\nLiking Users - X API v2\n======================\nEndpoint: GET https://api.x.com/2/tweets/:id/liking_users\nDocs: https"
},
{
"path": "python/posts/get_post_by_id.py",
"chars": 1120,
"preview": "\"\"\"\nSingle Post Lookup - X API v2\n=============================\nEndpoint: GET https://api.x.com/2/tweets/:id\nDocs: https"
},
{
"path": "python/posts/get_post_counts_all.py",
"chars": 1443,
"preview": "\"\"\"\nFull-Archive Post Counts - X API v2\n===================================\nEndpoint: GET https://api.x.com/2/tweets/cou"
},
{
"path": "python/posts/get_post_counts_recent.py",
"chars": 1223,
"preview": "\"\"\"\nRecent Post Counts - X API v2\n=============================\nEndpoint: GET https://api.x.com/2/tweets/counts/recent\nD"
},
{
"path": "python/posts/get_posts_by_ids.py",
"chars": 1242,
"preview": "\"\"\"\nPost Lookup - X API v2\n======================\nEndpoint: GET https://api.x.com/2/tweets\nDocs: https://developer.x.com"
},
{
"path": "python/posts/get_quoted_posts.py",
"chars": 1424,
"preview": "\"\"\"\nQuote Tweets Lookup - X API v2\n==============================\nEndpoint: GET https://api.x.com/2/tweets/:id/quote_twe"
},
{
"path": "python/posts/get_reposted_by.py",
"chars": 1636,
"preview": "\"\"\"\nRetweeted By (Users who reposted) - X API v2\n============================================\nEndpoint: GET https://api."
},
{
"path": "python/posts/hide_reply.py",
"chars": 2268,
"preview": "\"\"\"\nHide Reply - X API v2\n=====================\nEndpoint: PUT https://api.x.com/2/tweets/:id/hidden\nDocs: https://develo"
},
{
"path": "python/posts/search_all.py",
"chars": 1422,
"preview": "\"\"\"\nFull-Archive Search - X API v2\n==============================\nEndpoint: GET https://api.x.com/2/tweets/search/all\nDo"
},
{
"path": "python/posts/search_recent.py",
"chars": 1382,
"preview": "\"\"\"\nRecent Search - X API v2\n========================\nEndpoint: GET https://api.x.com/2/tweets/search/recent\nDocs: https"
},
{
"path": "python/requirements.txt",
"chars": 40,
"preview": "xdk>=0.4.5\nflask>=3.0.0\nwaitress>=3.0.0\n"
},
{
"path": "python/spaces/get_spaces_by_ids.py",
"chars": 1049,
"preview": "\"\"\"\nSpaces Lookup - X API v2\n========================\nEndpoint: GET https://api.x.com/2/spaces\nDocs: https://developer.x"
},
{
"path": "python/spaces/search_spaces.py",
"chars": 987,
"preview": "\"\"\"\nSearch Spaces - X API v2\n========================\nEndpoint: GET https://api.x.com/2/spaces/search\nDocs: https://deve"
},
{
"path": "python/streams/stream_posts_filtered.py",
"chars": 2378,
"preview": "\"\"\"\nFiltered Stream - X API v2\n==========================\nEndpoint: GET https://api.x.com/2/tweets/search/stream\nDocs: h"
},
{
"path": "python/streams/stream_posts_sample.py",
"chars": 718,
"preview": "\"\"\"\nSampled Stream (1% Volume) - X API v2\n=====================================\nEndpoint: GET https://api.x.com/2/tweets"
},
{
"path": "python/usage/get_usage.py",
"chars": 955,
"preview": "\"\"\"\nUsage Posts - X API v2\n======================\nEndpoint: GET https://api.x.com/2/usage/tweets\nDocs: https://developer"
},
{
"path": "python/users/block/get_blocking.py",
"chars": 3312,
"preview": "\"\"\"\nBlocked Users Lookup - X API v2\n===============================\nEndpoint: GET https://api.x.com/2/users/:id/blocking"
},
{
"path": "python/users/bookmark/create_bookmark.py",
"chars": 2203,
"preview": "\"\"\"\nCreate Bookmark - X API v2\n==========================\nEndpoint: POST https://api.x.com/2/users/:id/bookmarks\nDocs: h"
},
{
"path": "python/users/bookmark/delete_bookmark.py",
"chars": 2197,
"preview": "\"\"\"\nDelete Bookmark - X API v2\n==========================\nEndpoint: DELETE https://api.x.com/2/users/:id/bookmarks/:twee"
},
{
"path": "python/users/bookmark/get_bookmarks.py",
"chars": 2367,
"preview": "\"\"\"\nBookmarks Lookup - X API v2\n===========================\nEndpoint: GET https://api.x.com/2/users/:id/bookmarks\nDocs: "
},
{
"path": "python/users/follow/follow_user.py",
"chars": 2273,
"preview": "\"\"\"\nFollow User - X API v2\n======================\nEndpoint: POST https://api.x.com/2/users/:id/following\nDocs: https://d"
},
{
"path": "python/users/follow/get_followers.py",
"chars": 1274,
"preview": "\"\"\"\nUser Followers Lookup - X API v2\n================================\nEndpoint: GET https://api.x.com/2/users/:id/follow"
},
{
"path": "python/users/follow/get_following.py",
"chars": 1274,
"preview": "\"\"\"\nUser Following Lookup - X API v2\n================================\nEndpoint: GET https://api.x.com/2/users/:id/follow"
},
{
"path": "python/users/follow/unfollow_user.py",
"chars": 2291,
"preview": "\"\"\"\nUnfollow User - X API v2\n========================\nEndpoint: DELETE https://api.x.com/2/users/:source_user_id/followi"
},
{
"path": "python/users/get_users_by_usernames.py",
"chars": 1184,
"preview": "\"\"\"\nUser Lookup - X API v2\n======================\nEndpoint: GET https://api.x.com/2/users/by\nDocs: https://developer.x.c"
},
{
"path": "python/users/get_users_by_usernames_user_context.py",
"chars": 2481,
"preview": "\"\"\"\nUser Lookup (User Context) - X API v2\n=====================================\nEndpoint: GET https://api.x.com/2/users/"
},
{
"path": "python/users/get_users_me.py",
"chars": 2181,
"preview": "\"\"\"\nAuthenticated User Lookup (Me) - X API v2\n=========================================\nEndpoint: GET https://api.x.com/"
},
{
"path": "python/users/like/get_liked_posts.py",
"chars": 2925,
"preview": "\"\"\"\nLiked Tweets - X API v2\n======================\nEndpoint: GET https://api.x.com/2/users/:id/liked_tweets\nDocs: https:"
},
{
"path": "python/users/like/like_post.py",
"chars": 2258,
"preview": "\"\"\"\nLike a Tweet - X API v2\n======================\nEndpoint: POST https://api.x.com/2/users/:id/likes\nDocs: https://deve"
},
{
"path": "python/users/like/unlike_post.py",
"chars": 2259,
"preview": "\"\"\"\nUnlike a Tweet - X API v2\n========================\nEndpoint: DELETE https://api.x.com/2/users/:id/likes/:tweet_id\nDo"
},
{
"path": "python/users/lists/follow_list.py",
"chars": 2289,
"preview": "\"\"\"\nFollow List - X API v2\n=====================\nEndpoint: POST https://api.x.com/2/users/:id/followed_lists\nDocs: https"
},
{
"path": "python/users/lists/get_followed_lists.py",
"chars": 1516,
"preview": "\"\"\"\nUser Followed Lists Lookup - X API v2\n======================================\nEndpoint: GET https://api.x.com/2/users"
},
{
"path": "python/users/lists/get_list_memberships.py",
"chars": 1530,
"preview": "\"\"\"\nUser List Memberships Lookup - X API v2\n=======================================\nEndpoint: GET https://api.x.com/2/us"
},
{
"path": "python/users/lists/get_owned_lists.py",
"chars": 1472,
"preview": "\"\"\"\nUser Owned Lists Lookup - X API v2\n===================================\nEndpoint: GET https://api.x.com/2/users/:id/o"
},
{
"path": "python/users/lists/get_pinned_lists.py",
"chars": 2809,
"preview": "\"\"\"\nPinned Lists Lookup - X API v2\n==============================\nEndpoint: GET https://api.x.com/2/users/:id/pinned_lis"
},
{
"path": "python/users/lists/pin_list.py",
"chars": 2264,
"preview": "\"\"\"\nPin List - X API v2\n==================\nEndpoint: POST https://api.x.com/2/users/:id/pinned_lists\nDocs: https://devel"
},
{
"path": "python/users/lists/unfollow_list.py",
"chars": 2292,
"preview": "\"\"\"\nUnfollow List - X API v2\n========================\nEndpoint: DELETE https://api.x.com/2/users/:id/followed_lists/:lis"
},
{
"path": "python/users/lists/unpin_list.py",
"chars": 2267,
"preview": "\"\"\"\nUnpin List - X API v2\n=====================\nEndpoint: DELETE https://api.x.com/2/users/:id/pinned_lists/:list_id\nDoc"
},
{
"path": "python/users/mute/get_muting.py",
"chars": 3295,
"preview": "\"\"\"\nMuted Users Lookup - X API v2\n=============================\nEndpoint: GET https://api.x.com/2/users/:id/muting\nDocs:"
},
{
"path": "python/users/mute/mute_user.py",
"chars": 2271,
"preview": "\"\"\"\nMute User - X API v2\n====================\nEndpoint: POST https://api.x.com/2/users/:id/muting\nDocs: https://develope"
},
{
"path": "python/users/mute/unmute_user.py",
"chars": 2336,
"preview": "\"\"\"\nUnmute User - X API v2\n======================\nEndpoint: DELETE https://api.x.com/2/users/:source_user_id/muting/:tar"
},
{
"path": "python/users/repost/get_reposts_of_me.py",
"chars": 2814,
"preview": "\"\"\"\nReposts of Me - X API v2\n=========================\nEndpoint: GET https://api.x.com/2/users/reposts_of_me\nDocs: https"
},
{
"path": "python/users/repost/repost_post.py",
"chars": 2273,
"preview": "\"\"\"\nRetweet (Repost) - X API v2\n===========================\nEndpoint: POST https://api.x.com/2/users/:id/retweets\nDocs: "
},
{
"path": "python/users/repost/unrepost_post.py",
"chars": 2312,
"preview": "\"\"\"\nUndo Retweet (Unrepost) - X API v2\n==================================\nEndpoint: DELETE https://api.x.com/2/users/:id"
},
{
"path": "python/users/timeline/get_home_timeline.py",
"chars": 2915,
"preview": "\"\"\"\nReverse Chronological Home Timeline - X API v2\n==============================================\nEndpoint: GET https://"
},
{
"path": "python/users/timeline/get_mentions.py",
"chars": 1602,
"preview": "\"\"\"\nUser Mentions Timeline - X API v2\n==================================\nEndpoint: GET https://api.x.com/2/users/:id/men"
},
{
"path": "python/users/timeline/get_posts.py",
"chars": 1589,
"preview": "\"\"\"\nUser Posts Timeline - X API v2\n==============================\nEndpoint: GET https://api.x.com/2/users/:id/tweets\nDoc"
},
{
"path": "python/webhooks/delete_webhook.py",
"chars": 867,
"preview": "\"\"\"\nDelete Webhook - X API v2\n=========================\nEndpoint: DELETE https://api.x.com/2/webhooks/:webhook_id\nDocs: "
},
{
"path": "python/webhooks/list_webhooks.py",
"chars": 652,
"preview": "\"\"\"\nList Webhooks - X API v2\n========================\nEndpoint: GET https://api.x.com/2/webhooks\nDocs: https://docs.x.co"
},
{
"path": "python/webhooks/register_webhook.py",
"chars": 1121,
"preview": "\"\"\"\nRegister Webhook - X API v2\n===========================\nEndpoint: POST https://api.x.com/2/webhooks\nDocs: https://do"
},
{
"path": "python/webhooks/validate_webhook.py",
"chars": 1055,
"preview": "\"\"\"\nValidate Webhook (Trigger CRC) - X API v2\n==========================================\nEndpoint: PUT https://api.x.com"
},
{
"path": "python/webhooks/webhook_server.py",
"chars": 3336,
"preview": "\"\"\"\nWebhook Server - X API v2\n=========================\nDocs: https://docs.x.com/x-api/webhooks/introduction\n\nThis is a "
},
{
"path": "r/posts/full-archive-search.r",
"chars": 544,
"preview": "library(httr)\n\n# Replace the bearer token below with\nbearer_token = \"\"\n\nheaders = c(\n `Authorization` = sprintf('Bearer"
},
{
"path": "r/posts/full_archive_tweet_counts.r",
"chars": 471,
"preview": "library(httr)\n\n# Replace the bearer token below with\nbearer_token = \"\"\n\nheaders = c(\n `Authorization` = sprintf('Bearer"
},
{
"path": "r/posts/recent-search.r",
"chars": 521,
"preview": "require(httr)\n\n\nbearer_token = \"\"\nheaders = c(\n `Authorization` = sprintf('Bearer %s', bearer_token)\n)\n\n\nparams = list("
},
{
"path": "r/posts/recent_tweet_counts.r",
"chars": 474,
"preview": "library(httr)\n\n# Replace the bearer token below with\nbearer_token = \"\"\n\nheaders = c(\n `Authorization` = sprintf('Bearer"
},
{
"path": "r/users/get_users_with_bearer_token.r",
"chars": 424,
"preview": "require(httr)\n\nbearer_token <- \"\"\n\nheaders <- c(`Authorization` = sprintf('Bearer %s', bearer_token))\n\nparams <- list(`u"
},
{
"path": "ruby/Gemfile",
"chars": 77,
"preview": "source 'https://rubygems.org'\ngem 'typhoeus', '~> 1.4'\ngem 'oauth', '~> 1.1'\n"
},
{
"path": "ruby/README.md",
"chars": 4487,
"preview": "# X API v2 - Ruby Examples\n\nWorking Ruby code samples for the X (formerly Twitter) API v2.\n\n## Setup\n\n### 1. Install Rub"
},
{
"path": "ruby/bookmarks/bookmarks_lookup.rb",
"chars": 3165,
"preview": "require 'json'\nrequire 'typhoeus'\nrequire 'twitter_oauth2'\n\n# First, you will need to enable OAuth 2.0 in your App’s aut"
},
{
"path": "ruby/lists/List-Tweets.rb",
"chars": 1299,
"preview": "# This script uses your bearer token to authenticate and retrieve the specified Tweet objects (by List ID)\n\nrequire 'jso"
},
{
"path": "ruby/lists/Pinned-List.rb",
"chars": 2771,
"preview": "# This script implements the PIN-based OAuth flow to obtain access tokens for a user context request\nrequire 'oauth'\nreq"
},
{
"path": "ruby/lists/add_member.rb",
"chars": 2654,
"preview": "# This script implements the PIN-based OAuth flow to obtain access tokens for a user context request\nrequire 'oauth'\nreq"
},
{
"path": "ruby/lists/create_a_list.rb",
"chars": 2756,
"preview": "# This script implements the PIN-based OAuth flow to obtain access tokens for a user context request\n# It then makes a U"
},
{
"path": "ruby/lists/delete_a_list.rb",
"chars": 2665,
"preview": "# This script implements the PIN-based OAuth flow to obtain access tokens for a user context request\n# It then makes a U"
},
{
"path": "ruby/lists/follow_list.rb",
"chars": 2742,
"preview": "# This script implements the PIN-based OAuth flow to obtain access tokens for a user context request\nrequire 'oauth'\nreq"
},
{
"path": "ruby/lists/list-followers-lookup.rb",
"chars": 1191,
"preview": "# This script uses your bearer token to authenticate and retrieve followers of a List specified by List ID\n\nrequire 'jso"
},
{
"path": "ruby/lists/list-lookup-by-id.rb",
"chars": 1084,
"preview": "# This script uses your bearer token to authenticate and retrieve the specified List objects (by ID)\n\nrequire 'json'\nreq"
},
{
"path": "ruby/lists/list-member-lookup.rb",
"chars": 1185,
"preview": "# This script uses your bearer token to authenticate and retrieve members of a List specified by List ID\n\nrequire 'json'"
},
{
"path": "ruby/lists/lookup.rb",
"chars": 1000,
"preview": "# List Lookup - X API v2\n#\n# Endpoint: GET https://api.x.com/2/lists/:id\n# Docs: https://developer.x.com/en/docs/twitter"
},
{
"path": "ruby/lists/pin_list.rb",
"chars": 2710,
"preview": "# This script implements the PIN-based OAuth flow to obtain access tokens for a user context request\nrequire 'oauth'\nreq"
},
{
"path": "ruby/lists/remove_member.rb",
"chars": 2638,
"preview": "# This script implements the PIN-based OAuth flow to obtain access tokens for a user context request\nrequire 'oauth'\nreq"
},
{
"path": "ruby/lists/unfollow_list.rb",
"chars": 2765,
"preview": "# This script implements the PIN-based OAuth flow to obtain access tokens for a user context request\nrequire 'oauth'\nreq"
},
{
"path": "ruby/lists/unpin_list.rb",
"chars": 2739,
"preview": "# This script implements the PIN-based OAuth flow to obtain access tokens for a user context request\nrequire 'oauth'\nreq"
},
{
"path": "ruby/lists/update_a_list.rb",
"chars": 2958,
"preview": "# This script implements the PIN-based OAuth flow to obtain access tokens for a user context request\n# It then makes a U"
},
{
"path": "ruby/lists/user-list-followed.rb",
"chars": 1102,
"preview": "# This script uses your bearer token to authenticate and retrieve the specified List objects (by user ID)\n\nrequire 'json"
},
{
"path": "ruby/lists/user-list-memberships.rb",
"chars": 1104,
"preview": "# This script uses your bearer token to authenticate and retrieve the specified List objects (by user ID)\n\nrequire 'json"
},
{
"path": "ruby/lists/user-owned-list-lookup.rb",
"chars": 1133,
"preview": "# This script uses your bearer token to authenticate and retrieve any user owned Lists specified by user ID\n\nrequire 'js"
},
{
"path": "ruby/posts/create_tweet.rb",
"chars": 2602,
"preview": "require 'oauth'\nrequire 'json'\nrequire 'typhoeus'\nrequire 'oauth/request_proxy/typhoeus_request'\n\n# The code below sets "
},
{
"path": "ruby/posts/delete_tweet.rb",
"chars": 2345,
"preview": "require 'oauth'\nrequire 'json'\nrequire 'typhoeus'\nrequire 'oauth/request_proxy/typhoeus_request'\n\n# The code below sets "
},
{
"path": "ruby/posts/full-archive-search.rb",
"chars": 1702,
"preview": "# This script uses your bearer token to authenticate and make a Search request\n\nrequire 'json'\nrequire 'typhoeus'\n\n# The"
}
]
// ... and 36 more files (download for full content)
About this extraction
This page contains the full source code of the xdevplatform/Twitter-API-v2-sample-code GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 236 files (499.2 KB), approximately 127.0k tokens, and a symbol index with 330 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.