From 157f35b915853dc4422d2326364b1f5d6e01ae54 Mon Sep 17 00:00:00 2001 From: Taylor Caldwell <169854908+tcaldwell-x@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:20:25 -0800 Subject: [PATCH 1/4] feat: add full XDK sample parity for Java, C#, and JavaScript - Modernize java/ (80 samples + pom.xml + README.md) to official com.x:xdk (Java 17+), replacing legacy raw Apache HttpClient/TwitterCredentials demos - Add csharp/ (80 samples + XdkSamples.csproj + Program.cs CLI runner + README.md) powered by official XDevPlatform.Xdk (.NET 8+) - Backfill 25 missing JavaScript samples (activity, direct_messages, media, posts, users, webhooks) + package.json in javascript/ for full parity with python/ - Refresh root README.md, llms.txt, api-index.json, and .gitignore --- .gitignore | 57 +- README.md | 115 +- api-index.json | 1458 ++++++++++++++--- csharp/Program.cs | 117 ++ csharp/README.md | 100 ++ csharp/XdkSamples.csproj | 17 + csharp/activity/CreateSubscription.cs | 41 + csharp/activity/DeleteSubscription.cs | 32 + csharp/activity/ListSubscriptions.cs | 31 + csharp/activity/StreamEvents.cs | 38 + csharp/activity/UpdateSubscription.cs | 37 + csharp/compliance/CreateJobs.cs | 36 + csharp/compliance/DownloadResults.cs | 26 + csharp/compliance/GetJobs.cs | 31 + csharp/compliance/GetJobsById.cs | 32 + csharp/compliance/UploadIds.cs | 31 + .../GetEventsByConversation.cs | 84 + .../GetOneToOneConversationEvents.cs | 84 + .../GetUserConversationEvents.cs | 87 + .../direct_messages/PostDmToConversation.cs | 79 + .../PostGroupConversationDm.cs | 83 + csharp/direct_messages/PostOneToOneDm.cs | 79 + csharp/lists/AddMember.cs | 75 + csharp/lists/CreateList.cs | 79 + csharp/lists/DeleteList.cs | 74 + csharp/lists/GetListById.cs | 36 + csharp/lists/GetListFollowers.cs | 47 + csharp/lists/GetListMembers.cs | 47 + csharp/lists/GetListPosts.cs | 47 + csharp/lists/RemoveMember.cs | 75 + csharp/lists/UpdateList.cs | 80 + csharp/media/MediaUploadV2.cs | 120 ++ csharp/media/Upload.cs | 81 + csharp/posts/CreatePost.cs | 73 + csharp/posts/DeletePost.cs | 74 + csharp/posts/GetLikingUsers.cs | 89 + csharp/posts/GetPostById.cs | 36 + csharp/posts/GetPostCountsAll.cs | 43 + csharp/posts/GetPostCountsRecent.cs | 43 + csharp/posts/GetPostsByIds.cs | 36 + csharp/posts/GetQuotedPosts.cs | 47 + csharp/posts/GetRepostedBy.cs | 47 + csharp/posts/HideReply.cs | 74 + csharp/posts/SearchAll.cs | 47 + csharp/posts/SearchRecent.cs | 47 + csharp/spaces/GetSpacesByIds.cs | 37 + csharp/spaces/SearchSpaces.cs | 37 + csharp/streams/StreamPostsFiltered.cs | 72 + csharp/streams/StreamPostsSample.cs | 37 + csharp/usage/GetUsage.cs | 31 + csharp/users/GetUsersByUsernames.cs | 36 + .../users/GetUsersByUsernamesUserContext.cs | 78 + csharp/users/GetUsersMe.cs | 77 + csharp/users/block/GetBlocking.cs | 90 + csharp/users/bookmark/CreateBookmark.cs | 76 + csharp/users/bookmark/DeleteBookmark.cs | 76 + csharp/users/bookmark/GetBookmarks.cs | 90 + csharp/users/follow/FollowUser.cs | 76 + csharp/users/follow/GetFollowers.cs | 47 + csharp/users/follow/GetFollowing.cs | 47 + csharp/users/follow/UnfollowUser.cs | 76 + csharp/users/like/GetLikedPosts.cs | 90 + csharp/users/like/LikePost.cs | 76 + csharp/users/like/UnlikePost.cs | 76 + csharp/users/lists/FollowList.cs | 75 + csharp/users/lists/GetFollowedLists.cs | 47 + csharp/users/lists/GetListMemberships.cs | 47 + csharp/users/lists/GetOwnedLists.cs | 47 + csharp/users/lists/GetPinnedLists.cs | 78 + csharp/users/lists/PinList.cs | 75 + csharp/users/lists/UnfollowList.cs | 75 + csharp/users/lists/UnpinList.cs | 75 + csharp/users/mute/GetMuting.cs | 90 + csharp/users/mute/MuteUser.cs | 75 + csharp/users/mute/UnmuteUser.cs | 75 + csharp/users/repost/GetRepostsOfMe.cs | 88 + csharp/users/repost/RepostPost.cs | 76 + csharp/users/repost/UnrepostPost.cs | 76 + csharp/users/timeline/GetHomeTimeline.cs | 90 + csharp/users/timeline/GetMentions.cs | 47 + csharp/users/timeline/GetPosts.cs | 47 + csharp/webhooks/DeleteWebhook.cs | 32 + csharp/webhooks/ListWebhooks.cs | 31 + csharp/webhooks/RegisterWebhook.cs | 32 + csharp/webhooks/ValidateWebhook.cs | 32 + csharp/webhooks/WebhookServer.cs | 69 + java/README.md | 154 +- java/activity/CreateSubscription.java | 47 + java/activity/DeleteSubscription.java | 38 + java/activity/ListSubscriptions.java | 37 + java/activity/StreamEvents.java | 43 + java/activity/UpdateSubscription.java | 41 + java/compliance/CreateJobs.java | 40 + java/compliance/DownloadResults.java | 30 + java/compliance/GetJobs.java | 37 + java/compliance/GetJobsById.java | 38 + java/compliance/UploadIds.java | 32 + .../GetEventsByConversation.java | 95 ++ .../GetOneToOneConversationEvents.java | 95 ++ .../GetUserConversationEvents.java | 94 ++ .../direct_messages/PostDmToConversation.java | 90 + .../PostGroupConversationDm.java | 93 ++ java/direct_messages/PostOneToOneDm.java | 90 + java/lists/AddMember.java | 87 + java/lists/CreateList.java | 88 + java/lists/DeleteList.java | 85 + java/lists/GetListById.java | 40 + java/lists/GetListFollowers.java | 49 + java/lists/GetListMembers.java | 49 + java/lists/GetListPosts.java | 49 + java/lists/RemoveMember.java | 86 + java/lists/UpdateList.java | 89 + java/media/MediaUploadV2.java | 134 ++ java/media/Upload.java | 91 + java/pom.xml | 47 + java/posts/CreatePost.java | 85 + java/posts/DeletePost.java | 85 + java/posts/FullArchiveSearchDemo.java | 65 - java/posts/FullArchiveTweetCountsDemo.java | 67 - java/posts/GetLikingUsers.java | 96 ++ java/posts/GetPostById.java | 40 + java/posts/GetPostCountsAll.java | 47 + java/posts/GetPostCountsRecent.java | 47 + java/posts/GetPostsByIds.java | 40 + java/posts/GetQuotedPosts.java | 49 + java/posts/GetRepostedBy.java | 49 + java/posts/HideReply.java | 86 + java/posts/QuoteTweetsDemo.java | 64 - java/posts/RecentSearchDemo.java | 65 - java/posts/RecentTweetCountsDemo.java | 66 - java/posts/SearchAll.java | 49 + java/posts/SearchRecent.java | 83 +- java/posts/TweetsDemo.java | 65 - java/spaces/GetSpacesByIds.java | 41 + java/spaces/SearchSpaces.java | 41 + java/spaces/SearchSpacesDemo.java | 66 - java/spaces/SpacesLookupDemo.java | 66 - java/streams/FilteredStreamDemo.java | 183 --- java/streams/SampledStream.java | 60 - java/streams/StreamPostsFiltered.java | 69 + java/streams/StreamPostsSample.java | 42 + java/timelines/UserMentionsDemo.java | 64 - java/timelines/UserTweetsDemo.java | 64 - .../reverse-chron-home-timeline-java-sdk.java | 130 -- java/usage/GetUsage.java | 38 + java/usage/UsageTweetsDemo.java | 58 - java/users/FollowersLookupDemo.java | 64 - java/users/FollowingLookupDemo.java | 64 - java/users/GetUsersByUsernames.java | 40 + .../users/GetUsersByUsernamesUserContext.java | 87 + java/users/GetUsersMe.java | 86 + java/users/Lookup.java | 64 - java/users/UsersDemo.java | 66 - java/users/block/GetBlocking.java | 96 ++ java/users/bookmark/CreateBookmark.java | 87 + java/users/bookmark/DeleteBookmark.java | 86 + java/users/bookmark/GetBookmarks.java | 96 ++ java/users/follow/FollowUser.java | 87 + java/users/follow/GetFollowers.java | 49 + java/users/follow/GetFollowing.java | 49 + java/users/follow/UnfollowUser.java | 86 + java/users/like/GetLikedPosts.java | 96 ++ java/users/like/LikePost.java | 87 + java/users/like/UnlikePost.java | 86 + java/users/lists/FollowList.java | 87 + java/users/lists/GetFollowedLists.java | 49 + java/users/lists/GetListMemberships.java | 49 + java/users/lists/GetOwnedLists.java | 49 + java/users/lists/GetPinnedLists.java | 87 + java/users/lists/PinList.java | 87 + java/users/lists/UnfollowList.java | 86 + java/users/lists/UnpinList.java | 86 + java/users/mute/GetMuting.java | 96 ++ java/users/mute/MuteUser.java | 87 + java/users/mute/UnmuteUser.java | 86 + java/users/repost/GetRepostsOfMe.java | 95 ++ java/users/repost/RepostPost.java | 87 + java/users/repost/UnrepostPost.java | 86 + java/users/timeline/GetHomeTimeline.java | 96 ++ java/users/timeline/GetMentions.java | 49 + java/users/timeline/GetPosts.java | 49 + java/webhooks/DeleteWebhook.java | 38 + java/webhooks/ListWebhooks.java | 37 + java/webhooks/RegisterWebhook.java | 39 + java/webhooks/ValidateWebhook.java | 38 + java/webhooks/WebhookServer.java | 73 + javascript/README.md | 216 ++- javascript/activity/create_subscription.js | 29 + javascript/activity/delete_subscription.js | 22 + javascript/activity/list_subscriptions.js | 21 + javascript/activity/stream_events.js | 33 + javascript/activity/update_subscription.js | 24 + .../get_events_by_conversation.js | 97 ++ .../get_one_to_one_conversation_events.js | 97 ++ .../get_user_conversation_events.js | 97 ++ .../post_dm_to_conversation.js | 85 + .../post_group_conversation_dm.js | 88 + .../direct_messages/post_one_to_one_dm.js | 85 + javascript/media/media_upload_v2.js | 120 ++ javascript/media/upload.js | 89 + javascript/package.json | 12 + javascript/posts/get_post_by_id.js | 24 + javascript/posts/hide_reply.js | 82 + javascript/users/follow/follow_user.js | 84 + javascript/users/follow/get_following.js | 25 + javascript/users/follow/unfollow_user.js | 84 + javascript/users/lists/get_pinned_lists.js | 85 + javascript/users/repost/get_reposts_of_me.js | 97 ++ javascript/webhooks/delete_webhook.js | 22 + javascript/webhooks/list_webhooks.js | 21 + javascript/webhooks/register_webhook.js | 22 + javascript/webhooks/validate_webhook.js | 22 + javascript/webhooks/webhook_server.js | 56 + llms.txt | 214 +-- 214 files changed, 13543 insertions(+), 2096 deletions(-) create mode 100644 csharp/Program.cs create mode 100644 csharp/README.md create mode 100644 csharp/XdkSamples.csproj create mode 100644 csharp/activity/CreateSubscription.cs create mode 100644 csharp/activity/DeleteSubscription.cs create mode 100644 csharp/activity/ListSubscriptions.cs create mode 100644 csharp/activity/StreamEvents.cs create mode 100644 csharp/activity/UpdateSubscription.cs create mode 100644 csharp/compliance/CreateJobs.cs create mode 100644 csharp/compliance/DownloadResults.cs create mode 100644 csharp/compliance/GetJobs.cs create mode 100644 csharp/compliance/GetJobsById.cs create mode 100644 csharp/compliance/UploadIds.cs create mode 100644 csharp/direct_messages/GetEventsByConversation.cs create mode 100644 csharp/direct_messages/GetOneToOneConversationEvents.cs create mode 100644 csharp/direct_messages/GetUserConversationEvents.cs create mode 100644 csharp/direct_messages/PostDmToConversation.cs create mode 100644 csharp/direct_messages/PostGroupConversationDm.cs create mode 100644 csharp/direct_messages/PostOneToOneDm.cs create mode 100644 csharp/lists/AddMember.cs create mode 100644 csharp/lists/CreateList.cs create mode 100644 csharp/lists/DeleteList.cs create mode 100644 csharp/lists/GetListById.cs create mode 100644 csharp/lists/GetListFollowers.cs create mode 100644 csharp/lists/GetListMembers.cs create mode 100644 csharp/lists/GetListPosts.cs create mode 100644 csharp/lists/RemoveMember.cs create mode 100644 csharp/lists/UpdateList.cs create mode 100644 csharp/media/MediaUploadV2.cs create mode 100644 csharp/media/Upload.cs create mode 100644 csharp/posts/CreatePost.cs create mode 100644 csharp/posts/DeletePost.cs create mode 100644 csharp/posts/GetLikingUsers.cs create mode 100644 csharp/posts/GetPostById.cs create mode 100644 csharp/posts/GetPostCountsAll.cs create mode 100644 csharp/posts/GetPostCountsRecent.cs create mode 100644 csharp/posts/GetPostsByIds.cs create mode 100644 csharp/posts/GetQuotedPosts.cs create mode 100644 csharp/posts/GetRepostedBy.cs create mode 100644 csharp/posts/HideReply.cs create mode 100644 csharp/posts/SearchAll.cs create mode 100644 csharp/posts/SearchRecent.cs create mode 100644 csharp/spaces/GetSpacesByIds.cs create mode 100644 csharp/spaces/SearchSpaces.cs create mode 100644 csharp/streams/StreamPostsFiltered.cs create mode 100644 csharp/streams/StreamPostsSample.cs create mode 100644 csharp/usage/GetUsage.cs create mode 100644 csharp/users/GetUsersByUsernames.cs create mode 100644 csharp/users/GetUsersByUsernamesUserContext.cs create mode 100644 csharp/users/GetUsersMe.cs create mode 100644 csharp/users/block/GetBlocking.cs create mode 100644 csharp/users/bookmark/CreateBookmark.cs create mode 100644 csharp/users/bookmark/DeleteBookmark.cs create mode 100644 csharp/users/bookmark/GetBookmarks.cs create mode 100644 csharp/users/follow/FollowUser.cs create mode 100644 csharp/users/follow/GetFollowers.cs create mode 100644 csharp/users/follow/GetFollowing.cs create mode 100644 csharp/users/follow/UnfollowUser.cs create mode 100644 csharp/users/like/GetLikedPosts.cs create mode 100644 csharp/users/like/LikePost.cs create mode 100644 csharp/users/like/UnlikePost.cs create mode 100644 csharp/users/lists/FollowList.cs create mode 100644 csharp/users/lists/GetFollowedLists.cs create mode 100644 csharp/users/lists/GetListMemberships.cs create mode 100644 csharp/users/lists/GetOwnedLists.cs create mode 100644 csharp/users/lists/GetPinnedLists.cs create mode 100644 csharp/users/lists/PinList.cs create mode 100644 csharp/users/lists/UnfollowList.cs create mode 100644 csharp/users/lists/UnpinList.cs create mode 100644 csharp/users/mute/GetMuting.cs create mode 100644 csharp/users/mute/MuteUser.cs create mode 100644 csharp/users/mute/UnmuteUser.cs create mode 100644 csharp/users/repost/GetRepostsOfMe.cs create mode 100644 csharp/users/repost/RepostPost.cs create mode 100644 csharp/users/repost/UnrepostPost.cs create mode 100644 csharp/users/timeline/GetHomeTimeline.cs create mode 100644 csharp/users/timeline/GetMentions.cs create mode 100644 csharp/users/timeline/GetPosts.cs create mode 100644 csharp/webhooks/DeleteWebhook.cs create mode 100644 csharp/webhooks/ListWebhooks.cs create mode 100644 csharp/webhooks/RegisterWebhook.cs create mode 100644 csharp/webhooks/ValidateWebhook.cs create mode 100644 csharp/webhooks/WebhookServer.cs create mode 100644 java/activity/CreateSubscription.java create mode 100644 java/activity/DeleteSubscription.java create mode 100644 java/activity/ListSubscriptions.java create mode 100644 java/activity/StreamEvents.java create mode 100644 java/activity/UpdateSubscription.java create mode 100644 java/compliance/CreateJobs.java create mode 100644 java/compliance/DownloadResults.java create mode 100644 java/compliance/GetJobs.java create mode 100644 java/compliance/GetJobsById.java create mode 100644 java/compliance/UploadIds.java create mode 100644 java/direct_messages/GetEventsByConversation.java create mode 100644 java/direct_messages/GetOneToOneConversationEvents.java create mode 100644 java/direct_messages/GetUserConversationEvents.java create mode 100644 java/direct_messages/PostDmToConversation.java create mode 100644 java/direct_messages/PostGroupConversationDm.java create mode 100644 java/direct_messages/PostOneToOneDm.java create mode 100644 java/lists/AddMember.java create mode 100644 java/lists/CreateList.java create mode 100644 java/lists/DeleteList.java create mode 100644 java/lists/GetListById.java create mode 100644 java/lists/GetListFollowers.java create mode 100644 java/lists/GetListMembers.java create mode 100644 java/lists/GetListPosts.java create mode 100644 java/lists/RemoveMember.java create mode 100644 java/lists/UpdateList.java create mode 100644 java/media/MediaUploadV2.java create mode 100644 java/media/Upload.java create mode 100644 java/pom.xml create mode 100644 java/posts/CreatePost.java create mode 100644 java/posts/DeletePost.java delete mode 100644 java/posts/FullArchiveSearchDemo.java delete mode 100644 java/posts/FullArchiveTweetCountsDemo.java create mode 100644 java/posts/GetLikingUsers.java create mode 100644 java/posts/GetPostById.java create mode 100644 java/posts/GetPostCountsAll.java create mode 100644 java/posts/GetPostCountsRecent.java create mode 100644 java/posts/GetPostsByIds.java create mode 100644 java/posts/GetQuotedPosts.java create mode 100644 java/posts/GetRepostedBy.java create mode 100644 java/posts/HideReply.java delete mode 100644 java/posts/QuoteTweetsDemo.java delete mode 100644 java/posts/RecentSearchDemo.java delete mode 100644 java/posts/RecentTweetCountsDemo.java create mode 100644 java/posts/SearchAll.java delete mode 100644 java/posts/TweetsDemo.java create mode 100644 java/spaces/GetSpacesByIds.java create mode 100644 java/spaces/SearchSpaces.java delete mode 100644 java/spaces/SearchSpacesDemo.java delete mode 100644 java/spaces/SpacesLookupDemo.java delete mode 100644 java/streams/FilteredStreamDemo.java delete mode 100644 java/streams/SampledStream.java create mode 100644 java/streams/StreamPostsFiltered.java create mode 100644 java/streams/StreamPostsSample.java delete mode 100644 java/timelines/UserMentionsDemo.java delete mode 100644 java/timelines/UserTweetsDemo.java delete mode 100644 java/timelines/reverse-chron-home-timeline-java-sdk.java create mode 100644 java/usage/GetUsage.java delete mode 100644 java/usage/UsageTweetsDemo.java delete mode 100644 java/users/FollowersLookupDemo.java delete mode 100644 java/users/FollowingLookupDemo.java create mode 100644 java/users/GetUsersByUsernames.java create mode 100644 java/users/GetUsersByUsernamesUserContext.java create mode 100644 java/users/GetUsersMe.java delete mode 100644 java/users/Lookup.java delete mode 100644 java/users/UsersDemo.java create mode 100644 java/users/block/GetBlocking.java create mode 100644 java/users/bookmark/CreateBookmark.java create mode 100644 java/users/bookmark/DeleteBookmark.java create mode 100644 java/users/bookmark/GetBookmarks.java create mode 100644 java/users/follow/FollowUser.java create mode 100644 java/users/follow/GetFollowers.java create mode 100644 java/users/follow/GetFollowing.java create mode 100644 java/users/follow/UnfollowUser.java create mode 100644 java/users/like/GetLikedPosts.java create mode 100644 java/users/like/LikePost.java create mode 100644 java/users/like/UnlikePost.java create mode 100644 java/users/lists/FollowList.java create mode 100644 java/users/lists/GetFollowedLists.java create mode 100644 java/users/lists/GetListMemberships.java create mode 100644 java/users/lists/GetOwnedLists.java create mode 100644 java/users/lists/GetPinnedLists.java create mode 100644 java/users/lists/PinList.java create mode 100644 java/users/lists/UnfollowList.java create mode 100644 java/users/lists/UnpinList.java create mode 100644 java/users/mute/GetMuting.java create mode 100644 java/users/mute/MuteUser.java create mode 100644 java/users/mute/UnmuteUser.java create mode 100644 java/users/repost/GetRepostsOfMe.java create mode 100644 java/users/repost/RepostPost.java create mode 100644 java/users/repost/UnrepostPost.java create mode 100644 java/users/timeline/GetHomeTimeline.java create mode 100644 java/users/timeline/GetMentions.java create mode 100644 java/users/timeline/GetPosts.java create mode 100644 java/webhooks/DeleteWebhook.java create mode 100644 java/webhooks/ListWebhooks.java create mode 100644 java/webhooks/RegisterWebhook.java create mode 100644 java/webhooks/ValidateWebhook.java create mode 100644 java/webhooks/WebhookServer.java create mode 100644 javascript/activity/create_subscription.js create mode 100644 javascript/activity/delete_subscription.js create mode 100644 javascript/activity/list_subscriptions.js create mode 100644 javascript/activity/stream_events.js create mode 100644 javascript/activity/update_subscription.js create mode 100644 javascript/direct_messages/get_events_by_conversation.js create mode 100644 javascript/direct_messages/get_one_to_one_conversation_events.js create mode 100644 javascript/direct_messages/get_user_conversation_events.js create mode 100644 javascript/direct_messages/post_dm_to_conversation.js create mode 100644 javascript/direct_messages/post_group_conversation_dm.js create mode 100644 javascript/direct_messages/post_one_to_one_dm.js create mode 100644 javascript/media/media_upload_v2.js create mode 100644 javascript/media/upload.js create mode 100644 javascript/package.json create mode 100644 javascript/posts/get_post_by_id.js create mode 100644 javascript/posts/hide_reply.js create mode 100644 javascript/users/follow/follow_user.js create mode 100644 javascript/users/follow/get_following.js create mode 100644 javascript/users/follow/unfollow_user.js create mode 100644 javascript/users/lists/get_pinned_lists.js create mode 100644 javascript/users/repost/get_reposts_of_me.js create mode 100644 javascript/webhooks/delete_webhook.js create mode 100644 javascript/webhooks/list_webhooks.js create mode 100644 javascript/webhooks/register_webhook.js create mode 100644 javascript/webhooks/validate_webhook.js create mode 100644 javascript/webhooks/webhook_server.js diff --git a/.gitignore b/.gitignore index 7c7cedc..cf34c67 100644 --- a/.gitignore +++ b/.gitignore @@ -10,55 +10,46 @@ /test/version_tmp/ /tmp/ .DS_Store + +# Node.js / JavaScript node_modules/ package-lock.json -package.json yarn.lock -../node_modules/ -../package.json -../yarn.lock +pnpm-lock.yaml + +# Python +__pycache__/ +*.py[cod] +.venv/ +venv/ + +# Java / Maven / Gradle +target/ +*.class +.gradle/ +build/ -# Used by dotenv library to load environment variables. -# .env +# C# / .NET +bin/ +obj/ +*.user -# Ignore Byebug command history file. -.byebug_history +# Environment / Secrets (never commit!) +.env +.env.* -## Specific to RubyMotion: +# Ruby / Bundler +.byebug_history .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?--* diff --git a/README.md b/README.md index 78417ef..6f8b0d5 100644 --- a/README.md +++ b/README.md @@ -2,100 +2,105 @@ [![X API v2](https://img.shields.io/endpoint?url=https%3A%2F%2Ftwbadges.glitch.me%2Fbadges%2Fv2)](https://developer.x.com/en/docs/twitter-api) -Working code samples for the **X API v2** in Python, JavaScript, Ruby, Java, and R. +Official sample code for the **X API v2** across **Python**, **JavaScript / TypeScript**, **Java**, **C# / .NET**, **Ruby**, and **R**. -## 📁 Repository Structure +First-party SDK samples use the official **XDK** libraries: +- **Python**: [`xdk`](https://pypi.org/project/xdk/) ([`xdevplatform/xdk-python`](https://github.com/xdevplatform/xdk-python)) +- **JavaScript / TypeScript**: [`@xdevplatform/xdk`](https://www.npmjs.com/package/@xdevplatform/xdk) ([`xdevplatform/xdk-typescript`](https://github.com/xdevplatform/xdk-typescript)) +- **Java**: [`com.x:xdk`](https://central.sonatype.com/artifact/com.x/xdk) ([`xdevplatform/xdk-java`](https://github.com/xdevplatform/xdk-java)) +- **C# / .NET**: [`XDevPlatform.Xdk`](https://www.nuget.org/packages/XDevPlatform.Xdk) ([`xdevplatform/xdk-csharp`](https://github.com/xdevplatform/xdk-csharp)) + +## 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 +├── python/ # 80 Python samples (xdk) +├── javascript/ # 84 JavaScript / Node.js samples (@xdevplatform/xdk) +├── java/ # 80 Java 17+ samples (com.x:xdk) +├── csharp/ # 80 C# / .NET 8+ samples (XDevPlatform.Xdk) +├── ruby/ # 58 Ruby samples +├── r/ # 5 R samples +├── llms.txt # LLM-friendly documentation & SDK conventions +└── api-index.json # Machine-readable endpoint-to-sample catalog ``` -## 🚀 Quick Start +## Quick Start ### 1. Get API Credentials -Sign up at the [X Developer Portal](https://developer.x.com/en/portal/dashboard). +Sign up and create an App in the [X Developer Console](https://console.x.com). ### 2. Set Environment Variables -**For read-only operations (search, lookup):** +**For App-only read operations (search, lookup, streams, webhooks, activity):** ```bash export BEARER_TOKEN='your_bearer_token' ``` -**For user actions (post, like, repost, bookmark, etc.):** +**For User-context actions (post, like, repost, bookmark, DMs, media upload, 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' +export CLIENT_ID='your_oauth2_client_id' +export CLIENT_SECRET='your_oauth2_client_secret' ``` ### 3. Run an Example ```bash -# Python -cd python && pip install -r requirements.txt +# Python (xdk) +cd python && pip install xdk python posts/search_recent.py -# JavaScript -cd javascript +# JavaScript / Node.js (@xdevplatform/xdk) +cd javascript && npm install node posts/search_recent.js +# Java 17+ (com.x:xdk) +cd java +mvn compile exec:java -Dexec.mainClass="posts.SearchRecent" + +# C# / .NET 8+ (XDevPlatform.Xdk) +cd csharp +dotnet run -- posts/search_recent + # 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 +## Coverage 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 | ✅ | ✅ | | ✅ | | +| Category | Python (`xdk`) | JavaScript (`@xdevplatform/xdk`) | Java (`com.x:xdk`) | C# (`XDevPlatform.Xdk`) | Ruby | R | +|---|:---:|:---:|:---:|:---:|:---:|:---:| +| Activity (subscriptions & stream) | ✅ | ✅ | ✅ | ✅ | | | +| Compliance (batch jobs) | ✅ | ✅ | ✅ | ✅ | | | +| Direct Messages (1:1 & group DMs) | ✅ | ✅ | ✅ | ✅ | | | +| Lists (CRUD, members, followers, posts) | ✅ | ✅ | ✅ | ✅ | ✅ | | +| Media Upload (single & chunked v2) | ✅ | ✅ | ✅ | ✅ | | | +| Posts (search, counts, create, delete, hide reply, quotes) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| Spaces (lookup & search) | ✅ | ✅ | ✅ | ✅ | ✅ | | +| Streams (filtered rules & 1% sampled) | ✅ | ✅ | ✅ | ✅ | ✅ | | +| Usage (daily Post usage) | ✅ | ✅ | ✅ | ✅ | | | +| Users (lookup, timelines, likes, bookmarks, follows, mutes, blocks, reposts) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| Webhooks (register, list, validate CRC, delete, server) | ✅ | ✅ | ✅ | ✅ | | | -## 🔐 Authentication +## 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` | +| Bearer Token | App-only endpoints (search, lookup, streams, webhooks, activity) | `BEARER_TOKEN` | +| OAuth 2.0 PKCE | User-context actions (post, like, repost, bookmark, mute, follow, DMs, media) | `CLIENT_ID`, `CLIENT_SECRET` (or `ACCESS_TOKEN`) | +| Webhook HMAC | Webhook CRC verification (`webhook_server`) | `CONSUMER_SECRET` | -## 🤖 For LLMs +## For LLMs & Tooling -- **`llms.txt`** - Context file for AI assistants -- **`api-index.json`** - Machine-readable endpoint catalog +- **`llms.txt`** - Concise context file covering SDK packages, auth patterns, pagination, and streaming across all languages +- **`api-index.json`** - Machine-readable catalog mapping every endpoint to its exact file path in `python/`, `javascript/`, `java/`, `csharp/`, `ruby/`, and `r/` -## 🔗 Resources +## Resources -- [X API Documentation](https://developer.x.com/en/docs/twitter-api) -- [Developer Portal](https://developer.x.com/en/portal/dashboard) +- [X Developer Documentation](https://docs.x.com) +- [X Developer Console](https://console.x.com) +- [XDK Generator Monorepo (`xdevplatform/xdk`)](https://github.com/xdevplatform/xdk) -## 📄 License +## License Apache 2.0 diff --git a/api-index.json b/api-index.json index bd17e8d..c13fbe8 100644 --- a/api-index.json +++ b/api-index.json @@ -1,489 +1,1401 @@ { "name": "X API v2 Sample Code", - "version": "2.0", + "version": "3.0", "base_url": "https://api.x.com/2", - "languages": ["python", "javascript", "ruby", "java"], + "sdks": { + "python": { + "package": "xdk", + "registry": "https://pypi.org/project/xdk/", + "repo": "https://github.com/xdevplatform/xdk-python" + }, + "javascript": { + "package": "@xdevplatform/xdk", + "registry": "https://www.npmjs.com/package/@xdevplatform/xdk", + "repo": "https://github.com/xdevplatform/xdk-typescript" + }, + "java": { + "package": "com.x:xdk", + "registry": "https://central.sonatype.com/artifact/com.x/xdk", + "repo": "https://github.com/xdevplatform/xdk-java" + }, + "csharp": { + "package": "XDevPlatform.Xdk", + "registry": "https://www.nuget.org/packages/XDevPlatform.Xdk", + "repo": "https://github.com/xdevplatform/xdk-csharp" + } + }, + "languages": [ + "python", + "javascript", + "java", + "csharp", + "ruby", + "r" + ], "endpoints": [ { - "name": "Create Post", - "path": "/tweets", + "id": "activity/create_subscription", + "name": "* Create Activity Subscription", + "category": "activity", "method": "POST", - "auth": ["oauth1", "oauth2-user"], - "folder": "posts", + "path": "/activity/subscriptions", + "auth": [ + "bearer" + ], "files": { - "python": "create_post.py", - "javascript": "create_post.js" + "python": "python/activity/create_subscription.py", + "javascript": "javascript/activity/create_subscription.js", + "java": "java/activity/CreateSubscription.java", + "csharp": "csharp/activity/CreateSubscription.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets" + "docs": "https://docs.x.com/x-api/activity/introduction" }, { - "name": "Delete Post", - "path": "/tweets/:id", + "id": "activity/delete_subscription", + "name": "* Delete Activity Subscription", + "category": "activity", "method": "DELETE", - "auth": ["oauth1", "oauth2-user"], - "folder": "posts", + "path": "/activity/subscriptions/:id", + "auth": [ + "bearer" + ], "files": { - "python": "delete_post.py", - "javascript": "delete_post.js" + "python": "python/activity/delete_subscription.py", + "javascript": "javascript/activity/delete_subscription.js", + "java": "java/activity/DeleteSubscription.java", + "csharp": "csharp/activity/DeleteSubscription.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/delete-tweets-id" + "docs": "https://docs.x.com/x-api/activity/introduction" }, { - "name": "Post Lookup", - "path": "/tweets", + "id": "activity/list_subscriptions", + "name": "* List Activity Subscriptions", + "category": "activity", "method": "GET", - "auth": ["bearer", "oauth1", "oauth2-user"], - "folder": "posts", + "path": "/activity/subscriptions", + "auth": [ + "bearer" + ], "files": { - "python": "lookup.py", - "javascript": "lookup.js", - "ruby": "lookup.rb" + "python": "python/activity/list_subscriptions.py", + "javascript": "javascript/activity/list_subscriptions.js", + "java": "java/activity/ListSubscriptions.java", + "csharp": "csharp/activity/ListSubscriptions.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets" + "docs": "https://docs.x.com/x-api/activity/introduction" }, { - "name": "Recent Search", - "path": "/tweets/search/recent", + "id": "activity/stream_events", + "name": "* Activity Stream", + "category": "activity", "method": "GET", - "auth": ["bearer", "oauth2-user"], - "folder": "posts", + "path": "/activity/stream", + "auth": [ + "bearer" + ], "files": { - "python": "search_recent.py", - "javascript": "search_recent.js", - "ruby": "search_recent.rb", - "java": "SearchRecent.java" + "python": "python/activity/stream_events.py", + "javascript": "javascript/activity/stream_events.js", + "java": "java/activity/StreamEvents.java", + "csharp": "csharp/activity/StreamEvents.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent" + "docs": "https://docs.x.com/x-api/activity/introduction" }, { - "name": "Full Archive Search", - "path": "/tweets/search/all", + "id": "activity/update_subscription", + "name": "* Update Activity Subscription", + "category": "activity", + "method": "PUT", + "path": "/activity/subscriptions/:id", + "auth": [ + "bearer" + ], + "files": { + "python": "python/activity/update_subscription.py", + "javascript": "javascript/activity/update_subscription.js", + "java": "java/activity/UpdateSubscription.java", + "csharp": "csharp/activity/UpdateSubscription.cs" + }, + "docs": "https://docs.x.com/x-api/activity/introduction" + }, + { + "id": "compliance/create_jobs", + "name": "* Create Compliance Job", + "category": "compliance", + "method": "POST", + "path": "/compliance/jobs", + "auth": [ + "bearer" + ], + "files": { + "python": "python/compliance/create_jobs.py", + "javascript": "javascript/compliance/create_jobs.js", + "java": "java/compliance/CreateJobs.java", + "csharp": "csharp/compliance/CreateJobs.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/post-compliance-jobs" + }, + { + "id": "compliance/download_results", + "name": "* Download Compliance Results", + "category": "compliance", "method": "GET", - "auth": ["bearer"], - "folder": "posts", + "path": "", + "auth": [ + "bearer" + ], "files": { - "python": "search_full_archive.py" + "python": "python/compliance/download_results.py", + "javascript": "javascript/compliance/download_results.js", + "java": "java/compliance/DownloadResults.java", + "csharp": "csharp/compliance/DownloadResults.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-all", - "note": "Requires Academic Research access" + "docs": "https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/get-compliance-jobs-id" }, { - "name": "Recent Post Counts", - "path": "/tweets/counts/recent", + "id": "compliance/get_jobs", + "name": "* Get Compliance Jobs", + "category": "compliance", "method": "GET", - "auth": ["bearer"], - "folder": "posts", + "path": "/compliance/jobs", + "auth": [ + "bearer" + ], "files": { - "python": "counts_recent.py" + "python": "python/compliance/get_jobs.py", + "javascript": "javascript/compliance/get_jobs.js", + "java": "java/compliance/GetJobs.java", + "csharp": "csharp/compliance/GetJobs.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/counts/api-reference/get-tweets-counts-recent" + "docs": "https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/get-compliance-jobs" }, { - "name": "Quote Posts", - "path": "/tweets/:id/quote_tweets", + "id": "compliance/get_jobs_by_id", + "name": "* Get Compliance Job by ID", + "category": "compliance", "method": "GET", - "auth": ["bearer", "oauth2-user"], - "folder": "posts", + "path": "/compliance/jobs/:id", + "auth": [ + "bearer" + ], "files": { - "python": "quote_posts.py" + "python": "python/compliance/get_jobs_by_id.py", + "javascript": "javascript/compliance/get_jobs_by_id.js", + "java": "java/compliance/GetJobsById.java", + "csharp": "csharp/compliance/GetJobsById.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/quote-tweets/api-reference/get-tweets-id-quote_tweets" + "docs": "https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/get-compliance-jobs-id" }, { - "name": "Repost", - "path": "/users/:id/retweets", + "id": "compliance/upload_ids", + "name": "* Upload IDs for Compliance Job", + "category": "compliance", + "method": "PUT", + "path": "", + "auth": [ + "bearer" + ], + "files": { + "python": "python/compliance/upload_ids.py", + "javascript": "javascript/compliance/upload_ids.js", + "java": "java/compliance/UploadIds.java", + "csharp": "csharp/compliance/UploadIds.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/post-compliance-jobs" + }, + { + "id": "direct_messages/get_events_by_conversation", + "name": "* Get Events by Conversation ID", + "category": "direct_messages", + "method": "GET", + "path": "/dm_conversations/:dm_conversation_id/dm_events", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/direct_messages/get_events_by_conversation.py", + "javascript": "javascript/direct_messages/get_events_by_conversation.js", + "java": "java/direct_messages/GetEventsByConversation.java", + "csharp": "csharp/direct_messages/GetEventsByConversation.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-conversations-dm_conversation_id-dm_events" + }, + { + "id": "direct_messages/get_one_to_one_conversation_events", + "name": "* Get One-to-One Conversation Events", + "category": "direct_messages", + "method": "GET", + "path": "/dm_conversations/with/:participant_id/dm_events", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/direct_messages/get_one_to_one_conversation_events.py", + "javascript": "javascript/direct_messages/get_one_to_one_conversation_events.js", + "java": "java/direct_messages/GetOneToOneConversationEvents.java", + "csharp": "csharp/direct_messages/GetOneToOneConversationEvents.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-conversations-with-participant_id-dm_events" + }, + { + "id": "direct_messages/get_user_conversation_events", + "name": "* Get User Conversation Events", + "category": "direct_messages", + "method": "GET", + "path": "/dm_events", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/direct_messages/get_user_conversation_events.py", + "javascript": "javascript/direct_messages/get_user_conversation_events.js", + "java": "java/direct_messages/GetUserConversationEvents.java", + "csharp": "csharp/direct_messages/GetUserConversationEvents.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-events" + }, + { + "id": "direct_messages/post_dm_to_conversation", + "name": "* Post DM to Conversation", + "category": "direct_messages", "method": "POST", - "auth": ["oauth1", "oauth2-user"], - "folder": "posts", + "path": "/dm_conversations/:dm_conversation_id/messages", + "auth": [ + "oauth2-user" + ], "files": { - "python": "repost.py" + "python": "python/direct_messages/post_dm_to_conversation.py", + "javascript": "javascript/direct_messages/post_dm_to_conversation.js", + "java": "java/direct_messages/PostDmToConversation.java", + "csharp": "csharp/direct_messages/PostDmToConversation.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/post-users-id-retweets" + "docs": "https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations-dm_conversation_id-messages" }, { - "name": "Undo Repost", - "path": "/users/:id/retweets/:source_tweet_id", + "id": "direct_messages/post_group_conversation_dm", + "name": "* Post Group Conversation Direct Message", + "category": "direct_messages", + "method": "POST", + "path": "/dm_conversations", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/direct_messages/post_group_conversation_dm.py", + "javascript": "javascript/direct_messages/post_group_conversation_dm.js", + "java": "java/direct_messages/PostGroupConversationDm.java", + "csharp": "csharp/direct_messages/PostGroupConversationDm.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations" + }, + { + "id": "direct_messages/post_one_to_one_dm", + "name": "* Post One-to-One Direct Message", + "category": "direct_messages", + "method": "POST", + "path": "/dm_conversations/with/:participant_id/messages", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/direct_messages/post_one_to_one_dm.py", + "javascript": "javascript/direct_messages/post_one_to_one_dm.js", + "java": "java/direct_messages/PostOneToOneDm.java", + "csharp": "csharp/direct_messages/PostOneToOneDm.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations-with-participant_id-messages" + }, + { + "id": "lists/add_member", + "name": "* Add List Member", + "category": "lists", + "method": "POST", + "path": "/lists/:id/members", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/lists/add_member.py", + "javascript": "javascript/lists/add_member.js", + "java": "java/lists/AddMember.java", + "csharp": "csharp/lists/AddMember.cs", + "ruby": "ruby/lists/add_member.rb" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/lists/list-members/api-reference/post-lists-id-members" + }, + { + "id": "lists/create_list", + "name": "* Create List", + "category": "lists", + "method": "POST", + "path": "/lists", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/lists/create_list.py", + "javascript": "javascript/lists/create_list.js", + "java": "java/lists/CreateList.java", + "csharp": "csharp/lists/CreateList.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/post-lists" + }, + { + "id": "lists/delete_list", + "name": "* Delete List", + "category": "lists", "method": "DELETE", - "auth": ["oauth1", "oauth2-user"], - "folder": "posts", + "path": "/lists/:id", + "auth": [ + "oauth2-user" + ], "files": { - "python": "undo_repost.py" + "python": "python/lists/delete_list.py", + "javascript": "javascript/lists/delete_list.js", + "java": "java/lists/DeleteList.java", + "csharp": "csharp/lists/DeleteList.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/delete-users-id-retweets-tweet_id" + "docs": "https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/delete-lists-id" }, { - "name": "Reposted By", - "path": "/tweets/:id/retweeted_by", + "id": "lists/get_list_by_id", + "name": "* List Lookup by ID", + "category": "lists", "method": "GET", - "auth": ["bearer", "oauth2-user"], - "folder": "posts", + "path": "/lists/:id", + "auth": [ + "bearer" + ], "files": { - "python": "reposted_by.py" + "python": "python/lists/get_list_by_id.py", + "javascript": "javascript/lists/get_list_by_id.js", + "java": "java/lists/GetListById.java", + "csharp": "csharp/lists/GetListById.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/get-tweets-id-retweeted_by" + "docs": "https://developer.x.com/en/docs/twitter-api/lists/list-lookup/api-reference/get-lists-id" }, { - "name": "Like Post", - "path": "/users/:id/likes", + "id": "lists/get_list_followers", + "name": "* List Followers Lookup", + "category": "lists", + "method": "GET", + "path": "/lists/:id/followers", + "auth": [ + "bearer" + ], + "files": { + "python": "python/lists/get_list_followers.py", + "javascript": "javascript/lists/get_list_followers.js", + "java": "java/lists/GetListFollowers.java", + "csharp": "csharp/lists/GetListFollowers.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/lists/list-follows/api-reference/get-lists-id-followers" + }, + { + "id": "lists/get_list_members", + "name": "* List Members Lookup", + "category": "lists", + "method": "GET", + "path": "/lists/:id/members", + "auth": [ + "bearer" + ], + "files": { + "python": "python/lists/get_list_members.py", + "javascript": "javascript/lists/get_list_members.js", + "java": "java/lists/GetListMembers.java", + "csharp": "csharp/lists/GetListMembers.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/lists/list-members/api-reference/get-lists-id-members" + }, + { + "id": "lists/get_list_posts", + "name": "* List Posts", + "category": "lists", + "method": "GET", + "path": "/lists/:id/tweets", + "auth": [ + "bearer" + ], + "files": { + "python": "python/lists/get_list_posts.py", + "javascript": "javascript/lists/get_list_posts.js", + "java": "java/lists/GetListPosts.java", + "csharp": "csharp/lists/GetListPosts.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/lists/list-tweets/api-reference/get-lists-id-tweets" + }, + { + "id": "lists/remove_member", + "name": "* Remove List Member", + "category": "lists", + "method": "DELETE", + "path": "/lists/:id/members/:user_id", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/lists/remove_member.py", + "javascript": "javascript/lists/remove_member.js", + "java": "java/lists/RemoveMember.java", + "csharp": "csharp/lists/RemoveMember.cs", + "ruby": "ruby/lists/remove_member.rb" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/lists/list-members/api-reference/delete-lists-id-members-user_id" + }, + { + "id": "lists/update_list", + "name": "* Update List", + "category": "lists", + "method": "PUT", + "path": "/lists/:id", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/lists/update_list.py", + "javascript": "javascript/lists/update_list.js", + "java": "java/lists/UpdateList.java", + "csharp": "csharp/lists/UpdateList.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/put-lists-id" + }, + { + "id": "media/media_upload_v2", + "name": "* Media Upload v2 (Chunked Video Upload)", + "category": "media", "method": "POST", - "auth": ["oauth1", "oauth2-user"], - "folder": "posts", + "path": "/media/upload/initialize", + "auth": [ + "oauth2-user" + ], "files": { - "python": "like.py" + "python": "python/media/media_upload_v2.py", + "javascript": "javascript/media/media_upload_v2.js", + "java": "java/media/MediaUploadV2.java", + "csharp": "csharp/media/MediaUploadV2.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/post-users-id-likes" + "docs": "https://developer.x.com/en/docs/twitter-api/media/upload-media/api-reference" }, { - "name": "Unlike Post", - "path": "/users/:id/likes/:tweet_id", + "id": "media/upload", + "name": "* Media Upload (Single Payload)", + "category": "media", + "method": "POST", + "path": "/media/upload", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/media/upload.py", + "javascript": "javascript/media/upload.js", + "java": "java/media/Upload.java", + "csharp": "csharp/media/Upload.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/media/upload-media/api-reference" + }, + { + "id": "posts/create_post", + "name": "* Create Post", + "category": "posts", + "method": "POST", + "path": "/tweets", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/posts/create_post.py", + "javascript": "javascript/posts/create_post.js", + "java": "java/posts/CreatePost.java", + "csharp": "csharp/posts/CreatePost.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets" + }, + { + "id": "posts/delete_post", + "name": "* Delete Post", + "category": "posts", "method": "DELETE", - "auth": ["oauth1", "oauth2-user"], - "folder": "posts", + "path": "/tweets/:id", + "auth": [ + "oauth2-user" + ], "files": { - "python": "unlike.py" + "python": "python/posts/delete_post.py", + "javascript": "javascript/posts/delete_post.js", + "java": "java/posts/DeletePost.java", + "csharp": "csharp/posts/DeletePost.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/delete-users-id-likes-tweet_id" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/delete-tweets-id" }, { - "name": "Liking Users", - "path": "/tweets/:id/liking_users", + "id": "posts/get_liking_users", + "name": "* Liking Users", + "category": "posts", "method": "GET", - "auth": ["bearer", "oauth2-user"], - "folder": "posts", + "path": "/tweets/:id/liking_users", + "auth": [ + "oauth2-user" + ], "files": { - "python": "liking_users.py" + "python": "python/posts/get_liking_users.py", + "javascript": "javascript/posts/get_liking_users.js", + "java": "java/posts/GetLikingUsers.java", + "csharp": "csharp/posts/GetLikingUsers.cs" }, "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", + "id": "posts/get_post_by_id", + "name": "* Single Post Lookup", + "category": "posts", "method": "GET", - "auth": ["bearer", "oauth2-user"], - "folder": "posts", + "path": "/tweets/:id", + "auth": [ + "bearer" + ], "files": { - "python": "liked_posts.py" + "python": "python/posts/get_post_by_id.py", + "javascript": "javascript/posts/get_post_by_id.js", + "java": "java/posts/GetPostById.java", + "csharp": "csharp/posts/GetPostById.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/get-users-id-liked_tweets" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets-id" }, { - "name": "User Lookup", - "path": "/users/by", + "id": "posts/get_post_counts_all", + "name": "* Full-Archive Post Counts", + "category": "posts", "method": "GET", - "auth": ["bearer", "oauth1", "oauth2-user"], - "folder": "users", + "path": "/tweets/counts/all", + "auth": [ + "bearer" + ], "files": { - "python": "lookup.py", - "javascript": "lookup.js", - "ruby": "lookup.rb", - "java": "Lookup.java" + "python": "python/posts/get_post_counts_all.py", + "javascript": "javascript/posts/get_post_counts_all.js", + "java": "java/posts/GetPostCountsAll.java", + "csharp": "csharp/posts/GetPostCountsAll.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-by" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/counts/api-reference/get-tweets-counts-all" }, { - "name": "Authenticated User (Me)", - "path": "/users/me", + "id": "posts/get_post_counts_recent", + "name": "* Recent Post Counts", + "category": "posts", "method": "GET", - "auth": ["oauth1", "oauth2-user"], - "folder": "users", + "path": "/tweets/counts/recent", + "auth": [ + "bearer" + ], "files": { - "python": "me.py" + "python": "python/posts/get_post_counts_recent.py", + "javascript": "javascript/posts/get_post_counts_recent.js", + "java": "java/posts/GetPostCountsRecent.java", + "csharp": "csharp/posts/GetPostCountsRecent.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-me" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/counts/api-reference/get-tweets-counts-recent" }, { - "name": "User Followers", - "path": "/users/:id/followers", + "id": "posts/get_posts_by_ids", + "name": "* Post Lookup by IDs", + "category": "posts", "method": "GET", - "auth": ["bearer", "oauth2-user"], - "folder": "users", + "path": "/tweets", + "auth": [ + "bearer" + ], "files": { - "python": "followers.py", - "javascript": "followers.js", - "ruby": "followers.rb" + "python": "python/posts/get_posts_by_ids.py", + "javascript": "javascript/posts/get_posts_by_ids.js", + "java": "java/posts/GetPostsByIds.java", + "csharp": "csharp/posts/GetPostsByIds.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/get-users-id-followers" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets" }, { - "name": "User Following", - "path": "/users/:id/following", + "id": "posts/get_quoted_posts", + "name": "* Quote Posts Lookup", + "category": "posts", "method": "GET", - "auth": ["bearer", "oauth2-user"], - "folder": "users", + "path": "/tweets/:id/quote_tweets", + "auth": [ + "bearer" + ], "files": { - "python": "following.py" + "python": "python/posts/get_quoted_posts.py", + "javascript": "javascript/posts/get_quoted_posts.js", + "java": "java/posts/GetQuotedPosts.java", + "csharp": "csharp/posts/GetQuotedPosts.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/get-users-id-following" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/quote-tweets/api-reference/get-tweets-id-quote_tweets" }, { - "name": "Block User", - "path": "/users/:id/blocking", - "method": "POST", - "auth": ["oauth1", "oauth2-user"], - "folder": "users", + "id": "posts/get_reposted_by", + "name": "* Reposted By (Users who reposted)", + "category": "posts", + "method": "GET", + "path": "/tweets/:id/retweeted_by", + "auth": [ + "bearer" + ], "files": { - "python": "block.py" + "python": "python/posts/get_reposted_by.py", + "javascript": "javascript/posts/get_reposted_by.js", + "java": "java/posts/GetRepostedBy.java", + "csharp": "csharp/posts/GetRepostedBy.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/users/blocks/api-reference/post-users-user_id-blocking" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/get-tweets-id-retweeted_by" }, { - "name": "Unblock User", - "path": "/users/:source_user_id/blocking/:target_user_id", - "method": "DELETE", - "auth": ["oauth1", "oauth2-user"], - "folder": "users", + "id": "posts/hide_reply", + "name": "* Hide Reply", + "category": "posts", + "method": "PUT", + "path": "/tweets/:id/hidden", + "auth": [ + "oauth2-user" + ], "files": { - "python": "unblock.py" + "python": "python/posts/hide_reply.py", + "javascript": "javascript/posts/hide_reply.js", + "java": "java/posts/HideReply.java", + "csharp": "csharp/posts/HideReply.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/users/blocks/api-reference/delete-users-user_id-blocking" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/hide-replies/api-reference/put-tweets-id-hidden" }, { - "name": "Blocked Users", - "path": "/users/:id/blocking", + "id": "posts/search_all", + "name": "* Full-Archive Search", + "category": "posts", + "method": "GET", + "path": "/tweets/search/all", + "auth": [ + "bearer" + ], + "files": { + "python": "python/posts/search_all.py", + "javascript": "javascript/posts/search_all.js", + "java": "java/posts/SearchAll.java", + "csharp": "csharp/posts/SearchAll.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-all" + }, + { + "id": "posts/search_recent", + "name": "* Recent Search", + "category": "posts", + "method": "GET", + "path": "/tweets/search/recent", + "auth": [ + "bearer" + ], + "files": { + "python": "python/posts/search_recent.py", + "javascript": "javascript/posts/search_recent.js", + "java": "java/posts/SearchRecent.java", + "csharp": "csharp/posts/SearchRecent.cs", + "ruby": "ruby/posts/search_recent.rb" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent" + }, + { + "id": "spaces/get_spaces_by_ids", + "name": "* Spaces Lookup by IDs", + "category": "spaces", + "method": "GET", + "path": "/spaces", + "auth": [ + "bearer" + ], + "files": { + "python": "python/spaces/get_spaces_by_ids.py", + "javascript": "javascript/spaces/get_spaces_by_ids.js", + "java": "java/spaces/GetSpacesByIds.java", + "csharp": "csharp/spaces/GetSpacesByIds.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/spaces/lookup/api-reference/get-spaces" + }, + { + "id": "spaces/search_spaces", + "name": "* Search Spaces", + "category": "spaces", "method": "GET", - "auth": ["oauth1", "oauth2-user"], - "folder": "users", + "path": "/spaces/search", + "auth": [ + "bearer" + ], + "files": { + "python": "python/spaces/search_spaces.py", + "javascript": "javascript/spaces/search_spaces.js", + "java": "java/spaces/SearchSpaces.java", + "csharp": "csharp/spaces/SearchSpaces.cs", + "ruby": "ruby/spaces/search_spaces.rb" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/spaces/search/api-reference/get-spaces-search" + }, + { + "id": "streams/stream_posts_filtered", + "name": "* Filtered Stream", + "category": "streams", + "method": "GET", + "path": "/tweets/search/stream", + "auth": [ + "bearer" + ], + "files": { + "python": "python/streams/stream_posts_filtered.py", + "javascript": "javascript/streams/stream_posts_filtered.js", + "java": "java/streams/StreamPostsFiltered.java", + "csharp": "csharp/streams/StreamPostsFiltered.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/filtered-stream/api-reference/get-tweets-search-stream" + }, + { + "id": "streams/stream_posts_sample", + "name": "* Sampled Stream (1% Volume)", + "category": "streams", + "method": "GET", + "path": "/tweets/sample/stream", + "auth": [ + "bearer" + ], + "files": { + "python": "python/streams/stream_posts_sample.py", + "javascript": "javascript/streams/stream_posts_sample.js", + "java": "java/streams/StreamPostsSample.java", + "csharp": "csharp/streams/StreamPostsSample.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/volume-streams/api-reference/get-tweets-sample-stream" + }, + { + "id": "usage/get_usage", + "name": "* Usage Posts", + "category": "usage", + "method": "GET", + "path": "/usage/tweets", + "auth": [ + "bearer" + ], "files": { - "python": "blocked.py" + "python": "python/usage/get_usage.py", + "javascript": "javascript/usage/get_usage.js", + "java": "java/usage/GetUsage.java", + "csharp": "csharp/usage/GetUsage.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/usage/api-reference/get-usage-tweets" + }, + { + "id": "users/block/get_blocking", + "name": "* Blocked Users Lookup", + "category": "users", + "method": "GET", + "path": "/users/:id/blocking", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/users/block/get_blocking.py", + "javascript": "javascript/users/block/get_blocking.js", + "java": "java/users/block/GetBlocking.java", + "csharp": "csharp/users/block/GetBlocking.cs" }, "docs": "https://developer.x.com/en/docs/twitter-api/users/blocks/api-reference/get-users-blocking" }, { - "name": "Mute User", - "path": "/users/:id/muting", + "id": "users/bookmark/create_bookmark", + "name": "* Create Bookmark", + "category": "users", "method": "POST", - "auth": ["oauth1", "oauth2-user"], - "folder": "users", + "path": "/users/:id/bookmarks", + "auth": [ + "oauth2-user" + ], "files": { - "python": "mute.py" + "python": "python/users/bookmark/create_bookmark.py", + "javascript": "javascript/users/bookmark/create_bookmark.js", + "java": "java/users/bookmark/CreateBookmark.java", + "csharp": "csharp/users/bookmark/CreateBookmark.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/post-users-user_id-muting" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/post-users-id-bookmarks" }, { - "name": "Unmute User", - "path": "/users/:source_user_id/muting/:target_user_id", + "id": "users/bookmark/delete_bookmark", + "name": "* Delete Bookmark", + "category": "users", "method": "DELETE", - "auth": ["oauth1", "oauth2-user"], - "folder": "users", + "path": "/users/:id/bookmarks/:tweet_id", + "auth": [ + "oauth2-user" + ], "files": { - "python": "unmute.py" + "python": "python/users/bookmark/delete_bookmark.py", + "javascript": "javascript/users/bookmark/delete_bookmark.js", + "java": "java/users/bookmark/DeleteBookmark.java", + "csharp": "csharp/users/bookmark/DeleteBookmark.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/delete-users-user_id-muting" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/delete-users-id-bookmarks-tweet_id" }, { - "name": "Muted Users", - "path": "/users/:id/muting", + "id": "users/bookmark/get_bookmarks", + "name": "* Bookmarks Lookup", + "category": "users", "method": "GET", - "auth": ["oauth1", "oauth2-user"], - "folder": "users", + "path": "/users/:id/bookmarks", + "auth": [ + "oauth2-user" + ], "files": { - "python": "muted.py" + "python": "python/users/bookmark/get_bookmarks.py", + "javascript": "javascript/users/bookmark/get_bookmarks.js", + "java": "java/users/bookmark/GetBookmarks.java", + "csharp": "csharp/users/bookmark/GetBookmarks.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/get-users-muting" + "docs": "https://developer.x.com/en/docs/twitter-api/bookmarks/api-reference/get-users-id-bookmarks" }, { - "name": "User Posts Timeline", - "path": "/users/:id/tweets", + "id": "users/follow/follow_user", + "name": "* Follow User", + "category": "users", + "method": "POST", + "path": "/users/:id/following", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/users/follow/follow_user.py", + "javascript": "javascript/users/follow/follow_user.js", + "java": "java/users/follow/FollowUser.java", + "csharp": "csharp/users/follow/FollowUser.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/post-users-id-following" + }, + { + "id": "users/follow/get_followers", + "name": "* User Followers Lookup", + "category": "users", "method": "GET", - "auth": ["bearer", "oauth2-user"], - "folder": "timelines", + "path": "/users/:id/followers", + "auth": [ + "bearer" + ], "files": { - "python": "user_posts.py", - "javascript": "user_posts.js", - "ruby": "user_posts.rb" + "python": "python/users/follow/get_followers.py", + "javascript": "javascript/users/follow/get_followers.js", + "java": "java/users/follow/GetFollowers.java", + "csharp": "csharp/users/follow/GetFollowers.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-tweets" + "docs": "https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/get-users-id-followers" }, { - "name": "User Mentions Timeline", - "path": "/users/:id/mentions", + "id": "users/follow/get_following", + "name": "* User Following Lookup", + "category": "users", "method": "GET", - "auth": ["bearer", "oauth2-user"], - "folder": "timelines", + "path": "/users/:id/following", + "auth": [ + "bearer" + ], "files": { - "python": "user_mentions.py" + "python": "python/users/follow/get_following.py", + "javascript": "javascript/users/follow/get_following.js", + "java": "java/users/follow/GetFollowing.java", + "csharp": "csharp/users/follow/GetFollowing.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-mentions" + "docs": "https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/get-users-id-following" + }, + { + "id": "users/follow/unfollow_user", + "name": "* Unfollow User", + "category": "users", + "method": "DELETE", + "path": "/users/:source_user_id/following/:target_user_id", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/users/follow/unfollow_user.py", + "javascript": "javascript/users/follow/unfollow_user.js", + "java": "java/users/follow/UnfollowUser.java", + "csharp": "csharp/users/follow/UnfollowUser.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/delete-users-source_user_id-following" }, { - "name": "Home Timeline", - "path": "/users/:id/reverse_chronological_timeline", + "id": "users/get_users_by_usernames", + "name": "* User Lookup by Usernames", + "category": "users", "method": "GET", - "auth": ["oauth1", "oauth2-user"], - "folder": "timelines", + "path": "/users/by", + "auth": [ + "bearer" + ], "files": { - "python": "home_timeline.py" + "python": "python/users/get_users_by_usernames.py", + "javascript": "javascript/users/get_users_by_usernames.js", + "java": "java/users/GetUsersByUsernames.java", + "csharp": "csharp/users/GetUsersByUsernames.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-reverse-chronological-timeline" + "docs": "https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-by" }, { - "name": "Filtered Stream", - "path": "/tweets/search/stream", + "id": "users/get_users_by_usernames_user_context", + "name": "* User Lookup (User Context)", + "category": "users", "method": "GET", - "auth": ["bearer"], - "folder": "streams", + "path": "/users/by", + "auth": [ + "oauth2-user" + ], "files": { - "python": "filtered_stream.py", - "javascript": "filtered_stream.js" + "python": "python/users/get_users_by_usernames_user_context.py", + "javascript": "javascript/users/get_users_by_usernames_user_context.js", + "java": "java/users/GetUsersByUsernamesUserContext.java", + "csharp": "csharp/users/GetUsersByUsernamesUserContext.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/filtered-stream/api-reference/get-tweets-search-stream" + "docs": "https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-by" }, { - "name": "Sampled Stream", - "path": "/tweets/sample/stream", + "id": "users/get_users_me", + "name": "* Authenticated User Lookup (Me)", + "category": "users", "method": "GET", - "auth": ["bearer"], - "folder": "streams", + "path": "/users/me", + "auth": [ + "oauth2-user" + ], "files": { - "python": "sampled_stream.py" + "python": "python/users/get_users_me.py", + "javascript": "javascript/users/get_users_me.js", + "java": "java/users/GetUsersMe.java", + "csharp": "csharp/users/GetUsersMe.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/volume-streams/api-reference/get-tweets-sample-stream" + "docs": "https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-me" }, { - "name": "Bookmarks Lookup", - "path": "/users/:id/bookmarks", + "id": "users/like/get_liked_posts", + "name": "* Liked Posts", + "category": "users", "method": "GET", - "auth": ["oauth2-user"], - "folder": "bookmarks", + "path": "/users/:id/liked_tweets", + "auth": [ + "oauth2-user" + ], "files": { - "python": "lookup.py" + "python": "python/users/like/get_liked_posts.py", + "javascript": "javascript/users/like/get_liked_posts.js", + "java": "java/users/like/GetLikedPosts.java", + "csharp": "csharp/users/like/GetLikedPosts.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/get-users-id-bookmarks" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/get-users-id-liked_tweets" }, { - "name": "Create Bookmark", - "path": "/users/:id/bookmarks", + "id": "users/like/like_post", + "name": "* Like a Post", + "category": "users", "method": "POST", - "auth": ["oauth2-user"], - "folder": "bookmarks", + "path": "/users/:id/likes", + "auth": [ + "oauth2-user" + ], "files": { - "python": "create.py" + "python": "python/users/like/like_post.py", + "javascript": "javascript/users/like/like_post.js", + "java": "java/users/like/LikePost.java", + "csharp": "csharp/users/like/LikePost.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/post-users-id-bookmarks" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/post-users-id-likes" }, { - "name": "Delete Bookmark", - "path": "/users/:id/bookmarks/:tweet_id", + "id": "users/like/unlike_post", + "name": "* Unlike a Post", + "category": "users", "method": "DELETE", - "auth": ["oauth2-user"], - "folder": "bookmarks", + "path": "/users/:id/likes/:tweet_id", + "auth": [ + "oauth2-user" + ], "files": { - "python": "delete.py" + "python": "python/users/like/unlike_post.py", + "javascript": "javascript/users/like/unlike_post.js", + "java": "java/users/like/UnlikePost.java", + "csharp": "csharp/users/like/UnlikePost.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/delete-users-id-bookmarks-tweet_id" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/delete-users-id-likes-tweet_id" }, { - "name": "Spaces Lookup", - "path": "/spaces", + "id": "users/lists/follow_list", + "name": "* Follow List", + "category": "users", + "method": "POST", + "path": "/users/:id/followed_lists", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/users/lists/follow_list.py", + "javascript": "javascript/users/lists/follow_list.js", + "java": "java/users/lists/FollowList.java", + "csharp": "csharp/users/lists/FollowList.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/lists/list-follows/api-reference/post-users-id-followed_lists" + }, + { + "id": "users/lists/get_followed_lists", + "name": "* User Followed Lists Lookup", + "category": "users", "method": "GET", - "auth": ["bearer", "oauth2-user"], - "folder": "spaces", + "path": "/users/:id/followed_lists", + "auth": [ + "bearer" + ], "files": { - "python": "lookup.py", - "javascript": "lookup.js" + "python": "python/users/lists/get_followed_lists.py", + "javascript": "javascript/users/lists/get_followed_lists.js", + "java": "java/users/lists/GetFollowedLists.java", + "csharp": "csharp/users/lists/GetFollowedLists.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/spaces/lookup/api-reference/get-spaces" + "docs": "https://developer.x.com/en/docs/twitter-api/lists/list-follows/api-reference/get-users-id-followed_lists" }, { - "name": "Spaces Search", - "path": "/spaces/search", + "id": "users/lists/get_list_memberships", + "name": "* User List Memberships Lookup", + "category": "users", "method": "GET", - "auth": ["bearer", "oauth2-user"], - "folder": "spaces", + "path": "/users/:id/list_memberships", + "auth": [ + "bearer" + ], "files": { - "python": "search.py" + "python": "python/users/lists/get_list_memberships.py", + "javascript": "javascript/users/lists/get_list_memberships.js", + "java": "java/users/lists/GetListMemberships.java", + "csharp": "csharp/users/lists/GetListMemberships.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/spaces/search/api-reference/get-spaces-search" + "docs": "https://developer.x.com/en/docs/twitter-api/lists/list-members/api-reference/get-users-id-list_memberships" }, { - "name": "List Lookup", - "path": "/lists/:id", + "id": "users/lists/get_owned_lists", + "name": "* User Owned Lists Lookup", + "category": "users", "method": "GET", - "auth": ["bearer", "oauth2-user"], - "folder": "lists", + "path": "/users/:id/owned_lists", + "auth": [ + "bearer" + ], "files": { - "python": "lookup.py", - "javascript": "lookup.js", - "ruby": "lookup.rb" + "python": "python/users/lists/get_owned_lists.py", + "javascript": "javascript/users/lists/get_owned_lists.js", + "java": "java/users/lists/GetOwnedLists.java", + "csharp": "csharp/users/lists/GetOwnedLists.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/lists/list-lookup/api-reference/get-lists-id" + "docs": "https://developer.x.com/en/docs/twitter-api/lists/list-lookup/api-reference/get-users-id-owned_lists" }, { - "name": "Create List", - "path": "/lists", + "id": "users/lists/get_pinned_lists", + "name": "* Pinned Lists Lookup", + "category": "users", + "method": "GET", + "path": "/users/:id/pinned_lists", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/users/lists/get_pinned_lists.py", + "javascript": "javascript/users/lists/get_pinned_lists.js", + "java": "java/users/lists/GetPinnedLists.java", + "csharp": "csharp/users/lists/GetPinnedLists.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/lists/pinned-lists/api-reference/get-users-id-pinned_lists" + }, + { + "id": "users/lists/pin_list", + "name": "* Pin List", + "category": "users", "method": "POST", - "auth": ["oauth1", "oauth2-user"], - "folder": "lists", + "path": "/users/:id/pinned_lists", + "auth": [ + "oauth2-user" + ], "files": { - "python": "create.py" + "python": "python/users/lists/pin_list.py", + "javascript": "javascript/users/lists/pin_list.js", + "java": "java/users/lists/PinList.java", + "csharp": "csharp/users/lists/PinList.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/post-lists" + "docs": "https://developer.x.com/en/docs/twitter-api/lists/pinned-lists/api-reference/post-users-id-pinned_lists" }, { - "name": "Delete List", - "path": "/lists/:id", + "id": "users/lists/unfollow_list", + "name": "* Unfollow List", + "category": "users", "method": "DELETE", - "auth": ["oauth1", "oauth2-user"], - "folder": "lists", + "path": "/users/:id/followed_lists/:list_id", + "auth": [ + "oauth2-user" + ], "files": { - "python": "delete.py" + "python": "python/users/lists/unfollow_list.py", + "javascript": "javascript/users/lists/unfollow_list.js", + "java": "java/users/lists/UnfollowList.java", + "csharp": "csharp/users/lists/UnfollowList.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/delete-lists-id" + "docs": "https://developer.x.com/en/docs/twitter-api/lists/list-follows/api-reference/delete-users-id-followed_lists-list_id" }, { - "name": "DM Events Lookup", - "path": "/dm_events", + "id": "users/lists/unpin_list", + "name": "* Unpin List", + "category": "users", + "method": "DELETE", + "path": "/users/:id/pinned_lists/:list_id", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/users/lists/unpin_list.py", + "javascript": "javascript/users/lists/unpin_list.js", + "java": "java/users/lists/UnpinList.java", + "csharp": "csharp/users/lists/UnpinList.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/lists/pinned-lists/api-reference/delete-users-id-pinned_lists-list_id" + }, + { + "id": "users/mute/get_muting", + "name": "* Muted Users Lookup", + "category": "users", "method": "GET", - "auth": ["oauth1", "oauth2-user"], - "folder": "direct_messages", + "path": "/users/:id/muting", + "auth": [ + "oauth2-user" + ], "files": { - "python": "lookup.py" + "python": "python/users/mute/get_muting.py", + "javascript": "javascript/users/mute/get_muting.js", + "java": "java/users/mute/GetMuting.java", + "csharp": "csharp/users/mute/GetMuting.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-events" + "docs": "https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/get-users-muting" }, { - "name": "Send DM", - "path": "/dm_conversations/with/:participant_id/messages", + "id": "users/mute/mute_user", + "name": "* Mute User", + "category": "users", "method": "POST", - "auth": ["oauth1", "oauth2-user"], - "folder": "direct_messages", + "path": "/users/:id/muting", + "auth": [ + "oauth2-user" + ], "files": { - "python": "send.py" + "python": "python/users/mute/mute_user.py", + "javascript": "javascript/users/mute/mute_user.js", + "java": "java/users/mute/MuteUser.java", + "csharp": "csharp/users/mute/MuteUser.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations-with-participant_id-messages" + "docs": "https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/post-users-user_id-muting" }, { - "name": "Create Compliance Job", - "path": "/compliance/jobs", + "id": "users/mute/unmute_user", + "name": "* Unmute User", + "category": "users", + "method": "DELETE", + "path": "/users/:source_user_id/muting/:target_user_id", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/users/mute/unmute_user.py", + "javascript": "javascript/users/mute/unmute_user.js", + "java": "java/users/mute/UnmuteUser.java", + "csharp": "csharp/users/mute/UnmuteUser.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/delete-users-user_id-muting" + }, + { + "id": "users/repost/get_reposts_of_me", + "name": "* Reposts of Me", + "category": "users", + "method": "GET", + "path": "/users/reposts_of_me", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/users/repost/get_reposts_of_me.py", + "javascript": "javascript/users/repost/get_reposts_of_me.js", + "java": "java/users/repost/GetRepostsOfMe.java", + "csharp": "csharp/users/repost/GetRepostsOfMe.cs" + }, + "docs": "https://docs.x.com/x-api/users/get-reposts-of-me" + }, + { + "id": "users/repost/repost_post", + "name": "* Repost a Post", + "category": "users", "method": "POST", - "auth": ["bearer"], - "folder": "compliance", + "path": "/users/:id/retweets", + "auth": [ + "oauth2-user" + ], "files": { - "python": "create_job.py" + "python": "python/users/repost/repost_post.py", + "javascript": "javascript/users/repost/repost_post.js", + "java": "java/users/repost/RepostPost.java", + "csharp": "csharp/users/repost/RepostPost.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/post-compliance-jobs" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/post-users-id-retweets" }, { - "name": "Get Compliance Jobs", - "path": "/compliance/jobs", + "id": "users/repost/unrepost_post", + "name": "* Undo Repost", + "category": "users", + "method": "DELETE", + "path": "/users/:id/retweets/:source_tweet_id", + "auth": [ + "oauth2-user" + ], + "files": { + "python": "python/users/repost/unrepost_post.py", + "javascript": "javascript/users/repost/unrepost_post.js", + "java": "java/users/repost/UnrepostPost.java", + "csharp": "csharp/users/repost/UnrepostPost.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/delete-users-id-retweets-tweet_id" + }, + { + "id": "users/timeline/get_home_timeline", + "name": "* Reverse Chronological Home Timeline", + "category": "users", "method": "GET", - "auth": ["bearer"], - "folder": "compliance", + "path": "/users/:id/timelines/reverse_chronological", + "auth": [ + "oauth2-user" + ], "files": { - "python": "get_jobs.py" + "python": "python/users/timeline/get_home_timeline.py", + "javascript": "javascript/users/timeline/get_home_timeline.js", + "java": "java/users/timeline/GetHomeTimeline.java", + "csharp": "csharp/users/timeline/GetHomeTimeline.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/get-compliance-jobs" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-reverse-chronological-timeline" }, { - "name": "API Usage", - "path": "/usage/tweets", + "id": "users/timeline/get_mentions", + "name": "* User Mentions Timeline", + "category": "users", "method": "GET", - "auth": ["bearer"], - "folder": "usage", + "path": "/users/:id/mentions", + "auth": [ + "bearer" + ], "files": { - "python": "get_usage.py" + "python": "python/users/timeline/get_mentions.py", + "javascript": "javascript/users/timeline/get_mentions.js", + "java": "java/users/timeline/GetMentions.java", + "csharp": "csharp/users/timeline/GetMentions.cs" }, - "docs": "https://developer.x.com/en/docs/twitter-api/usage/api-reference/get-usage-tweets" + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-mentions" + }, + { + "id": "users/timeline/get_posts", + "name": "* User Posts Timeline", + "category": "users", + "method": "GET", + "path": "/users/:id/tweets", + "auth": [ + "bearer" + ], + "files": { + "python": "python/users/timeline/get_posts.py", + "javascript": "javascript/users/timeline/get_posts.js", + "java": "java/users/timeline/GetPosts.java", + "csharp": "csharp/users/timeline/GetPosts.cs" + }, + "docs": "https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-tweets" + }, + { + "id": "webhooks/delete_webhook", + "name": "* Delete Webhook", + "category": "webhooks", + "method": "DELETE", + "path": "/webhooks/:webhook_id", + "auth": [ + "bearer" + ], + "files": { + "python": "python/webhooks/delete_webhook.py", + "javascript": "javascript/webhooks/delete_webhook.js", + "java": "java/webhooks/DeleteWebhook.java", + "csharp": "csharp/webhooks/DeleteWebhook.cs" + }, + "docs": "https://docs.x.com/x-api/webhooks/introduction" + }, + { + "id": "webhooks/list_webhooks", + "name": "* List Webhooks", + "category": "webhooks", + "method": "GET", + "path": "/webhooks", + "auth": [ + "bearer" + ], + "files": { + "python": "python/webhooks/list_webhooks.py", + "javascript": "javascript/webhooks/list_webhooks.js", + "java": "java/webhooks/ListWebhooks.java", + "csharp": "csharp/webhooks/ListWebhooks.cs" + }, + "docs": "https://docs.x.com/x-api/webhooks/introduction" + }, + { + "id": "webhooks/register_webhook", + "name": "* Register Webhook", + "category": "webhooks", + "method": "POST", + "path": "/webhooks", + "auth": [ + "bearer" + ], + "files": { + "python": "python/webhooks/register_webhook.py", + "javascript": "javascript/webhooks/register_webhook.js", + "java": "java/webhooks/RegisterWebhook.java", + "csharp": "csharp/webhooks/RegisterWebhook.cs" + }, + "docs": "https://docs.x.com/x-api/webhooks/introduction" + }, + { + "id": "webhooks/validate_webhook", + "name": "* Validate Webhook (Trigger CRC)", + "category": "webhooks", + "method": "PUT", + "path": "/webhooks/:webhook_id", + "auth": [ + "bearer" + ], + "files": { + "python": "python/webhooks/validate_webhook.py", + "javascript": "javascript/webhooks/validate_webhook.js", + "java": "java/webhooks/ValidateWebhook.java", + "csharp": "csharp/webhooks/ValidateWebhook.cs" + }, + "docs": "https://docs.x.com/x-api/webhooks/introduction" + }, + { + "id": "webhooks/webhook_server", + "name": "* Webhook Server (CRC + Event Delivery)", + "category": "webhooks", + "method": "GET", + "path": "", + "auth": [ + "hmac-sha256" + ], + "files": { + "python": "python/webhooks/webhook_server.py", + "javascript": "javascript/webhooks/webhook_server.js", + "java": "java/webhooks/WebhookServer.java", + "csharp": "csharp/webhooks/WebhookServer.cs" + }, + "docs": "https://docs.x.com/x-api/webhooks/introduction" } ] } diff --git a/csharp/Program.cs b/csharp/Program.cs new file mode 100644 index 0000000..5b6cdfe --- /dev/null +++ b/csharp/Program.cs @@ -0,0 +1,117 @@ +public static class SamplesRunner +{ + private static readonly Dictionary Action)> Registry = + new(StringComparer.OrdinalIgnoreCase) + { + ["activity/create_subscription"] = ("Create Activity Subscription", Samples.Activity.CreateSubscription.RunAsync), + ["activity/delete_subscription"] = ("Delete Activity Subscription", Samples.Activity.DeleteSubscription.RunAsync), + ["activity/list_subscriptions"] = ("List Activity Subscriptions", Samples.Activity.ListSubscriptions.RunAsync), + ["activity/stream_events"] = ("Activity Stream", Samples.Activity.StreamEvents.RunAsync), + ["activity/update_subscription"] = ("Update Activity Subscription", Samples.Activity.UpdateSubscription.RunAsync), + ["compliance/create_jobs"] = ("Create Compliance Job", Samples.Compliance.CreateJobs.RunAsync), + ["compliance/download_results"] = ("Download Compliance Results", Samples.Compliance.DownloadResults.RunAsync), + ["compliance/get_jobs"] = ("Get Compliance Jobs", Samples.Compliance.GetJobs.RunAsync), + ["compliance/get_jobs_by_id"] = ("Get Compliance Job by ID", Samples.Compliance.GetJobsById.RunAsync), + ["compliance/upload_ids"] = ("Upload IDs for Compliance Job", Samples.Compliance.UploadIds.RunAsync), + ["direct_messages/get_events_by_conversation"] = ("Get Events by Conversation ID", Samples.DirectMessages.GetEventsByConversation.RunAsync), + ["direct_messages/get_one_to_one_conversation_events"] = ("Get One-to-One Conversation Events", Samples.DirectMessages.GetOneToOneConversationEvents.RunAsync), + ["direct_messages/get_user_conversation_events"] = ("Get User Conversation Events", Samples.DirectMessages.GetUserConversationEvents.RunAsync), + ["direct_messages/post_dm_to_conversation"] = ("Post DM to Conversation", Samples.DirectMessages.PostDmToConversation.RunAsync), + ["direct_messages/post_group_conversation_dm"] = ("Post Group Conversation Direct Message", Samples.DirectMessages.PostGroupConversationDm.RunAsync), + ["direct_messages/post_one_to_one_dm"] = ("Post One-to-One Direct Message", Samples.DirectMessages.PostOneToOneDm.RunAsync), + ["lists/add_member"] = ("Add List Member", Samples.Lists.AddMember.RunAsync), + ["lists/create_list"] = ("Create List", Samples.Lists.CreateList.RunAsync), + ["lists/delete_list"] = ("Delete List", Samples.Lists.DeleteList.RunAsync), + ["lists/get_list_by_id"] = ("List Lookup by ID", Samples.Lists.GetListById.RunAsync), + ["lists/get_list_followers"] = ("List Followers Lookup", Samples.Lists.GetListFollowers.RunAsync), + ["lists/get_list_members"] = ("List Members Lookup", Samples.Lists.GetListMembers.RunAsync), + ["lists/get_list_posts"] = ("List Posts", Samples.Lists.GetListPosts.RunAsync), + ["lists/remove_member"] = ("Remove List Member", Samples.Lists.RemoveMember.RunAsync), + ["lists/update_list"] = ("Update List", Samples.Lists.UpdateList.RunAsync), + ["media/media_upload_v2"] = ("Media Upload v2 (Chunked Video Upload)", Samples.Media.MediaUploadV2.RunAsync), + ["media/upload"] = ("Media Upload (Single Payload)", Samples.Media.Upload.RunAsync), + ["posts/create_post"] = ("Create Post", Samples.Posts.CreatePost.RunAsync), + ["posts/delete_post"] = ("Delete Post", Samples.Posts.DeletePost.RunAsync), + ["posts/get_liking_users"] = ("Liking Users", Samples.Posts.GetLikingUsers.RunAsync), + ["posts/get_post_by_id"] = ("Single Post Lookup", Samples.Posts.GetPostById.RunAsync), + ["posts/get_post_counts_all"] = ("Full-Archive Post Counts", Samples.Posts.GetPostCountsAll.RunAsync), + ["posts/get_post_counts_recent"] = ("Recent Post Counts", Samples.Posts.GetPostCountsRecent.RunAsync), + ["posts/get_posts_by_ids"] = ("Post Lookup by IDs", Samples.Posts.GetPostsByIds.RunAsync), + ["posts/get_quoted_posts"] = ("Quote Posts Lookup", Samples.Posts.GetQuotedPosts.RunAsync), + ["posts/get_reposted_by"] = ("Reposted By (Users who reposted)", Samples.Posts.GetRepostedBy.RunAsync), + ["posts/hide_reply"] = ("Hide Reply", Samples.Posts.HideReply.RunAsync), + ["posts/search_all"] = ("Full-Archive Search", Samples.Posts.SearchAll.RunAsync), + ["posts/search_recent"] = ("Recent Search", Samples.Posts.SearchRecent.RunAsync), + ["spaces/get_spaces_by_ids"] = ("Spaces Lookup by IDs", Samples.Spaces.GetSpacesByIds.RunAsync), + ["spaces/search_spaces"] = ("Search Spaces", Samples.Spaces.SearchSpaces.RunAsync), + ["streams/stream_posts_filtered"] = ("Filtered Stream", Samples.Streams.StreamPostsFiltered.RunAsync), + ["streams/stream_posts_sample"] = ("Sampled Stream (1% Volume)", Samples.Streams.StreamPostsSample.RunAsync), + ["usage/get_usage"] = ("Usage Posts", Samples.Usage.GetUsage.RunAsync), + ["users/block/get_blocking"] = ("Blocked Users Lookup", Samples.Users.Block.GetBlocking.RunAsync), + ["users/bookmark/create_bookmark"] = ("Create Bookmark", Samples.Users.Bookmark.CreateBookmark.RunAsync), + ["users/bookmark/delete_bookmark"] = ("Delete Bookmark", Samples.Users.Bookmark.DeleteBookmark.RunAsync), + ["users/bookmark/get_bookmarks"] = ("Bookmarks Lookup", Samples.Users.Bookmark.GetBookmarks.RunAsync), + ["users/follow/follow_user"] = ("Follow User", Samples.Users.Follow.FollowUser.RunAsync), + ["users/follow/get_followers"] = ("User Followers Lookup", Samples.Users.Follow.GetFollowers.RunAsync), + ["users/follow/get_following"] = ("User Following Lookup", Samples.Users.Follow.GetFollowing.RunAsync), + ["users/follow/unfollow_user"] = ("Unfollow User", Samples.Users.Follow.UnfollowUser.RunAsync), + ["users/get_users_by_usernames"] = ("User Lookup by Usernames", Samples.Users.GetUsersByUsernames.RunAsync), + ["users/get_users_by_usernames_user_context"] = ("User Lookup (User Context)", Samples.Users.GetUsersByUsernamesUserContext.RunAsync), + ["users/get_users_me"] = ("Authenticated User Lookup (Me)", Samples.Users.GetUsersMe.RunAsync), + ["users/like/get_liked_posts"] = ("Liked Posts", Samples.Users.Like.GetLikedPosts.RunAsync), + ["users/like/like_post"] = ("Like a Post", Samples.Users.Like.LikePost.RunAsync), + ["users/like/unlike_post"] = ("Unlike a Post", Samples.Users.Like.UnlikePost.RunAsync), + ["users/lists/follow_list"] = ("Follow List", Samples.Users.Lists.FollowList.RunAsync), + ["users/lists/get_followed_lists"] = ("User Followed Lists Lookup", Samples.Users.Lists.GetFollowedLists.RunAsync), + ["users/lists/get_list_memberships"] = ("User List Memberships Lookup", Samples.Users.Lists.GetListMemberships.RunAsync), + ["users/lists/get_owned_lists"] = ("User Owned Lists Lookup", Samples.Users.Lists.GetOwnedLists.RunAsync), + ["users/lists/get_pinned_lists"] = ("Pinned Lists Lookup", Samples.Users.Lists.GetPinnedLists.RunAsync), + ["users/lists/pin_list"] = ("Pin List", Samples.Users.Lists.PinList.RunAsync), + ["users/lists/unfollow_list"] = ("Unfollow List", Samples.Users.Lists.UnfollowList.RunAsync), + ["users/lists/unpin_list"] = ("Unpin List", Samples.Users.Lists.UnpinList.RunAsync), + ["users/mute/get_muting"] = ("Muted Users Lookup", Samples.Users.Mute.GetMuting.RunAsync), + ["users/mute/mute_user"] = ("Mute User", Samples.Users.Mute.MuteUser.RunAsync), + ["users/mute/unmute_user"] = ("Unmute User", Samples.Users.Mute.UnmuteUser.RunAsync), + ["users/repost/get_reposts_of_me"] = ("Reposts of Me", Samples.Users.Repost.GetRepostsOfMe.RunAsync), + ["users/repost/repost_post"] = ("Repost a Post", Samples.Users.Repost.RepostPost.RunAsync), + ["users/repost/unrepost_post"] = ("Undo Repost", Samples.Users.Repost.UnrepostPost.RunAsync), + ["users/timeline/get_home_timeline"] = ("Reverse Chronological Home Timeline", Samples.Users.Timeline.GetHomeTimeline.RunAsync), + ["users/timeline/get_mentions"] = ("User Mentions Timeline", Samples.Users.Timeline.GetMentions.RunAsync), + ["users/timeline/get_posts"] = ("User Posts Timeline", Samples.Users.Timeline.GetPosts.RunAsync), + ["webhooks/delete_webhook"] = ("Delete Webhook", Samples.Webhooks.DeleteWebhook.RunAsync), + ["webhooks/list_webhooks"] = ("List Webhooks", Samples.Webhooks.ListWebhooks.RunAsync), + ["webhooks/register_webhook"] = ("Register Webhook", Samples.Webhooks.RegisterWebhook.RunAsync), + ["webhooks/validate_webhook"] = ("Validate Webhook (Trigger CRC)", Samples.Webhooks.ValidateWebhook.RunAsync), + ["webhooks/webhook_server"] = ("Webhook Server (CRC + Event Delivery)", Samples.Webhooks.WebhookServer.RunAsync), + }; + + public static async Task Main(string[] args) + { + if (args.Length == 0 || args[0] is "-h" or "--help" or "list") + { + Console.WriteLine("X API v2 C# Samples (XDevPlatform.Xdk)"); + Console.WriteLine("Usage: dotnet run -- \n"); + Console.WriteLine($"Available samples ({Registry.Count}):"); + foreach (var (key, entry) in Registry.OrderBy(kv => kv.Key)) + { + Console.WriteLine($" {key,-48} {entry.Title}"); + } + return 0; + } + + var requested = args[0].Trim().Replace("\\", "/").TrimEnd('/'); + if (requested.EndsWith(".cs", StringComparison.OrdinalIgnoreCase)) + { + requested = requested[..^3]; + } + + if (!Registry.TryGetValue(requested, out var sample)) + { + Console.Error.WriteLine($"Unknown sample '{args[0]}'. Run 'dotnet run -- --help' to list all {Registry.Count} samples."); + return 1; + } + + await sample.Action(); + return 0; + } +} diff --git a/csharp/README.md b/csharp/README.md new file mode 100644 index 0000000..8709ad7 --- /dev/null +++ b/csharp/README.md @@ -0,0 +1,100 @@ +# C# / .NET Samples for X API v2 (`XDevPlatform.Xdk`) + +Official C# / .NET 8+ sample code for the X API v2 powered by the official [**XDK for C#** (`XDevPlatform.Xdk`)](https://github.com/xdevplatform/xdk-csharp). + +## Prerequisites + +- **.NET 8.0 SDK or later** (`dotnet --version`) +- An [X Developer Account](https://console.x.com) with API credentials + +## Installation + +Add `XDevPlatform.Xdk` to your project (already configured in [`csharp/XdkSamples.csproj`](./XdkSamples.csproj)): + +```bash +dotnet add package XDevPlatform.Xdk +``` + +Build all 80 samples at once: + +```bash +cd csharp +dotnet build +``` + +List all available samples: + +```bash +dotnet run -- --help +``` + +## Authentication + +### Bearer Token (App-Only Endpoints) + +```bash +export BEARER_TOKEN="your_bearer_token" +dotnet run -- posts/search_recent +``` + +### OAuth 2.0 PKCE (User-Context Endpoints) + +Samples that act on behalf of a user (creating posts, managing lists/bookmarks/likes/DMs, media upload) support either a pre-generated `ACCESS_TOKEN` or interactive OAuth 2.0 PKCE via `CLIENT_ID` (and optional `CLIENT_SECRET`): + +```bash +export CLIENT_ID="your_oauth2_client_id" +export CLIENT_SECRET="your_oauth2_client_secret" # optional for public clients +export REDIRECT_URI="https://example.com" # must match your App settings + +dotnet run -- posts/create_post +``` + +## Sample Categories (80 Samples) + +| Category | Samples | Example Command | +|---|---:|---| +| `activity/` | 5 | `dotnet run -- activity/list_subscriptions` | +| `compliance/` | 5 | `dotnet run -- compliance/get_jobs` | +| `direct_messages/` | 6 | `dotnet run -- direct_messages/get_user_conversation_events` | +| `lists/` | 9 | `dotnet run -- lists/get_list_by_id` | +| `media/` | 2 | `dotnet run -- media/media_upload_v2` | +| `posts/` | 12 | `dotnet run -- posts/search_recent` | +| `spaces/` | 2 | `dotnet run -- spaces/search_spaces` | +| `streams/` | 2 | `dotnet run -- streams/stream_posts_filtered` | +| `usage/` | 1 | `dotnet run -- usage/get_usage` | +| `users/` | 31 | `dotnet run -- users/get_users_by_usernames` | +| `webhooks/` | 5 | `dotnet run -- webhooks/list_webhooks` | + +## Key SDK Patterns + +### Async Cursor Pagination (`IAsyncEnumerable`) + +Every paginated endpoint exposes a `*Pages(...)` helper returning `Paginator : IAsyncEnumerable`: + +```csharp +var options = new PostsClient.SearchRecentOptions +{ + MaxResults = 100, + PostFields = new List { "author_id", "created_at" }, +}; + +await foreach (var page in client.Posts.SearchRecentPages("from:XDevelopers", options)) +{ + foreach (var post in page.Data ?? Enumerable.Empty()) + { + Console.WriteLine($"{post.Id}: {post.Text}"); + } +} +``` + +### Real-Time NDJSON Streaming (`EventStream`) + +Streaming endpoints return `EventStream : IAsyncEnumerable, IAsyncDisposable`: + +```csharp +await using var stream = client.Stream.PostsStream(); +await foreach (var evt in stream) +{ + Console.WriteLine(evt.Data?.Text); +} +``` diff --git a/csharp/XdkSamples.csproj b/csharp/XdkSamples.csproj new file mode 100644 index 0000000..4e79921 --- /dev/null +++ b/csharp/XdkSamples.csproj @@ -0,0 +1,17 @@ + + + + Exe + net8.0 + enable + enable + latest + SamplesRunner + Samples + + + + + + + diff --git a/csharp/activity/CreateSubscription.cs b/csharp/activity/CreateSubscription.cs new file mode 100644 index 0000000..b4fefc2 --- /dev/null +++ b/csharp/activity/CreateSubscription.cs @@ -0,0 +1,41 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Activity; + +/// +/// Create Activity Subscription - X API v2 +/// Endpoint: POST https://api.x.com/2/activity/subscriptions +/// Docs: https://docs.x.com/x-api/activity/introduction +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class CreateSubscription +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var userId = "2244994945"; + var eventType = "profile.update.bio"; + + var request = new CreateActivitySubscriptionRequest + { + EventType = eventType, + Filter = new CreateActivitySubscriptionFilter { UserId = userId }, + Tag = $"{eventType} for user {userId}", + }; + + var response = await client.Activity.CreateSubscriptionAsync(request); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/activity/DeleteSubscription.cs b/csharp/activity/DeleteSubscription.cs new file mode 100644 index 0000000..31b22f9 --- /dev/null +++ b/csharp/activity/DeleteSubscription.cs @@ -0,0 +1,32 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Activity; + +/// +/// Delete Activity Subscription - X API v2 +/// Endpoint: DELETE https://api.x.com/2/activity/subscriptions/:id +/// Docs: https://docs.x.com/x-api/activity/introduction +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class DeleteSubscription +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var subscriptionId = "your-subscription-id"; + var response = await client.Activity.DeleteSubscriptionAsync(subscriptionId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/activity/ListSubscriptions.cs b/csharp/activity/ListSubscriptions.cs new file mode 100644 index 0000000..e7c0d56 --- /dev/null +++ b/csharp/activity/ListSubscriptions.cs @@ -0,0 +1,31 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Activity; + +/// +/// List Activity Subscriptions - X API v2 +/// Endpoint: GET https://api.x.com/2/activity/subscriptions +/// Docs: https://docs.x.com/x-api/activity/introduction +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class ListSubscriptions +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var response = await client.Activity.GetSubscriptionsAsync(); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/activity/StreamEvents.cs b/csharp/activity/StreamEvents.cs new file mode 100644 index 0000000..2a24d81 --- /dev/null +++ b/csharp/activity/StreamEvents.cs @@ -0,0 +1,38 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Activity; + +/// +/// Activity Stream - X API v2 +/// Endpoint: GET https://api.x.com/2/activity/stream +/// Docs: https://docs.x.com/x-api/activity/introduction +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class StreamEvents +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + Console.WriteLine("Connecting to activity stream... (press Ctrl+C to stop)"); + await using var stream = client.Stream.ActivityStream(); + await foreach (var evt in stream) + { + if (evt.Data is not null) + { + Console.WriteLine(JsonSerializer.Serialize(evt.Data, PrettyJson)); + } + } + } +} diff --git a/csharp/activity/UpdateSubscription.cs b/csharp/activity/UpdateSubscription.cs new file mode 100644 index 0000000..da49bf0 --- /dev/null +++ b/csharp/activity/UpdateSubscription.cs @@ -0,0 +1,37 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Activity; + +/// +/// Update Activity Subscription - X API v2 +/// Endpoint: PUT https://api.x.com/2/activity/subscriptions/:id +/// Docs: https://docs.x.com/x-api/activity/introduction +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class UpdateSubscription +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var subscriptionId = "your-subscription-id"; + var request = new UpdateActivitySubscriptionRequest + { + Tag = "updated-activity-tag", + }; + + var response = await client.Activity.UpdateSubscriptionAsync(subscriptionId, request); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/compliance/CreateJobs.cs b/csharp/compliance/CreateJobs.cs new file mode 100644 index 0000000..085623a --- /dev/null +++ b/csharp/compliance/CreateJobs.cs @@ -0,0 +1,36 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Compliance; + +/// +/// Create Compliance Job - X API v2 +/// Endpoint: POST https://api.x.com/2/compliance/jobs +/// Docs: https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/post-compliance-jobs +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class CreateJobs +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var request = new CreateComplianceJobsRequest + { + Type = "tweets", + Name = "my_batch_compliance_job", + }; + var response = await client.Compliance.CreateJobsAsync(request); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/compliance/DownloadResults.cs b/csharp/compliance/DownloadResults.cs new file mode 100644 index 0000000..9ac8a6c --- /dev/null +++ b/csharp/compliance/DownloadResults.cs @@ -0,0 +1,26 @@ +namespace Samples.Compliance; + +/// +/// Download Compliance Results - X API v2 +/// Endpoint: GET <download_url> (pre-signed URL from compliance job status) +/// Docs: https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/get-compliance-jobs-id +/// +public static class DownloadResults +{ + public static async Task RunAsync() + { + var downloadUrl = Environment.GetEnvironmentVariable("COMPLIANCE_DOWNLOAD_URL") ?? "https://example.com/download"; + using var http = new HttpClient(); + using var response = await http.GetAsync(downloadUrl); + Console.WriteLine($"Response code: {(int)response.StatusCode}"); + var body = await response.Content.ReadAsStringAsync(); + if (!response.IsSuccessStatusCode) + { + throw new InvalidOperationException($"Download failed with status {(int)response.StatusCode}: {body}"); + } + foreach (var line in body.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) + { + Console.WriteLine(line); + } + } +} diff --git a/csharp/compliance/GetJobs.cs b/csharp/compliance/GetJobs.cs new file mode 100644 index 0000000..623c087 --- /dev/null +++ b/csharp/compliance/GetJobs.cs @@ -0,0 +1,31 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Compliance; + +/// +/// Get Compliance Jobs - X API v2 +/// Endpoint: GET https://api.x.com/2/compliance/jobs +/// Docs: https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/get-compliance-jobs +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetJobs +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var response = await client.Compliance.GetJobsAsync("tweets"); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/compliance/GetJobsById.cs b/csharp/compliance/GetJobsById.cs new file mode 100644 index 0000000..c1a0ed3 --- /dev/null +++ b/csharp/compliance/GetJobsById.cs @@ -0,0 +1,32 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Compliance; + +/// +/// Get Compliance Job by ID - X API v2 +/// Endpoint: GET https://api.x.com/2/compliance/jobs/:id +/// Docs: https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/get-compliance-jobs-id +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetJobsById +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var jobId = "your-compliance-job-id"; + var response = await client.Compliance.GetJobsByIdAsync(jobId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/compliance/UploadIds.cs b/csharp/compliance/UploadIds.cs new file mode 100644 index 0000000..b31916d --- /dev/null +++ b/csharp/compliance/UploadIds.cs @@ -0,0 +1,31 @@ +using System.Net.Http.Headers; + +namespace Samples.Compliance; + +/// +/// Upload IDs for Compliance Job - X API v2 +/// Endpoint: PUT <upload_url> (pre-signed URL from compliance job creation) +/// Docs: https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/post-compliance-jobs +/// +public static class UploadIds +{ + public static async Task RunAsync() + { + var uploadUrl = Environment.GetEnvironmentVariable("COMPLIANCE_UPLOAD_URL") ?? "https://example.com/upload"; + var idsFile = Environment.GetEnvironmentVariable("COMPLIANCE_IDS_FILE") ?? "ids.txt"; + + var bytes = await File.ReadAllBytesAsync(idsFile); + using var http = new HttpClient(); + using var content = new ByteArrayContent(bytes); + content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); + + using var response = await http.PutAsync(uploadUrl, content); + Console.WriteLine($"Response code: {(int)response.StatusCode}"); + var body = await response.Content.ReadAsStringAsync(); + if (!response.IsSuccessStatusCode) + { + throw new InvalidOperationException($"Upload failed with status {(int)response.StatusCode}: {body}"); + } + Console.WriteLine(body); + } +} diff --git a/csharp/direct_messages/GetEventsByConversation.cs b/csharp/direct_messages/GetEventsByConversation.cs new file mode 100644 index 0000000..9d125b5 --- /dev/null +++ b/csharp/direct_messages/GetEventsByConversation.cs @@ -0,0 +1,84 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.DirectMessages; + +/// +/// Get Events by Conversation ID - X API v2 +/// Endpoint: GET https://api.x.com/2/dm_conversations/:dm_conversation_id/dm_events +/// Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-conversations-dm_conversation_id-dm_events +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class GetEventsByConversation +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "dm.read", "tweet.read", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var dmConversationId = "1512210732774948865"; + var options = new DirectMessagesClient.GetEventsByConversationIdOptions { MaxResults = 100 }; + + var allEvents = new List(); + await foreach (var page in client.DirectMessages.GetEventsByConversationIdPages(dmConversationId, options)) + { + if (page.Data is not null) + { + allEvents.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} events (total: {allEvents.Count})"); + } + } + Console.WriteLine(JsonSerializer.Serialize(allEvents, PrettyJson)); + } +} diff --git a/csharp/direct_messages/GetOneToOneConversationEvents.cs b/csharp/direct_messages/GetOneToOneConversationEvents.cs new file mode 100644 index 0000000..244302a --- /dev/null +++ b/csharp/direct_messages/GetOneToOneConversationEvents.cs @@ -0,0 +1,84 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.DirectMessages; + +/// +/// Get One-to-One Conversation Events - X API v2 +/// Endpoint: GET https://api.x.com/2/dm_conversations/with/:participant_id/dm_events +/// Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-conversations-with-participant_id-dm_events +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class GetOneToOneConversationEvents +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "dm.read", "tweet.read", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var participantId = "1716450569358098432"; + var options = new DirectMessagesClient.GetEventsByParticipantIdOptions { MaxResults = 100 }; + + var allEvents = new List(); + await foreach (var page in client.DirectMessages.GetEventsByParticipantIdPages(participantId, options)) + { + if (page.Data is not null) + { + allEvents.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} events (total: {allEvents.Count})"); + } + } + Console.WriteLine(JsonSerializer.Serialize(allEvents, PrettyJson)); + } +} diff --git a/csharp/direct_messages/GetUserConversationEvents.cs b/csharp/direct_messages/GetUserConversationEvents.cs new file mode 100644 index 0000000..ecf7966 --- /dev/null +++ b/csharp/direct_messages/GetUserConversationEvents.cs @@ -0,0 +1,87 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.DirectMessages; + +/// +/// Get User Conversation Events - X API v2 +/// Endpoint: GET https://api.x.com/2/dm_events +/// Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-events +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class GetUserConversationEvents +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "dm.read", "tweet.read", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var options = new DirectMessagesClient.GetEventsOptions + { + MaxResults = 100, + DmEventFields = new List { "id", "text", "event_type", "created_at", "sender_id" }, + }; + + var allEvents = new List(); + await foreach (var page in client.DirectMessages.GetEventsPages(options)) + { + if (page.Data is not null) + { + allEvents.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} events (total: {allEvents.Count})"); + } + } + Console.WriteLine(JsonSerializer.Serialize(allEvents, PrettyJson)); + } +} diff --git a/csharp/direct_messages/PostDmToConversation.cs b/csharp/direct_messages/PostDmToConversation.cs new file mode 100644 index 0000000..bed4e5a --- /dev/null +++ b/csharp/direct_messages/PostDmToConversation.cs @@ -0,0 +1,79 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.DirectMessages; + +/// +/// Post DM to Conversation - X API v2 +/// Endpoint: POST https://api.x.com/2/dm_conversations/:dm_conversation_id/messages +/// Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations-dm_conversation_id-messages +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class PostDmToConversation +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "dm.read", "dm.write", "tweet.read", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var dmConversationId = "1856843062712176900"; + var request = new CreateDirectMessagesByConversationIdRequest + { + Text = "Hi, I am adding a message to an existing conversation using XDK for C#.", + }; + + var response = await client.DirectMessages.CreateByConversationIdAsync(dmConversationId, request); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/direct_messages/PostGroupConversationDm.cs b/csharp/direct_messages/PostGroupConversationDm.cs new file mode 100644 index 0000000..addeda2 --- /dev/null +++ b/csharp/direct_messages/PostGroupConversationDm.cs @@ -0,0 +1,83 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.DirectMessages; + +/// +/// Post Group Conversation Direct Message - X API v2 +/// Endpoint: POST https://api.x.com/2/dm_conversations +/// Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class PostGroupConversationDm +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "dm.read", "dm.write", "tweet.read", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var request = new CreateDirectMessagesConversationRequest + { + ConversationType = "Group", + ParticipantIds = new List { "2244994945", "1716450569358098432" }, + Message = new CreateDirectMessagesConversationMessage + { + Text = "Hi, creating a new group conversation via XDK for C#.", + }, + }; + + var response = await client.DirectMessages.CreateConversationAsync(request); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/direct_messages/PostOneToOneDm.cs b/csharp/direct_messages/PostOneToOneDm.cs new file mode 100644 index 0000000..e4aed6c --- /dev/null +++ b/csharp/direct_messages/PostOneToOneDm.cs @@ -0,0 +1,79 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.DirectMessages; + +/// +/// Post One-to-One Direct Message - X API v2 +/// Endpoint: POST https://api.x.com/2/dm_conversations/with/:participant_id/messages +/// Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations-with-participant_id-messages +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class PostOneToOneDm +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "dm.read", "dm.write", "tweet.read", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var participantId = "1716450569358098432"; + var request = new CreateDirectMessagesByParticipantIdRequest + { + Text = "Hi, DMing you using the v2 one-to-one endpoint via XDK for C#.", + }; + + var response = await client.DirectMessages.CreateByParticipantIdAsync(participantId, request); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/lists/AddMember.cs b/csharp/lists/AddMember.cs new file mode 100644 index 0000000..923133e --- /dev/null +++ b/csharp/lists/AddMember.cs @@ -0,0 +1,75 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Lists; + +/// +/// Add List Member - X API v2 +/// Endpoint: POST https://api.x.com/2/lists/:id/members +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/list-members/api-reference/post-lists-id-members +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class AddMember +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "list.read", "list.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var listId = "your-list-id"; + var userId = "user-id-to-add"; + var response = await client.Lists.AddMemberAsync(listId, new AddListsMemberRequest { UserId = userId }); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/lists/CreateList.cs b/csharp/lists/CreateList.cs new file mode 100644 index 0000000..54b9469 --- /dev/null +++ b/csharp/lists/CreateList.cs @@ -0,0 +1,79 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Lists; + +/// +/// Create List - X API v2 +/// Endpoint: POST https://api.x.com/2/lists +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/post-lists +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class CreateList +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "list.read", "list.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var request = new CreateListsRequest + { + Name = "name-of-list", + Description = "description-of-list", + Private = false, + }; + var response = await client.Lists.CreateAsync(request); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/lists/DeleteList.cs b/csharp/lists/DeleteList.cs new file mode 100644 index 0000000..6d23e95 --- /dev/null +++ b/csharp/lists/DeleteList.cs @@ -0,0 +1,74 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Lists; + +/// +/// Delete List - X API v2 +/// Endpoint: DELETE https://api.x.com/2/lists/:id +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/delete-lists-id +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class DeleteList +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "list.read", "list.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var listId = "your-list-id"; + var response = await client.Lists.DeleteAsync(listId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/lists/GetListById.cs b/csharp/lists/GetListById.cs new file mode 100644 index 0000000..8bb8da4 --- /dev/null +++ b/csharp/lists/GetListById.cs @@ -0,0 +1,36 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Lists; + +/// +/// List Lookup by ID - 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) — set BEARER_TOKEN +/// +public static class GetListById +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var listId = "list-id"; + var options = new ListsClient.GetByIdOptions + { + ListFields = new List { "created_at", "follower_count", "member_count", "owner_id", "description" }, + }; + var response = await client.Lists.GetByIdAsync(listId, options); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/lists/GetListFollowers.cs b/csharp/lists/GetListFollowers.cs new file mode 100644 index 0000000..13ce3a9 --- /dev/null +++ b/csharp/lists/GetListFollowers.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Lists; + +/// +/// List Followers Lookup - X API v2 +/// Endpoint: GET https://api.x.com/2/lists/:id/followers +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/list-follows/api-reference/get-lists-id-followers +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetListFollowers +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var listId = "list-id"; + var options = new ListsClient.GetFollowersOptions + { + MaxResults = 100, + UserFields = new List { "created_at", "description", "verified" }, + }; + + var allUsers = new List(); + await foreach (var page in client.Lists.GetFollowersPages(listId, options)) + { + if (page.Data is not null) + { + allUsers.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} users (total: {allUsers.Count})"); + } + } + Console.WriteLine($"Total Followers: {allUsers.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allUsers.Take(5), PrettyJson)); + } +} diff --git a/csharp/lists/GetListMembers.cs b/csharp/lists/GetListMembers.cs new file mode 100644 index 0000000..d9c6a75 --- /dev/null +++ b/csharp/lists/GetListMembers.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Lists; + +/// +/// List Members Lookup - X API v2 +/// Endpoint: GET https://api.x.com/2/lists/:id/members +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/list-members/api-reference/get-lists-id-members +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetListMembers +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var listId = "list-id"; + var options = new ListsClient.GetMembersOptions + { + MaxResults = 100, + UserFields = new List { "created_at", "description", "verified" }, + }; + + var allUsers = new List(); + await foreach (var page in client.Lists.GetMembersPages(listId, options)) + { + if (page.Data is not null) + { + allUsers.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} users (total: {allUsers.Count})"); + } + } + Console.WriteLine($"Total Members: {allUsers.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allUsers.Take(5), PrettyJson)); + } +} diff --git a/csharp/lists/GetListPosts.cs b/csharp/lists/GetListPosts.cs new file mode 100644 index 0000000..72460bd --- /dev/null +++ b/csharp/lists/GetListPosts.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Lists; + +/// +/// List Posts - X API v2 +/// Endpoint: GET https://api.x.com/2/lists/:id/tweets +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/list-tweets/api-reference/get-lists-id-tweets +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetListPosts +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var listId = "list-id"; + var options = new ListsClient.GetPostsOptions + { + MaxResults = 100, + PostFields = new List { "lang", "author_id" }, + }; + + var allPosts = new List(); + await foreach (var page in client.Lists.GetPostsPages(listId, options)) + { + if (page.Data is not null) + { + allPosts.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} posts (total: {allPosts.Count})"); + } + } + Console.WriteLine($"Total Posts: {allPosts.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allPosts.Take(5), PrettyJson)); + } +} diff --git a/csharp/lists/RemoveMember.cs b/csharp/lists/RemoveMember.cs new file mode 100644 index 0000000..f3ee6f3 --- /dev/null +++ b/csharp/lists/RemoveMember.cs @@ -0,0 +1,75 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Lists; + +/// +/// Remove List Member - X API v2 +/// Endpoint: DELETE https://api.x.com/2/lists/:id/members/:user_id +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/list-members/api-reference/delete-lists-id-members-user_id +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class RemoveMember +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "list.read", "list.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var listId = "your-list-id"; + var userId = "user-id-to-remove"; + var response = await client.Lists.RemoveMemberByUserIdAsync(listId, userId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/lists/UpdateList.cs b/csharp/lists/UpdateList.cs new file mode 100644 index 0000000..fbf77bf --- /dev/null +++ b/csharp/lists/UpdateList.cs @@ -0,0 +1,80 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Lists; + +/// +/// Update List - X API v2 +/// Endpoint: PUT https://api.x.com/2/lists/:id +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/put-lists-id +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class UpdateList +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "list.read", "list.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var listId = "list-id"; + var request = new UpdateListsRequest + { + Name = "update-name-of-list", + Description = "update-description-of-list", + Private = false, + }; + var response = await client.Lists.UpdateAsync(listId, request); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/media/MediaUploadV2.cs b/csharp/media/MediaUploadV2.cs new file mode 100644 index 0000000..6bff439 --- /dev/null +++ b/csharp/media/MediaUploadV2.cs @@ -0,0 +1,120 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Media; + +/// +/// Media Upload v2 (Chunked Video Upload) - X API v2 +/// Endpoint: POST https://api.x.com/2/media/upload/initialize | append | finalize +/// Docs: https://developer.x.com/en/docs/twitter-api/media/upload-media/api-reference +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class MediaUploadV2 +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "media.write", "users.read", "tweet.read", "tweet.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var videoPath = Environment.GetEnvironmentVariable("VIDEO_FILE") ?? "path/to/your/video.mp4"; + var allBytes = await File.ReadAllBytesAsync(videoPath); + + // 1. Initialize chunked upload + var initRes = await client.Media.InitializeUploadAsync(new InitializeMediaUploadRequest + { + MediaType = "video/mp4", + MediaCategory = "tweet_video", + TotalBytes = allBytes.LongLength, + }); + var mediaId = initRes.Data?.Id ?? throw new InvalidOperationException("No media ID returned"); + Console.WriteLine($"Initialized upload for mediaId: {mediaId}"); + + // 2. Append 4 MiB chunks + const int chunkSize = 4 * 1024 * 1024; + var segmentIndex = 0; + for (var offset = 0; offset < allBytes.Length; offset += chunkSize) + { + var count = Math.Min(chunkSize, allBytes.Length - offset); + var base64Chunk = Convert.ToBase64String(allBytes, offset, count); + await client.Media.AppendUploadAsync(mediaId, new AppendMediaUploadRequest + { + SegmentIndex = segmentIndex++, + Media = base64Chunk, + }); + Console.WriteLine($"Uploaded {offset + count} / {allBytes.Length} bytes"); + } + + // 3. Finalize & poll processing status + var finRes = await client.Media.FinalizeUploadAsync(mediaId); + var state = finRes.Data?.ProcessingInfo?.State; + var checkAfterSecs = finRes.Data?.ProcessingInfo?.CheckAfterSecs ?? 2L; + while (!string.IsNullOrEmpty(state) && state != "succeeded" && state != "failed") + { + await Task.Delay(TimeSpan.FromSeconds(checkAfterSecs)); + var statusRes = await client.Media.GetUploadStatusAsync( + mediaId, + new MediaClient.GetUploadStatusOptions { Command = "STATUS" }); + state = statusRes.Data?.ProcessingInfo?.State; + checkAfterSecs = statusRes.Data?.ProcessingInfo?.CheckAfterSecs ?? 2L; + } + + // 4. Create post with attached video + var postRes = await client.Posts.CreateAsync(new CreatePostsRequest + { + Text = "Uploaded a video using XDK for C#!", + Media = new CreatePostsMedia { MediaIds = new List { mediaId } }, + }); + Console.WriteLine(JsonSerializer.Serialize(postRes.Data, PrettyJson)); + } +} diff --git a/csharp/media/Upload.cs b/csharp/media/Upload.cs new file mode 100644 index 0000000..8085bef --- /dev/null +++ b/csharp/media/Upload.cs @@ -0,0 +1,81 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Media; + +/// +/// Media Upload (Single Payload) - X API v2 +/// Endpoint: POST https://api.x.com/2/media/upload +/// Docs: https://developer.x.com/en/docs/twitter-api/media/upload-media/api-reference +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class Upload +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "media.write", "tweet.read", "tweet.write", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var mediaPath = Environment.GetEnvironmentVariable("MEDIA_FILE") ?? "path/to/your/image.jpg"; + var base64Media = Convert.ToBase64String(await File.ReadAllBytesAsync(mediaPath)); + + var response = await client.Media.UploadAsync(new MediaUploadRequest + { + Media = base64Media, + MediaCategory = "tweet_image", + }); + Console.WriteLine($"Media ID: {response.Data?.Id}"); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/posts/CreatePost.cs b/csharp/posts/CreatePost.cs new file mode 100644 index 0000000..2047b56 --- /dev/null +++ b/csharp/posts/CreatePost.cs @@ -0,0 +1,73 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Posts; + +/// +/// Create Post - X API v2 +/// Endpoint: POST https://api.x.com/2/tweets +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class CreatePost +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "tweet.write", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var response = await client.Posts.CreateAsync(new CreatePostsRequest { Text = "Hello world!" }); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/posts/DeletePost.cs b/csharp/posts/DeletePost.cs new file mode 100644 index 0000000..459c4d8 --- /dev/null +++ b/csharp/posts/DeletePost.cs @@ -0,0 +1,74 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Posts; + +/// +/// Delete Post - X API v2 +/// Endpoint: DELETE https://api.x.com/2/tweets/:id +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/delete-tweets-id +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class DeletePost +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "tweet.write", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var postId = "1997118644242014409"; + var response = await client.Posts.DeleteAsync(postId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/posts/GetLikingUsers.cs b/csharp/posts/GetLikingUsers.cs new file mode 100644 index 0000000..4aa24b2 --- /dev/null +++ b/csharp/posts/GetLikingUsers.cs @@ -0,0 +1,89 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Posts; + +/// +/// Liking Users - X API v2 +/// Endpoint: GET https://api.x.com/2/tweets/:id/liking_users +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/get-tweets-id-liking_users +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class GetLikingUsers +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "like.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var postId = "post-id"; + var options = new PostsClient.GetLikingUsersOptions + { + MaxResults = 100, + UserFields = new List { "created_at", "description" }, + }; + + var allUsers = new List(); + await foreach (var page in client.Posts.GetLikingUsersPages(postId, options)) + { + if (page.Data is not null) + { + allUsers.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} users (total: {allUsers.Count})"); + } + } + Console.WriteLine($"Total Users: {allUsers.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allUsers.Take(5), PrettyJson)); + } +} diff --git a/csharp/posts/GetPostById.cs b/csharp/posts/GetPostById.cs new file mode 100644 index 0000000..b3370a7 --- /dev/null +++ b/csharp/posts/GetPostById.cs @@ -0,0 +1,36 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Posts; + +/// +/// Single Post Lookup - X API v2 +/// Endpoint: GET https://api.x.com/2/tweets/:id +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets-id +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetPostById +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var postId = "post-id"; + var options = new PostsClient.GetByIdOptions + { + PostFields = new List { "created_at", "author_id", "lang", "source", "public_metrics", "entities" }, + }; + var response = await client.Posts.GetByIdAsync(postId, options); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/posts/GetPostCountsAll.cs b/csharp/posts/GetPostCountsAll.cs new file mode 100644 index 0000000..27824f9 --- /dev/null +++ b/csharp/posts/GetPostCountsAll.cs @@ -0,0 +1,43 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Posts; + +/// +/// Full-Archive Post Counts - X API v2 +/// Endpoint: GET https://api.x.com/2/tweets/counts/all +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/counts/api-reference/get-tweets-counts-all +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetPostCountsAll +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var query = "from:XDevelopers"; + var options = new PostsClient.GetCountsAllOptions { Granularity = "day" }; + + var allCounts = new List(); + await foreach (var page in client.Posts.GetCountsAllPages(query, options)) + { + if (page.Data is not null) + { + allCounts.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} count buckets (total: {allCounts.Count})"); + } + } + Console.WriteLine($"Total Count Buckets: {allCounts.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allCounts, PrettyJson)); + } +} diff --git a/csharp/posts/GetPostCountsRecent.cs b/csharp/posts/GetPostCountsRecent.cs new file mode 100644 index 0000000..3ff3c1f --- /dev/null +++ b/csharp/posts/GetPostCountsRecent.cs @@ -0,0 +1,43 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Posts; + +/// +/// Recent Post Counts - X API v2 +/// Endpoint: GET https://api.x.com/2/tweets/counts/recent +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/counts/api-reference/get-tweets-counts-recent +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetPostCountsRecent +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var query = "from:XDevelopers"; + var options = new PostsClient.GetCountsRecentOptions { Granularity = "day" }; + + var allCounts = new List(); + await foreach (var page in client.Posts.GetCountsRecentPages(query, options)) + { + if (page.Data is not null) + { + allCounts.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} count buckets (total: {allCounts.Count})"); + } + } + Console.WriteLine($"Total Count Buckets: {allCounts.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allCounts, PrettyJson)); + } +} diff --git a/csharp/posts/GetPostsByIds.cs b/csharp/posts/GetPostsByIds.cs new file mode 100644 index 0000000..e3dadd2 --- /dev/null +++ b/csharp/posts/GetPostsByIds.cs @@ -0,0 +1,36 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Posts; + +/// +/// Post Lookup by IDs - X API v2 +/// Endpoint: GET https://api.x.com/2/tweets +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetPostsByIds +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var postIds = new List { "post-id-1", "post-id-2" }; + var options = new PostsClient.GetByIdsOptions + { + PostFields = new List { "created_at", "author_id", "lang", "source", "public_metrics", "context_annotations", "entities" }, + }; + var response = await client.Posts.GetByIdsAsync(postIds, options); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/posts/GetQuotedPosts.cs b/csharp/posts/GetQuotedPosts.cs new file mode 100644 index 0000000..7560b84 --- /dev/null +++ b/csharp/posts/GetQuotedPosts.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Posts; + +/// +/// Quote Posts Lookup - X API v2 +/// Endpoint: GET https://api.x.com/2/tweets/:id/quote_tweets +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/quote-tweets/api-reference/get-tweets-id-quote_tweets +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetQuotedPosts +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var postId = "1409931481552543749"; + var options = new PostsClient.GetQuotedOptions + { + MaxResults = 100, + PostFields = new List { "created_at" }, + }; + + var allPosts = new List(); + await foreach (var page in client.Posts.GetQuotedPages(postId, options)) + { + if (page.Data is not null) + { + allPosts.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} posts (total: {allPosts.Count})"); + } + } + Console.WriteLine($"Total Quote Posts: {allPosts.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allPosts.Take(5), PrettyJson)); + } +} diff --git a/csharp/posts/GetRepostedBy.cs b/csharp/posts/GetRepostedBy.cs new file mode 100644 index 0000000..d08702b --- /dev/null +++ b/csharp/posts/GetRepostedBy.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Posts; + +/// +/// Reposted By (Users who reposted) - X API v2 +/// Endpoint: GET https://api.x.com/2/tweets/:id/retweeted_by +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/get-tweets-id-retweeted_by +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetRepostedBy +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var postId = "post-id"; + var options = new PostsClient.GetRepostedByOptions + { + MaxResults = 100, + UserFields = new List { "created_at", "description" }, + }; + + var allUsers = new List(); + await foreach (var page in client.Posts.GetRepostedByPages(postId, options)) + { + if (page.Data is not null) + { + allUsers.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} users (total: {allUsers.Count})"); + } + } + Console.WriteLine($"Total Users: {allUsers.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allUsers.Take(5), PrettyJson)); + } +} diff --git a/csharp/posts/HideReply.cs b/csharp/posts/HideReply.cs new file mode 100644 index 0000000..874fedd --- /dev/null +++ b/csharp/posts/HideReply.cs @@ -0,0 +1,74 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Posts; + +/// +/// Hide Reply - X API v2 +/// Endpoint: PUT https://api.x.com/2/tweets/:id/hidden +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/hide-replies/api-reference/put-tweets-id-hidden +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class HideReply +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "tweet.write", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var replyPostId = "reply-tweet-id-to-hide"; + var response = await client.Posts.HideReplyAsync(replyPostId, new HidePostsReplyRequest { Hidden = true }); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/posts/SearchAll.cs b/csharp/posts/SearchAll.cs new file mode 100644 index 0000000..c21bc88 --- /dev/null +++ b/csharp/posts/SearchAll.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Posts; + +/// +/// Full-Archive Search - X API v2 +/// Endpoint: GET https://api.x.com/2/tweets/search/all +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-all +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class SearchAll +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var query = "(from:XDevelopers -is:retweet) OR #XDevelopers"; + var options = new PostsClient.SearchAllOptions + { + MaxResults = 100, + PostFields = new List { "author_id", "created_at" }, + }; + + var allPosts = new List(); + await foreach (var page in client.Posts.SearchAllPages(query, options)) + { + if (page.Data is not null) + { + allPosts.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} posts (total: {allPosts.Count})"); + } + } + Console.WriteLine($"Total Posts: {allPosts.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allPosts.Take(5), PrettyJson)); + } +} diff --git a/csharp/posts/SearchRecent.cs b/csharp/posts/SearchRecent.cs new file mode 100644 index 0000000..9545aea --- /dev/null +++ b/csharp/posts/SearchRecent.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Posts; + +/// +/// 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) — set BEARER_TOKEN +/// +public static class SearchRecent +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var query = "(from:XDevelopers -is:retweet) OR #XDevelopers"; + var options = new PostsClient.SearchRecentOptions + { + MaxResults = 100, + PostFields = new List { "author_id", "created_at" }, + }; + + var allPosts = new List(); + await foreach (var page in client.Posts.SearchRecentPages(query, options)) + { + if (page.Data is not null) + { + allPosts.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} posts (total: {allPosts.Count})"); + } + } + Console.WriteLine($"Total Posts: {allPosts.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allPosts.Take(5), PrettyJson)); + } +} diff --git a/csharp/spaces/GetSpacesByIds.cs b/csharp/spaces/GetSpacesByIds.cs new file mode 100644 index 0000000..cbac6a7 --- /dev/null +++ b/csharp/spaces/GetSpacesByIds.cs @@ -0,0 +1,37 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Spaces; + +/// +/// Spaces Lookup by IDs - 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) — set BEARER_TOKEN +/// +public static class GetSpacesByIds +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var spaceIds = new List { "space-id-1", "space-id-2" }; + var options = new SpacesClient.GetByIdsOptions + { + SpaceFields = new List { "title", "created_at" }, + Expansions = new List { "creator_id" }, + }; + var response = await client.Spaces.GetByIdsAsync(spaceIds, options); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/spaces/SearchSpaces.cs b/csharp/spaces/SearchSpaces.cs new file mode 100644 index 0000000..886a645 --- /dev/null +++ b/csharp/spaces/SearchSpaces.cs @@ -0,0 +1,37 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Spaces; + +/// +/// Search Spaces - X API v2 +/// Endpoint: GET https://api.x.com/2/spaces/search +/// Docs: https://developer.x.com/en/docs/twitter-api/spaces/search/api-reference/get-spaces-search +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class SearchSpaces +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var searchTerm = "NBA"; + var options = new SpacesClient.SearchOptions + { + SpaceFields = new List { "title", "created_at" }, + Expansions = new List { "creator_id" }, + }; + var response = await client.Spaces.SearchAsync(searchTerm, options); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/streams/StreamPostsFiltered.cs b/csharp/streams/StreamPostsFiltered.cs new file mode 100644 index 0000000..8b79113 --- /dev/null +++ b/csharp/streams/StreamPostsFiltered.cs @@ -0,0 +1,72 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Streams; + +/// +/// Filtered Stream - X API v2 +/// Endpoint: GET https://api.x.com/2/tweets/search/stream +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/filtered-stream/api-reference/get-tweets-search-stream +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class StreamPostsFiltered +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + // 1. Fetch existing rules + var currentRules = await client.Stream.GetRulesAsync(); + + // 2. Delete existing rules by value if present + if (currentRules.Data is { Count: > 0 }) + { + var values = currentRules.Data + .Where(r => !string.IsNullOrEmpty(r.Value)) + .Select(r => r.Value!) + .ToList(); + if (values.Count > 0) + { + await client.Stream.UpdateRulesAsync(new UpdateRulesRequest + { + Delete = new UpdateRulesDelete { Values = values }, + }); + } + } + + // 3. Add sample filter rules + var added = await client.Stream.UpdateRulesAsync(new UpdateRulesRequest + { + Add = new List + { + new() { Value = "dog has:images", Tag = "dog pictures" }, + new() { Value = "cat has:images -grumpy", Tag = "cat pictures" }, + }, + }); + Console.WriteLine(JsonSerializer.Serialize(added.Data, PrettyJson)); + + // 4. Stream matching posts in real time + var options = new StreamClient.PostsOptions + { + TweetFields = new List { "id", "text", "created_at" }, + }; + await using var stream = client.Stream.PostsStream(options); + await foreach (var evt in stream) + { + if (evt.Data is not null) + { + Console.WriteLine(JsonSerializer.Serialize(evt.Data, PrettyJson)); + } + } + } +} diff --git a/csharp/streams/StreamPostsSample.cs b/csharp/streams/StreamPostsSample.cs new file mode 100644 index 0000000..431c551 --- /dev/null +++ b/csharp/streams/StreamPostsSample.cs @@ -0,0 +1,37 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Streams; + +/// +/// Sampled Stream (1% Volume) - X API v2 +/// Endpoint: GET https://api.x.com/2/tweets/sample/stream +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/volume-streams/api-reference/get-tweets-sample-stream +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class StreamPostsSample +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + await using var stream = client.Stream.PostsSampleStream(); + await foreach (var evt in stream) + { + if (evt.Data is not null) + { + Console.WriteLine(JsonSerializer.Serialize(evt.Data, PrettyJson)); + } + } + } +} diff --git a/csharp/usage/GetUsage.cs b/csharp/usage/GetUsage.cs new file mode 100644 index 0000000..05af3a6 --- /dev/null +++ b/csharp/usage/GetUsage.cs @@ -0,0 +1,31 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Usage; + +/// +/// Usage Posts - X API v2 +/// Endpoint: GET https://api.x.com/2/usage/tweets +/// Docs: https://developer.x.com/en/docs/twitter-api/usage/api-reference/get-usage-tweets +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetUsage +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var response = await client.Usage.GetAsync(new UsageClient.GetOptions { Days = 7 }); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/GetUsersByUsernames.cs b/csharp/users/GetUsersByUsernames.cs new file mode 100644 index 0000000..47684a7 --- /dev/null +++ b/csharp/users/GetUsersByUsernames.cs @@ -0,0 +1,36 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Users; + +/// +/// User Lookup by Usernames - 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) — set BEARER_TOKEN +/// +public static class GetUsersByUsernames +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var usernames = new List { "XDevelopers", "API" }; + var options = new UsersClient.GetByUsernamesOptions + { + UserFields = new List { "description", "created_at" }, + }; + var response = await client.Users.GetByUsernamesAsync(usernames, options); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/GetUsersByUsernamesUserContext.cs b/csharp/users/GetUsersByUsernamesUserContext.cs new file mode 100644 index 0000000..619c3d0 --- /dev/null +++ b/csharp/users/GetUsersByUsernamesUserContext.cs @@ -0,0 +1,78 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users; + +/// +/// User Lookup (User Context) - 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: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class GetUsersByUsernamesUserContext +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var usernames = new List { "XDevelopers", "API" }; + var options = new UsersClient.GetByUsernamesOptions + { + UserFields = new List { "created_at", "description" }, + }; + var response = await client.Users.GetByUsernamesAsync(usernames, options); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/GetUsersMe.cs b/csharp/users/GetUsersMe.cs new file mode 100644 index 0000000..520de1f --- /dev/null +++ b/csharp/users/GetUsersMe.cs @@ -0,0 +1,77 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users; + +/// +/// Authenticated User Lookup (Me) - X API v2 +/// Endpoint: GET https://api.x.com/2/users/me +/// Docs: https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-me +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class GetUsersMe +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var options = new UsersClient.GetMeOptions + { + UserFields = new List { "created_at", "description" }, + }; + var response = await client.Users.GetMeAsync(options); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/block/GetBlocking.cs b/csharp/users/block/GetBlocking.cs new file mode 100644 index 0000000..e7c7e07 --- /dev/null +++ b/csharp/users/block/GetBlocking.cs @@ -0,0 +1,90 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Block; + +/// +/// Blocked Users Lookup - X API v2 +/// Endpoint: GET https://api.x.com/2/users/:id/blocking +/// Docs: https://developer.x.com/en/docs/twitter-api/users/blocks/api-reference/get-users-blocking +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class GetBlocking +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "offline.access", "block.read" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var me = await client.Users.GetMeAsync(); + var userId = me.Data?.Id ?? throw new InvalidOperationException("Could not resolve authenticated user ID"); + var options = new UsersClient.GetBlockingOptions + { + MaxResults = 100, + UserFields = new List { "created_at", "description" }, + }; + + var allUsers = new List(); + await foreach (var page in client.Users.GetBlockingPages(userId, options)) + { + if (page.Data is not null) + { + allUsers.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} users (total: {allUsers.Count})"); + } + } + Console.WriteLine($"Total Blocked Users: {allUsers.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allUsers.Take(5), PrettyJson)); + } +} diff --git a/csharp/users/bookmark/CreateBookmark.cs b/csharp/users/bookmark/CreateBookmark.cs new file mode 100644 index 0000000..554dea4 --- /dev/null +++ b/csharp/users/bookmark/CreateBookmark.cs @@ -0,0 +1,76 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Bookmark; + +/// +/// Create Bookmark - X API v2 +/// Endpoint: POST https://api.x.com/2/users/:id/bookmarks +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/post-users-id-bookmarks +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class CreateBookmark +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "bookmark.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var postId = "post-id-to-bookmark"; + var me = await client.Users.GetMeAsync(); + var userId = me.Data?.Id ?? throw new InvalidOperationException("Could not resolve authenticated user ID"); + var response = await client.Users.CreateBookmarkAsync(userId, new CreateUsersBookmarkRequest { TweetId = postId }); + Console.WriteLine(JsonSerializer.Serialize(response, PrettyJson)); + } +} diff --git a/csharp/users/bookmark/DeleteBookmark.cs b/csharp/users/bookmark/DeleteBookmark.cs new file mode 100644 index 0000000..6d19f3b --- /dev/null +++ b/csharp/users/bookmark/DeleteBookmark.cs @@ -0,0 +1,76 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Bookmark; + +/// +/// Delete Bookmark - X API v2 +/// Endpoint: DELETE https://api.x.com/2/users/:id/bookmarks/:tweet_id +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/delete-users-id-bookmarks-tweet_id +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class DeleteBookmark +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "bookmark.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var postId = "post-id-to-unbookmark"; + var me = await client.Users.GetMeAsync(); + var userId = me.Data?.Id ?? throw new InvalidOperationException("Could not resolve authenticated user ID"); + var response = await client.Users.DeleteBookmarkAsync(userId, postId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/bookmark/GetBookmarks.cs b/csharp/users/bookmark/GetBookmarks.cs new file mode 100644 index 0000000..926a383 --- /dev/null +++ b/csharp/users/bookmark/GetBookmarks.cs @@ -0,0 +1,90 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Bookmark; + +/// +/// Bookmarks Lookup - X API v2 +/// Endpoint: GET https://api.x.com/2/users/:id/bookmarks +/// Docs: https://developer.x.com/en/docs/twitter-api/bookmarks/api-reference/get-users-id-bookmarks +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class GetBookmarks +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "bookmark.read", "tweet.read", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var me = await client.Users.GetMeAsync(); + var userId = me.Data?.Id ?? throw new InvalidOperationException("Could not resolve authenticated user ID"); + var options = new UsersClient.GetBookmarksOptions + { + MaxResults = 100, + PostFields = new List { "created_at" }, + }; + + var allBookmarks = new List(); + await foreach (var page in client.Users.GetBookmarksPages(userId, options)) + { + if (page.Data is not null) + { + allBookmarks.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} bookmarks (total: {allBookmarks.Count})"); + } + } + Console.WriteLine($"Total Bookmarks: {allBookmarks.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allBookmarks.Take(5), PrettyJson)); + } +} diff --git a/csharp/users/follow/FollowUser.cs b/csharp/users/follow/FollowUser.cs new file mode 100644 index 0000000..3c60d51 --- /dev/null +++ b/csharp/users/follow/FollowUser.cs @@ -0,0 +1,76 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Follow; + +/// +/// Follow User - X API v2 +/// Endpoint: POST https://api.x.com/2/users/:id/following +/// Docs: https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/post-users-id-following +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class FollowUser +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "follows.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var targetUserId = "user-id-to-follow"; + var me = await client.Users.GetMeAsync(); + var userId = me.Data?.Id ?? throw new InvalidOperationException("Could not resolve authenticated user ID"); + var response = await client.Users.FollowUserAsync(userId, new FollowUserRequest { TargetUserId = targetUserId }); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/follow/GetFollowers.cs b/csharp/users/follow/GetFollowers.cs new file mode 100644 index 0000000..495f779 --- /dev/null +++ b/csharp/users/follow/GetFollowers.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Users.Follow; + +/// +/// User Followers Lookup - 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) — set BEARER_TOKEN +/// +public static class GetFollowers +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var userId = "2244994945"; + var options = new UsersClient.GetFollowersOptions + { + MaxResults = 100, + UserFields = new List { "created_at" }, + }; + + var allUsers = new List(); + await foreach (var page in client.Users.GetFollowersPages(userId, options)) + { + if (page.Data is not null) + { + allUsers.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} users (total: {allUsers.Count})"); + } + } + Console.WriteLine($"Total Followers: {allUsers.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allUsers.Take(5), PrettyJson)); + } +} diff --git a/csharp/users/follow/GetFollowing.cs b/csharp/users/follow/GetFollowing.cs new file mode 100644 index 0000000..e91d208 --- /dev/null +++ b/csharp/users/follow/GetFollowing.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Users.Follow; + +/// +/// User Following Lookup - 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) — set BEARER_TOKEN +/// +public static class GetFollowing +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var userId = "2244994945"; + var options = new UsersClient.GetFollowingOptions + { + MaxResults = 100, + UserFields = new List { "created_at" }, + }; + + var allUsers = new List(); + await foreach (var page in client.Users.GetFollowingPages(userId, options)) + { + if (page.Data is not null) + { + allUsers.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} users (total: {allUsers.Count})"); + } + } + Console.WriteLine($"Total Following: {allUsers.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allUsers.Take(5), PrettyJson)); + } +} diff --git a/csharp/users/follow/UnfollowUser.cs b/csharp/users/follow/UnfollowUser.cs new file mode 100644 index 0000000..68eaf89 --- /dev/null +++ b/csharp/users/follow/UnfollowUser.cs @@ -0,0 +1,76 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Follow; + +/// +/// Unfollow User - X API v2 +/// Endpoint: DELETE https://api.x.com/2/users/:source_user_id/following/:target_user_id +/// Docs: https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/delete-users-source_user_id-following +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class UnfollowUser +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "follows.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var targetUserId = "user-id-to-unfollow"; + var me = await client.Users.GetMeAsync(); + var userId = me.Data?.Id ?? throw new InvalidOperationException("Could not resolve authenticated user ID"); + var response = await client.Users.UnfollowUserAsync(userId, targetUserId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/like/GetLikedPosts.cs b/csharp/users/like/GetLikedPosts.cs new file mode 100644 index 0000000..37dfe50 --- /dev/null +++ b/csharp/users/like/GetLikedPosts.cs @@ -0,0 +1,90 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Like; + +/// +/// Liked Posts - X API v2 +/// Endpoint: GET https://api.x.com/2/users/:id/liked_tweets +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/get-users-id-liked_tweets +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class GetLikedPosts +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "like.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var me = await client.Users.GetMeAsync(); + var userId = me.Data?.Id ?? throw new InvalidOperationException("Could not resolve authenticated user ID"); + var options = new UsersClient.GetLikedPostsOptions + { + MaxResults = 100, + PostFields = new List { "lang", "author_id" }, + }; + + var allPosts = new List(); + await foreach (var page in client.Users.GetLikedPostsPages(userId, options)) + { + if (page.Data is not null) + { + allPosts.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} posts (total: {allPosts.Count})"); + } + } + Console.WriteLine($"Total Liked Posts: {allPosts.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allPosts.Take(5), PrettyJson)); + } +} diff --git a/csharp/users/like/LikePost.cs b/csharp/users/like/LikePost.cs new file mode 100644 index 0000000..fb0689a --- /dev/null +++ b/csharp/users/like/LikePost.cs @@ -0,0 +1,76 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Like; + +/// +/// Like a Post - X API v2 +/// Endpoint: POST https://api.x.com/2/users/:id/likes +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/post-users-id-likes +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class LikePost +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "tweet.write", "users.read", "offline.access", "like.write" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var postId = "post-id"; + var me = await client.Users.GetMeAsync(); + var userId = me.Data?.Id ?? throw new InvalidOperationException("Could not resolve authenticated user ID"); + var response = await client.Users.LikePostAsync(userId, new LikePostRequest { TweetId = postId }); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/like/UnlikePost.cs b/csharp/users/like/UnlikePost.cs new file mode 100644 index 0000000..f55d3a7 --- /dev/null +++ b/csharp/users/like/UnlikePost.cs @@ -0,0 +1,76 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Like; + +/// +/// Unlike a Post - X API v2 +/// Endpoint: DELETE https://api.x.com/2/users/:id/likes/:tweet_id +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/delete-users-id-likes-tweet_id +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class UnlikePost +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "tweet.write", "users.read", "offline.access", "like.write" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var postId = "post-id"; + var me = await client.Users.GetMeAsync(); + var userId = me.Data?.Id ?? throw new InvalidOperationException("Could not resolve authenticated user ID"); + var response = await client.Users.UnlikePostAsync(userId, postId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/lists/FollowList.cs b/csharp/users/lists/FollowList.cs new file mode 100644 index 0000000..77db48e --- /dev/null +++ b/csharp/users/lists/FollowList.cs @@ -0,0 +1,75 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Lists; + +/// +/// Follow List - X API v2 +/// Endpoint: POST https://api.x.com/2/users/:id/followed_lists +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/list-follows/api-reference/post-users-id-followed_lists +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class FollowList +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "list.read", "list.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var userId = "your-user-id"; + var listId = "list-id-to-follow"; + var response = await client.Users.FollowListAsync(userId, new FollowListRequest { ListId = listId }); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/lists/GetFollowedLists.cs b/csharp/users/lists/GetFollowedLists.cs new file mode 100644 index 0000000..eb4e075 --- /dev/null +++ b/csharp/users/lists/GetFollowedLists.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Users.Lists; + +/// +/// User Followed Lists Lookup - X API v2 +/// Endpoint: GET https://api.x.com/2/users/:id/followed_lists +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/list-follows/api-reference/get-users-id-followed_lists +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetFollowedLists +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var userId = "user-id"; + var options = new UsersClient.GetFollowedListsOptions + { + MaxResults = 100, + ListFields = new List { "created_at", "follower_count" }, + }; + + var allLists = new List(); + await foreach (var page in client.Users.GetFollowedListsPages(userId, options)) + { + if (page.Data is not null) + { + allLists.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} lists (total: {allLists.Count})"); + } + } + Console.WriteLine($"Total Followed Lists: {allLists.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allLists.Take(5), PrettyJson)); + } +} diff --git a/csharp/users/lists/GetListMemberships.cs b/csharp/users/lists/GetListMemberships.cs new file mode 100644 index 0000000..29633c0 --- /dev/null +++ b/csharp/users/lists/GetListMemberships.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Users.Lists; + +/// +/// User List Memberships Lookup - X API v2 +/// Endpoint: GET https://api.x.com/2/users/:id/list_memberships +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/list-members/api-reference/get-users-id-list_memberships +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetListMemberships +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var userId = "user-id"; + var options = new UsersClient.GetListMembershipsOptions + { + MaxResults = 100, + ListFields = new List { "created_at", "follower_count" }, + }; + + var allLists = new List(); + await foreach (var page in client.Users.GetListMembershipsPages(userId, options)) + { + if (page.Data is not null) + { + allLists.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} lists (total: {allLists.Count})"); + } + } + Console.WriteLine($"Total List Memberships: {allLists.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allLists.Take(5), PrettyJson)); + } +} diff --git a/csharp/users/lists/GetOwnedLists.cs b/csharp/users/lists/GetOwnedLists.cs new file mode 100644 index 0000000..2b45e22 --- /dev/null +++ b/csharp/users/lists/GetOwnedLists.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Users.Lists; + +/// +/// User Owned Lists Lookup - X API v2 +/// Endpoint: GET https://api.x.com/2/users/:id/owned_lists +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/list-lookup/api-reference/get-users-id-owned_lists +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetOwnedLists +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var userId = "user-id"; + var options = new UsersClient.GetOwnedListsOptions + { + MaxResults = 100, + ListFields = new List { "created_at", "follower_count" }, + }; + + var allLists = new List(); + await foreach (var page in client.Users.GetOwnedListsPages(userId, options)) + { + if (page.Data is not null) + { + allLists.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} lists (total: {allLists.Count})"); + } + } + Console.WriteLine($"Total Owned Lists: {allLists.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allLists.Take(5), PrettyJson)); + } +} diff --git a/csharp/users/lists/GetPinnedLists.cs b/csharp/users/lists/GetPinnedLists.cs new file mode 100644 index 0000000..633f14d --- /dev/null +++ b/csharp/users/lists/GetPinnedLists.cs @@ -0,0 +1,78 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Lists; + +/// +/// Pinned Lists Lookup - X API v2 +/// Endpoint: GET https://api.x.com/2/users/:id/pinned_lists +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/pinned-lists/api-reference/get-users-id-pinned_lists +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class GetPinnedLists +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "list.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var userId = "your-user-id"; + var options = new UsersClient.GetPinnedListsOptions + { + ListFields = new List { "created_at", "description", "private" }, + }; + var response = await client.Users.GetPinnedListsAsync(userId, options); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/lists/PinList.cs b/csharp/users/lists/PinList.cs new file mode 100644 index 0000000..5ebe278 --- /dev/null +++ b/csharp/users/lists/PinList.cs @@ -0,0 +1,75 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Lists; + +/// +/// Pin List - X API v2 +/// Endpoint: POST https://api.x.com/2/users/:id/pinned_lists +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/pinned-lists/api-reference/post-users-id-pinned_lists +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class PinList +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "list.read", "list.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var userId = "your-user-id"; + var listId = "list-id-to-pin"; + var response = await client.Users.PinListAsync(userId, new PinListRequest { ListId = listId }); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/lists/UnfollowList.cs b/csharp/users/lists/UnfollowList.cs new file mode 100644 index 0000000..6a630fe --- /dev/null +++ b/csharp/users/lists/UnfollowList.cs @@ -0,0 +1,75 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Lists; + +/// +/// Unfollow List - X API v2 +/// Endpoint: DELETE https://api.x.com/2/users/:id/followed_lists/:list_id +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/list-follows/api-reference/delete-users-id-followed_lists-list_id +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class UnfollowList +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "list.read", "list.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var userId = "your-user-id"; + var listId = "list-id-to-unfollow"; + var response = await client.Users.UnfollowListAsync(userId, listId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/lists/UnpinList.cs b/csharp/users/lists/UnpinList.cs new file mode 100644 index 0000000..356763f --- /dev/null +++ b/csharp/users/lists/UnpinList.cs @@ -0,0 +1,75 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Lists; + +/// +/// Unpin List - X API v2 +/// Endpoint: DELETE https://api.x.com/2/users/:id/pinned_lists/:list_id +/// Docs: https://developer.x.com/en/docs/twitter-api/lists/pinned-lists/api-reference/delete-users-id-pinned_lists-list_id +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class UnpinList +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "list.read", "list.write", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var userId = "your-user-id"; + var listId = "list-id-to-unpin"; + var response = await client.Users.UnpinListAsync(userId, listId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/mute/GetMuting.cs b/csharp/users/mute/GetMuting.cs new file mode 100644 index 0000000..3975031 --- /dev/null +++ b/csharp/users/mute/GetMuting.cs @@ -0,0 +1,90 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Mute; + +/// +/// Muted Users Lookup - X API v2 +/// Endpoint: GET https://api.x.com/2/users/:id/muting +/// Docs: https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/get-users-muting +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class GetMuting +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "offline.access", "mute.read" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var me = await client.Users.GetMeAsync(); + var userId = me.Data?.Id ?? throw new InvalidOperationException("Could not resolve authenticated user ID"); + var options = new UsersClient.GetMutingOptions + { + MaxResults = 100, + UserFields = new List { "created_at", "description" }, + }; + + var allUsers = new List(); + await foreach (var page in client.Users.GetMutingPages(userId, options)) + { + if (page.Data is not null) + { + allUsers.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} users (total: {allUsers.Count})"); + } + } + Console.WriteLine($"Total Muted Users: {allUsers.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allUsers.Take(5), PrettyJson)); + } +} diff --git a/csharp/users/mute/MuteUser.cs b/csharp/users/mute/MuteUser.cs new file mode 100644 index 0000000..3ebdaa1 --- /dev/null +++ b/csharp/users/mute/MuteUser.cs @@ -0,0 +1,75 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Mute; + +/// +/// Mute User - X API v2 +/// Endpoint: POST https://api.x.com/2/users/:id/muting +/// Docs: https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/post-users-user_id-muting +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class MuteUser +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "tweet.write", "offline.access", "mute.write" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var userId = "your-user-id"; + var targetUserId = "id-to-mute"; + var response = await client.Users.MuteUserAsync(userId, new MuteUserRequest { TargetUserId = targetUserId }); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/mute/UnmuteUser.cs b/csharp/users/mute/UnmuteUser.cs new file mode 100644 index 0000000..a19986e --- /dev/null +++ b/csharp/users/mute/UnmuteUser.cs @@ -0,0 +1,75 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Mute; + +/// +/// Unmute User - X API v2 +/// Endpoint: DELETE https://api.x.com/2/users/:source_user_id/muting/:target_user_id +/// Docs: https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/delete-users-user_id-muting +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class UnmuteUser +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "tweet.write", "offline.access", "mute.write" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var userId = "your-user-id"; + var targetUserId = "id-to-unmute"; + var response = await client.Users.UnmuteUserAsync(userId, targetUserId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/repost/GetRepostsOfMe.cs b/csharp/users/repost/GetRepostsOfMe.cs new file mode 100644 index 0000000..636d32d --- /dev/null +++ b/csharp/users/repost/GetRepostsOfMe.cs @@ -0,0 +1,88 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Repost; + +/// +/// Reposts of Me - X API v2 +/// Endpoint: GET https://api.x.com/2/users/reposts_of_me +/// Docs: https://docs.x.com/x-api/users/get-reposts-of-me +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class GetRepostsOfMe +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var options = new UsersClient.GetRepostsOfMeOptions + { + MaxResults = 100, + PostFields = new List { "created_at", "public_metrics" }, + }; + + var allPosts = new List(); + await foreach (var page in client.Users.GetRepostsOfMePages(options)) + { + if (page.Data is not null) + { + allPosts.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} posts (total: {allPosts.Count})"); + } + } + Console.WriteLine($"Total Reposted Posts: {allPosts.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allPosts.Take(5), PrettyJson)); + } +} diff --git a/csharp/users/repost/RepostPost.cs b/csharp/users/repost/RepostPost.cs new file mode 100644 index 0000000..0e8ae20 --- /dev/null +++ b/csharp/users/repost/RepostPost.cs @@ -0,0 +1,76 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Repost; + +/// +/// Repost a Post - X API v2 +/// Endpoint: POST https://api.x.com/2/users/:id/retweets +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/post-users-id-retweets +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class RepostPost +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "tweet.write", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var postId = "post-id"; + var me = await client.Users.GetMeAsync(); + var userId = me.Data?.Id ?? throw new InvalidOperationException("Could not resolve authenticated user ID"); + var response = await client.Users.RepostPostAsync(userId, new RepostPostRequest { TweetId = postId }); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/repost/UnrepostPost.cs b/csharp/users/repost/UnrepostPost.cs new file mode 100644 index 0000000..07fa6b9 --- /dev/null +++ b/csharp/users/repost/UnrepostPost.cs @@ -0,0 +1,76 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Repost; + +/// +/// Undo Repost - X API v2 +/// Endpoint: DELETE https://api.x.com/2/users/:id/retweets/:source_tweet_id +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/delete-users-id-retweets-tweet_id +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class UnrepostPost +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "tweet.write", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var sourcePostId = "post-id"; + var me = await client.Users.GetMeAsync(); + var userId = me.Data?.Id ?? throw new InvalidOperationException("Could not resolve authenticated user ID"); + var response = await client.Users.UnrepostPostAsync(userId, sourcePostId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/users/timeline/GetHomeTimeline.cs b/csharp/users/timeline/GetHomeTimeline.cs new file mode 100644 index 0000000..2377dc6 --- /dev/null +++ b/csharp/users/timeline/GetHomeTimeline.cs @@ -0,0 +1,90 @@ +using System.Text.Json; +using Xdk; +using Xdk.Auth; +using Xdk.Clients; +using Xdk.Models; + +namespace Samples.Users.Timeline; + +/// +/// Reverse Chronological Home Timeline - X API v2 +/// Endpoint: GET https://api.x.com/2/users/:id/timelines/reverse_chronological +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-reverse-chronological-timeline +/// Authentication: OAuth 2.0 PKCE (User Context) — set CLIENT_ID / CLIENT_SECRET or ACCESS_TOKEN +/// +public static class GetHomeTimeline +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + private static string ExtractAuthorizationCode(string callbackInput) + { + var trimmed = callbackInput.Trim(); + if (!trimmed.Contains("://") && !trimmed.Contains("code=")) + { + return trimmed; + } + var query = trimmed.Contains('?') ? new Uri(trimmed).Query.TrimStart('?') : trimmed; + foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var kv = pair.Split('=', 2); + if (kv.Length == 2 && kv[0] == "code") + { + return Uri.UnescapeDataString(kv[1]); + } + } + throw new ArgumentException("No 'code' query parameter found in callback URL"); + } + + private static async Task ResolveAccessTokenAsync(string[] scopes) + { + var directToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN"); + if (!string.IsNullOrWhiteSpace(directToken)) + { + return directToken; + } + + var clientId = Environment.GetEnvironmentVariable("CLIENT_ID"); + var clientSecret = Environment.GetEnvironmentVariable("CLIENT_SECRET"); + if (string.IsNullOrWhiteSpace(clientId)) + { + throw new InvalidOperationException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + var redirectUri = Environment.GetEnvironmentVariable("REDIRECT_URI") ?? "https://example.com"; + var oauth2 = new OAuth2Pkce(clientId, redirectUri, clientSecret: clientSecret, scopes: scopes); + var authUrl = oauth2.GetAuthorizationUrl("sample-state"); + Console.WriteLine("Visit the following URL to authorize your App:"); + Console.WriteLine(authUrl); + Console.Write("Paste the full callback URL (or code) here: "); + var callbackUrl = Console.ReadLine() ?? string.Empty; + var token = await oauth2.ExchangeCodeAsync(ExtractAuthorizationCode(callbackUrl)); + return token.AccessToken ?? throw new InvalidOperationException("OAuth2 token response did not include access_token"); + } + + public static async Task RunAsync() + { + var scopes = new[] { "tweet.read", "users.read", "offline.access" }; + var accessToken = await ResolveAccessTokenAsync(scopes); + + using var client = new XClient(new XClientOptions { AccessToken = accessToken }); + var me = await client.Users.GetMeAsync(); + var userId = me.Data?.Id ?? throw new InvalidOperationException("Could not resolve authenticated user ID"); + var options = new UsersClient.GetTimelineOptions + { + MaxResults = 100, + PostFields = new List { "created_at" }, + }; + + var allPosts = new List(); + await foreach (var page in client.Users.GetTimelinePages(userId, options)) + { + if (page.Data is not null) + { + allPosts.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} posts (total: {allPosts.Count})"); + } + } + Console.WriteLine($"Total Posts: {allPosts.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allPosts.Take(5), PrettyJson)); + } +} diff --git a/csharp/users/timeline/GetMentions.cs b/csharp/users/timeline/GetMentions.cs new file mode 100644 index 0000000..c1e38cd --- /dev/null +++ b/csharp/users/timeline/GetMentions.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Users.Timeline; + +/// +/// User Mentions Timeline - X API v2 +/// Endpoint: GET https://api.x.com/2/users/:id/mentions +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-mentions +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetMentions +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var userId = "2244994945"; + var options = new UsersClient.GetMentionsOptions + { + MaxResults = 100, + PostFields = new List { "created_at" }, + }; + + var allPosts = new List(); + await foreach (var page in client.Users.GetMentionsPages(userId, options)) + { + if (page.Data is not null) + { + allPosts.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} posts (total: {allPosts.Count})"); + } + } + Console.WriteLine($"Total Mentions: {allPosts.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allPosts.Take(5), PrettyJson)); + } +} diff --git a/csharp/users/timeline/GetPosts.cs b/csharp/users/timeline/GetPosts.cs new file mode 100644 index 0000000..5e3aae8 --- /dev/null +++ b/csharp/users/timeline/GetPosts.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Users.Timeline; + +/// +/// User Posts Timeline - X API v2 +/// Endpoint: GET https://api.x.com/2/users/:id/tweets +/// Docs: https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-tweets +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class GetPosts +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var userId = "2244994945"; + var options = new UsersClient.GetPostsOptions + { + MaxResults = 100, + PostFields = new List { "created_at" }, + }; + + var allPosts = new List(); + await foreach (var page in client.Users.GetPostsPages(userId, options)) + { + if (page.Data is not null) + { + allPosts.AddRange(page.Data); + Console.WriteLine($"Fetched {page.Data.Count} posts (total: {allPosts.Count})"); + } + } + Console.WriteLine($"Total Posts: {allPosts.Count}"); + Console.WriteLine(JsonSerializer.Serialize(allPosts.Take(5), PrettyJson)); + } +} diff --git a/csharp/webhooks/DeleteWebhook.cs b/csharp/webhooks/DeleteWebhook.cs new file mode 100644 index 0000000..78447de --- /dev/null +++ b/csharp/webhooks/DeleteWebhook.cs @@ -0,0 +1,32 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Webhooks; + +/// +/// Delete Webhook - X API v2 +/// Endpoint: DELETE https://api.x.com/2/webhooks/:webhook_id +/// Docs: https://docs.x.com/x-api/webhooks/introduction +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class DeleteWebhook +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var webhookId = "your-webhook-id"; + var response = await client.Webhooks.DeleteAsync(webhookId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/webhooks/ListWebhooks.cs b/csharp/webhooks/ListWebhooks.cs new file mode 100644 index 0000000..1249795 --- /dev/null +++ b/csharp/webhooks/ListWebhooks.cs @@ -0,0 +1,31 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Webhooks; + +/// +/// List Webhooks - X API v2 +/// Endpoint: GET https://api.x.com/2/webhooks +/// Docs: https://docs.x.com/x-api/webhooks/introduction +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class ListWebhooks +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var response = await client.Webhooks.GetAsync(); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/webhooks/RegisterWebhook.cs b/csharp/webhooks/RegisterWebhook.cs new file mode 100644 index 0000000..2d38210 --- /dev/null +++ b/csharp/webhooks/RegisterWebhook.cs @@ -0,0 +1,32 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Webhooks; + +/// +/// Register Webhook - X API v2 +/// Endpoint: POST https://api.x.com/2/webhooks +/// Docs: https://docs.x.com/x-api/webhooks/introduction +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class RegisterWebhook +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var webhookUrl = "https://your-domain.com/webhooks"; + var response = await client.Webhooks.CreateAsync(new CreateWebhooksRequest { Url = webhookUrl }); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/webhooks/ValidateWebhook.cs b/csharp/webhooks/ValidateWebhook.cs new file mode 100644 index 0000000..ed5893f --- /dev/null +++ b/csharp/webhooks/ValidateWebhook.cs @@ -0,0 +1,32 @@ +using System.Text.Json; +using Xdk; +using Xdk.Clients; +using Xdk.Models; +using Xdk.Streaming; + +namespace Samples.Webhooks; + +/// +/// Validate Webhook (Trigger CRC) - X API v2 +/// Endpoint: PUT https://api.x.com/2/webhooks/:webhook_id +/// Docs: https://docs.x.com/x-api/webhooks/introduction +/// Authentication: Bearer Token (App-only) — set BEARER_TOKEN +/// +public static class ValidateWebhook +{ + private static readonly JsonSerializerOptions PrettyJson = new() { WriteIndented = true }; + + public static async Task RunAsync() + { + var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN"); + if (string.IsNullOrWhiteSpace(bearerToken)) + { + throw new InvalidOperationException("BEARER_TOKEN environment variable is not set"); + } + + using var client = new XClient(new XClientOptions { BearerToken = bearerToken }); + var webhookId = "your-webhook-id"; + var response = await client.Webhooks.ValidateAsync(webhookId); + Console.WriteLine(JsonSerializer.Serialize(response.Data, PrettyJson)); + } +} diff --git a/csharp/webhooks/WebhookServer.cs b/csharp/webhooks/WebhookServer.cs new file mode 100644 index 0000000..64155b4 --- /dev/null +++ b/csharp/webhooks/WebhookServer.cs @@ -0,0 +1,69 @@ +using System.Net; +using System.Security.Cryptography; +using System.Text; + +namespace Samples.Webhooks; + +/// +/// Webhook Server (CRC + Event Delivery) - X API v2 +/// Docs: https://docs.x.com/x-api/webhooks/introduction +/// Required env vars: CONSUMER_SECRET +/// +public static class WebhookServer +{ + public static async Task RunAsync() + { + var consumerSecret = Environment.GetEnvironmentVariable("CONSUMER_SECRET"); + if (string.IsNullOrWhiteSpace(consumerSecret)) + { + throw new InvalidOperationException("CONSUMER_SECRET environment variable is not set"); + } + + using var listener = new HttpListener(); + listener.Prefixes.Add("http://localhost:8080/webhooks/"); + listener.Start(); + Console.WriteLine("Listening on http://localhost:8080/webhooks/"); + + while (listener.IsListening) + { + var context = await listener.GetContextAsync(); + var request = context.Request; + var response = context.Response; + + if (string.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) + { + var crcToken = request.QueryString["crc_token"]; + if (string.IsNullOrEmpty(crcToken)) + { + response.StatusCode = 400; + var errBytes = Encoding.UTF8.GetBytes("{\"error\":\"No crc_token\"}"); + response.ContentType = "application/json"; + await response.OutputStream.WriteAsync(errBytes); + response.Close(); + continue; + } + + using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(consumerSecret)); + var digest = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(crcToken))); + var bodyBytes = Encoding.UTF8.GetBytes($"{{\"response_token\":\"sha256={digest}\"}}"); + response.StatusCode = 200; + response.ContentType = "application/json"; + await response.OutputStream.WriteAsync(bodyBytes); + response.Close(); + } + else if (string.Equals(request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase)) + { + using var reader = new StreamReader(request.InputStream, Encoding.UTF8); + var payload = await reader.ReadToEndAsync(); + Console.WriteLine(payload); + response.StatusCode = 200; + response.Close(); + } + else + { + response.StatusCode = 405; + response.Close(); + } + } + } +} diff --git a/java/README.md b/java/README.md index 1c1d5eb..c488078 100644 --- a/java/README.md +++ b/java/README.md @@ -1,105 +1,103 @@ -# X API v2 - Java Examples +# Java Samples for X API v2 (`com.x:xdk`) -Working Java code samples for the X (formerly Twitter) API v2. +Official Java 17+ sample code for the X API v2 powered by the official [**XDK for Java** (`com.x:xdk`)](https://github.com/xdevplatform/xdk-java). -## Setup +## Prerequisites -### 1. Install Java 11+ +- **Java 17+** (`java -version`) +- **Apache Maven 3.9+** (`mvn -version`) +- An [X Developer Account](https://console.x.com) with API credentials -```bash -java --version -``` - -### 2. Add dependencies +## Installation -Using Maven, add to your `pom.xml`: +Add `com.x:xdk` to your `pom.xml` (already configured in [`java/pom.xml`](./pom.xml)): ```xml - - - org.apache.httpcomponents - httpclient - 4.5.13 - - - com.google.code.gson - gson - 2.9.1 - - + + com.x + xdk + [0.1.0,) + ``` -### 3. Set environment variables +Or with Gradle (`build.gradle.kts`): -**For read-only operations (search, lookup):** -```bash -export BEARER_TOKEN='your_bearer_token' +```kotlin +dependencies { + implementation("com.x:xdk:0.1.+") +} ``` -**For user actions (post, like, repost, bookmark, etc.):** +Compile all 80 samples at once: + ```bash -export CLIENT_ID='your_client_id' -export CLIENT_SECRET='your_client_secret' +cd java +mvn compile ``` -**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 +## Authentication -### Streams -- `streams/FilteredStreamDemo.java` - Filtered stream with rules -- `streams/SampledStream.java` - Sampled stream +### Bearer Token (App-Only Endpoints) -### Spaces -- `spaces/SearchSpacesDemo.java` - Search for Spaces -- `spaces/SpacesLookupDemo.java` - Look up Spaces by ID - -### Usage -- `usage/UsageTweetsDemo.java` - Get API usage information +```bash +export BEARER_TOKEN="your_bearer_token" +mvn compile exec:java -Dexec.mainClass="posts.SearchRecent" +``` -## Building and Running +### OAuth 2.0 PKCE (User-Context Endpoints) -### Compile +Samples that act on behalf of a user (creating posts, managing lists/bookmarks/likes/DMs, media upload) support either a pre-generated `ACCESS_TOKEN` or interactive OAuth 2.0 PKCE via `CLIENT_ID` (and optional `CLIENT_SECRET`): ```bash -# Compile a single file -javac -cp ".:lib/*" posts/SearchRecent.java +export CLIENT_ID="your_oauth2_client_id" +export CLIENT_SECRET="your_oauth2_client_secret" # optional for public clients +export REDIRECT_URI="https://example.com" # must match your App settings -# Or compile all files -find . -name "*.java" -exec javac -cp ".:lib/*" {} \; +mvn compile exec:java -Dexec.mainClass="posts.CreatePost" ``` -### Run - -```bash -# Run a single example -java -cp ".:lib/*" posts.SearchRecent - -# Or with package structure -java -cp ".:lib/*" posts/RecentSearchDemo +## Sample Categories (80 Samples) + +| Category | Samples | Example Command | +|---|---:|---| +| `activity/` | 5 | `mvn compile exec:java -Dexec.mainClass="activity.ListSubscriptions"` | +| `compliance/` | 5 | `mvn compile exec:java -Dexec.mainClass="compliance.GetJobs"` | +| `direct_messages/` | 6 | `mvn compile exec:java -Dexec.mainClass="direct_messages.GetUserConversationEvents"` | +| `lists/` | 9 | `mvn compile exec:java -Dexec.mainClass="lists.GetListById"` | +| `media/` | 2 | `mvn compile exec:java -Dexec.mainClass="media.MediaUploadV2"` | +| `posts/` | 12 | `mvn compile exec:java -Dexec.mainClass="posts.SearchRecent"` | +| `spaces/` | 2 | `mvn compile exec:java -Dexec.mainClass="spaces.SearchSpaces"` | +| `streams/` | 2 | `mvn compile exec:java -Dexec.mainClass="streams.StreamPostsFiltered"` | +| `usage/` | 1 | `mvn compile exec:java -Dexec.mainClass="usage.GetUsage"` | +| `users/` | 31 | `mvn compile exec:java -Dexec.mainClass="users.GetUsersByUsernames"` | +| `webhooks/` | 5 | `mvn compile exec:java -Dexec.mainClass="webhooks.ListWebhooks"` | + +## Key SDK Patterns + +### Automatic Cursor Pagination + +Every paginated endpoint exposes a `*Pages(...)` helper returning `Paginator implements Iterable`: + +```java +PostsClient.SearchRecentOptions options = PostsClient.SearchRecentOptions.builder() + .maxResults(100) + .postFields(List.of("author_id", "created_at")); + +for (Schemas.SearchPostsRecentResponse page : client.posts().searchRecentPages("from:XDevelopers", options)) { + if (page.getData() != null) { + page.getData().forEach(post -> System.out.println(post.getId() + ": " + post.getText())); + } +} ``` -## More Information +### Real-Time Streaming -- [X API Documentation](https://developer.x.com/en/docs/twitter-api) -- [X Developer Portal](https://developer.x.com/en/portal/dashboard) +Streaming endpoints return `EventStream implements Iterable, AutoCloseable`: + +```java +try (EventStream stream = client.stream().posts()) { + for (Schemas.StreamPostsResponse event : stream) { + System.out.println(event.getData()); + } +} +``` diff --git a/java/activity/CreateSubscription.java b/java/activity/CreateSubscription.java new file mode 100644 index 0000000..c80a280 --- /dev/null +++ b/java/activity/CreateSubscription.java @@ -0,0 +1,47 @@ +package activity; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Create Activity Subscription - X API v2 + * + * Endpoint: POST https://api.x.com/2/activity/subscriptions + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class CreateSubscription { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String userId = "2244994945"; + String eventType = "profile.update.bio"; + + Schemas.CreateActivitySubscriptionFilter filter = new Schemas.CreateActivitySubscriptionFilter() + .userId(userId); + Schemas.CreateActivitySubscriptionRequest request = new Schemas.CreateActivitySubscriptionRequest() + .eventType(eventType) + .filter(filter) + .tag(eventType + " for user " + userId); + + Schemas.CreateActivitySubscriptionResponse response = client.activity().createSubscription(request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/activity/DeleteSubscription.java b/java/activity/DeleteSubscription.java new file mode 100644 index 0000000..513259a --- /dev/null +++ b/java/activity/DeleteSubscription.java @@ -0,0 +1,38 @@ +package activity; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Delete Activity Subscription - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/activity/subscriptions/:id + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class DeleteSubscription { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String subscriptionId = "your-subscription-id"; + Schemas.DeleteActivitySubscriptionResponse response = client.activity().deleteSubscription(subscriptionId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/activity/ListSubscriptions.java b/java/activity/ListSubscriptions.java new file mode 100644 index 0000000..4f06da9 --- /dev/null +++ b/java/activity/ListSubscriptions.java @@ -0,0 +1,37 @@ +package activity; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * List Activity Subscriptions - X API v2 + * + * Endpoint: GET https://api.x.com/2/activity/subscriptions + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class ListSubscriptions { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + Schemas.GetActivitySubscriptionsResponse response = client.activity().getSubscriptions(); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/activity/StreamEvents.java b/java/activity/StreamEvents.java new file mode 100644 index 0000000..e80705d --- /dev/null +++ b/java/activity/StreamEvents.java @@ -0,0 +1,43 @@ +package activity; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Activity Stream - X API v2 + * + * Endpoint: GET https://api.x.com/2/activity/stream + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class StreamEvents { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + System.out.println("Connecting to activity stream... (press Ctrl+C to stop)"); + try (EventStream stream = client.stream().activity()) { + for (Schemas.ActivityStreamResponse event : stream) { + if (event.getData() != null) { + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(event.getData())); + } + } + } + } + } +} diff --git a/java/activity/UpdateSubscription.java b/java/activity/UpdateSubscription.java new file mode 100644 index 0000000..a4f18d4 --- /dev/null +++ b/java/activity/UpdateSubscription.java @@ -0,0 +1,41 @@ +package activity; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Update Activity Subscription - X API v2 + * + * Endpoint: PUT https://api.x.com/2/activity/subscriptions/:id + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class UpdateSubscription { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String subscriptionId = "your-subscription-id"; + Schemas.UpdateActivitySubscriptionRequest request = new Schemas.UpdateActivitySubscriptionRequest() + .tag("updated-activity-tag"); + + Schemas.UpdateActivitySubscriptionResponse response = client.activity().updateSubscription(subscriptionId, request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/compliance/CreateJobs.java b/java/compliance/CreateJobs.java new file mode 100644 index 0000000..f5c152d --- /dev/null +++ b/java/compliance/CreateJobs.java @@ -0,0 +1,40 @@ +package compliance; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Create Compliance Job - X API v2 + * + * Endpoint: POST https://api.x.com/2/compliance/jobs + * Docs: https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/post-compliance-jobs + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class CreateJobs { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + Schemas.CreateComplianceJobsRequest request = new Schemas.CreateComplianceJobsRequest() + .type("tweets") + .name("my_batch_compliance_job"); + Schemas.CreateComplianceJobsResponse response = client.compliance().createJobs(request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/compliance/DownloadResults.java b/java/compliance/DownloadResults.java new file mode 100644 index 0000000..66eb570 --- /dev/null +++ b/java/compliance/DownloadResults.java @@ -0,0 +1,30 @@ +package compliance; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; + +/** + * Download Compliance Results - X API v2 + * + * Endpoint: GET (pre-signed URL from compliance job status) + * Docs: https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/get-compliance-jobs-id + */ +public class DownloadResults { + public static void main(String[] args) throws Exception { + String downloadUrl = System.getenv().getOrDefault("COMPLIANCE_DOWNLOAD_URL", "https://example.com/download"); + HttpClient http = HttpClient.newHttpClient(); + HttpRequest req = HttpRequest.newBuilder(URI.create(downloadUrl)).GET().build(); + HttpResponse response = http.send(req, HttpResponse.BodyHandlers.ofString()); + System.out.println("Response code: " + response.statusCode()); + if (response.statusCode() != 200) { + throw new IllegalStateException("Download failed with status " + response.statusCode() + ": " + response.body()); + } + for (String line : response.body().lines().toList()) { + if (!line.isBlank()) { + System.out.println(line); + } + } + } +} diff --git a/java/compliance/GetJobs.java b/java/compliance/GetJobs.java new file mode 100644 index 0000000..66439be --- /dev/null +++ b/java/compliance/GetJobs.java @@ -0,0 +1,37 @@ +package compliance; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Get Compliance Jobs - X API v2 + * + * Endpoint: GET https://api.x.com/2/compliance/jobs + * Docs: https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/get-compliance-jobs + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetJobs { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + Schemas.GetComplianceJobsResponse response = client.compliance().getJobs("tweets"); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/compliance/GetJobsById.java b/java/compliance/GetJobsById.java new file mode 100644 index 0000000..71e4310 --- /dev/null +++ b/java/compliance/GetJobsById.java @@ -0,0 +1,38 @@ +package compliance; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Get Compliance Job by ID - X API v2 + * + * Endpoint: GET https://api.x.com/2/compliance/jobs/:id + * Docs: https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/get-compliance-jobs-id + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetJobsById { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String jobId = "your-compliance-job-id"; + Schemas.GetComplianceJobsByIdResponse response = client.compliance().getJobsById(jobId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/compliance/UploadIds.java b/java/compliance/UploadIds.java new file mode 100644 index 0000000..9492c0f --- /dev/null +++ b/java/compliance/UploadIds.java @@ -0,0 +1,32 @@ +package compliance; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Path; + +/** + * Upload IDs for Compliance Job - X API v2 + * + * Endpoint: PUT (pre-signed URL from compliance job creation) + * Docs: https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/post-compliance-jobs + */ +public class UploadIds { + public static void main(String[] args) throws Exception { + String uploadUrl = System.getenv().getOrDefault("COMPLIANCE_UPLOAD_URL", "https://example.com/upload"); + Path idsFile = Path.of(System.getenv().getOrDefault("COMPLIANCE_IDS_FILE", "ids.txt")); + + HttpClient http = HttpClient.newHttpClient(); + HttpRequest req = HttpRequest.newBuilder(URI.create(uploadUrl)) + .header("Content-Type", "text/plain") + .PUT(HttpRequest.BodyPublishers.ofFile(idsFile)) + .build(); + HttpResponse response = http.send(req, HttpResponse.BodyHandlers.ofString()); + System.out.println("Response code: " + response.statusCode()); + if (response.statusCode() != 200) { + throw new IllegalStateException("Upload failed with status " + response.statusCode() + ": " + response.body()); + } + System.out.println(response.body()); + } +} diff --git a/java/direct_messages/GetEventsByConversation.java b/java/direct_messages/GetEventsByConversation.java new file mode 100644 index 0000000..a3d64db --- /dev/null +++ b/java/direct_messages/GetEventsByConversation.java @@ -0,0 +1,95 @@ +package direct_messages; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Get Events by Conversation ID - X API v2 + * + * Endpoint: GET https://api.x.com/2/dm_conversations/:dm_conversation_id/dm_events + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-conversations-dm_conversation_id-dm_events + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class GetEventsByConversation { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("dm.read", "tweet.read", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String dmConversationId = "1512210732774948865"; + DirectMessagesClient.GetEventsByConversationIdOptions options = + DirectMessagesClient.GetEventsByConversationIdOptions.builder().maxResults(100); + + List allEvents = new ArrayList<>(); + for (Schemas.GetDirectMessagesEventsByConversationIdResponse page : + client.directMessages().getEventsByConversationIdPages(dmConversationId, options)) { + if (page.getData() != null) { + allEvents.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " events (total: " + allEvents.size() + ")"); + } + } + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allEvents)); + } + } +} diff --git a/java/direct_messages/GetOneToOneConversationEvents.java b/java/direct_messages/GetOneToOneConversationEvents.java new file mode 100644 index 0000000..b772804 --- /dev/null +++ b/java/direct_messages/GetOneToOneConversationEvents.java @@ -0,0 +1,95 @@ +package direct_messages; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Get One-to-One Conversation Events - X API v2 + * + * Endpoint: GET https://api.x.com/2/dm_conversations/with/:participant_id/dm_events + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-conversations-with-participant_id-dm_events + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class GetOneToOneConversationEvents { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("dm.read", "tweet.read", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String participantId = "1716450569358098432"; + DirectMessagesClient.GetEventsByParticipantIdOptions options = + DirectMessagesClient.GetEventsByParticipantIdOptions.builder().maxResults(100); + + List allEvents = new ArrayList<>(); + for (Schemas.GetDirectMessagesEventsByParticipantIdResponse page : + client.directMessages().getEventsByParticipantIdPages(participantId, options)) { + if (page.getData() != null) { + allEvents.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " events (total: " + allEvents.size() + ")"); + } + } + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allEvents)); + } + } +} diff --git a/java/direct_messages/GetUserConversationEvents.java b/java/direct_messages/GetUserConversationEvents.java new file mode 100644 index 0000000..4db9819 --- /dev/null +++ b/java/direct_messages/GetUserConversationEvents.java @@ -0,0 +1,94 @@ +package direct_messages; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Get User Conversation Events - X API v2 + * + * Endpoint: GET https://api.x.com/2/dm_events + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-events + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class GetUserConversationEvents { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("dm.read", "tweet.read", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + DirectMessagesClient.GetEventsOptions options = DirectMessagesClient.GetEventsOptions.builder() + .maxResults(100) + .dmEventFields(Arrays.asList("id", "text", "event_type", "created_at", "sender_id")); + + List allEvents = new ArrayList<>(); + for (Schemas.GetDirectMessagesEventsResponse page : client.directMessages().getEventsPages(options)) { + if (page.getData() != null) { + allEvents.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " events (total: " + allEvents.size() + ")"); + } + } + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allEvents)); + } + } +} diff --git a/java/direct_messages/PostDmToConversation.java b/java/direct_messages/PostDmToConversation.java new file mode 100644 index 0000000..bda18df --- /dev/null +++ b/java/direct_messages/PostDmToConversation.java @@ -0,0 +1,90 @@ +package direct_messages; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Post DM to Conversation - X API v2 + * + * Endpoint: POST https://api.x.com/2/dm_conversations/:dm_conversation_id/messages + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations-dm_conversation_id-messages + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class PostDmToConversation { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("dm.read", "dm.write", "tweet.read", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String dmConversationId = "1856843062712176900"; + Schemas.CreateDirectMessagesByConversationIdRequest request = + new Schemas.CreateDirectMessagesByConversationIdRequest() + .text("Hi, I am adding a message to an existing conversation using XDK for Java."); + + Schemas.CreateDirectMessagesByConversationIdResponse response = + client.directMessages().createByConversationId(dmConversationId, request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/direct_messages/PostGroupConversationDm.java b/java/direct_messages/PostGroupConversationDm.java new file mode 100644 index 0000000..881cdce --- /dev/null +++ b/java/direct_messages/PostGroupConversationDm.java @@ -0,0 +1,93 @@ +package direct_messages; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Post Group Conversation Direct Message - X API v2 + * + * Endpoint: POST https://api.x.com/2/dm_conversations + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class PostGroupConversationDm { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("dm.read", "dm.write", "tweet.read", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + Schemas.CreateDirectMessagesConversationMessage message = + new Schemas.CreateDirectMessagesConversationMessage() + .text("Hi, creating a new group conversation via XDK for Java."); + Schemas.CreateDirectMessagesConversationRequest request = + new Schemas.CreateDirectMessagesConversationRequest() + .conversationType("Group") + .participantIds(Arrays.asList("2244994945", "1716450569358098432")) + .message(message); + + Schemas.CreateDirectMessagesConversationResponse response = client.directMessages().createConversation(request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/direct_messages/PostOneToOneDm.java b/java/direct_messages/PostOneToOneDm.java new file mode 100644 index 0000000..88c04e3 --- /dev/null +++ b/java/direct_messages/PostOneToOneDm.java @@ -0,0 +1,90 @@ +package direct_messages; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Post One-to-One Direct Message - X API v2 + * + * Endpoint: POST https://api.x.com/2/dm_conversations/with/:participant_id/messages + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations-with-participant_id-messages + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class PostOneToOneDm { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("dm.read", "dm.write", "tweet.read", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String participantId = "1716450569358098432"; + Schemas.CreateDirectMessagesByParticipantIdRequest request = + new Schemas.CreateDirectMessagesByParticipantIdRequest() + .text("Hi, DMing you using the v2 one-to-one endpoint via XDK for Java."); + + Schemas.CreateDirectMessagesByParticipantIdResponse response = + client.directMessages().createByParticipantId(participantId, request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/lists/AddMember.java b/java/lists/AddMember.java new file mode 100644 index 0000000..ca6f8a7 --- /dev/null +++ b/java/lists/AddMember.java @@ -0,0 +1,87 @@ +package lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Add List Member - X API v2 + * + * Endpoint: POST https://api.x.com/2/lists/:id/members + * Docs: https://developer.x.com/en/docs/twitter-api/lists/list-members/api-reference/post-lists-id-members + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class AddMember { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "list.read", "list.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String listId = "your-list-id"; + String userId = "user-id-to-add"; + Schemas.AddListsMemberRequest request = new Schemas.AddListsMemberRequest().userId(userId); + Schemas.AddListsMemberResponse response = client.lists().addMember(listId, request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/lists/CreateList.java b/java/lists/CreateList.java new file mode 100644 index 0000000..034c2f4 --- /dev/null +++ b/java/lists/CreateList.java @@ -0,0 +1,88 @@ +package lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Create List - X API v2 + * + * Endpoint: POST https://api.x.com/2/lists + * Docs: https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/post-lists + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class CreateList { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "list.read", "list.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + Schemas.CreateListsRequest request = new Schemas.CreateListsRequest() + .name("name-of-list") + .description("description-of-list") + .privateValue(false); + Schemas.CreateListsResponse response = client.lists().create(request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/lists/DeleteList.java b/java/lists/DeleteList.java new file mode 100644 index 0000000..f25c798 --- /dev/null +++ b/java/lists/DeleteList.java @@ -0,0 +1,85 @@ +package lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Delete List - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/lists/:id + * Docs: https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/delete-lists-id + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class DeleteList { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "list.read", "list.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String listId = "your-list-id"; + Schemas.DeleteListsResponse response = client.lists().delete(listId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/lists/GetListById.java b/java/lists/GetListById.java new file mode 100644 index 0000000..6f1a76e --- /dev/null +++ b/java/lists/GetListById.java @@ -0,0 +1,40 @@ +package lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * List Lookup by ID - 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) + * Required env vars: BEARER_TOKEN + */ +public class GetListById { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String listId = "list-id"; + ListsClient.GetByIdOptions options = ListsClient.GetByIdOptions.builder() + .listFields(Arrays.asList("created_at", "follower_count", "member_count", "owner_id", "description")); + Schemas.GetListsByIdResponse response = client.lists().getById(listId, options); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/lists/GetListFollowers.java b/java/lists/GetListFollowers.java new file mode 100644 index 0000000..921adec --- /dev/null +++ b/java/lists/GetListFollowers.java @@ -0,0 +1,49 @@ +package lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * List Followers Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/lists/:id/followers + * Docs: https://developer.x.com/en/docs/twitter-api/lists/list-follows/api-reference/get-lists-id-followers + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetListFollowers { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String listId = "list-id"; + ListsClient.GetFollowersOptions options = ListsClient.GetFollowersOptions.builder() + .maxResults(100) + .userFields(Arrays.asList("created_at", "description", "verified")); + + List allUsers = new ArrayList<>(); + for (Schemas.GetListsFollowersResponse page : client.lists().getFollowersPages(listId, options)) { + if (page.getData() != null) { + allUsers.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " users (total: " + allUsers.size() + ")"); + } + } + System.out.println("Total Followers: " + allUsers.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allUsers.subList(0, Math.min(5, allUsers.size())))); + } + } +} diff --git a/java/lists/GetListMembers.java b/java/lists/GetListMembers.java new file mode 100644 index 0000000..66a7f02 --- /dev/null +++ b/java/lists/GetListMembers.java @@ -0,0 +1,49 @@ +package lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * List Members Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/lists/:id/members + * Docs: https://developer.x.com/en/docs/twitter-api/lists/list-members/api-reference/get-lists-id-members + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetListMembers { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String listId = "list-id"; + ListsClient.GetMembersOptions options = ListsClient.GetMembersOptions.builder() + .maxResults(100) + .userFields(Arrays.asList("created_at", "description", "verified")); + + List allUsers = new ArrayList<>(); + for (Schemas.GetListsMembersResponse page : client.lists().getMembersPages(listId, options)) { + if (page.getData() != null) { + allUsers.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " users (total: " + allUsers.size() + ")"); + } + } + System.out.println("Total Members: " + allUsers.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allUsers.subList(0, Math.min(5, allUsers.size())))); + } + } +} diff --git a/java/lists/GetListPosts.java b/java/lists/GetListPosts.java new file mode 100644 index 0000000..e13651c --- /dev/null +++ b/java/lists/GetListPosts.java @@ -0,0 +1,49 @@ +package lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * List Posts - X API v2 + * + * Endpoint: GET https://api.x.com/2/lists/:id/tweets + * Docs: https://developer.x.com/en/docs/twitter-api/lists/list-tweets/api-reference/get-lists-id-tweets + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetListPosts { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String listId = "list-id"; + ListsClient.GetPostsOptions options = ListsClient.GetPostsOptions.builder() + .maxResults(100) + .postFields(Arrays.asList("lang", "author_id")); + + List allPosts = new ArrayList<>(); + for (Schemas.GetListsPostsResponse page : client.lists().getPostsPages(listId, options)) { + if (page.getData() != null) { + allPosts.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " posts (total: " + allPosts.size() + ")"); + } + } + System.out.println("Total Posts: " + allPosts.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allPosts.subList(0, Math.min(5, allPosts.size())))); + } + } +} diff --git a/java/lists/RemoveMember.java b/java/lists/RemoveMember.java new file mode 100644 index 0000000..d2124b4 --- /dev/null +++ b/java/lists/RemoveMember.java @@ -0,0 +1,86 @@ +package lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Remove List Member - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/lists/:id/members/:user_id + * Docs: https://developer.x.com/en/docs/twitter-api/lists/list-members/api-reference/delete-lists-id-members-user_id + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class RemoveMember { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "list.read", "list.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String listId = "your-list-id"; + String userId = "user-id-to-remove"; + Schemas.RemoveListsMemberByUserIdResponse response = client.lists().removeMemberByUserId(listId, userId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/lists/UpdateList.java b/java/lists/UpdateList.java new file mode 100644 index 0000000..161a98b --- /dev/null +++ b/java/lists/UpdateList.java @@ -0,0 +1,89 @@ +package lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Update List - X API v2 + * + * Endpoint: PUT https://api.x.com/2/lists/:id + * Docs: https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/put-lists-id + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class UpdateList { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "list.read", "list.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String listId = "list-id"; + Schemas.UpdateListsRequest request = new Schemas.UpdateListsRequest() + .name("update-name-of-list") + .description("update-description-of-list") + .privateValue(false); + Schemas.UpdateListsResponse response = client.lists().update(listId, request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/media/MediaUploadV2.java b/java/media/MediaUploadV2.java new file mode 100644 index 0000000..08fc96d --- /dev/null +++ b/java/media/MediaUploadV2.java @@ -0,0 +1,134 @@ +package media; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Media Upload v2 (Chunked Video Upload) - X API v2 + * + * Endpoint: POST https://api.x.com/2/media/upload/initialize | append | finalize + * Docs: https://developer.x.com/en/docs/twitter-api/media/upload-media/api-reference + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class MediaUploadV2 { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("media.write", "users.read", "tweet.read", "tweet.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + Path videoPath = Path.of(System.getenv().getOrDefault("VIDEO_FILE", "path/to/your/video.mp4")); + byte[] allBytes = Files.readAllBytes(videoPath); + + // 1. Initialize chunked upload + Schemas.InitializeMediaUploadResponse initRes = client.media().initializeUpload( + new Schemas.InitializeMediaUploadRequest() + .mediaType("video/mp4") + .mediaCategory("tweet_video") + .totalBytes((long) allBytes.length)); + String mediaId = initRes.getData().getId(); + System.out.println("Initialized upload for mediaId: " + mediaId); + + // 2. Append 4 MiB chunks + int chunkSize = 4 * 1024 * 1024; + int segmentIndex = 0; + for (int offset = 0; offset < allBytes.length; offset += chunkSize) { + int end = Math.min(offset + chunkSize, allBytes.length); + byte[] chunk = Arrays.copyOfRange(allBytes, offset, end); + client.media().appendUpload( + mediaId, + new Schemas.AppendMediaUploadRequest() + .segmentIndex(segmentIndex++) + .media(Base64.getEncoder().encodeToString(chunk))); + System.out.println("Uploaded " + end + " / " + allBytes.length + " bytes"); + } + + // 3. Finalize & poll processing status + Schemas.FinalizeMediaUploadResponse finRes = client.media().finalizeUpload(mediaId); + Schemas.FinalizeMediaUploadResponseDataProcessingInfo proc = + finRes.getData() != null ? finRes.getData().getProcessingInfo() : null; + while (proc != null && proc.getState() != null + && !"succeeded".equals(proc.getState()) && !"failed".equals(proc.getState())) { + long waitSecs = proc.getCheckAfterSecs() != null ? proc.getCheckAfterSecs() : 2L; + Thread.sleep(waitSecs * 1000L); + Schemas.GetMediaUploadStatusResponse statusRes = client.media().getUploadStatus( + mediaId, MediaClient.GetUploadStatusOptions.builder().command("STATUS")); + Schemas.GetMediaUploadStatusResponseDataProcessingInfo nextProc = + statusRes.getData() != null ? statusRes.getData().getProcessingInfo() : null; + if (nextProc == null) { + break; + } + proc = new Schemas.FinalizeMediaUploadResponseDataProcessingInfo() + .state(nextProc.getState()) + .checkAfterSecs(nextProc.getCheckAfterSecs()); + } + + // 4. Create post with attached video + Schemas.CreatePostsResponse postRes = client.posts().create( + new Schemas.CreatePostsRequest() + .text("Uploaded a video using XDK for Java!") + .media(new Schemas.CreatePostsMedia().mediaIds(Arrays.asList(mediaId)))); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(postRes.getData())); + } + } +} diff --git a/java/media/Upload.java b/java/media/Upload.java new file mode 100644 index 0000000..838e4a9 --- /dev/null +++ b/java/media/Upload.java @@ -0,0 +1,91 @@ +package media; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Media Upload (Single Payload) - X API v2 + * + * Endpoint: POST https://api.x.com/2/media/upload + * Docs: https://developer.x.com/en/docs/twitter-api/media/upload-media/api-reference + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class Upload { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("media.write", "tweet.read", "tweet.write", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + Path mediaPath = Path.of(System.getenv().getOrDefault("MEDIA_FILE", "path/to/your/image.jpg")); + String base64Media = Base64.getEncoder().encodeToString(Files.readAllBytes(mediaPath)); + + Schemas.MediaUploadRequest request = new Schemas.MediaUploadRequest() + .media(base64Media) + .mediaCategory("tweet_image"); + Schemas.MediaUploadResponse response = client.media().upload(request); + System.out.println("Media ID: " + response.getData().getId()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/pom.xml b/java/pom.xml new file mode 100644 index 0000000..88bf9bc --- /dev/null +++ b/java/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + + com.x + xdk-java-samples + 1.0.0 + jar + + X API v2 Java Samples (XDK) + Official Java 17+ sample code for the X API v2 powered by com.x:xdk + + + UTF-8 + 17 + [0.1.0,) + + + + + com.x + xdk + ${xdk.version} + + + + + ${project.basedir} + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 17 + + + + org.codehaus.mojo + exec-maven-plugin + 3.1.0 + + + + diff --git a/java/posts/CreatePost.java b/java/posts/CreatePost.java new file mode 100644 index 0000000..bd0c5c1 --- /dev/null +++ b/java/posts/CreatePost.java @@ -0,0 +1,85 @@ +package posts; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Create Post - X API v2 + * + * Endpoint: POST https://api.x.com/2/tweets + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class CreatePost { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "tweet.write", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + Schemas.CreatePostsRequest request = new Schemas.CreatePostsRequest().text("Hello world!"); + Schemas.CreatePostsResponse response = client.posts().create(request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/posts/DeletePost.java b/java/posts/DeletePost.java new file mode 100644 index 0000000..1ba8a38 --- /dev/null +++ b/java/posts/DeletePost.java @@ -0,0 +1,85 @@ +package posts; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Delete Post - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/tweets/:id + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/delete-tweets-id + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class DeletePost { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "tweet.write", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String postId = "1997118644242014409"; + Schemas.DeletePostsResponse response = client.posts().delete(postId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/posts/FullArchiveSearchDemo.java b/java/posts/FullArchiveSearchDemo.java deleted file mode 100644 index 9f058c2..0000000 --- a/java/posts/FullArchiveSearchDemo.java +++ /dev/null @@ -1,65 +0,0 @@ -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'='' - - 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 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; - } - -} \ No newline at end of file diff --git a/java/posts/FullArchiveTweetCountsDemo.java b/java/posts/FullArchiveTweetCountsDemo.java deleted file mode 100644 index 65bb037..0000000 --- a/java/posts/FullArchiveTweetCountsDemo.java +++ /dev/null @@ -1,67 +0,0 @@ -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'='' - - 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 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; - } - -} \ No newline at end of file diff --git a/java/posts/GetLikingUsers.java b/java/posts/GetLikingUsers.java new file mode 100644 index 0000000..8dbefcb --- /dev/null +++ b/java/posts/GetLikingUsers.java @@ -0,0 +1,96 @@ +package posts; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Liking Users - X API v2 + * + * Endpoint: GET https://api.x.com/2/tweets/:id/liking_users + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/get-tweets-id-liking_users + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class GetLikingUsers { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "like.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String postId = "post-id"; + PostsClient.GetLikingUsersOptions options = PostsClient.GetLikingUsersOptions.builder() + .maxResults(100) + .userFields(Arrays.asList("created_at", "description")); + + List allUsers = new ArrayList<>(); + for (Schemas.GetPostsLikingUsersResponse page : client.posts().getLikingUsersPages(postId, options)) { + if (page.getData() != null) { + allUsers.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " users (total: " + allUsers.size() + ")"); + } + } + System.out.println("Total Users: " + allUsers.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allUsers.subList(0, Math.min(5, allUsers.size())))); + } + } +} diff --git a/java/posts/GetPostById.java b/java/posts/GetPostById.java new file mode 100644 index 0000000..4c00c12 --- /dev/null +++ b/java/posts/GetPostById.java @@ -0,0 +1,40 @@ +package posts; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Single Post Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/tweets/:id + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets-id + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetPostById { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String postId = "post-id"; + PostsClient.GetByIdOptions options = PostsClient.GetByIdOptions.builder() + .postFields(Arrays.asList("created_at", "author_id", "lang", "source", "public_metrics", "entities")); + Schemas.GetPostsByIdResponse response = client.posts().getById(postId, options); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/posts/GetPostCountsAll.java b/java/posts/GetPostCountsAll.java new file mode 100644 index 0000000..346e1ef --- /dev/null +++ b/java/posts/GetPostCountsAll.java @@ -0,0 +1,47 @@ +package posts; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Full-Archive Post Counts - X API v2 + * + * Endpoint: GET https://api.x.com/2/tweets/counts/all + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/counts/api-reference/get-tweets-counts-all + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetPostCountsAll { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String query = "from:XDevelopers"; + PostsClient.GetCountsAllOptions options = PostsClient.GetCountsAllOptions.builder().granularity("day"); + + List allCounts = new ArrayList<>(); + for (Schemas.GetPostsCountsAllResponse page : client.posts().getCountsAllPages(query, options)) { + if (page.getData() != null) { + allCounts.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " count buckets (total: " + allCounts.size() + ")"); + } + } + System.out.println("Total Count Buckets: " + allCounts.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allCounts)); + } + } +} diff --git a/java/posts/GetPostCountsRecent.java b/java/posts/GetPostCountsRecent.java new file mode 100644 index 0000000..9df3e7e --- /dev/null +++ b/java/posts/GetPostCountsRecent.java @@ -0,0 +1,47 @@ +package posts; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Recent Post Counts - X API v2 + * + * Endpoint: GET https://api.x.com/2/tweets/counts/recent + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/counts/api-reference/get-tweets-counts-recent + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetPostCountsRecent { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String query = "from:XDevelopers"; + PostsClient.GetCountsRecentOptions options = PostsClient.GetCountsRecentOptions.builder().granularity("day"); + + List allCounts = new ArrayList<>(); + for (Schemas.GetPostsCountsRecentResponse page : client.posts().getCountsRecentPages(query, options)) { + if (page.getData() != null) { + allCounts.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " count buckets (total: " + allCounts.size() + ")"); + } + } + System.out.println("Total Count Buckets: " + allCounts.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allCounts)); + } + } +} diff --git a/java/posts/GetPostsByIds.java b/java/posts/GetPostsByIds.java new file mode 100644 index 0000000..e654f35 --- /dev/null +++ b/java/posts/GetPostsByIds.java @@ -0,0 +1,40 @@ +package posts; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Post Lookup by IDs - X API v2 + * + * Endpoint: GET https://api.x.com/2/tweets + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetPostsByIds { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + List postIds = Arrays.asList("post-id-1", "post-id-2"); + PostsClient.GetByIdsOptions options = PostsClient.GetByIdsOptions.builder() + .postFields(Arrays.asList("created_at", "author_id", "lang", "source", "public_metrics", "context_annotations", "entities")); + Schemas.GetPostsByIdsResponse response = client.posts().getByIds(postIds, options); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/posts/GetQuotedPosts.java b/java/posts/GetQuotedPosts.java new file mode 100644 index 0000000..572d5cc --- /dev/null +++ b/java/posts/GetQuotedPosts.java @@ -0,0 +1,49 @@ +package posts; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Quote Posts Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/tweets/:id/quote_tweets + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/quote-tweets/api-reference/get-tweets-id-quote_tweets + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetQuotedPosts { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String postId = "1409931481552543749"; + PostsClient.GetQuotedOptions options = PostsClient.GetQuotedOptions.builder() + .maxResults(100) + .postFields(Arrays.asList("created_at")); + + List allPosts = new ArrayList<>(); + for (Schemas.GetPostsQuotedPostsResponse page : client.posts().getQuotedPages(postId, options)) { + if (page.getData() != null) { + allPosts.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " posts (total: " + allPosts.size() + ")"); + } + } + System.out.println("Total Quote Posts: " + allPosts.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allPosts.subList(0, Math.min(5, allPosts.size())))); + } + } +} diff --git a/java/posts/GetRepostedBy.java b/java/posts/GetRepostedBy.java new file mode 100644 index 0000000..f91e3f4 --- /dev/null +++ b/java/posts/GetRepostedBy.java @@ -0,0 +1,49 @@ +package posts; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Reposted By (Users who reposted) - X API v2 + * + * Endpoint: GET https://api.x.com/2/tweets/:id/retweeted_by + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/get-tweets-id-retweeted_by + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetRepostedBy { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String postId = "post-id"; + PostsClient.GetRepostedByOptions options = PostsClient.GetRepostedByOptions.builder() + .maxResults(100) + .userFields(Arrays.asList("created_at", "description")); + + List allUsers = new ArrayList<>(); + for (Schemas.GetPostsRepostedByResponse page : client.posts().getRepostedByPages(postId, options)) { + if (page.getData() != null) { + allUsers.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " users (total: " + allUsers.size() + ")"); + } + } + System.out.println("Total Users: " + allUsers.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allUsers.subList(0, Math.min(5, allUsers.size())))); + } + } +} diff --git a/java/posts/HideReply.java b/java/posts/HideReply.java new file mode 100644 index 0000000..1cdbd06 --- /dev/null +++ b/java/posts/HideReply.java @@ -0,0 +1,86 @@ +package posts; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Hide Reply - X API v2 + * + * Endpoint: PUT https://api.x.com/2/tweets/:id/hidden + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/hide-replies/api-reference/put-tweets-id-hidden + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class HideReply { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "tweet.write", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String replyPostId = "reply-tweet-id-to-hide"; + Schemas.HidePostsReplyRequest request = new Schemas.HidePostsReplyRequest().hidden(true); + Schemas.HidePostsReplyResponse response = client.posts().hideReply(replyPostId, request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/posts/QuoteTweetsDemo.java b/java/posts/QuoteTweetsDemo.java deleted file mode 100644 index e9fc858..0000000 --- a/java/posts/QuoteTweetsDemo.java +++ /dev/null @@ -1,64 +0,0 @@ -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'='' - - 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 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; - } -} diff --git a/java/posts/RecentSearchDemo.java b/java/posts/RecentSearchDemo.java deleted file mode 100644 index e504b46..0000000 --- a/java/posts/RecentSearchDemo.java +++ /dev/null @@ -1,65 +0,0 @@ -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'='' - - 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 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; - } - -} \ No newline at end of file diff --git a/java/posts/RecentTweetCountsDemo.java b/java/posts/RecentTweetCountsDemo.java deleted file mode 100644 index 1735b9c..0000000 --- a/java/posts/RecentTweetCountsDemo.java +++ /dev/null @@ -1,66 +0,0 @@ -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'='' - - 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 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; - } - -} \ No newline at end of file diff --git a/java/posts/SearchAll.java b/java/posts/SearchAll.java new file mode 100644 index 0000000..75db13d --- /dev/null +++ b/java/posts/SearchAll.java @@ -0,0 +1,49 @@ +package posts; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Full-Archive Search - X API v2 + * + * Endpoint: GET https://api.x.com/2/tweets/search/all + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-all + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class SearchAll { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String query = "(from:XDevelopers -is:retweet) OR #XDevelopers"; + PostsClient.SearchAllOptions options = PostsClient.SearchAllOptions.builder() + .maxResults(100) + .postFields(Arrays.asList("author_id", "created_at")); + + List allPosts = new ArrayList<>(); + for (Schemas.SearchPostsAllResponse page : client.posts().searchAllPages(query, options)) { + if (page.getData() != null) { + allPosts.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " posts (total: " + allPosts.size() + ")"); + } + } + System.out.println("Total Posts: " + allPosts.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allPosts.subList(0, Math.min(5, allPosts.size())))); + } + } +} diff --git a/java/posts/SearchRecent.java b/java/posts/SearchRecent.java index 9540c56..6356200 100644 --- a/java/posts/SearchRecent.java +++ b/java/posts/SearchRecent.java @@ -1,64 +1,49 @@ +package posts; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + /** * 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 { + private static final ObjectMapper MAPPER = new ObjectMapper(); - public static void main(String[] args) throws IOException, URISyntaxException { + public static void main(String[] args) throws Exception { String bearerToken = System.getenv("BEARER_TOKEN"); - - if (bearerToken == null) { - System.err.println("BEARER_TOKEN environment variable not set"); - System.exit(1); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); } - 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"; + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String query = "(from:XDevelopers -is:retweet) OR #XDevelopers"; + PostsClient.SearchRecentOptions options = PostsClient.SearchRecentOptions.builder() + .maxResults(100) + .postFields(Arrays.asList("author_id", "created_at")); + + List allPosts = new ArrayList<>(); + for (Schemas.SearchPostsRecentResponse page : client.posts().searchRecentPages(query, options)) { + if (page.getData() != null) { + allPosts.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " posts (total: " + allPosts.size() + ")"); + } + } + System.out.println("Total Posts: " + allPosts.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allPosts.subList(0, Math.min(5, allPosts.size())))); } } } diff --git a/java/posts/TweetsDemo.java b/java/posts/TweetsDemo.java deleted file mode 100644 index 60c41e6..0000000 --- a/java/posts/TweetsDemo.java +++ /dev/null @@ -1,65 +0,0 @@ -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'='' - - 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 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; - } -} \ No newline at end of file diff --git a/java/spaces/GetSpacesByIds.java b/java/spaces/GetSpacesByIds.java new file mode 100644 index 0000000..0c013c7 --- /dev/null +++ b/java/spaces/GetSpacesByIds.java @@ -0,0 +1,41 @@ +package spaces; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Spaces Lookup by IDs - 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) + * Required env vars: BEARER_TOKEN + */ +public class GetSpacesByIds { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + List spaceIds = Arrays.asList("space-id-1", "space-id-2"); + SpacesClient.GetByIdsOptions options = SpacesClient.GetByIdsOptions.builder() + .spaceFields(Arrays.asList("title", "created_at")) + .expansions(Arrays.asList("creator_id")); + Schemas.GetSpacesByIdsResponse response = client.spaces().getByIds(spaceIds, options); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/spaces/SearchSpaces.java b/java/spaces/SearchSpaces.java new file mode 100644 index 0000000..5366ea9 --- /dev/null +++ b/java/spaces/SearchSpaces.java @@ -0,0 +1,41 @@ +package spaces; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Search Spaces - X API v2 + * + * Endpoint: GET https://api.x.com/2/spaces/search + * Docs: https://developer.x.com/en/docs/twitter-api/spaces/search/api-reference/get-spaces-search + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class SearchSpaces { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String searchTerm = "NBA"; + SpacesClient.SearchOptions options = SpacesClient.SearchOptions.builder() + .spaceFields(Arrays.asList("title", "created_at")) + .expansions(Arrays.asList("creator_id")); + Schemas.SearchSpacesResponse response = client.spaces().search(searchTerm, options); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/spaces/SearchSpacesDemo.java b/java/spaces/SearchSpacesDemo.java deleted file mode 100644 index 2e92b2a..0000000 --- a/java/spaces/SearchSpacesDemo.java +++ /dev/null @@ -1,66 +0,0 @@ -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'='' - - 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 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; - } - -} \ No newline at end of file diff --git a/java/spaces/SpacesLookupDemo.java b/java/spaces/SpacesLookupDemo.java deleted file mode 100644 index 2e92b2a..0000000 --- a/java/spaces/SpacesLookupDemo.java +++ /dev/null @@ -1,66 +0,0 @@ -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'='' - - 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 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; - } - -} \ No newline at end of file diff --git a/java/streams/FilteredStreamDemo.java b/java/streams/FilteredStreamDemo.java deleted file mode 100644 index 6a30c85..0000000 --- a/java/streams/FilteredStreamDemo.java +++ /dev/null @@ -1,183 +0,0 @@ -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'='' - - public static void main(String args[]) throws IOException, URISyntaxException { - String bearerToken = System.getenv("BEARER_TOKEN"); - if (null != bearerToken) { - Map 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 rules) throws IOException, URISyntaxException { - List 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 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 getRules(String bearerToken) throws URISyntaxException, IOException { - List 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 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 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 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 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)); - } - } - -} diff --git a/java/streams/SampledStream.java b/java/streams/SampledStream.java deleted file mode 100644 index 4d0444e..0000000 --- a/java/streams/SampledStream.java +++ /dev/null @@ -1,60 +0,0 @@ -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'='' - - 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(); - } - } - - } -} diff --git a/java/streams/StreamPostsFiltered.java b/java/streams/StreamPostsFiltered.java new file mode 100644 index 0000000..619d721 --- /dev/null +++ b/java/streams/StreamPostsFiltered.java @@ -0,0 +1,69 @@ +package streams; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Filtered Stream - X API v2 + * + * Endpoint: GET https://api.x.com/2/tweets/search/stream + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/filtered-stream/api-reference/get-tweets-search-stream + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class StreamPostsFiltered { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + // 1. Fetch existing rules + Schemas.GetRulesResponse currentRules = client.stream().getRules(); + + // 2. Delete existing rules by value if present + if (currentRules.getData() != null && !currentRules.getData().isEmpty()) { + List existingValues = new ArrayList<>(); + for (Schemas.GetRulesResponseData rule : currentRules.getData()) { + if (rule.getValue() != null) { + existingValues.add(rule.getValue()); + } + } + if (!existingValues.isEmpty()) { + client.stream().updateRules(new Schemas.UpdateRulesRequest() + .delete(new Schemas.UpdateRulesDelete().values(existingValues))); + } + } + + // 3. Add sample filter rules + List sampleRules = Arrays.asList( + new Schemas.UpdateRulesAdd().value("dog has:images").tag("dog pictures"), + new Schemas.UpdateRulesAdd().value("cat has:images -grumpy").tag("cat pictures")); + Schemas.UpdateRulesResponse added = client.stream().updateRules(new Schemas.UpdateRulesRequest().add(sampleRules)); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(added.getData())); + + // 4. Stream matching posts in real time + StreamClient.PostsOptions options = StreamClient.PostsOptions.builder() + .tweetFields(Arrays.asList("id", "text", "created_at")); + try (EventStream stream = client.stream().posts(options)) { + for (Schemas.StreamPostsResponse event : stream) { + if (event.getData() != null) { + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(event.getData())); + } + } + } + } + } +} diff --git a/java/streams/StreamPostsSample.java b/java/streams/StreamPostsSample.java new file mode 100644 index 0000000..e493527 --- /dev/null +++ b/java/streams/StreamPostsSample.java @@ -0,0 +1,42 @@ +package streams; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Sampled Stream (1% Volume) - X API v2 + * + * Endpoint: GET https://api.x.com/2/tweets/sample/stream + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/volume-streams/api-reference/get-tweets-sample-stream + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class StreamPostsSample { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + try (EventStream stream = client.stream().postsSample()) { + for (Schemas.StreamPostsSampleResponse event : stream) { + if (event.getData() != null) { + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(event.getData())); + } + } + } + } + } +} diff --git a/java/timelines/UserMentionsDemo.java b/java/timelines/UserMentionsDemo.java deleted file mode 100644 index efff5a3..0000000 --- a/java/timelines/UserMentionsDemo.java +++ /dev/null @@ -1,64 +0,0 @@ -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'='' - - 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 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; - } -} diff --git a/java/timelines/UserTweetsDemo.java b/java/timelines/UserTweetsDemo.java deleted file mode 100644 index d0b1edb..0000000 --- a/java/timelines/UserTweetsDemo.java +++ /dev/null @@ -1,64 +0,0 @@ -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'='' - - 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 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; - } -} diff --git a/java/timelines/reverse-chron-home-timeline-java-sdk.java b/java/timelines/reverse-chron-home-timeline-java-sdk.java deleted file mode 100644 index 4605598..0000000 --- a/java/timelines/reverse-chron-home-timeline-java-sdk.java +++ /dev/null @@ -1,130 +0,0 @@ -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 expansions = new HashSet<>(Arrays.asList()); // Set | A comma separated list of fields to expand. - Set tweetFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Tweet fields to display. - Set userFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of User fields to display. - Set mediaFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Media fields to display. - Set placeFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Place fields to display. - Set pollFields = new HashSet<>(Arrays.asList()); // Set | 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(); - } - } -} diff --git a/java/usage/GetUsage.java b/java/usage/GetUsage.java new file mode 100644 index 0000000..4e9ad39 --- /dev/null +++ b/java/usage/GetUsage.java @@ -0,0 +1,38 @@ +package usage; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Usage Posts - X API v2 + * + * Endpoint: GET https://api.x.com/2/usage/tweets + * Docs: https://developer.x.com/en/docs/twitter-api/usage/api-reference/get-usage-tweets + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetUsage { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + UsageClient.GetOptions options = UsageClient.GetOptions.builder().days(7); + Schemas.GetUsageResponse response = client.usage().get(options); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/usage/UsageTweetsDemo.java b/java/usage/UsageTweetsDemo.java deleted file mode 100644 index ecae4b7..0000000 --- a/java/usage/UsageTweetsDemo.java +++ /dev/null @@ -1,58 +0,0 @@ -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'='' - - 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; - } -} \ No newline at end of file diff --git a/java/users/FollowersLookupDemo.java b/java/users/FollowersLookupDemo.java deleted file mode 100644 index 015d8f8..0000000 --- a/java/users/FollowersLookupDemo.java +++ /dev/null @@ -1,64 +0,0 @@ -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'='' - - 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 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; - } -} diff --git a/java/users/FollowingLookupDemo.java b/java/users/FollowingLookupDemo.java deleted file mode 100644 index 6b1d453..0000000 --- a/java/users/FollowingLookupDemo.java +++ /dev/null @@ -1,64 +0,0 @@ -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'='' - - 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 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; - } -} diff --git a/java/users/GetUsersByUsernames.java b/java/users/GetUsersByUsernames.java new file mode 100644 index 0000000..39e461d --- /dev/null +++ b/java/users/GetUsersByUsernames.java @@ -0,0 +1,40 @@ +package users; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * User Lookup by Usernames - 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 + */ +public class GetUsersByUsernames { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + List usernames = Arrays.asList("XDevelopers", "API"); + UsersClient.GetByUsernamesOptions options = UsersClient.GetByUsernamesOptions.builder() + .userFields(Arrays.asList("description", "created_at")); + Schemas.GetUsersByUsernamesResponse response = client.users().getByUsernames(usernames, options); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/GetUsersByUsernamesUserContext.java b/java/users/GetUsersByUsernamesUserContext.java new file mode 100644 index 0000000..309deaf --- /dev/null +++ b/java/users/GetUsersByUsernamesUserContext.java @@ -0,0 +1,87 @@ +package users; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * User Lookup (User Context) - 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: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class GetUsersByUsernamesUserContext { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + List usernames = Arrays.asList("XDevelopers", "API"); + UsersClient.GetByUsernamesOptions options = UsersClient.GetByUsernamesOptions.builder() + .userFields(Arrays.asList("created_at", "description")); + Schemas.GetUsersByUsernamesResponse response = client.users().getByUsernames(usernames, options); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/GetUsersMe.java b/java/users/GetUsersMe.java new file mode 100644 index 0000000..98c7bda --- /dev/null +++ b/java/users/GetUsersMe.java @@ -0,0 +1,86 @@ +package users; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Authenticated User Lookup (Me) - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/me + * Docs: https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-me + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class GetUsersMe { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + UsersClient.GetMeOptions options = UsersClient.GetMeOptions.builder() + .userFields(Arrays.asList("created_at", "description")); + Schemas.GetUsersMeResponse response = client.users().getMe(options); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/Lookup.java b/java/users/Lookup.java deleted file mode 100644 index ff0d781..0000000 --- a/java/users/Lookup.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 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"; - } - } -} diff --git a/java/users/UsersDemo.java b/java/users/UsersDemo.java deleted file mode 100644 index f9fd8c9..0000000 --- a/java/users/UsersDemo.java +++ /dev/null @@ -1,66 +0,0 @@ -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'='' - - 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 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; - } - -} \ No newline at end of file diff --git a/java/users/block/GetBlocking.java b/java/users/block/GetBlocking.java new file mode 100644 index 0000000..0f9b899 --- /dev/null +++ b/java/users/block/GetBlocking.java @@ -0,0 +1,96 @@ +package users.block; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Blocked Users Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/blocking + * Docs: https://developer.x.com/en/docs/twitter-api/users/blocks/api-reference/get-users-blocking + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class GetBlocking { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "offline.access", "block.read"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String userId = client.users().getMe().getData().getId(); + UsersClient.GetBlockingOptions options = UsersClient.GetBlockingOptions.builder() + .maxResults(100) + .userFields(Arrays.asList("created_at", "description")); + + List allUsers = new ArrayList<>(); + for (Schemas.GetUsersBlockingResponse page : client.users().getBlockingPages(userId, options)) { + if (page.getData() != null) { + allUsers.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " users (total: " + allUsers.size() + ")"); + } + } + System.out.println("Total Blocked Users: " + allUsers.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allUsers.subList(0, Math.min(5, allUsers.size())))); + } + } +} diff --git a/java/users/bookmark/CreateBookmark.java b/java/users/bookmark/CreateBookmark.java new file mode 100644 index 0000000..94cb394 --- /dev/null +++ b/java/users/bookmark/CreateBookmark.java @@ -0,0 +1,87 @@ +package users.bookmark; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Create Bookmark - X API v2 + * + * Endpoint: POST https://api.x.com/2/users/:id/bookmarks + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/post-users-id-bookmarks + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class CreateBookmark { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "bookmark.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String postId = "post-id-to-bookmark"; + String userId = client.users().getMe().getData().getId(); + Schemas.CreateUsersBookmarkRequest request = new Schemas.CreateUsersBookmarkRequest().tweetId(postId); + Object response = client.users().createBookmark(userId, request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response)); + } + } +} diff --git a/java/users/bookmark/DeleteBookmark.java b/java/users/bookmark/DeleteBookmark.java new file mode 100644 index 0000000..893294d --- /dev/null +++ b/java/users/bookmark/DeleteBookmark.java @@ -0,0 +1,86 @@ +package users.bookmark; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Delete Bookmark - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/users/:id/bookmarks/:tweet_id + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/delete-users-id-bookmarks-tweet_id + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class DeleteBookmark { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "bookmark.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String postId = "post-id-to-unbookmark"; + String userId = client.users().getMe().getData().getId(); + Schemas.DeleteUsersBookmarkResponse response = client.users().deleteBookmark(userId, postId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/bookmark/GetBookmarks.java b/java/users/bookmark/GetBookmarks.java new file mode 100644 index 0000000..e72506c --- /dev/null +++ b/java/users/bookmark/GetBookmarks.java @@ -0,0 +1,96 @@ +package users.bookmark; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Bookmarks Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/bookmarks + * Docs: https://developer.x.com/en/docs/twitter-api/bookmarks/api-reference/get-users-id-bookmarks + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class GetBookmarks { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("bookmark.read", "tweet.read", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String userId = client.users().getMe().getData().getId(); + UsersClient.GetBookmarksOptions options = UsersClient.GetBookmarksOptions.builder() + .maxResults(100) + .postFields(Arrays.asList("created_at")); + + List allBookmarks = new ArrayList<>(); + for (Schemas.GetUsersBookmarksResponse page : client.users().getBookmarksPages(userId, options)) { + if (page.getData() != null) { + allBookmarks.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " bookmarks (total: " + allBookmarks.size() + ")"); + } + } + System.out.println("Total Bookmarks: " + allBookmarks.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allBookmarks.subList(0, Math.min(5, allBookmarks.size())))); + } + } +} diff --git a/java/users/follow/FollowUser.java b/java/users/follow/FollowUser.java new file mode 100644 index 0000000..6f5d749 --- /dev/null +++ b/java/users/follow/FollowUser.java @@ -0,0 +1,87 @@ +package users.follow; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Follow User - X API v2 + * + * Endpoint: POST https://api.x.com/2/users/:id/following + * Docs: https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/post-users-id-following + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class FollowUser { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "follows.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String targetUserId = "user-id-to-follow"; + String userId = client.users().getMe().getData().getId(); + Schemas.FollowUserRequest request = new Schemas.FollowUserRequest().targetUserId(targetUserId); + Schemas.FollowUserResponse response = client.users().followUser(userId, request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/follow/GetFollowers.java b/java/users/follow/GetFollowers.java new file mode 100644 index 0000000..f511ef2 --- /dev/null +++ b/java/users/follow/GetFollowers.java @@ -0,0 +1,49 @@ +package users.follow; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * User Followers Lookup - 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) + * Required env vars: BEARER_TOKEN + */ +public class GetFollowers { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String userId = "2244994945"; + UsersClient.GetFollowersOptions options = UsersClient.GetFollowersOptions.builder() + .maxResults(100) + .userFields(Arrays.asList("created_at")); + + List allUsers = new ArrayList<>(); + for (Schemas.GetUsersFollowersResponse page : client.users().getFollowersPages(userId, options)) { + if (page.getData() != null) { + allUsers.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " users (total: " + allUsers.size() + ")"); + } + } + System.out.println("Total Followers: " + allUsers.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allUsers.subList(0, Math.min(5, allUsers.size())))); + } + } +} diff --git a/java/users/follow/GetFollowing.java b/java/users/follow/GetFollowing.java new file mode 100644 index 0000000..291e038 --- /dev/null +++ b/java/users/follow/GetFollowing.java @@ -0,0 +1,49 @@ +package users.follow; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * User Following Lookup - 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) + * Required env vars: BEARER_TOKEN + */ +public class GetFollowing { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String userId = "2244994945"; + UsersClient.GetFollowingOptions options = UsersClient.GetFollowingOptions.builder() + .maxResults(100) + .userFields(Arrays.asList("created_at")); + + List allUsers = new ArrayList<>(); + for (Schemas.GetUsersFollowingResponse page : client.users().getFollowingPages(userId, options)) { + if (page.getData() != null) { + allUsers.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " users (total: " + allUsers.size() + ")"); + } + } + System.out.println("Total Following: " + allUsers.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allUsers.subList(0, Math.min(5, allUsers.size())))); + } + } +} diff --git a/java/users/follow/UnfollowUser.java b/java/users/follow/UnfollowUser.java new file mode 100644 index 0000000..629b40f --- /dev/null +++ b/java/users/follow/UnfollowUser.java @@ -0,0 +1,86 @@ +package users.follow; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Unfollow User - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/users/:source_user_id/following/:target_user_id + * Docs: https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/delete-users-source_user_id-following + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class UnfollowUser { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "follows.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String targetUserId = "user-id-to-unfollow"; + String userId = client.users().getMe().getData().getId(); + Schemas.UnfollowUserResponse response = client.users().unfollowUser(userId, targetUserId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/like/GetLikedPosts.java b/java/users/like/GetLikedPosts.java new file mode 100644 index 0000000..a9f1bc6 --- /dev/null +++ b/java/users/like/GetLikedPosts.java @@ -0,0 +1,96 @@ +package users.like; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Liked Posts - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/liked_tweets + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/get-users-id-liked_tweets + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class GetLikedPosts { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "like.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String userId = client.users().getMe().getData().getId(); + UsersClient.GetLikedPostsOptions options = UsersClient.GetLikedPostsOptions.builder() + .maxResults(100) + .postFields(Arrays.asList("lang", "author_id")); + + List allPosts = new ArrayList<>(); + for (Schemas.GetUsersLikedPostsResponse page : client.users().getLikedPostsPages(userId, options)) { + if (page.getData() != null) { + allPosts.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " posts (total: " + allPosts.size() + ")"); + } + } + System.out.println("Total Liked Posts: " + allPosts.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allPosts.subList(0, Math.min(5, allPosts.size())))); + } + } +} diff --git a/java/users/like/LikePost.java b/java/users/like/LikePost.java new file mode 100644 index 0000000..83a23e0 --- /dev/null +++ b/java/users/like/LikePost.java @@ -0,0 +1,87 @@ +package users.like; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Like a Post - X API v2 + * + * Endpoint: POST https://api.x.com/2/users/:id/likes + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/post-users-id-likes + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class LikePost { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "tweet.write", "users.read", "offline.access", "like.write"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String postId = "post-id"; + String userId = client.users().getMe().getData().getId(); + Schemas.LikePostRequest request = new Schemas.LikePostRequest().tweetId(postId); + Schemas.LikePostResponse response = client.users().likePost(userId, request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/like/UnlikePost.java b/java/users/like/UnlikePost.java new file mode 100644 index 0000000..8e7e4ec --- /dev/null +++ b/java/users/like/UnlikePost.java @@ -0,0 +1,86 @@ +package users.like; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Unlike a Post - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/users/:id/likes/:tweet_id + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/delete-users-id-likes-tweet_id + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class UnlikePost { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "tweet.write", "users.read", "offline.access", "like.write"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String postId = "post-id"; + String userId = client.users().getMe().getData().getId(); + Schemas.UnlikePostResponse response = client.users().unlikePost(userId, postId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/lists/FollowList.java b/java/users/lists/FollowList.java new file mode 100644 index 0000000..32f831c --- /dev/null +++ b/java/users/lists/FollowList.java @@ -0,0 +1,87 @@ +package users.lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Follow List - X API v2 + * + * Endpoint: POST https://api.x.com/2/users/:id/followed_lists + * Docs: https://developer.x.com/en/docs/twitter-api/lists/list-follows/api-reference/post-users-id-followed_lists + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class FollowList { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "list.read", "list.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String userId = "your-user-id"; + String listId = "list-id-to-follow"; + Schemas.FollowListRequest request = new Schemas.FollowListRequest().listId(listId); + Schemas.FollowListResponse response = client.users().followList(userId, request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/lists/GetFollowedLists.java b/java/users/lists/GetFollowedLists.java new file mode 100644 index 0000000..1504ab9 --- /dev/null +++ b/java/users/lists/GetFollowedLists.java @@ -0,0 +1,49 @@ +package users.lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * User Followed Lists Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/followed_lists + * Docs: https://developer.x.com/en/docs/twitter-api/lists/list-follows/api-reference/get-users-id-followed_lists + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetFollowedLists { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String userId = "user-id"; + UsersClient.GetFollowedListsOptions options = UsersClient.GetFollowedListsOptions.builder() + .maxResults(100) + .listFields(Arrays.asList("created_at", "follower_count")); + + List allLists = new ArrayList<>(); + for (Schemas.GetUsersFollowedListsResponse page : client.users().getFollowedListsPages(userId, options)) { + if (page.getData() != null) { + allLists.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " lists (total: " + allLists.size() + ")"); + } + } + System.out.println("Total Followed Lists: " + allLists.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allLists.subList(0, Math.min(5, allLists.size())))); + } + } +} diff --git a/java/users/lists/GetListMemberships.java b/java/users/lists/GetListMemberships.java new file mode 100644 index 0000000..da5f7c9 --- /dev/null +++ b/java/users/lists/GetListMemberships.java @@ -0,0 +1,49 @@ +package users.lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * User List Memberships Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/list_memberships + * Docs: https://developer.x.com/en/docs/twitter-api/lists/list-members/api-reference/get-users-id-list_memberships + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetListMemberships { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String userId = "user-id"; + UsersClient.GetListMembershipsOptions options = UsersClient.GetListMembershipsOptions.builder() + .maxResults(100) + .listFields(Arrays.asList("created_at", "follower_count")); + + List allLists = new ArrayList<>(); + for (Schemas.GetUsersListMembershipsResponse page : client.users().getListMembershipsPages(userId, options)) { + if (page.getData() != null) { + allLists.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " lists (total: " + allLists.size() + ")"); + } + } + System.out.println("Total List Memberships: " + allLists.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allLists.subList(0, Math.min(5, allLists.size())))); + } + } +} diff --git a/java/users/lists/GetOwnedLists.java b/java/users/lists/GetOwnedLists.java new file mode 100644 index 0000000..ee975c1 --- /dev/null +++ b/java/users/lists/GetOwnedLists.java @@ -0,0 +1,49 @@ +package users.lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * User Owned Lists Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/owned_lists + * Docs: https://developer.x.com/en/docs/twitter-api/lists/list-lookup/api-reference/get-users-id-owned_lists + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetOwnedLists { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String userId = "user-id"; + UsersClient.GetOwnedListsOptions options = UsersClient.GetOwnedListsOptions.builder() + .maxResults(100) + .listFields(Arrays.asList("created_at", "follower_count")); + + List allLists = new ArrayList<>(); + for (Schemas.GetUsersOwnedListsResponse page : client.users().getOwnedListsPages(userId, options)) { + if (page.getData() != null) { + allLists.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " lists (total: " + allLists.size() + ")"); + } + } + System.out.println("Total Owned Lists: " + allLists.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allLists.subList(0, Math.min(5, allLists.size())))); + } + } +} diff --git a/java/users/lists/GetPinnedLists.java b/java/users/lists/GetPinnedLists.java new file mode 100644 index 0000000..fc4f3fb --- /dev/null +++ b/java/users/lists/GetPinnedLists.java @@ -0,0 +1,87 @@ +package users.lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Pinned Lists Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/pinned_lists + * Docs: https://developer.x.com/en/docs/twitter-api/lists/pinned-lists/api-reference/get-users-id-pinned_lists + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class GetPinnedLists { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "list.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String userId = "your-user-id"; + UsersClient.GetPinnedListsOptions options = UsersClient.GetPinnedListsOptions.builder() + .listFields(Arrays.asList("created_at", "description", "private")); + Schemas.GetUsersPinnedListsResponse response = client.users().getPinnedLists(userId, options); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/lists/PinList.java b/java/users/lists/PinList.java new file mode 100644 index 0000000..73a2dde --- /dev/null +++ b/java/users/lists/PinList.java @@ -0,0 +1,87 @@ +package users.lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Pin List - X API v2 + * + * Endpoint: POST https://api.x.com/2/users/:id/pinned_lists + * Docs: https://developer.x.com/en/docs/twitter-api/lists/pinned-lists/api-reference/post-users-id-pinned_lists + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class PinList { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "list.read", "list.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String userId = "your-user-id"; + String listId = "list-id-to-pin"; + Schemas.PinListRequest request = new Schemas.PinListRequest().listId(listId); + Schemas.PinListResponse response = client.users().pinList(userId, request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/lists/UnfollowList.java b/java/users/lists/UnfollowList.java new file mode 100644 index 0000000..1770122 --- /dev/null +++ b/java/users/lists/UnfollowList.java @@ -0,0 +1,86 @@ +package users.lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Unfollow List - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/users/:id/followed_lists/:list_id + * Docs: https://developer.x.com/en/docs/twitter-api/lists/list-follows/api-reference/delete-users-id-followed_lists-list_id + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class UnfollowList { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "list.read", "list.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String userId = "your-user-id"; + String listId = "list-id-to-unfollow"; + Schemas.UnfollowListResponse response = client.users().unfollowList(userId, listId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/lists/UnpinList.java b/java/users/lists/UnpinList.java new file mode 100644 index 0000000..6998be2 --- /dev/null +++ b/java/users/lists/UnpinList.java @@ -0,0 +1,86 @@ +package users.lists; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Unpin List - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/users/:id/pinned_lists/:list_id + * Docs: https://developer.x.com/en/docs/twitter-api/lists/pinned-lists/api-reference/delete-users-id-pinned_lists-list_id + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class UnpinList { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "list.read", "list.write", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String userId = "your-user-id"; + String listId = "list-id-to-unpin"; + Schemas.UnpinListResponse response = client.users().unpinList(userId, listId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/mute/GetMuting.java b/java/users/mute/GetMuting.java new file mode 100644 index 0000000..22dc7f5 --- /dev/null +++ b/java/users/mute/GetMuting.java @@ -0,0 +1,96 @@ +package users.mute; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Muted Users Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/muting + * Docs: https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/get-users-muting + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class GetMuting { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "offline.access", "mute.read"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String userId = client.users().getMe().getData().getId(); + UsersClient.GetMutingOptions options = UsersClient.GetMutingOptions.builder() + .maxResults(100) + .userFields(Arrays.asList("created_at", "description")); + + List allUsers = new ArrayList<>(); + for (Schemas.GetUsersMutingResponse page : client.users().getMutingPages(userId, options)) { + if (page.getData() != null) { + allUsers.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " users (total: " + allUsers.size() + ")"); + } + } + System.out.println("Total Muted Users: " + allUsers.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allUsers.subList(0, Math.min(5, allUsers.size())))); + } + } +} diff --git a/java/users/mute/MuteUser.java b/java/users/mute/MuteUser.java new file mode 100644 index 0000000..95fbf22 --- /dev/null +++ b/java/users/mute/MuteUser.java @@ -0,0 +1,87 @@ +package users.mute; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Mute User - X API v2 + * + * Endpoint: POST https://api.x.com/2/users/:id/muting + * Docs: https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/post-users-user_id-muting + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class MuteUser { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "tweet.write", "offline.access", "mute.write"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String userId = "your-user-id"; + String targetUserId = "id-to-mute"; + Schemas.MuteUserRequest request = new Schemas.MuteUserRequest().targetUserId(targetUserId); + Schemas.MuteUserResponse response = client.users().muteUser(userId, request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/mute/UnmuteUser.java b/java/users/mute/UnmuteUser.java new file mode 100644 index 0000000..cb06f1b --- /dev/null +++ b/java/users/mute/UnmuteUser.java @@ -0,0 +1,86 @@ +package users.mute; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Unmute User - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/users/:source_user_id/muting/:target_user_id + * Docs: https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/delete-users-user_id-muting + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class UnmuteUser { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "tweet.write", "offline.access", "mute.write"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String userId = "your-user-id"; + String targetUserId = "id-to-unmute"; + Schemas.UnmuteUserResponse response = client.users().unmuteUser(userId, targetUserId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/repost/GetRepostsOfMe.java b/java/users/repost/GetRepostsOfMe.java new file mode 100644 index 0000000..11b96b9 --- /dev/null +++ b/java/users/repost/GetRepostsOfMe.java @@ -0,0 +1,95 @@ +package users.repost; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Reposts of Me - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/reposts_of_me + * Docs: https://docs.x.com/x-api/users/get-reposts-of-me + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class GetRepostsOfMe { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + UsersClient.GetRepostsOfMeOptions options = UsersClient.GetRepostsOfMeOptions.builder() + .maxResults(100) + .postFields(Arrays.asList("created_at", "public_metrics")); + + List allPosts = new ArrayList<>(); + for (Schemas.GetUsersRepostsOfMeResponse page : client.users().getRepostsOfMePages(options)) { + if (page.getData() != null) { + allPosts.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " posts (total: " + allPosts.size() + ")"); + } + } + System.out.println("Total Reposted Posts: " + allPosts.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allPosts.subList(0, Math.min(5, allPosts.size())))); + } + } +} diff --git a/java/users/repost/RepostPost.java b/java/users/repost/RepostPost.java new file mode 100644 index 0000000..ad56d85 --- /dev/null +++ b/java/users/repost/RepostPost.java @@ -0,0 +1,87 @@ +package users.repost; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Repost a Post - X API v2 + * + * Endpoint: POST https://api.x.com/2/users/:id/retweets + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/post-users-id-retweets + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class RepostPost { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "tweet.write", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String postId = "post-id"; + String userId = client.users().getMe().getData().getId(); + Schemas.RepostPostRequest request = new Schemas.RepostPostRequest().tweetId(postId); + Schemas.RepostPostResponse response = client.users().repostPost(userId, request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/repost/UnrepostPost.java b/java/users/repost/UnrepostPost.java new file mode 100644 index 0000000..f3327bd --- /dev/null +++ b/java/users/repost/UnrepostPost.java @@ -0,0 +1,86 @@ +package users.repost; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Undo Repost - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/users/:id/retweets/:source_tweet_id + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/delete-users-id-retweets-tweet_id + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class UnrepostPost { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "tweet.write", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String sourcePostId = "post-id"; + String userId = client.users().getMe().getData().getId(); + Schemas.UnrepostPostResponse response = client.users().unrepostPost(userId, sourcePostId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/users/timeline/GetHomeTimeline.java b/java/users/timeline/GetHomeTimeline.java new file mode 100644 index 0000000..68cd544 --- /dev/null +++ b/java/users/timeline/GetHomeTimeline.java @@ -0,0 +1,96 @@ +package users.timeline; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.auth.OAuth2Pkce; +import com.x.xdk.auth.OAuth2Token; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Scanner; + +/** + * Reverse Chronological Home Timeline - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/timelines/reverse_chronological + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-reverse-chronological-timeline + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ +public class GetHomeTimeline { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static String extractAuthorizationCode(String callbackInput) { + String trimmed = callbackInput.trim(); + if (!trimmed.contains("://") && !trimmed.contains("code=")) { + return trimmed; + } + String query = trimmed.contains("?") ? URI.create(trimmed).getRawQuery() : trimmed; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "code".equals(kv[0])) { + return URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + throw new IllegalArgumentException("No 'code' query parameter found in callback URL"); + } + + private static String resolveAccessToken(List scopes) { + String directToken = System.getenv("ACCESS_TOKEN"); + if (directToken != null && !directToken.isBlank()) { + return directToken; + } + + String clientId = System.getenv("CLIENT_ID"); + String clientSecret = System.getenv("CLIENT_SECRET"); + if (clientId == null || clientId.isBlank()) { + throw new IllegalStateException("Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN"); + } + + String redirectUri = System.getenv().getOrDefault("REDIRECT_URI", "https://example.com"); + OAuth2Pkce oauth2 = new OAuth2Pkce(clientId, clientSecret, redirectUri, scopes); + String authUrl = oauth2.getAuthorizationUrl("sample-state"); + System.out.println("Visit the following URL to authorize your App:"); + System.out.println(authUrl); + System.out.print("Paste the full callback URL (or code) here: "); + Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); + String callbackUrl = scanner.nextLine(); + OAuth2Token token = oauth2.exchangeCode(extractAuthorizationCode(callbackUrl)); + return token.getAccessToken(); + } + + public static void main(String[] args) throws Exception { + List scopes = Arrays.asList("tweet.read", "users.read", "offline.access"); + String accessToken = resolveAccessToken(scopes); + + try (XClient client = new XClient(XClientConfig.builder().accessToken(accessToken).build())) { + String userId = client.users().getMe().getData().getId(); + UsersClient.GetTimelineOptions options = UsersClient.GetTimelineOptions.builder() + .maxResults(100) + .postFields(Arrays.asList("created_at")); + + List allPosts = new ArrayList<>(); + for (Schemas.GetUsersTimelineResponse page : client.users().getTimelinePages(userId, options)) { + if (page.getData() != null) { + allPosts.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " posts (total: " + allPosts.size() + ")"); + } + } + System.out.println("Total Posts: " + allPosts.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allPosts.subList(0, Math.min(5, allPosts.size())))); + } + } +} diff --git a/java/users/timeline/GetMentions.java b/java/users/timeline/GetMentions.java new file mode 100644 index 0000000..aedb185 --- /dev/null +++ b/java/users/timeline/GetMentions.java @@ -0,0 +1,49 @@ +package users.timeline; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * User Mentions Timeline - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/mentions + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-mentions + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetMentions { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String userId = "2244994945"; + UsersClient.GetMentionsOptions options = UsersClient.GetMentionsOptions.builder() + .maxResults(100) + .postFields(Arrays.asList("created_at")); + + List allPosts = new ArrayList<>(); + for (Schemas.GetUsersMentionsResponse page : client.users().getMentionsPages(userId, options)) { + if (page.getData() != null) { + allPosts.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " posts (total: " + allPosts.size() + ")"); + } + } + System.out.println("Total Mentions: " + allPosts.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allPosts.subList(0, Math.min(5, allPosts.size())))); + } + } +} diff --git a/java/users/timeline/GetPosts.java b/java/users/timeline/GetPosts.java new file mode 100644 index 0000000..1d25f71 --- /dev/null +++ b/java/users/timeline/GetPosts.java @@ -0,0 +1,49 @@ +package users.timeline; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * User Posts Timeline - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/tweets + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-tweets + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class GetPosts { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String userId = "2244994945"; + UsersClient.GetPostsOptions options = UsersClient.GetPostsOptions.builder() + .maxResults(100) + .postFields(Arrays.asList("created_at")); + + List allPosts = new ArrayList<>(); + for (Schemas.GetUsersPostsResponse page : client.users().getPostsPages(userId, options)) { + if (page.getData() != null) { + allPosts.addAll(page.getData()); + System.out.println("Fetched " + page.getData().size() + " posts (total: " + allPosts.size() + ")"); + } + } + System.out.println("Total Posts: " + allPosts.size()); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(allPosts.subList(0, Math.min(5, allPosts.size())))); + } + } +} diff --git a/java/webhooks/DeleteWebhook.java b/java/webhooks/DeleteWebhook.java new file mode 100644 index 0000000..89902d4 --- /dev/null +++ b/java/webhooks/DeleteWebhook.java @@ -0,0 +1,38 @@ +package webhooks; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Delete Webhook - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/webhooks/:webhook_id + * Docs: https://docs.x.com/x-api/webhooks/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class DeleteWebhook { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String webhookId = "your-webhook-id"; + Schemas.DeleteWebhooksResponse response = client.webhooks().delete(webhookId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/webhooks/ListWebhooks.java b/java/webhooks/ListWebhooks.java new file mode 100644 index 0000000..2a34f40 --- /dev/null +++ b/java/webhooks/ListWebhooks.java @@ -0,0 +1,37 @@ +package webhooks; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * List Webhooks - X API v2 + * + * Endpoint: GET https://api.x.com/2/webhooks + * Docs: https://docs.x.com/x-api/webhooks/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class ListWebhooks { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + Schemas.GetWebhooksResponse response = client.webhooks().get(); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/webhooks/RegisterWebhook.java b/java/webhooks/RegisterWebhook.java new file mode 100644 index 0000000..fdf478c --- /dev/null +++ b/java/webhooks/RegisterWebhook.java @@ -0,0 +1,39 @@ +package webhooks; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Register Webhook - X API v2 + * + * Endpoint: POST https://api.x.com/2/webhooks + * Docs: https://docs.x.com/x-api/webhooks/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class RegisterWebhook { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String webhookUrl = "https://your-domain.com/webhooks"; + Schemas.CreateWebhooksRequest request = new Schemas.CreateWebhooksRequest().url(webhookUrl); + Schemas.CreateWebhooksResponse response = client.webhooks().create(request); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/webhooks/ValidateWebhook.java b/java/webhooks/ValidateWebhook.java new file mode 100644 index 0000000..a8fef94 --- /dev/null +++ b/java/webhooks/ValidateWebhook.java @@ -0,0 +1,38 @@ +package webhooks; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.x.xdk.Paginator; +import com.x.xdk.XClient; +import com.x.xdk.XClientConfig; +import com.x.xdk.clients.*; +import com.x.xdk.models.Schemas; +import com.x.xdk.streaming.EventStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Validate Webhook (Trigger CRC) - X API v2 + * + * Endpoint: PUT https://api.x.com/2/webhooks/:webhook_id + * Docs: https://docs.x.com/x-api/webhooks/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ +public class ValidateWebhook { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (bearerToken == null || bearerToken.isBlank()) { + throw new IllegalStateException("BEARER_TOKEN environment variable is not set"); + } + + try (XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build())) { + String webhookId = "your-webhook-id"; + Schemas.ValidateWebhooksResponse response = client.webhooks().validate(webhookId); + System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(response.getData())); + } + } +} diff --git a/java/webhooks/WebhookServer.java b/java/webhooks/WebhookServer.java new file mode 100644 index 0000000..e9259c0 --- /dev/null +++ b/java/webhooks/WebhookServer.java @@ -0,0 +1,73 @@ +package webhooks; + +import com.sun.net.httpserver.HttpServer; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +/** + * Webhook Server (CRC + Event Delivery) - X API v2 + * + * Docs: https://docs.x.com/x-api/webhooks/introduction + * Required env vars: CONSUMER_SECRET + */ +public class WebhookServer { + public static void main(String[] args) throws Exception { + String consumerSecret = System.getenv("CONSUMER_SECRET"); + if (consumerSecret == null || consumerSecret.isBlank()) { + throw new IllegalStateException("CONSUMER_SECRET environment variable is not set"); + } + + HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", 8080), 0); + server.createContext("/webhooks", exchange -> { + String method = exchange.getRequestMethod(); + if ("GET".equalsIgnoreCase(method)) { + String query = exchange.getRequestURI().getRawQuery(); + String crcToken = null; + if (query != null) { + for (String pair : query.split("&")) { + String[] kv = pair.split("=", 2); + if (kv.length == 2 && "crc_token".equals(kv[0])) { + crcToken = URLDecoder.decode(kv[1], StandardCharsets.UTF_8); + } + } + } + if (crcToken == null) { + byte[] err = "{\"error\":\"No crc_token\"}".getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(400, err.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(err); + } + return; + } + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(consumerSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + String digest = Base64.getEncoder().encodeToString(mac.doFinal(crcToken.getBytes(StandardCharsets.UTF_8))); + byte[] body = ("{\"response_token\":\"sha256=" + digest + "\"}").getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, body.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(body); + } + } catch (Exception e) { + exchange.sendResponseHeaders(500, -1); + } + } else if ("POST".equalsIgnoreCase(method)) { + String payload = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); + System.out.println(payload); + exchange.sendResponseHeaders(200, -1); + } else { + exchange.sendResponseHeaders(405, -1); + } + }); + + System.out.println("Listening on http://0.0.0.0:8080/webhooks"); + server.start(); + } +} diff --git a/javascript/README.md b/javascript/README.md index 5ec0b1b..c05d743 100644 --- a/javascript/README.md +++ b/javascript/README.md @@ -1,136 +1,126 @@ -# X API v2 - JavaScript (Node.js) Examples +# JavaScript / TypeScript (Node.js) Samples for X API v2 (`@xdevplatform/xdk`) -Working JavaScript code samples for the X (formerly Twitter) API v2. +Official JavaScript (Node.js 18+) sample code for the X API v2 powered by [**XDK for TypeScript / JavaScript** (`@xdevplatform/xdk`)](https://github.com/xdevplatform/xdk-typescript). ## Setup -### 1. Install Node.js 14+ +### 1. Prerequisites + +- **Node.js 18+** (`node --version`) +- An [X Developer Account](https://console.x.com) with API credentials + +### 2. Install `@xdevplatform/xdk` ```bash -node --version +cd javascript +npm install ``` -### 2. Install dependencies - -No package.json is required. Examples use Node.js built-in modules or standard libraries. +### 3. Set Environment Variables -### 3. Set environment variables +**For App-only read operations (search, lookup, streams, webhooks, activity):** -**For read-only operations (search, lookup):** ```bash -export BEARER_TOKEN='your_bearer_token' +export BEARER_TOKEN="your_bearer_token" ``` -**For user actions (post, like, repost, bookmark, mute, etc.):** +**For User-context actions (create post, like, repost, bookmark, mute, follow, DMs, media upload):** + ```bash -export CLIENT_ID='your_client_id' -export CLIENT_SECRET='your_client_secret' +export CLIENT_ID="your_oauth2_client_id" +export CLIENT_SECRET="your_oauth2_client_secret" # optional for public clients +export REDIRECT_URI="https://example.com" # must match your App settings ``` -**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) +*(You can also set `ACCESS_TOKEN` directly if you already have a valid OAuth 2.0 user token.)* -### 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 +## Examples by Category (84 Samples) -### Usage -- `usage/get_usage.js` - Get API usage information +### Activity (5) +- `activity/create_subscription.js` - Subscribe to real-time X Activity events +- `activity/delete_subscription.js` - Delete an Activity subscription +- `activity/list_subscriptions.js` - List active Activity subscriptions +- `activity/stream_events.js` - Stream real-time Activity events +- `activity/update_subscription.js` - Update an Activity subscription tag / webhook -## Running Examples +### Compliance (5) +- `compliance/create_jobs.js` - Create a batch compliance job +- `compliance/download_results.js` - Download compliance results +- `compliance/get_jobs.js` - List compliance jobs +- `compliance/get_jobs_by_id.js` - Get compliance job status by ID +- `compliance/upload_ids.js` - Upload Post/User IDs to a compliance job + +### Direct Messages (6) +- `direct_messages/get_events_by_conversation.js` - Fetch DM events in a conversation +- `direct_messages/get_one_to_one_conversation_events.js` - Fetch 1-to-1 DM events with a participant +- `direct_messages/get_user_conversation_events.js` - Fetch recent DM events across conversations +- `direct_messages/post_dm_to_conversation.js` - Send a message to an existing conversation +- `direct_messages/post_group_conversation_dm.js` - Create a new group DM conversation +- `direct_messages/post_one_to_one_dm.js` - Send a 1-to-1 Direct Message + +### Lists (9) +- `lists/add_member.js` - Add a member to a List +- `lists/create_list.js` - Create a new List +- `lists/delete_list.js` - Delete a List +- `lists/get_list_by_id.js` - Look up a 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 a member from a List +- `lists/update_list.js` - Update a List + +### Media (2) +- `media/upload.js` - Single-payload image upload (`POST /2/media/upload`) +- `media/media_upload_v2.js` - Chunked video upload (`initialize` -> `append` -> `finalize` -> `STATUS` -> `posts.create`) + +### Posts (13) +- `posts/create_post.js` - Create a Post +- `posts/delete_post.js` - Delete a Post +- `posts/get_liking_users.js` - Get users who liked a Post +- `posts/get_post_by_id.js` - Look up a single Post by ID +- `posts/get_post_counts_all.js` - Full-archive Post counts +- `posts/get_post_counts_recent.js` - Recent Post counts (last 7 days) +- `posts/get_posts_by_ids.js` - Look up multiple Posts by IDs (Bearer Token) +- `posts/get_posts_by_ids_user_context.js` - Look up multiple Posts by IDs (OAuth 2.0 User Context) +- `posts/get_quoted_posts.js` - Get Quote Posts for a Post +- `posts/get_reposted_by.js` - Get users who reposted a Post +- `posts/hide_reply.js` - Hide or unhide a reply +- `posts/search_all.js` - Full-archive search +- `posts/search_recent.js` - Recent search (last 7 days) + +### Spaces (2) +- `spaces/get_spaces_by_ids.js` - Look up Spaces by IDs +- `spaces/search_spaces.js` - Search live/scheduled Spaces + +### Streams (2) +- `streams/stream_posts_filtered.js` - Filtered stream with rule management +- `streams/stream_posts_sample.js` - 1% sampled volume stream + +### Usage (1) +- `usage/get_usage.js` - Daily API Post usage metrics + +### Users (34) +- `users/get_users_by_usernames.js`, `users/get_users_by_usernames_user_context.js`, `users/get_users_me.js` +- `users/block/get_blocking.js` +- `users/bookmark/{create_bookmark,delete_bookmark,get_bookmarks}.js` +- `users/follow/{follow_user,get_followers,get_followers_paginated,get_following,get_following_paginated,unfollow_user}.js` +- `users/like/{get_liked_posts,like_post,unlike_post}.js` +- `users/lists/{follow_list,get_followed_lists,get_list_memberships,get_owned_lists,get_pinned_lists,pin_list,unfollow_list,unpin_list}.js` +- `users/mute/{get_muting,mute_user,unmute_user}.js` +- `users/repost/{get_reposts_of_me,repost_post,unrepost_post}.js` +- `users/timeline/{get_home_timeline,get_mentions,get_posts,get_posts_paginated}.js` + +### Webhooks (5) +- `webhooks/register_webhook.js` - Register a webhook URL +- `webhooks/list_webhooks.js` - List registered webhooks +- `webhooks/validate_webhook.js` - Trigger a CRC validation check +- `webhooks/delete_webhook.js` - Delete a webhook +- `webhooks/webhook_server.js` - Minimal Node.js HTTP server handling CRC (`HMAC-SHA256`) and POST deliveries + +## Running Any Sample ```bash -# Make sure environment variables are set +cd javascript +npm install 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) diff --git a/javascript/activity/create_subscription.js b/javascript/activity/create_subscription.js new file mode 100644 index 0000000..dd3324d --- /dev/null +++ b/javascript/activity/create_subscription.js @@ -0,0 +1,29 @@ +/** + * Create Activity Subscription - X API v2 + * + * Endpoint: POST https://api.x.com/2/activity/subscriptions + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +const { Client } = require('@xdevplatform/xdk'); + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const userId = '2244994945'; + const eventType = 'profile.update.bio'; + + const response = await client.activity.createSubscription({ + eventType, + filter: { userId }, + tag: `${eventType} for user ${userId}`, + }); + + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/activity/delete_subscription.js b/javascript/activity/delete_subscription.js new file mode 100644 index 0000000..6fe5a58 --- /dev/null +++ b/javascript/activity/delete_subscription.js @@ -0,0 +1,22 @@ +/** + * Delete Activity Subscription - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/activity/subscriptions/:id + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +const { Client } = require('@xdevplatform/xdk'); + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const subscriptionId = 'your-subscription-id'; + const response = await client.activity.deleteSubscription(subscriptionId); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/activity/list_subscriptions.js b/javascript/activity/list_subscriptions.js new file mode 100644 index 0000000..6a01335 --- /dev/null +++ b/javascript/activity/list_subscriptions.js @@ -0,0 +1,21 @@ +/** + * List Activity Subscriptions - X API v2 + * + * Endpoint: GET https://api.x.com/2/activity/subscriptions + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +const { Client } = require('@xdevplatform/xdk'); + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const response = await client.activity.getSubscriptions(); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/activity/stream_events.js b/javascript/activity/stream_events.js new file mode 100644 index 0000000..407d116 --- /dev/null +++ b/javascript/activity/stream_events.js @@ -0,0 +1,33 @@ +/** + * Activity Stream - X API v2 + * + * Endpoint: GET https://api.x.com/2/activity/stream + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +const { Client } = require('@xdevplatform/xdk'); + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + console.log('Connecting to activity stream... (press Ctrl+C to stop)'); + const stream = await client.stream.activity(); + + stream.on('data', (event) => { + console.dir(event, { depth: null }); + }); + + stream.on('error', (err) => { + console.error('Stream error:', err); + }); + + stream.on('close', () => { + console.log('Activity stream closed'); + }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/activity/update_subscription.js b/javascript/activity/update_subscription.js new file mode 100644 index 0000000..c95b035 --- /dev/null +++ b/javascript/activity/update_subscription.js @@ -0,0 +1,24 @@ +/** + * Update Activity Subscription - X API v2 + * + * Endpoint: PUT https://api.x.com/2/activity/subscriptions/:id + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +const { Client } = require('@xdevplatform/xdk'); + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const subscriptionId = 'your-subscription-id'; + const response = await client.activity.updateSubscription(subscriptionId, { + tag: 'updated-activity-tag', + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/direct_messages/get_events_by_conversation.js b/javascript/direct_messages/get_events_by_conversation.js new file mode 100644 index 0000000..2cac811 --- /dev/null +++ b/javascript/direct_messages/get_events_by_conversation.js @@ -0,0 +1,97 @@ +/** + * Get Events by Conversation ID - X API v2 + * + * Endpoint: GET https://api.x.com/2/dm_conversations/:dm_conversation_id/dm_events + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-conversations-dm_conversation_id-dm_events + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +const { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, + PostPaginator, + UserPaginator, +} = require('@xdevplatform/xdk'); + +function promptLine(question) { + const rl = require('readline').createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput) { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes) { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['dm.read', 'tweet.read', 'users.read', 'offline.access']); + const dmConversationId = '1512210732774948865'; + + const paginator = new EventPaginator(async (token) => { + const res = await client.directMessages.getEventsByConversationId(dmConversationId, { + maxResults: 100, + paginationToken: token, + }); + return { + data: res.data ?? [], + meta: res.meta, + includes: res.includes, + errors: res.errors, + }; + }); + + for await (const event of paginator) { + console.dir(event, { depth: null }); + } +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/direct_messages/get_one_to_one_conversation_events.js b/javascript/direct_messages/get_one_to_one_conversation_events.js new file mode 100644 index 0000000..e969ad8 --- /dev/null +++ b/javascript/direct_messages/get_one_to_one_conversation_events.js @@ -0,0 +1,97 @@ +/** + * Get One-to-One Conversation Events - X API v2 + * + * Endpoint: GET https://api.x.com/2/dm_conversations/with/:participant_id/dm_events + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-conversations-with-participant_id-dm_events + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +const { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, + PostPaginator, + UserPaginator, +} = require('@xdevplatform/xdk'); + +function promptLine(question) { + const rl = require('readline').createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput) { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes) { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['dm.read', 'tweet.read', 'users.read', 'offline.access']); + const participantId = '1716450569358098432'; + + const paginator = new EventPaginator(async (token) => { + const res = await client.directMessages.getEventsByParticipantId(participantId, { + maxResults: 100, + paginationToken: token, + }); + return { + data: res.data ?? [], + meta: res.meta, + includes: res.includes, + errors: res.errors, + }; + }); + + for await (const event of paginator) { + console.dir(event, { depth: null }); + } +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/direct_messages/get_user_conversation_events.js b/javascript/direct_messages/get_user_conversation_events.js new file mode 100644 index 0000000..1c899d4 --- /dev/null +++ b/javascript/direct_messages/get_user_conversation_events.js @@ -0,0 +1,97 @@ +/** + * Get User Conversation Events - X API v2 + * + * Endpoint: GET https://api.x.com/2/dm_events + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-events + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +const { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, + PostPaginator, + UserPaginator, +} = require('@xdevplatform/xdk'); + +function promptLine(question) { + const rl = require('readline').createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput) { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes) { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['dm.read', 'tweet.read', 'users.read', 'offline.access']); + + const paginator = new EventPaginator(async (token) => { + const res = await client.directMessages.getEvents({ + maxResults: 100, + paginationToken: token, + dmEventFields: ['id', 'text', 'event_type', 'created_at', 'sender_id'], + }); + return { + data: res.data ?? [], + meta: res.meta, + includes: res.includes, + errors: res.errors, + }; + }); + + for await (const event of paginator) { + console.dir(event, { depth: null }); + } +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/direct_messages/post_dm_to_conversation.js b/javascript/direct_messages/post_dm_to_conversation.js new file mode 100644 index 0000000..991fb84 --- /dev/null +++ b/javascript/direct_messages/post_dm_to_conversation.js @@ -0,0 +1,85 @@ +/** + * Post DM to Conversation - X API v2 + * + * Endpoint: POST https://api.x.com/2/dm_conversations/:dm_conversation_id/messages + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations-dm_conversation_id-messages + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +const { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, + PostPaginator, + UserPaginator, +} = require('@xdevplatform/xdk'); + +function promptLine(question) { + const rl = require('readline').createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput) { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes) { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['dm.read', 'dm.write', 'tweet.read', 'users.read', 'offline.access']); + const dmConversationId = '1856843062712176900'; + + const response = await client.directMessages.createByConversationId(dmConversationId, { + text: 'Hi, I am adding a message to an existing conversation using @xdevplatform/xdk.', + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/direct_messages/post_group_conversation_dm.js b/javascript/direct_messages/post_group_conversation_dm.js new file mode 100644 index 0000000..4d48b72 --- /dev/null +++ b/javascript/direct_messages/post_group_conversation_dm.js @@ -0,0 +1,88 @@ +/** + * Post Group Conversation Direct Message - X API v2 + * + * Endpoint: POST https://api.x.com/2/dm_conversations + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +const { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, + PostPaginator, + UserPaginator, +} = require('@xdevplatform/xdk'); + +function promptLine(question) { + const rl = require('readline').createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput) { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes) { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['dm.read', 'dm.write', 'tweet.read', 'users.read', 'offline.access']); + + const response = await client.directMessages.createConversation({ + conversationType: 'Group', + participantIds: ['2244994945', '1716450569358098432'], + message: { + text: 'Hi, creating a new group conversation via @xdevplatform/xdk.', + }, + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/direct_messages/post_one_to_one_dm.js b/javascript/direct_messages/post_one_to_one_dm.js new file mode 100644 index 0000000..8dd551f --- /dev/null +++ b/javascript/direct_messages/post_one_to_one_dm.js @@ -0,0 +1,85 @@ +/** + * Post One-to-One Direct Message - X API v2 + * + * Endpoint: POST https://api.x.com/2/dm_conversations/with/:participant_id/messages + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations-with-participant_id-messages + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +const { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, + PostPaginator, + UserPaginator, +} = require('@xdevplatform/xdk'); + +function promptLine(question) { + const rl = require('readline').createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput) { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes) { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['dm.read', 'dm.write', 'tweet.read', 'users.read', 'offline.access']); + const participantId = '1716450569358098432'; + + const response = await client.directMessages.createByParticipantId(participantId, { + text: 'Hi, DMing you using the v2 one-to-one endpoint via @xdevplatform/xdk.', + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/media/media_upload_v2.js b/javascript/media/media_upload_v2.js new file mode 100644 index 0000000..6c2a748 --- /dev/null +++ b/javascript/media/media_upload_v2.js @@ -0,0 +1,120 @@ +/** + * Media Upload v2 (Chunked Video Upload) - X API v2 + * + * Endpoint: POST https://api.x.com/2/media/upload/initialize | append | finalize + * Docs: https://developer.x.com/en/docs/twitter-api/media/upload-media/api-reference + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +const fs = require('fs'); +const { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, + PostPaginator, + UserPaginator, +} = require('@xdevplatform/xdk'); + +function promptLine(question) { + const rl = require('readline').createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput) { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes) { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['media.write', 'users.read', 'tweet.read', 'tweet.write', 'offline.access']); + const videoPath = process.env.VIDEO_FILE || 'path/to/your/video.mp4'; + const allBytes = fs.readFileSync(videoPath); + + // 1. Initialize chunked upload + const initRes = await client.media.initializeUpload({ + mediaType: 'video/mp4', + mediaCategory: 'tweet_video', + totalBytes: allBytes.length, + }); + const mediaId = initRes.data.id; + console.log('Initialized upload for mediaId:', mediaId); + + // 2. Append 4 MiB chunks + const chunkSize = 4 * 1024 * 1024; + let segmentIndex = 0; + for (let offset = 0; offset < allBytes.length; offset += chunkSize) { + const chunk = allBytes.subarray(offset, Math.min(offset + chunkSize, allBytes.length)); + await client.media.appendUpload(mediaId, { + segmentIndex: segmentIndex++, + media: chunk.toString('base64'), + }); + console.log(`Uploaded ${Math.min(offset + chunkSize, allBytes.length)} / ${allBytes.length} bytes`); + } + + // 3. Finalize & poll processing status + const finRes = await client.media.finalizeUpload(mediaId); + let proc = finRes.data?.processingInfo || finRes.data?.processing_info; + while (proc && proc.state && proc.state !== 'succeeded' && proc.state !== 'failed') { + const waitSecs = proc.checkAfterSecs ?? proc.check_after_secs ?? 2; + await new Promise((r) => setTimeout(r, waitSecs * 1000)); + const statusRes = await client.media.getUploadStatus(mediaId, { command: 'STATUS' }); + proc = statusRes.data?.processingInfo || statusRes.data?.processing_info; + } + + // 4. Create post with attached video + const postRes = await client.posts.create({ + text: 'Uploaded a video using @xdevplatform/xdk!', + media: { mediaIds: [mediaId] }, + }); + console.dir(postRes, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/media/upload.js b/javascript/media/upload.js new file mode 100644 index 0000000..c604382 --- /dev/null +++ b/javascript/media/upload.js @@ -0,0 +1,89 @@ +/** + * Media Upload (Single Payload) - X API v2 + * + * Endpoint: POST https://api.x.com/2/media/upload + * Docs: https://developer.x.com/en/docs/twitter-api/media/upload-media/api-reference + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +const fs = require('fs'); +const { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, + PostPaginator, + UserPaginator, +} = require('@xdevplatform/xdk'); + +function promptLine(question) { + const rl = require('readline').createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput) { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes) { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['media.write', 'tweet.read', 'tweet.write', 'users.read', 'offline.access']); + const mediaPath = process.env.MEDIA_FILE || 'path/to/your/image.jpg'; + const base64Media = fs.readFileSync(mediaPath).toString('base64'); + + const response = await client.media.upload({ + media: base64Media, + mediaCategory: 'tweet_image', + }); + console.log('Media ID:', response.data?.id); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/package.json b/javascript/package.json new file mode 100644 index 0000000..2e43f2f --- /dev/null +++ b/javascript/package.json @@ -0,0 +1,12 @@ +{ + "name": "x-api-v2-javascript-samples", + "version": "1.0.0", + "private": true, + "description": "Official JavaScript (Node.js) sample code for the X API v2 powered by @xdevplatform/xdk", + "engines": { + "node": ">=18.0.0" + }, + "dependencies": { + "@xdevplatform/xdk": "^0.7.0" + } +} diff --git a/javascript/posts/get_post_by_id.js b/javascript/posts/get_post_by_id.js new file mode 100644 index 0000000..ccff867 --- /dev/null +++ b/javascript/posts/get_post_by_id.js @@ -0,0 +1,24 @@ +/** + * Single Post Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/tweets/:id + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets-id + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +const { Client } = require('@xdevplatform/xdk'); + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const postId = 'post-id'; + const response = await client.posts.getById(postId, { + tweetFields: ['created_at', 'author_id', 'lang', 'source', 'public_metrics', 'entities'], + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/posts/hide_reply.js b/javascript/posts/hide_reply.js new file mode 100644 index 0000000..99347aa --- /dev/null +++ b/javascript/posts/hide_reply.js @@ -0,0 +1,82 @@ +/** + * Hide Reply - X API v2 + * + * Endpoint: PUT https://api.x.com/2/tweets/:id/hidden + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/hide-replies/api-reference/put-tweets-id-hidden + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +const { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, + PostPaginator, + UserPaginator, +} = require('@xdevplatform/xdk'); + +function promptLine(question) { + const rl = require('readline').createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput) { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes) { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['tweet.read', 'tweet.write', 'users.read', 'offline.access']); + const replyPostId = 'reply-tweet-id-to-hide'; + const response = await client.posts.hideReply(replyPostId, { hidden: true }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/users/follow/follow_user.js b/javascript/users/follow/follow_user.js new file mode 100644 index 0000000..95d7b5a --- /dev/null +++ b/javascript/users/follow/follow_user.js @@ -0,0 +1,84 @@ +/** + * Follow User - X API v2 + * + * Endpoint: POST https://api.x.com/2/users/:id/following + * Docs: https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/post-users-id-following + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +const { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, + PostPaginator, + UserPaginator, +} = require('@xdevplatform/xdk'); + +function promptLine(question) { + const rl = require('readline').createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput) { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes) { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['tweet.read', 'users.read', 'follows.write', 'offline.access']); + const me = await client.users.getMe(); + const targetUserId = 'user-id-to-follow'; + + const response = await client.users.followUser(me.data.id, { targetUserId }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/users/follow/get_following.js b/javascript/users/follow/get_following.js new file mode 100644 index 0000000..0414a0e --- /dev/null +++ b/javascript/users/follow/get_following.js @@ -0,0 +1,25 @@ +/** + * User Following Lookup - 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) + * Required env vars: BEARER_TOKEN + */ + +const { Client } = require('@xdevplatform/xdk'); + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const userId = '2244994945'; + const response = await client.users.getFollowing(userId, { + maxResults: 100, + userFields: ['created_at'], + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/users/follow/unfollow_user.js b/javascript/users/follow/unfollow_user.js new file mode 100644 index 0000000..c3a899d --- /dev/null +++ b/javascript/users/follow/unfollow_user.js @@ -0,0 +1,84 @@ +/** + * Unfollow User - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/users/:source_user_id/following/:target_user_id + * Docs: https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/delete-users-source_user_id-following + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +const { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, + PostPaginator, + UserPaginator, +} = require('@xdevplatform/xdk'); + +function promptLine(question) { + const rl = require('readline').createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput) { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes) { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['tweet.read', 'users.read', 'follows.write', 'offline.access']); + const me = await client.users.getMe(); + const targetUserId = 'user-id-to-unfollow'; + + const response = await client.users.unfollowUser(me.data.id, targetUserId); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/users/lists/get_pinned_lists.js b/javascript/users/lists/get_pinned_lists.js new file mode 100644 index 0000000..2806d00 --- /dev/null +++ b/javascript/users/lists/get_pinned_lists.js @@ -0,0 +1,85 @@ +/** + * Pinned Lists Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/pinned_lists + * Docs: https://developer.x.com/en/docs/twitter-api/lists/pinned-lists/api-reference/get-users-id-pinned_lists + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +const { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, + PostPaginator, + UserPaginator, +} = require('@xdevplatform/xdk'); + +function promptLine(question) { + const rl = require('readline').createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput) { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes) { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['tweet.read', 'users.read', 'list.read', 'offline.access']); + const userId = 'your-user-id'; + + const response = await client.users.getPinnedLists(userId, { + listFields: ['created_at', 'description', 'private'], + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/users/repost/get_reposts_of_me.js b/javascript/users/repost/get_reposts_of_me.js new file mode 100644 index 0000000..c6a203c --- /dev/null +++ b/javascript/users/repost/get_reposts_of_me.js @@ -0,0 +1,97 @@ +/** + * Reposts of Me - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/reposts_of_me + * Docs: https://docs.x.com/x-api/users/get-reposts-of-me + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +const { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, + PostPaginator, + UserPaginator, +} = require('@xdevplatform/xdk'); + +function promptLine(question) { + const rl = require('readline').createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput) { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes) { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['tweet.read', 'users.read', 'offline.access']); + + const paginator = new PostPaginator(async (token) => { + const res = await client.users.getRepostsOfMe({ + maxResults: 100, + paginationToken: token, + tweetFields: ['created_at', 'public_metrics'], + }); + return { + data: res.data ?? [], + meta: res.meta, + includes: res.includes, + errors: res.errors, + }; + }); + + for await (const post of paginator) { + console.dir(post, { depth: null }); + } +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/webhooks/delete_webhook.js b/javascript/webhooks/delete_webhook.js new file mode 100644 index 0000000..a69d053 --- /dev/null +++ b/javascript/webhooks/delete_webhook.js @@ -0,0 +1,22 @@ +/** + * Delete Webhook - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/webhooks/:webhook_id + * Docs: https://docs.x.com/x-api/webhooks/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +const { Client } = require('@xdevplatform/xdk'); + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const webhookId = 'your-webhook-id'; + const response = await client.webhooks.delete(webhookId); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/webhooks/list_webhooks.js b/javascript/webhooks/list_webhooks.js new file mode 100644 index 0000000..92b433b --- /dev/null +++ b/javascript/webhooks/list_webhooks.js @@ -0,0 +1,21 @@ +/** + * List Webhooks - X API v2 + * + * Endpoint: GET https://api.x.com/2/webhooks + * Docs: https://docs.x.com/x-api/webhooks/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +const { Client } = require('@xdevplatform/xdk'); + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const response = await client.webhooks.get(); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/webhooks/register_webhook.js b/javascript/webhooks/register_webhook.js new file mode 100644 index 0000000..e2948c4 --- /dev/null +++ b/javascript/webhooks/register_webhook.js @@ -0,0 +1,22 @@ +/** + * Register Webhook - X API v2 + * + * Endpoint: POST https://api.x.com/2/webhooks + * Docs: https://docs.x.com/x-api/webhooks/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +const { Client } = require('@xdevplatform/xdk'); + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const webhookUrl = 'https://your-domain.com/webhooks'; + const response = await client.webhooks.create({ url: webhookUrl }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/webhooks/validate_webhook.js b/javascript/webhooks/validate_webhook.js new file mode 100644 index 0000000..43829b2 --- /dev/null +++ b/javascript/webhooks/validate_webhook.js @@ -0,0 +1,22 @@ +/** + * Validate Webhook (Trigger CRC) - X API v2 + * + * Endpoint: PUT https://api.x.com/2/webhooks/:webhook_id + * Docs: https://docs.x.com/x-api/webhooks/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +const { Client } = require('@xdevplatform/xdk'); + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const webhookId = 'your-webhook-id'; + const response = await client.webhooks.validate(webhookId); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/javascript/webhooks/webhook_server.js b/javascript/webhooks/webhook_server.js new file mode 100644 index 0000000..2651fc4 --- /dev/null +++ b/javascript/webhooks/webhook_server.js @@ -0,0 +1,56 @@ +/** + * Webhook Server (CRC + Event Delivery) - X API v2 + * + * Docs: https://docs.x.com/x-api/webhooks/introduction + * Required env vars: CONSUMER_SECRET + */ + +const http = require('http'); +const crypto = require('crypto'); + +const consumerSecret = process.env.CONSUMER_SECRET; +if (!consumerSecret) { + throw new Error('CONSUMER_SECRET environment variable is not set'); +} + +const server = http.createServer((req, res) => { + const url = new URL(req.url, `http://${req.headers.host || 'localhost:8080'}`); + if (url.pathname !== '/webhooks') { + res.writeHead(404); + res.end(); + return; + } + + if (req.method === 'GET') { + const crcToken = url.searchParams.get('crc_token'); + if (!crcToken) { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'No crc_token' })); + return; + } + const digest = crypto.createHmac('sha256', consumerSecret).update(crcToken).digest('base64'); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ response_token: `sha256=${digest}` })); + } else if (req.method === 'POST') { + let body = ''; + req.on('data', (chunk) => { + body += chunk; + }); + req.on('end', () => { + try { + console.dir(JSON.parse(body), { depth: null }); + } catch { + console.log(body); + } + res.writeHead(200); + res.end(); + }); + } else { + res.writeHead(405); + res.end(); + } +}); + +server.listen(8080, '0.0.0.0', () => { + console.log('Listening on http://0.0.0.0:8080/webhooks'); +}); diff --git a/llms.txt b/llms.txt index 254197a..a79dad4 100644 --- a/llms.txt +++ b/llms.txt @@ -1,156 +1,62 @@ # X API v2 Sample Code Repository -> This file provides context for LLMs (Large Language Models) to understand and navigate this codebase. - -## Purpose - -This repository contains working code examples for the X (formerly Twitter) API v2. Examples are provided in Python, JavaScript (Node.js), Ruby, and Java. - -## Repository Structure - -``` -/ -├── python/ # Python examples -│ ├── posts/ # Create, delete, search, lookup posts -│ ├── users/ # User lookup, followers, blocks, mutes -│ ├── timelines/ # User posts, mentions, home timeline -│ ├── streams/ # Filtered and sampled streams -│ ├── bookmarks/ # Bookmark management -│ ├── spaces/ # Spaces lookup and search -│ ├── lists/ # List management -│ ├── direct_messages/ # DM lookup and sending -│ ├── media/ # Media upload -│ ├── compliance/ # Batch compliance jobs -│ └── usage/ # API usage stats -├── javascript/ # JavaScript (Node.js) examples -├── ruby/ # Ruby examples -├── java/ # Java examples -└── docs/ # Endpoint documentation (language-agnostic) -``` - -## File Naming Conventions - -- Python: `snake_case.py` (e.g., `create_post.py`) -- JavaScript: `snake_case.js` (e.g., `create_post.js`) -- Ruby: `snake_case.rb` (e.g., `search_recent.rb`) -- Java: `PascalCase.java` (e.g., `SearchRecent.java`) - -## Authentication Types - -1. **Bearer Token** (App-only): For read-only endpoints that don't require user context - - Env var: `BEARER_TOKEN` - -2. **OAuth 1.0a** (User Context): For endpoints that act on behalf of a user - - Env vars: `CONSUMER_KEY`, `CONSUMER_SECRET` - -3. **OAuth 2.0 with PKCE** (User Context): For newer endpoints like bookmarks - - Requires OAuth 2.0 flow to get user access token - -## API Base URL - -All endpoints use: `https://api.x.com/2/` - -## Key Terminology (Rebrand) - -| Old Term | New Term | -|----------|----------| -| Tweet | Post | -| Retweet | Repost | -| Twitter | X | -| TwitterDev | XDevelopers | - -Note: The API endpoints still use `/tweets/` in the URL path for backwards compatibility. - -## Common Operations by Category - -### Posts (formerly Tweets) -- `POST /2/tweets` - Create a post -- `DELETE /2/tweets/:id` - Delete a post -- `GET /2/tweets` - Look up posts by ID -- `GET /2/tweets/search/recent` - Search recent posts (7 days) -- `GET /2/tweets/search/all` - Search all posts (Academic access) -- `GET /2/tweets/counts/recent` - Count recent posts -- `GET /2/tweets/:id/quote_tweets` - Get quote posts -- `POST /2/users/:id/retweets` - Repost -- `DELETE /2/users/:id/retweets/:tweet_id` - Undo repost - -### Users -- `GET /2/users/by` - Look up users by username -- `GET /2/users/me` - Get authenticated user -- `GET /2/users/:id/followers` - Get followers -- `GET /2/users/:id/following` - Get following -- `POST /2/users/:id/blocking` - Block user -- `POST /2/users/:id/muting` - Mute user - -### Timelines -- `GET /2/users/:id/tweets` - User's posts -- `GET /2/users/:id/mentions` - User's mentions -- `GET /2/users/:id/reverse_chronological_timeline` - Home timeline - -### Streams (Real-time) -- `GET /2/tweets/search/stream` - Filtered stream -- `GET /2/tweets/sample/stream` - 1% sampled stream - -### Likes -- `POST /2/users/:id/likes` - Like a post -- `DELETE /2/users/:id/likes/:tweet_id` - Unlike a post -- `GET /2/tweets/:id/liking_users` - Users who liked -- `GET /2/users/:id/liked_tweets` - Posts user liked - -### Bookmarks -- `GET /2/users/:id/bookmarks` - Get bookmarks -- `POST /2/users/:id/bookmarks` - Create bookmark -- `DELETE /2/users/:id/bookmarks/:tweet_id` - Delete bookmark - -### Lists -- `GET /2/lists/:id` - Look up list -- `POST /2/lists` - Create list -- `DELETE /2/lists/:id` - Delete list - -### Spaces -- `GET /2/spaces` - Look up Spaces by ID -- `GET /2/spaces/search` - Search Spaces - -### Direct Messages -- `GET /2/dm_events` - Get DM events -- `POST /2/dm_conversations/with/:participant_id/messages` - Send DM - -## Quick Start - -1. Get API credentials at https://developer.x.com/portal -2. Set environment variables: - ```bash - export BEARER_TOKEN='your_token' - export CONSUMER_KEY='your_key' - export CONSUMER_SECRET='your_secret' - ``` -3. Navigate to desired language folder -4. Install dependencies (see language-specific README) -5. Run example - -## Dependencies by Language - -### Python -```bash -pip install requests requests-oauthlib -``` - -### JavaScript -```bash -npm install needle got oauth-1.0a -``` - -### Ruby -```bash -gem install typhoeus oauth -``` - -### Java -- Apache HttpClient 4.5+ -- Gson 2.9+ - -## External Resources - -- API Documentation: https://developer.x.com/en/docs/twitter-api -- Developer Portal: https://developer.x.com/en/portal/dashboard -- API Reference: https://developer.x.com/en/docs/api-reference-index +> Context file for LLMs and AI coding agents navigating `xdevplatform/samples`. + +## Official XDK Packages Used + +All four primary SDK sample suites use the official first-party **XDK** libraries generated from `https://api.x.com/2/openapi.json`: + +| Language | Directory | Package | Install | Run | +|---|---|---|---|---| +| Python 3.10+ | `python/` (80 files) | `xdk` (PyPI) | `pip install xdk` | `python posts/search_recent.py` | +| JavaScript (Node 18+) | `javascript/` (84 files) | `@xdevplatform/xdk` (npm) | `cd javascript && npm install` | `node posts/search_recent.js` | +| Java 17+ | `java/` (80 files) | `com.x:xdk` (Maven Central) | `cd java && mvn compile` | `mvn compile exec:java -Dexec.mainClass="posts.SearchRecent"` | +| C# / .NET 8+ | `csharp/` (80 files) | `XDevPlatform.Xdk` (NuGet) | `cd csharp && dotnet build` | `dotnet run -- posts/search_recent` | + +Additional community/HTTP samples are available in `ruby/` (58 files) and `r/` (5 files). + +## File Naming & Directory Layout + +Every XDK language mirrors the same 11 top-level endpoint categories: + +- `activity/` — `create_subscription`, `delete_subscription`, `list_subscriptions`, `stream_events`, `update_subscription` +- `compliance/` — `create_jobs`, `download_results`, `get_jobs`, `get_jobs_by_id`, `upload_ids` +- `direct_messages/` — `get_events_by_conversation`, `get_one_to_one_conversation_events`, `get_user_conversation_events`, `post_dm_to_conversation`, `post_group_conversation_dm`, `post_one_to_one_dm` +- `lists/` — `add_member`, `create_list`, `delete_list`, `get_list_by_id`, `get_list_followers`, `get_list_members`, `get_list_posts`, `remove_member`, `update_list` +- `media/` — `upload`, `media_upload_v2` +- `posts/` — `create_post`, `delete_post`, `get_liking_users`, `get_post_by_id`, `get_post_counts_all`, `get_post_counts_recent`, `get_posts_by_ids`, `get_quoted_posts`, `get_reposted_by`, `hide_reply`, `search_all`, `search_recent` +- `spaces/` — `get_spaces_by_ids`, `search_spaces` +- `streams/` — `stream_posts_filtered`, `stream_posts_sample` +- `usage/` — `get_usage` +- `users/` — `get_users_by_usernames`, `get_users_by_usernames_user_context`, `get_users_me`, plus `block/`, `bookmark/`, `follow/`, `like/`, `lists/`, `mute/`, `repost/`, `timeline/` +- `webhooks/` — `delete_webhook`, `list_webhooks`, `register_webhook`, `validate_webhook`, `webhook_server` + +Naming conventions per language: +- **Python**: `snake_case.py` (e.g., `python/posts/search_recent.py`) +- **JavaScript**: `snake_case.js` (e.g., `javascript/posts/search_recent.js`) +- **Java**: `PascalCase.java` with matching package declarations (e.g., `java/posts/SearchRecent.java`, `package posts;`) +- **C#**: `PascalCase.cs` with `Samples.` namespaces and `SamplesRunner` CLI in `csharp/Program.cs` (e.g., `csharp/posts/SearchRecent.cs`) + +## SDK Idioms Across Languages + +### 1. Client Initialization (Bearer Token) +- **Python**: `from xdk import Client; client = Client(bearer_token=os.environ["BEARER_TOKEN"])` +- **JavaScript**: `const { Client } = require('@xdevplatform/xdk'); const client = new Client({ bearerToken: process.env.BEARER_TOKEN });` +- **Java**: `XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build());` +- **C#**: `using var client = new XClient(new XClientOptions { BearerToken = bearerToken });` + +### 2. Cursor Pagination +- **Python**: `for page in client.posts.search_recent(query="...", max_results=100): ...` +- **JavaScript**: `const paginator = new PostPaginator(async (token) => client.posts.searchRecent(query, { maxResults: 100, nextToken: token })); for await (const post of paginator) { ... }` +- **Java**: `for (var page : client.posts().searchRecentPages(query, options)) { ... }` +- **C#**: `await foreach (var page in client.Posts.SearchRecentPages(query, options)) { ... }` + +### 3. Real-Time Streaming +- **Python**: `for event in client.stream.posts(tweet_fields=["id", "text"]): ...` +- **JavaScript**: `const stream = await client.stream.posts({ tweetFields: ['id', 'text'] }); stream.on('data', console.log);` +- **Java**: `try (var stream = client.stream().posts(options)) { for (var event : stream) { ... } }` +- **C#**: `await using var stream = client.Stream.PostsStream(options); await foreach (var event in stream) { ... }` + +## Machine-Readable Index + +See `api-index.json` at the repository root for an exact JSON mapping from every sample slug, HTTP method, and `/2/*` endpoint path to the corresponding files across `python`, `javascript`, `java`, `csharp`, `ruby`, and `r`. From 52f77b9766c58b473419aba66acdcebcf946ca38 Mon Sep 17 00:00:00 2001 From: Taylor Caldwell <169854908+tcaldwell-x@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:43:07 -0800 Subject: [PATCH 2/4] feat: add TypeScript ESM samples, Verify Samples CI, and fix pre-existing Python/JS SDK calls --- .github/workflows/ci.yml | 250 ++++++++++++++++++ .github/workflows/cla.yml | 25 -- README.md | 39 +-- api-index.json | 86 ++++++ javascript/compliance/download_results.js | 2 +- javascript/compliance/get_jobs.js | 8 +- .../get_user_conversation_events.js | 3 +- javascript/lists/add_member.js | 2 +- javascript/lists/create_list.js | 2 +- javascript/lists/get_list_by_id.js | 3 +- javascript/lists/get_list_followers.js | 4 +- javascript/lists/get_list_members.js | 4 +- javascript/lists/update_list.js | 2 +- javascript/spaces/get_spaces_by_ids.js | 3 +- javascript/users/bookmark/create_bookmark.js | 2 +- javascript/users/get_users_by_usernames.js | 2 +- .../get_users_by_usernames_user_context.js | 2 +- javascript/users/get_users_me.js | 2 +- javascript/users/like/like_post.js | 2 +- javascript/users/lists/follow_list.js | 2 +- javascript/users/lists/get_followed_lists.js | 2 +- .../users/lists/get_list_memberships.js | 2 +- javascript/users/lists/get_owned_lists.js | 2 +- javascript/users/lists/pin_list.js | 2 +- javascript/users/mute/mute_user.js | 2 +- javascript/users/repost/repost_post.js | 2 +- llms.txt | 17 +- python/activity/stream_events.py | 4 +- python/compliance/create_jobs.py | 2 +- python/compliance/get_jobs_by_id.py | 2 +- python/lists/delete_list.py | 2 +- python/lists/remove_member.py | 2 +- python/media/upload.py | 12 +- typescript/README.md | 133 ++++++++++ typescript/activity/create_subscription.ts | 29 ++ typescript/activity/delete_subscription.ts | 22 ++ typescript/activity/list_subscriptions.ts | 21 ++ typescript/activity/stream_events.ts | 33 +++ typescript/activity/update_subscription.ts | 24 ++ typescript/compliance/create_jobs.ts | 30 +++ typescript/compliance/download_results.ts | 32 +++ typescript/compliance/get_jobs.ts | 26 ++ typescript/compliance/get_jobs_by_id.ts | 26 ++ typescript/compliance/upload_ids.ts | 45 ++++ .../get_events_by_conversation.ts | 96 +++++++ .../get_one_to_one_conversation_events.ts | 96 +++++++ .../get_user_conversation_events.ts | 97 +++++++ .../post_dm_to_conversation.ts | 83 ++++++ .../post_group_conversation_dm.ts | 86 ++++++ .../direct_messages/post_one_to_one_dm.ts | 83 ++++++ typescript/lists/add_member.ts | 98 +++++++ typescript/lists/create_list.ts | 99 +++++++ typescript/lists/delete_list.ts | 94 +++++++ typescript/lists/get_list_by_id.ts | 32 +++ typescript/lists/get_list_followers.ts | 29 ++ typescript/lists/get_list_members.ts | 29 ++ typescript/lists/get_list_posts.ts | 30 +++ typescript/lists/remove_member.ts | 98 +++++++ typescript/lists/update_list.ts | 102 +++++++ typescript/media/media_upload_v2.ts | 121 +++++++++ typescript/media/upload.ts | 87 ++++++ typescript/package.json | 21 ++ typescript/posts/create_post.ts | 99 +++++++ typescript/posts/delete_post.ts | 96 +++++++ typescript/posts/get_liking_users.ts | 100 +++++++ typescript/posts/get_post_by_id.ts | 24 ++ typescript/posts/get_post_counts_all.ts | 30 +++ typescript/posts/get_post_counts_recent.ts | 30 +++ typescript/posts/get_posts_by_ids.ts | 37 +++ .../posts/get_posts_by_ids_user_context.ts | 103 ++++++++ typescript/posts/get_quoted_posts.ts | 51 ++++ typescript/posts/get_reposted_by.ts | 54 ++++ typescript/posts/hide_reply.ts | 80 ++++++ typescript/posts/search_all.ts | 50 ++++ typescript/posts/search_recent.ts | 58 ++++ typescript/spaces/get_spaces_by_ids.ts | 32 +++ typescript/spaces/search_spaces.ts | 32 +++ typescript/streams/stream_posts_filtered.ts | 72 +++++ typescript/streams/stream_posts_sample.ts | 47 ++++ typescript/tsconfig.json | 17 ++ typescript/usage/get_usage.ts | 27 ++ typescript/users/block/get_blocking.ts | 95 +++++++ typescript/users/bookmark/create_bookmark.ts | 101 +++++++ typescript/users/bookmark/delete_bookmark.ts | 101 +++++++ typescript/users/bookmark/get_bookmarks.ts | 105 ++++++++ typescript/users/follow/follow_user.ts | 86 ++++++ typescript/users/follow/get_followers.ts | 44 +++ .../users/follow/get_followers_paginated.ts | 56 ++++ typescript/users/follow/get_following.ts | 25 ++ .../users/follow/get_following_paginated.ts | 55 ++++ typescript/users/follow/unfollow_user.ts | 86 ++++++ typescript/users/get_users_by_usernames.ts | 31 +++ .../get_users_by_usernames_user_context.ts | 102 +++++++ typescript/users/get_users_me.ts | 94 +++++++ typescript/users/like/get_liked_posts.ts | 124 +++++++++ typescript/users/like/like_post.ts | 98 +++++++ typescript/users/like/unlike_post.ts | 98 +++++++ typescript/users/lists/follow_list.ts | 98 +++++++ typescript/users/lists/get_followed_lists.ts | 29 ++ .../users/lists/get_list_memberships.ts | 29 ++ typescript/users/lists/get_owned_lists.ts | 29 ++ typescript/users/lists/get_pinned_lists.ts | 83 ++++++ typescript/users/lists/pin_list.ts | 98 +++++++ typescript/users/lists/unfollow_list.ts | 98 +++++++ typescript/users/lists/unpin_list.ts | 98 +++++++ typescript/users/mute/get_muting.ts | 95 +++++++ typescript/users/mute/mute_user.ts | 99 +++++++ typescript/users/mute/unmute_user.ts | 98 +++++++ typescript/users/repost/get_reposts_of_me.ts | 96 +++++++ typescript/users/repost/repost_post.ts | 98 +++++++ typescript/users/repost/unrepost_post.ts | 98 +++++++ .../users/timeline/get_home_timeline.ts | 95 +++++++ typescript/users/timeline/get_mentions.ts | 51 ++++ typescript/users/timeline/get_posts.ts | 35 +++ .../users/timeline/get_posts_paginated.ts | 69 +++++ typescript/webhooks/delete_webhook.ts | 22 ++ typescript/webhooks/list_webhooks.ts | 21 ++ typescript/webhooks/register_webhook.ts | 22 ++ typescript/webhooks/validate_webhook.ts | 22 ++ typescript/webhooks/webhook_server.ts | 56 ++++ 120 files changed, 6090 insertions(+), 89 deletions(-) create mode 100644 .github/workflows/ci.yml delete mode 100644 .github/workflows/cla.yml create mode 100644 typescript/README.md create mode 100644 typescript/activity/create_subscription.ts create mode 100644 typescript/activity/delete_subscription.ts create mode 100644 typescript/activity/list_subscriptions.ts create mode 100644 typescript/activity/stream_events.ts create mode 100644 typescript/activity/update_subscription.ts create mode 100644 typescript/compliance/create_jobs.ts create mode 100644 typescript/compliance/download_results.ts create mode 100644 typescript/compliance/get_jobs.ts create mode 100644 typescript/compliance/get_jobs_by_id.ts create mode 100644 typescript/compliance/upload_ids.ts create mode 100644 typescript/direct_messages/get_events_by_conversation.ts create mode 100644 typescript/direct_messages/get_one_to_one_conversation_events.ts create mode 100644 typescript/direct_messages/get_user_conversation_events.ts create mode 100644 typescript/direct_messages/post_dm_to_conversation.ts create mode 100644 typescript/direct_messages/post_group_conversation_dm.ts create mode 100644 typescript/direct_messages/post_one_to_one_dm.ts create mode 100644 typescript/lists/add_member.ts create mode 100644 typescript/lists/create_list.ts create mode 100644 typescript/lists/delete_list.ts create mode 100644 typescript/lists/get_list_by_id.ts create mode 100644 typescript/lists/get_list_followers.ts create mode 100644 typescript/lists/get_list_members.ts create mode 100644 typescript/lists/get_list_posts.ts create mode 100644 typescript/lists/remove_member.ts create mode 100644 typescript/lists/update_list.ts create mode 100644 typescript/media/media_upload_v2.ts create mode 100644 typescript/media/upload.ts create mode 100644 typescript/package.json create mode 100644 typescript/posts/create_post.ts create mode 100644 typescript/posts/delete_post.ts create mode 100644 typescript/posts/get_liking_users.ts create mode 100644 typescript/posts/get_post_by_id.ts create mode 100644 typescript/posts/get_post_counts_all.ts create mode 100644 typescript/posts/get_post_counts_recent.ts create mode 100644 typescript/posts/get_posts_by_ids.ts create mode 100644 typescript/posts/get_posts_by_ids_user_context.ts create mode 100644 typescript/posts/get_quoted_posts.ts create mode 100644 typescript/posts/get_reposted_by.ts create mode 100644 typescript/posts/hide_reply.ts create mode 100644 typescript/posts/search_all.ts create mode 100644 typescript/posts/search_recent.ts create mode 100644 typescript/spaces/get_spaces_by_ids.ts create mode 100644 typescript/spaces/search_spaces.ts create mode 100644 typescript/streams/stream_posts_filtered.ts create mode 100644 typescript/streams/stream_posts_sample.ts create mode 100644 typescript/tsconfig.json create mode 100644 typescript/usage/get_usage.ts create mode 100644 typescript/users/block/get_blocking.ts create mode 100644 typescript/users/bookmark/create_bookmark.ts create mode 100644 typescript/users/bookmark/delete_bookmark.ts create mode 100644 typescript/users/bookmark/get_bookmarks.ts create mode 100644 typescript/users/follow/follow_user.ts create mode 100644 typescript/users/follow/get_followers.ts create mode 100644 typescript/users/follow/get_followers_paginated.ts create mode 100644 typescript/users/follow/get_following.ts create mode 100644 typescript/users/follow/get_following_paginated.ts create mode 100644 typescript/users/follow/unfollow_user.ts create mode 100644 typescript/users/get_users_by_usernames.ts create mode 100644 typescript/users/get_users_by_usernames_user_context.ts create mode 100644 typescript/users/get_users_me.ts create mode 100644 typescript/users/like/get_liked_posts.ts create mode 100644 typescript/users/like/like_post.ts create mode 100644 typescript/users/like/unlike_post.ts create mode 100644 typescript/users/lists/follow_list.ts create mode 100644 typescript/users/lists/get_followed_lists.ts create mode 100644 typescript/users/lists/get_list_memberships.ts create mode 100644 typescript/users/lists/get_owned_lists.ts create mode 100644 typescript/users/lists/get_pinned_lists.ts create mode 100644 typescript/users/lists/pin_list.ts create mode 100644 typescript/users/lists/unfollow_list.ts create mode 100644 typescript/users/lists/unpin_list.ts create mode 100644 typescript/users/mute/get_muting.ts create mode 100644 typescript/users/mute/mute_user.ts create mode 100644 typescript/users/mute/unmute_user.ts create mode 100644 typescript/users/repost/get_reposts_of_me.ts create mode 100644 typescript/users/repost/repost_post.ts create mode 100644 typescript/users/repost/unrepost_post.ts create mode 100644 typescript/users/timeline/get_home_timeline.ts create mode 100644 typescript/users/timeline/get_mentions.ts create mode 100644 typescript/users/timeline/get_posts.ts create mode 100644 typescript/users/timeline/get_posts_paginated.ts create mode 100644 typescript/webhooks/delete_webhook.ts create mode 100644 typescript/webhooks/list_webhooks.ts create mode 100644 typescript/webhooks/register_webhook.ts create mode 100644 typescript/webhooks/validate_webhook.ts create mode 100644 typescript/webhooks/webhook_server.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..9c3c6c1 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,250 @@ +name: Verify Samples + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + schedule: + # Weekly check against latest published XDK packages (Mondays 09:00 UTC) + - cron: '0 9 * * 1' + +permissions: + contents: read + +jobs: + python: + name: Python (xdk) & Catalog + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install xdk from PyPI + run: python -m pip install --upgrade pip xdk + + - name: Verify Python samples & api-index.json + run: | + python - <<'PY' + import json + import pathlib + import py_compile + import re + from xdk import Client + + client = Client(bearer_token="test") + py_files = sorted(pathlib.Path("python").rglob("*.py")) + assert len(py_files) >= 80, f"Expected >=80 Python samples, found {len(py_files)}" + + bad_calls = [] + for f in py_files: + py_compile.compile(str(f), doraise=True) + src = f.read_text(encoding="utf-8") + for m in re.finditer(r"\bclient\.([A-Za-z0-9_]+)\.([A-Za-z0-9_]+)\s*\(", src): + sub, meth = m.group(1), m.group(2) + sub_obj = getattr(client, sub, None) + if sub_obj is None or not callable(getattr(sub_obj, meth, None)): + bad_calls.append((str(f), sub, meth)) + + if bad_calls: + raise SystemExit(f"Unresolved xdk method calls: {bad_calls}") + + catalog = json.loads(pathlib.Path("api-index.json").read_text(encoding="utf-8")) + missing_paths = [] + for ep in catalog.get("endpoints", []): + for lang, rel_path in ep.get("files", {}).items(): + if not pathlib.Path(rel_path).is_file(): + missing_paths.append((ep.get("id"), lang, rel_path)) + + if missing_paths: + raise SystemExit(f"Missing files in api-index.json: {missing_paths}") + + print(f"Verified {len(py_files)} Python samples and {len(catalog.get('endpoints', []))} catalog endpoints.") + PY + + javascript-typescript: + name: JavaScript & TypeScript (@xdevplatform/xdk) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Verify JavaScript samples + run: | + cd javascript + npm install --no-audit --no-fund + find . -name "*.js" -not -path "./node_modules/*" -exec node --check {} + + node - <<'JS' + const fs = require('fs'); + const path = require('path'); + const { Client } = require('@xdevplatform/xdk'); + const client = new Client({ bearerToken: 'test' }); + + function walk(dir) { + const out = []; + for (const ent of fs.readdirSync(dir, { withFileTypes: true })) { + if (ent.name === 'node_modules') continue; + const full = path.join(dir, ent.name); + if (ent.isDirectory()) out.push(...walk(full)); + else if (ent.name.endsWith('.js')) out.push(full); + } + return out; + } + + const files = walk('.'); + const bad = []; + for (const f of files) { + const src = fs.readFileSync(f, 'utf8'); + const re = /client\.([A-Za-z0-9_]+)\.([A-Za-z0-9_]+)\s*\(/g; + let m; + while ((m = re.exec(src)) !== null) { + const [, sub, meth] = m; + if (!client[sub] || typeof client[sub][meth] !== 'function') { + bad.push({ file: f, sub, meth }); + } + } + } + if (bad.length > 0) { + console.error('Unresolved @xdevplatform/xdk calls:', bad); + process.exit(1); + } + console.log(`Verified ${files.length} JavaScript samples.`); + JS + + - name: Type-check TypeScript samples (tsc --noEmit --strict) + run: | + cd typescript + npm install --no-audit --no-fund + npm run typecheck + + java: + name: Java 17+ (com.x:xdk) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: '21' + + - name: Compile Java samples + run: | + if curl -fsSI https://repo1.maven.org/maven2/com/x/xdk/maven-metadata.xml >/dev/null 2>&1; then + mvn -B -f java/pom.xml compile + else + echo "::notice::com.x:xdk is awaiting initial Maven Central publication; running JDK 17 AST syntax check until com.x:xdk 0.1.0 is indexed on Central." + python3 - <<'PY' + import pathlib, subprocess, tempfile + code = """ + import com.sun.source.util.JavacTask; + import java.io.File; + import java.nio.file.*; + import java.util.*; + import java.util.stream.*; + import javax.tools.*; + + public class ParseCheck { + public static void main(String[] args) throws Exception { + List files; + try (Stream walk = Files.walk(Paths.get("java"))) { + files = walk.filter(p -> p.toString().endsWith(".java")) + .map(Path::toFile) + .collect(Collectors.toList()); + } + if (files.size() < 80) { + throw new IllegalStateException("Expected >=80 Java files, found " + files.size()); + } + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + try (StandardJavaFileManager fm = compiler.getStandardFileManager(diagnostics, null, null)) { + Iterable units = fm.getJavaFileObjectsFromFiles(files); + JavacTask task = (JavacTask) compiler.getTask( + null, fm, diagnostics, List.of("--release", "17"), null, units); + task.parse(); + } + long errors = diagnostics.getDiagnostics().stream() + .filter(d -> d.getKind() == Diagnostic.Kind.ERROR) + .peek(System.err::println) + .count(); + System.out.println("Parsed " + files.size() + " Java files cleanly."); + if (errors > 0) System.exit(1); + } + } + """ + with tempfile.TemporaryDirectory() as d: + p = pathlib.Path(d) / "ParseCheck.java" + p.write_text(code) + subprocess.run(["java", str(p)], check=True) + PY + fi + + csharp: + name: C# / .NET 8 (XDevPlatform.Xdk) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '8.0.x' + + - name: Build C# samples + run: | + if curl -fsSI https://api.nuget.org/v3-flatcontainer/xdevplatform.xdk/index.json >/dev/null 2>&1; then + dotnet build csharp/XdkSamples.csproj -warnaserror + dotnet run --project csharp/XdkSamples.csproj --no-build -- --help >/dev/null + else + echo "::notice::XDevPlatform.Xdk is awaiting initial NuGet.org publication; running Roslyn C# AST check until XDevPlatform.Xdk 0.1.0 is indexed on NuGet.org." + python3 - <<'PY' + import pathlib, subprocess, tempfile, textwrap + sdk_line = subprocess.check_output(["dotnet", "--list-sdks"], text=True).strip().splitlines()[-1] + ver, rest = sdk_line.split(" [", 1) + roslyn = pathlib.Path(rest.rstrip("]")) / ver / "Roslyn" / "bincore" + csproj = f""" + + Exe + net8.0 + enable + + + {roslyn}/Microsoft.CodeAnalysis.dll + {roslyn}/Microsoft.CodeAnalysis.CSharp.dll + + """ + prog = textwrap.dedent("""\ + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + + var csFiles = Directory.EnumerateFiles(args[0], "*.cs", SearchOption.AllDirectories) + .Where(p => !p.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}") + && !p.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}")) + .OrderBy(p => p) + .ToList(); + if (csFiles.Count < 81) throw new Exception($"Expected >=81 C# files, found {csFiles.Count}"); + var errors = 0; + foreach (var f in csFiles) + { + var tree = CSharpSyntaxTree.ParseText(File.ReadAllText(f), path: f); + foreach (var diag in tree.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error)) + { + Console.Error.WriteLine(diag); + errors++; + } + } + Console.WriteLine($"Parsed {csFiles.Count} C# files cleanly with Roslyn."); + return errors > 0 ? 1 : 0; + """) + with tempfile.TemporaryDirectory() as d: + dp = pathlib.Path(d) + (dp / "Check.csproj").write_text(csproj) + (dp / "Program.cs").write_text(prog) + subprocess.run(["dotnet", "run", "--project", str(dp / "Check.csproj"), "--", "csharp"], check=True) + PY + fi diff --git a/.github/workflows/cla.yml b/.github/workflows/cla.yml deleted file mode 100644 index b5eac6a..0000000 --- a/.github/workflows/cla.yml +++ /dev/null @@ -1,25 +0,0 @@ -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' diff --git a/README.md b/README.md index 6f8b0d5..bfdee9e 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,11 @@ [![X API v2](https://img.shields.io/endpoint?url=https%3A%2F%2Ftwbadges.glitch.me%2Fbadges%2Fv2)](https://developer.x.com/en/docs/twitter-api) -Official sample code for the **X API v2** across **Python**, **JavaScript / TypeScript**, **Java**, **C# / .NET**, **Ruby**, and **R**. +Official sample code for the **X API v2** across **Python**, **TypeScript**, **JavaScript**, **Java**, **C# / .NET**, **Ruby**, and **R**. First-party SDK samples use the official **XDK** libraries: - **Python**: [`xdk`](https://pypi.org/project/xdk/) ([`xdevplatform/xdk-python`](https://github.com/xdevplatform/xdk-python)) -- **JavaScript / TypeScript**: [`@xdevplatform/xdk`](https://www.npmjs.com/package/@xdevplatform/xdk) ([`xdevplatform/xdk-typescript`](https://github.com/xdevplatform/xdk-typescript)) +- **TypeScript / JavaScript**: [`@xdevplatform/xdk`](https://www.npmjs.com/package/@xdevplatform/xdk) ([`xdevplatform/xdk-typescript`](https://github.com/xdevplatform/xdk-typescript)) - **Java**: [`com.x:xdk`](https://central.sonatype.com/artifact/com.x/xdk) ([`xdevplatform/xdk-java`](https://github.com/xdevplatform/xdk-java)) - **C# / .NET**: [`XDevPlatform.Xdk`](https://www.nuget.org/packages/XDevPlatform.Xdk) ([`xdevplatform/xdk-csharp`](https://github.com/xdevplatform/xdk-csharp)) @@ -14,7 +14,8 @@ First-party SDK samples use the official **XDK** libraries: ``` ├── python/ # 80 Python samples (xdk) -├── javascript/ # 84 JavaScript / Node.js samples (@xdevplatform/xdk) +├── typescript/ # 84 TypeScript ESM samples (@xdevplatform/xdk, strict tsc) +├── javascript/ # 84 JavaScript / Node.js CommonJS samples (@xdevplatform/xdk) ├── java/ # 80 Java 17+ samples (com.x:xdk) ├── csharp/ # 80 C# / .NET 8+ samples (XDevPlatform.Xdk) ├── ruby/ # 58 Ruby samples @@ -49,6 +50,10 @@ export CLIENT_SECRET='your_oauth2_client_secret' cd python && pip install xdk python posts/search_recent.py +# TypeScript (@xdevplatform/xdk) +cd typescript && npm install +npx tsx posts/search_recent.ts + # JavaScript / Node.js (@xdevplatform/xdk) cd javascript && npm install node posts/search_recent.js @@ -68,19 +73,19 @@ ruby posts/search_recent.rb ## Coverage by Category -| Category | Python (`xdk`) | JavaScript (`@xdevplatform/xdk`) | Java (`com.x:xdk`) | C# (`XDevPlatform.Xdk`) | Ruby | R | -|---|:---:|:---:|:---:|:---:|:---:|:---:| -| Activity (subscriptions & stream) | ✅ | ✅ | ✅ | ✅ | | | -| Compliance (batch jobs) | ✅ | ✅ | ✅ | ✅ | | | -| Direct Messages (1:1 & group DMs) | ✅ | ✅ | ✅ | ✅ | | | -| Lists (CRUD, members, followers, posts) | ✅ | ✅ | ✅ | ✅ | ✅ | | -| Media Upload (single & chunked v2) | ✅ | ✅ | ✅ | ✅ | | | -| Posts (search, counts, create, delete, hide reply, quotes) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| Spaces (lookup & search) | ✅ | ✅ | ✅ | ✅ | ✅ | | -| Streams (filtered rules & 1% sampled) | ✅ | ✅ | ✅ | ✅ | ✅ | | -| Usage (daily Post usage) | ✅ | ✅ | ✅ | ✅ | | | -| Users (lookup, timelines, likes, bookmarks, follows, mutes, blocks, reposts) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| Webhooks (register, list, validate CRC, delete, server) | ✅ | ✅ | ✅ | ✅ | | | +| Category | Python (`xdk`) | TypeScript (`@xdevplatform/xdk`) | JavaScript (`@xdevplatform/xdk`) | Java (`com.x:xdk`) | C# (`XDevPlatform.Xdk`) | Ruby | R | +|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:| +| Activity (subscriptions & stream) | ✅ | ✅ | ✅ | ✅ | ✅ | | | +| Compliance (batch jobs) | ✅ | ✅ | ✅ | ✅ | ✅ | | | +| Direct Messages (1:1 & group DMs) | ✅ | ✅ | ✅ | ✅ | ✅ | | | +| Lists (CRUD, members, followers, posts) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | +| Media Upload (single & chunked v2) | ✅ | ✅ | ✅ | ✅ | ✅ | | | +| Posts (search, counts, create, delete, hide reply, quotes) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| Spaces (lookup & search) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | +| Streams (filtered rules & 1% sampled) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | +| Usage (daily Post usage) | ✅ | ✅ | ✅ | ✅ | ✅ | | | +| Users (lookup, timelines, likes, bookmarks, follows, mutes, blocks, reposts) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| Webhooks (register, list, validate CRC, delete, server) | ✅ | ✅ | ✅ | ✅ | ✅ | | | ## Authentication @@ -93,7 +98,7 @@ ruby posts/search_recent.rb ## For LLMs & Tooling - **`llms.txt`** - Concise context file covering SDK packages, auth patterns, pagination, and streaming across all languages -- **`api-index.json`** - Machine-readable catalog mapping every endpoint to its exact file path in `python/`, `javascript/`, `java/`, `csharp/`, `ruby/`, and `r/` +- **`api-index.json`** - Machine-readable catalog mapping every endpoint to its exact file path in `python/`, `typescript/`, `javascript/`, `java/`, `csharp/`, `ruby/`, and `r/` ## Resources diff --git a/api-index.json b/api-index.json index c13fbe8..48cbb83 100644 --- a/api-index.json +++ b/api-index.json @@ -8,6 +8,11 @@ "registry": "https://pypi.org/project/xdk/", "repo": "https://github.com/xdevplatform/xdk-python" }, + "typescript": { + "package": "@xdevplatform/xdk", + "registry": "https://www.npmjs.com/package/@xdevplatform/xdk", + "repo": "https://github.com/xdevplatform/xdk-typescript" + }, "javascript": { "package": "@xdevplatform/xdk", "registry": "https://www.npmjs.com/package/@xdevplatform/xdk", @@ -26,6 +31,7 @@ }, "languages": [ "python", + "typescript", "javascript", "java", "csharp", @@ -44,6 +50,7 @@ ], "files": { "python": "python/activity/create_subscription.py", + "typescript": "typescript/activity/create_subscription.ts", "javascript": "javascript/activity/create_subscription.js", "java": "java/activity/CreateSubscription.java", "csharp": "csharp/activity/CreateSubscription.cs" @@ -61,6 +68,7 @@ ], "files": { "python": "python/activity/delete_subscription.py", + "typescript": "typescript/activity/delete_subscription.ts", "javascript": "javascript/activity/delete_subscription.js", "java": "java/activity/DeleteSubscription.java", "csharp": "csharp/activity/DeleteSubscription.cs" @@ -78,6 +86,7 @@ ], "files": { "python": "python/activity/list_subscriptions.py", + "typescript": "typescript/activity/list_subscriptions.ts", "javascript": "javascript/activity/list_subscriptions.js", "java": "java/activity/ListSubscriptions.java", "csharp": "csharp/activity/ListSubscriptions.cs" @@ -95,6 +104,7 @@ ], "files": { "python": "python/activity/stream_events.py", + "typescript": "typescript/activity/stream_events.ts", "javascript": "javascript/activity/stream_events.js", "java": "java/activity/StreamEvents.java", "csharp": "csharp/activity/StreamEvents.cs" @@ -112,6 +122,7 @@ ], "files": { "python": "python/activity/update_subscription.py", + "typescript": "typescript/activity/update_subscription.ts", "javascript": "javascript/activity/update_subscription.js", "java": "java/activity/UpdateSubscription.java", "csharp": "csharp/activity/UpdateSubscription.cs" @@ -129,6 +140,7 @@ ], "files": { "python": "python/compliance/create_jobs.py", + "typescript": "typescript/compliance/create_jobs.ts", "javascript": "javascript/compliance/create_jobs.js", "java": "java/compliance/CreateJobs.java", "csharp": "csharp/compliance/CreateJobs.cs" @@ -146,6 +158,7 @@ ], "files": { "python": "python/compliance/download_results.py", + "typescript": "typescript/compliance/download_results.ts", "javascript": "javascript/compliance/download_results.js", "java": "java/compliance/DownloadResults.java", "csharp": "csharp/compliance/DownloadResults.cs" @@ -163,6 +176,7 @@ ], "files": { "python": "python/compliance/get_jobs.py", + "typescript": "typescript/compliance/get_jobs.ts", "javascript": "javascript/compliance/get_jobs.js", "java": "java/compliance/GetJobs.java", "csharp": "csharp/compliance/GetJobs.cs" @@ -180,6 +194,7 @@ ], "files": { "python": "python/compliance/get_jobs_by_id.py", + "typescript": "typescript/compliance/get_jobs_by_id.ts", "javascript": "javascript/compliance/get_jobs_by_id.js", "java": "java/compliance/GetJobsById.java", "csharp": "csharp/compliance/GetJobsById.cs" @@ -197,6 +212,7 @@ ], "files": { "python": "python/compliance/upload_ids.py", + "typescript": "typescript/compliance/upload_ids.ts", "javascript": "javascript/compliance/upload_ids.js", "java": "java/compliance/UploadIds.java", "csharp": "csharp/compliance/UploadIds.cs" @@ -214,6 +230,7 @@ ], "files": { "python": "python/direct_messages/get_events_by_conversation.py", + "typescript": "typescript/direct_messages/get_events_by_conversation.ts", "javascript": "javascript/direct_messages/get_events_by_conversation.js", "java": "java/direct_messages/GetEventsByConversation.java", "csharp": "csharp/direct_messages/GetEventsByConversation.cs" @@ -231,6 +248,7 @@ ], "files": { "python": "python/direct_messages/get_one_to_one_conversation_events.py", + "typescript": "typescript/direct_messages/get_one_to_one_conversation_events.ts", "javascript": "javascript/direct_messages/get_one_to_one_conversation_events.js", "java": "java/direct_messages/GetOneToOneConversationEvents.java", "csharp": "csharp/direct_messages/GetOneToOneConversationEvents.cs" @@ -248,6 +266,7 @@ ], "files": { "python": "python/direct_messages/get_user_conversation_events.py", + "typescript": "typescript/direct_messages/get_user_conversation_events.ts", "javascript": "javascript/direct_messages/get_user_conversation_events.js", "java": "java/direct_messages/GetUserConversationEvents.java", "csharp": "csharp/direct_messages/GetUserConversationEvents.cs" @@ -265,6 +284,7 @@ ], "files": { "python": "python/direct_messages/post_dm_to_conversation.py", + "typescript": "typescript/direct_messages/post_dm_to_conversation.ts", "javascript": "javascript/direct_messages/post_dm_to_conversation.js", "java": "java/direct_messages/PostDmToConversation.java", "csharp": "csharp/direct_messages/PostDmToConversation.cs" @@ -282,6 +302,7 @@ ], "files": { "python": "python/direct_messages/post_group_conversation_dm.py", + "typescript": "typescript/direct_messages/post_group_conversation_dm.ts", "javascript": "javascript/direct_messages/post_group_conversation_dm.js", "java": "java/direct_messages/PostGroupConversationDm.java", "csharp": "csharp/direct_messages/PostGroupConversationDm.cs" @@ -299,6 +320,7 @@ ], "files": { "python": "python/direct_messages/post_one_to_one_dm.py", + "typescript": "typescript/direct_messages/post_one_to_one_dm.ts", "javascript": "javascript/direct_messages/post_one_to_one_dm.js", "java": "java/direct_messages/PostOneToOneDm.java", "csharp": "csharp/direct_messages/PostOneToOneDm.cs" @@ -316,6 +338,7 @@ ], "files": { "python": "python/lists/add_member.py", + "typescript": "typescript/lists/add_member.ts", "javascript": "javascript/lists/add_member.js", "java": "java/lists/AddMember.java", "csharp": "csharp/lists/AddMember.cs", @@ -334,6 +357,7 @@ ], "files": { "python": "python/lists/create_list.py", + "typescript": "typescript/lists/create_list.ts", "javascript": "javascript/lists/create_list.js", "java": "java/lists/CreateList.java", "csharp": "csharp/lists/CreateList.cs" @@ -351,6 +375,7 @@ ], "files": { "python": "python/lists/delete_list.py", + "typescript": "typescript/lists/delete_list.ts", "javascript": "javascript/lists/delete_list.js", "java": "java/lists/DeleteList.java", "csharp": "csharp/lists/DeleteList.cs" @@ -368,6 +393,7 @@ ], "files": { "python": "python/lists/get_list_by_id.py", + "typescript": "typescript/lists/get_list_by_id.ts", "javascript": "javascript/lists/get_list_by_id.js", "java": "java/lists/GetListById.java", "csharp": "csharp/lists/GetListById.cs" @@ -385,6 +411,7 @@ ], "files": { "python": "python/lists/get_list_followers.py", + "typescript": "typescript/lists/get_list_followers.ts", "javascript": "javascript/lists/get_list_followers.js", "java": "java/lists/GetListFollowers.java", "csharp": "csharp/lists/GetListFollowers.cs" @@ -402,6 +429,7 @@ ], "files": { "python": "python/lists/get_list_members.py", + "typescript": "typescript/lists/get_list_members.ts", "javascript": "javascript/lists/get_list_members.js", "java": "java/lists/GetListMembers.java", "csharp": "csharp/lists/GetListMembers.cs" @@ -419,6 +447,7 @@ ], "files": { "python": "python/lists/get_list_posts.py", + "typescript": "typescript/lists/get_list_posts.ts", "javascript": "javascript/lists/get_list_posts.js", "java": "java/lists/GetListPosts.java", "csharp": "csharp/lists/GetListPosts.cs" @@ -436,6 +465,7 @@ ], "files": { "python": "python/lists/remove_member.py", + "typescript": "typescript/lists/remove_member.ts", "javascript": "javascript/lists/remove_member.js", "java": "java/lists/RemoveMember.java", "csharp": "csharp/lists/RemoveMember.cs", @@ -454,6 +484,7 @@ ], "files": { "python": "python/lists/update_list.py", + "typescript": "typescript/lists/update_list.ts", "javascript": "javascript/lists/update_list.js", "java": "java/lists/UpdateList.java", "csharp": "csharp/lists/UpdateList.cs" @@ -471,6 +502,7 @@ ], "files": { "python": "python/media/media_upload_v2.py", + "typescript": "typescript/media/media_upload_v2.ts", "javascript": "javascript/media/media_upload_v2.js", "java": "java/media/MediaUploadV2.java", "csharp": "csharp/media/MediaUploadV2.cs" @@ -488,6 +520,7 @@ ], "files": { "python": "python/media/upload.py", + "typescript": "typescript/media/upload.ts", "javascript": "javascript/media/upload.js", "java": "java/media/Upload.java", "csharp": "csharp/media/Upload.cs" @@ -505,6 +538,7 @@ ], "files": { "python": "python/posts/create_post.py", + "typescript": "typescript/posts/create_post.ts", "javascript": "javascript/posts/create_post.js", "java": "java/posts/CreatePost.java", "csharp": "csharp/posts/CreatePost.cs" @@ -522,6 +556,7 @@ ], "files": { "python": "python/posts/delete_post.py", + "typescript": "typescript/posts/delete_post.ts", "javascript": "javascript/posts/delete_post.js", "java": "java/posts/DeletePost.java", "csharp": "csharp/posts/DeletePost.cs" @@ -539,6 +574,7 @@ ], "files": { "python": "python/posts/get_liking_users.py", + "typescript": "typescript/posts/get_liking_users.ts", "javascript": "javascript/posts/get_liking_users.js", "java": "java/posts/GetLikingUsers.java", "csharp": "csharp/posts/GetLikingUsers.cs" @@ -556,6 +592,7 @@ ], "files": { "python": "python/posts/get_post_by_id.py", + "typescript": "typescript/posts/get_post_by_id.ts", "javascript": "javascript/posts/get_post_by_id.js", "java": "java/posts/GetPostById.java", "csharp": "csharp/posts/GetPostById.cs" @@ -573,6 +610,7 @@ ], "files": { "python": "python/posts/get_post_counts_all.py", + "typescript": "typescript/posts/get_post_counts_all.ts", "javascript": "javascript/posts/get_post_counts_all.js", "java": "java/posts/GetPostCountsAll.java", "csharp": "csharp/posts/GetPostCountsAll.cs" @@ -590,6 +628,7 @@ ], "files": { "python": "python/posts/get_post_counts_recent.py", + "typescript": "typescript/posts/get_post_counts_recent.ts", "javascript": "javascript/posts/get_post_counts_recent.js", "java": "java/posts/GetPostCountsRecent.java", "csharp": "csharp/posts/GetPostCountsRecent.cs" @@ -607,6 +646,7 @@ ], "files": { "python": "python/posts/get_posts_by_ids.py", + "typescript": "typescript/posts/get_posts_by_ids.ts", "javascript": "javascript/posts/get_posts_by_ids.js", "java": "java/posts/GetPostsByIds.java", "csharp": "csharp/posts/GetPostsByIds.cs" @@ -624,6 +664,7 @@ ], "files": { "python": "python/posts/get_quoted_posts.py", + "typescript": "typescript/posts/get_quoted_posts.ts", "javascript": "javascript/posts/get_quoted_posts.js", "java": "java/posts/GetQuotedPosts.java", "csharp": "csharp/posts/GetQuotedPosts.cs" @@ -641,6 +682,7 @@ ], "files": { "python": "python/posts/get_reposted_by.py", + "typescript": "typescript/posts/get_reposted_by.ts", "javascript": "javascript/posts/get_reposted_by.js", "java": "java/posts/GetRepostedBy.java", "csharp": "csharp/posts/GetRepostedBy.cs" @@ -658,6 +700,7 @@ ], "files": { "python": "python/posts/hide_reply.py", + "typescript": "typescript/posts/hide_reply.ts", "javascript": "javascript/posts/hide_reply.js", "java": "java/posts/HideReply.java", "csharp": "csharp/posts/HideReply.cs" @@ -675,6 +718,7 @@ ], "files": { "python": "python/posts/search_all.py", + "typescript": "typescript/posts/search_all.ts", "javascript": "javascript/posts/search_all.js", "java": "java/posts/SearchAll.java", "csharp": "csharp/posts/SearchAll.cs" @@ -692,6 +736,7 @@ ], "files": { "python": "python/posts/search_recent.py", + "typescript": "typescript/posts/search_recent.ts", "javascript": "javascript/posts/search_recent.js", "java": "java/posts/SearchRecent.java", "csharp": "csharp/posts/SearchRecent.cs", @@ -710,6 +755,7 @@ ], "files": { "python": "python/spaces/get_spaces_by_ids.py", + "typescript": "typescript/spaces/get_spaces_by_ids.ts", "javascript": "javascript/spaces/get_spaces_by_ids.js", "java": "java/spaces/GetSpacesByIds.java", "csharp": "csharp/spaces/GetSpacesByIds.cs" @@ -727,6 +773,7 @@ ], "files": { "python": "python/spaces/search_spaces.py", + "typescript": "typescript/spaces/search_spaces.ts", "javascript": "javascript/spaces/search_spaces.js", "java": "java/spaces/SearchSpaces.java", "csharp": "csharp/spaces/SearchSpaces.cs", @@ -745,6 +792,7 @@ ], "files": { "python": "python/streams/stream_posts_filtered.py", + "typescript": "typescript/streams/stream_posts_filtered.ts", "javascript": "javascript/streams/stream_posts_filtered.js", "java": "java/streams/StreamPostsFiltered.java", "csharp": "csharp/streams/StreamPostsFiltered.cs" @@ -762,6 +810,7 @@ ], "files": { "python": "python/streams/stream_posts_sample.py", + "typescript": "typescript/streams/stream_posts_sample.ts", "javascript": "javascript/streams/stream_posts_sample.js", "java": "java/streams/StreamPostsSample.java", "csharp": "csharp/streams/StreamPostsSample.cs" @@ -779,6 +828,7 @@ ], "files": { "python": "python/usage/get_usage.py", + "typescript": "typescript/usage/get_usage.ts", "javascript": "javascript/usage/get_usage.js", "java": "java/usage/GetUsage.java", "csharp": "csharp/usage/GetUsage.cs" @@ -796,6 +846,7 @@ ], "files": { "python": "python/users/block/get_blocking.py", + "typescript": "typescript/users/block/get_blocking.ts", "javascript": "javascript/users/block/get_blocking.js", "java": "java/users/block/GetBlocking.java", "csharp": "csharp/users/block/GetBlocking.cs" @@ -813,6 +864,7 @@ ], "files": { "python": "python/users/bookmark/create_bookmark.py", + "typescript": "typescript/users/bookmark/create_bookmark.ts", "javascript": "javascript/users/bookmark/create_bookmark.js", "java": "java/users/bookmark/CreateBookmark.java", "csharp": "csharp/users/bookmark/CreateBookmark.cs" @@ -830,6 +882,7 @@ ], "files": { "python": "python/users/bookmark/delete_bookmark.py", + "typescript": "typescript/users/bookmark/delete_bookmark.ts", "javascript": "javascript/users/bookmark/delete_bookmark.js", "java": "java/users/bookmark/DeleteBookmark.java", "csharp": "csharp/users/bookmark/DeleteBookmark.cs" @@ -847,6 +900,7 @@ ], "files": { "python": "python/users/bookmark/get_bookmarks.py", + "typescript": "typescript/users/bookmark/get_bookmarks.ts", "javascript": "javascript/users/bookmark/get_bookmarks.js", "java": "java/users/bookmark/GetBookmarks.java", "csharp": "csharp/users/bookmark/GetBookmarks.cs" @@ -864,6 +918,7 @@ ], "files": { "python": "python/users/follow/follow_user.py", + "typescript": "typescript/users/follow/follow_user.ts", "javascript": "javascript/users/follow/follow_user.js", "java": "java/users/follow/FollowUser.java", "csharp": "csharp/users/follow/FollowUser.cs" @@ -881,6 +936,7 @@ ], "files": { "python": "python/users/follow/get_followers.py", + "typescript": "typescript/users/follow/get_followers.ts", "javascript": "javascript/users/follow/get_followers.js", "java": "java/users/follow/GetFollowers.java", "csharp": "csharp/users/follow/GetFollowers.cs" @@ -898,6 +954,7 @@ ], "files": { "python": "python/users/follow/get_following.py", + "typescript": "typescript/users/follow/get_following.ts", "javascript": "javascript/users/follow/get_following.js", "java": "java/users/follow/GetFollowing.java", "csharp": "csharp/users/follow/GetFollowing.cs" @@ -915,6 +972,7 @@ ], "files": { "python": "python/users/follow/unfollow_user.py", + "typescript": "typescript/users/follow/unfollow_user.ts", "javascript": "javascript/users/follow/unfollow_user.js", "java": "java/users/follow/UnfollowUser.java", "csharp": "csharp/users/follow/UnfollowUser.cs" @@ -932,6 +990,7 @@ ], "files": { "python": "python/users/get_users_by_usernames.py", + "typescript": "typescript/users/get_users_by_usernames.ts", "javascript": "javascript/users/get_users_by_usernames.js", "java": "java/users/GetUsersByUsernames.java", "csharp": "csharp/users/GetUsersByUsernames.cs" @@ -949,6 +1008,7 @@ ], "files": { "python": "python/users/get_users_by_usernames_user_context.py", + "typescript": "typescript/users/get_users_by_usernames_user_context.ts", "javascript": "javascript/users/get_users_by_usernames_user_context.js", "java": "java/users/GetUsersByUsernamesUserContext.java", "csharp": "csharp/users/GetUsersByUsernamesUserContext.cs" @@ -966,6 +1026,7 @@ ], "files": { "python": "python/users/get_users_me.py", + "typescript": "typescript/users/get_users_me.ts", "javascript": "javascript/users/get_users_me.js", "java": "java/users/GetUsersMe.java", "csharp": "csharp/users/GetUsersMe.cs" @@ -983,6 +1044,7 @@ ], "files": { "python": "python/users/like/get_liked_posts.py", + "typescript": "typescript/users/like/get_liked_posts.ts", "javascript": "javascript/users/like/get_liked_posts.js", "java": "java/users/like/GetLikedPosts.java", "csharp": "csharp/users/like/GetLikedPosts.cs" @@ -1000,6 +1062,7 @@ ], "files": { "python": "python/users/like/like_post.py", + "typescript": "typescript/users/like/like_post.ts", "javascript": "javascript/users/like/like_post.js", "java": "java/users/like/LikePost.java", "csharp": "csharp/users/like/LikePost.cs" @@ -1017,6 +1080,7 @@ ], "files": { "python": "python/users/like/unlike_post.py", + "typescript": "typescript/users/like/unlike_post.ts", "javascript": "javascript/users/like/unlike_post.js", "java": "java/users/like/UnlikePost.java", "csharp": "csharp/users/like/UnlikePost.cs" @@ -1034,6 +1098,7 @@ ], "files": { "python": "python/users/lists/follow_list.py", + "typescript": "typescript/users/lists/follow_list.ts", "javascript": "javascript/users/lists/follow_list.js", "java": "java/users/lists/FollowList.java", "csharp": "csharp/users/lists/FollowList.cs" @@ -1051,6 +1116,7 @@ ], "files": { "python": "python/users/lists/get_followed_lists.py", + "typescript": "typescript/users/lists/get_followed_lists.ts", "javascript": "javascript/users/lists/get_followed_lists.js", "java": "java/users/lists/GetFollowedLists.java", "csharp": "csharp/users/lists/GetFollowedLists.cs" @@ -1068,6 +1134,7 @@ ], "files": { "python": "python/users/lists/get_list_memberships.py", + "typescript": "typescript/users/lists/get_list_memberships.ts", "javascript": "javascript/users/lists/get_list_memberships.js", "java": "java/users/lists/GetListMemberships.java", "csharp": "csharp/users/lists/GetListMemberships.cs" @@ -1085,6 +1152,7 @@ ], "files": { "python": "python/users/lists/get_owned_lists.py", + "typescript": "typescript/users/lists/get_owned_lists.ts", "javascript": "javascript/users/lists/get_owned_lists.js", "java": "java/users/lists/GetOwnedLists.java", "csharp": "csharp/users/lists/GetOwnedLists.cs" @@ -1102,6 +1170,7 @@ ], "files": { "python": "python/users/lists/get_pinned_lists.py", + "typescript": "typescript/users/lists/get_pinned_lists.ts", "javascript": "javascript/users/lists/get_pinned_lists.js", "java": "java/users/lists/GetPinnedLists.java", "csharp": "csharp/users/lists/GetPinnedLists.cs" @@ -1119,6 +1188,7 @@ ], "files": { "python": "python/users/lists/pin_list.py", + "typescript": "typescript/users/lists/pin_list.ts", "javascript": "javascript/users/lists/pin_list.js", "java": "java/users/lists/PinList.java", "csharp": "csharp/users/lists/PinList.cs" @@ -1136,6 +1206,7 @@ ], "files": { "python": "python/users/lists/unfollow_list.py", + "typescript": "typescript/users/lists/unfollow_list.ts", "javascript": "javascript/users/lists/unfollow_list.js", "java": "java/users/lists/UnfollowList.java", "csharp": "csharp/users/lists/UnfollowList.cs" @@ -1153,6 +1224,7 @@ ], "files": { "python": "python/users/lists/unpin_list.py", + "typescript": "typescript/users/lists/unpin_list.ts", "javascript": "javascript/users/lists/unpin_list.js", "java": "java/users/lists/UnpinList.java", "csharp": "csharp/users/lists/UnpinList.cs" @@ -1170,6 +1242,7 @@ ], "files": { "python": "python/users/mute/get_muting.py", + "typescript": "typescript/users/mute/get_muting.ts", "javascript": "javascript/users/mute/get_muting.js", "java": "java/users/mute/GetMuting.java", "csharp": "csharp/users/mute/GetMuting.cs" @@ -1187,6 +1260,7 @@ ], "files": { "python": "python/users/mute/mute_user.py", + "typescript": "typescript/users/mute/mute_user.ts", "javascript": "javascript/users/mute/mute_user.js", "java": "java/users/mute/MuteUser.java", "csharp": "csharp/users/mute/MuteUser.cs" @@ -1204,6 +1278,7 @@ ], "files": { "python": "python/users/mute/unmute_user.py", + "typescript": "typescript/users/mute/unmute_user.ts", "javascript": "javascript/users/mute/unmute_user.js", "java": "java/users/mute/UnmuteUser.java", "csharp": "csharp/users/mute/UnmuteUser.cs" @@ -1221,6 +1296,7 @@ ], "files": { "python": "python/users/repost/get_reposts_of_me.py", + "typescript": "typescript/users/repost/get_reposts_of_me.ts", "javascript": "javascript/users/repost/get_reposts_of_me.js", "java": "java/users/repost/GetRepostsOfMe.java", "csharp": "csharp/users/repost/GetRepostsOfMe.cs" @@ -1238,6 +1314,7 @@ ], "files": { "python": "python/users/repost/repost_post.py", + "typescript": "typescript/users/repost/repost_post.ts", "javascript": "javascript/users/repost/repost_post.js", "java": "java/users/repost/RepostPost.java", "csharp": "csharp/users/repost/RepostPost.cs" @@ -1255,6 +1332,7 @@ ], "files": { "python": "python/users/repost/unrepost_post.py", + "typescript": "typescript/users/repost/unrepost_post.ts", "javascript": "javascript/users/repost/unrepost_post.js", "java": "java/users/repost/UnrepostPost.java", "csharp": "csharp/users/repost/UnrepostPost.cs" @@ -1272,6 +1350,7 @@ ], "files": { "python": "python/users/timeline/get_home_timeline.py", + "typescript": "typescript/users/timeline/get_home_timeline.ts", "javascript": "javascript/users/timeline/get_home_timeline.js", "java": "java/users/timeline/GetHomeTimeline.java", "csharp": "csharp/users/timeline/GetHomeTimeline.cs" @@ -1289,6 +1368,7 @@ ], "files": { "python": "python/users/timeline/get_mentions.py", + "typescript": "typescript/users/timeline/get_mentions.ts", "javascript": "javascript/users/timeline/get_mentions.js", "java": "java/users/timeline/GetMentions.java", "csharp": "csharp/users/timeline/GetMentions.cs" @@ -1306,6 +1386,7 @@ ], "files": { "python": "python/users/timeline/get_posts.py", + "typescript": "typescript/users/timeline/get_posts.ts", "javascript": "javascript/users/timeline/get_posts.js", "java": "java/users/timeline/GetPosts.java", "csharp": "csharp/users/timeline/GetPosts.cs" @@ -1323,6 +1404,7 @@ ], "files": { "python": "python/webhooks/delete_webhook.py", + "typescript": "typescript/webhooks/delete_webhook.ts", "javascript": "javascript/webhooks/delete_webhook.js", "java": "java/webhooks/DeleteWebhook.java", "csharp": "csharp/webhooks/DeleteWebhook.cs" @@ -1340,6 +1422,7 @@ ], "files": { "python": "python/webhooks/list_webhooks.py", + "typescript": "typescript/webhooks/list_webhooks.ts", "javascript": "javascript/webhooks/list_webhooks.js", "java": "java/webhooks/ListWebhooks.java", "csharp": "csharp/webhooks/ListWebhooks.cs" @@ -1357,6 +1440,7 @@ ], "files": { "python": "python/webhooks/register_webhook.py", + "typescript": "typescript/webhooks/register_webhook.ts", "javascript": "javascript/webhooks/register_webhook.js", "java": "java/webhooks/RegisterWebhook.java", "csharp": "csharp/webhooks/RegisterWebhook.cs" @@ -1374,6 +1458,7 @@ ], "files": { "python": "python/webhooks/validate_webhook.py", + "typescript": "typescript/webhooks/validate_webhook.ts", "javascript": "javascript/webhooks/validate_webhook.js", "java": "java/webhooks/ValidateWebhook.java", "csharp": "csharp/webhooks/ValidateWebhook.cs" @@ -1391,6 +1476,7 @@ ], "files": { "python": "python/webhooks/webhook_server.py", + "typescript": "typescript/webhooks/webhook_server.ts", "javascript": "javascript/webhooks/webhook_server.js", "java": "java/webhooks/WebhookServer.java", "csharp": "csharp/webhooks/WebhookServer.cs" diff --git a/javascript/compliance/download_results.js b/javascript/compliance/download_results.js index 3896c86..3630b17 100644 --- a/javascript/compliance/download_results.js +++ b/javascript/compliance/download_results.js @@ -1,5 +1,5 @@ // Replace with your job download_url -downloadUrl = '' +const downloadUrl = ''; async function getRequest() { const res = await fetch(downloadUrl, { diff --git a/javascript/compliance/get_jobs.js b/javascript/compliance/get_jobs.js index 4a94e5b..63083ca 100644 --- a/javascript/compliance/get_jobs.js +++ b/javascript/compliance/get_jobs.js @@ -6,15 +6,13 @@ const { Client } = require('@xdevplatform/xdk'); 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" -}; +// For User Compliance job, replace "tweets" with "users" +const jobType = "tweets"; (async () => { try { // Make request - const response = await client.compliance.getJobs(params); + const response = await client.compliance.getJobs(jobType); console.dir(response, { depth: null diff --git a/javascript/direct_messages/get_user_conversation_events.js b/javascript/direct_messages/get_user_conversation_events.js index 1c899d4..5653eae 100644 --- a/javascript/direct_messages/get_user_conversation_events.js +++ b/javascript/direct_messages/get_user_conversation_events.js @@ -78,7 +78,8 @@ async function createUserClient(scopes) { const res = await client.directMessages.getEvents({ maxResults: 100, paginationToken: token, - dmEventFields: ['id', 'text', 'event_type', 'created_at', 'sender_id'], + dmEventFields: ['id', 'text', 'event_type', 'created_at', 'dm_conversation_id'], + expansions: ['sender_id'], }); return { data: res.data ?? [], diff --git a/javascript/lists/add_member.js b/javascript/lists/add_member.js index bdb057a..67a8d13 100644 --- a/javascript/lists/add_member.js +++ b/javascript/lists/add_member.js @@ -92,7 +92,7 @@ const getQueryStringParams = (query) => { }); // Make the request using SDK - const response = await client.lists.addMember(listId, { body: { user_id: userId } }); + const response = await client.lists.addMember(listId, { userId }); console.dir(response, { depth: null, }); diff --git a/javascript/lists/create_list.js b/javascript/lists/create_list.js index 3b48aec..9091e43 100644 --- a/javascript/lists/create_list.js +++ b/javascript/lists/create_list.js @@ -93,7 +93,7 @@ const getQueryStringParams = (query) => { }); // Make the request using SDK - const response = await client.lists.create({ body: data }); + const response = await client.lists.create(data); console.dir(response, { depth: null, }); diff --git a/javascript/lists/get_list_by_id.js b/javascript/lists/get_list_by_id.js index d1eb1e1..68e442e 100644 --- a/javascript/lists/get_list_by_id.js +++ b/javascript/lists/get_list_by_id.js @@ -19,7 +19,8 @@ const listId = "84839422"; (async () => { try { const response = await client.lists.getById(listId, { - listFields: ['created_at', 'follower_count', 'member_count', 'owner_id', 'description'] + listFields: ['created_at', 'follower_count', 'member_count', 'description'], + expansions: ['owner_id'] }); console.dir(response, { depth: null }); diff --git a/javascript/lists/get_list_followers.js b/javascript/lists/get_list_followers.js index 6ccc1bc..78779e5 100644 --- a/javascript/lists/get_list_followers.js +++ b/javascript/lists/get_list_followers.js @@ -13,8 +13,8 @@ const id = "list-id"; // 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 + userFields: ['created_at', 'description'], // Edit optional query parameters here + expansions: ['pinned_post_id'], // expansions is used to include the Post object tweetFields: ['created_at'] // Edit optional query parameters here }); diff --git a/javascript/lists/get_list_members.js b/javascript/lists/get_list_members.js index b366185..8b61bd0 100644 --- a/javascript/lists/get_list_members.js +++ b/javascript/lists/get_list_members.js @@ -13,8 +13,8 @@ const id = "list-id"; // 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 + userFields: ['created_at', 'description'], // Edit optional query parameters here + expansions: ['pinned_post_id'], // expansions is used to include the Post object tweetFields: ['created_at'] // Edit optional query parameters here }); diff --git a/javascript/lists/update_list.js b/javascript/lists/update_list.js index 13091af..80d39e9 100644 --- a/javascript/lists/update_list.js +++ b/javascript/lists/update_list.js @@ -96,7 +96,7 @@ const getQueryStringParams = (query) => { }); // Make the request using SDK - const response = await client.lists.update(targetListId, { body: data }); + const response = await client.lists.update(targetListId, data); console.dir(response, { depth: null, }); diff --git a/javascript/spaces/get_spaces_by_ids.js b/javascript/spaces/get_spaces_by_ids.js index 671c388..8fb6273 100644 --- a/javascript/spaces/get_spaces_by_ids.js +++ b/javascript/spaces/get_spaces_by_ids.js @@ -19,7 +19,8 @@ const spaceIds = ['1DXxyRYNejbKM']; 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'] + spaceFields: ['created_at', 'participant_count', 'title', 'state'], + expansions: ['creator_id', 'host_ids'] }); console.dir(response, { depth: null }); diff --git a/javascript/users/bookmark/create_bookmark.js b/javascript/users/bookmark/create_bookmark.js index 1b7ee7e..a5338fa 100644 --- a/javascript/users/bookmark/create_bookmark.js +++ b/javascript/users/bookmark/create_bookmark.js @@ -95,7 +95,7 @@ const tweetId = "post-id"; // Replace with the ID of the Post you wish to bookma } //Makes api call - const postBookmark = await client.users.createBookmark(userId, { tweet_id: tweetId }); + const postBookmark = await client.users.createBookmark(userId, { tweetId }); console.dir(postBookmark, { depth: null, }); diff --git a/javascript/users/get_users_by_usernames.js b/javascript/users/get_users_by_usernames.js index 75e486a..1381aa7 100644 --- a/javascript/users/get_users_by_usernames.js +++ b/javascript/users/get_users_by_usernames.js @@ -19,7 +19,7 @@ const usernames = ['XDevelopers', 'X']; // Usernames to look up (up to 100) const response = await client.users.getByUsernames(usernames, { userFields: ['created_at', 'description', 'public_metrics'], - expansions: ['pinned_tweet_id'] + expansions: ['pinned_post_id'] }); console.dir(response, { depth: null }); diff --git a/javascript/users/get_users_by_usernames_user_context.js b/javascript/users/get_users_by_usernames_user_context.js index 7e64b9f..0e3692e 100644 --- a/javascript/users/get_users_by_usernames_user_context.js +++ b/javascript/users/get_users_by_usernames_user_context.js @@ -93,7 +93,7 @@ const getQueryStringParams = (query) => { // Make the request using SDK const response = await client.users.getByUsernames(usernames, { userFields: ['created_at', 'description'], - expansions: ['pinned_tweet_id'] + expansions: ['pinned_post_id'] }); console.dir(response, { diff --git a/javascript/users/get_users_me.js b/javascript/users/get_users_me.js index 591e4ef..f80129f 100644 --- a/javascript/users/get_users_me.js +++ b/javascript/users/get_users_me.js @@ -85,7 +85,7 @@ const getQueryStringParams = (query) => { // Make the request using SDK - get authenticated user const response = await client.users.getMe({ userFields: ['created_at', 'description'], - expansions: ['pinned_tweet_id'] + expansions: ['pinned_post_id'] }); console.dir(response, { diff --git a/javascript/users/like/like_post.js b/javascript/users/like/like_post.js index 594cf32..ab97356 100644 --- a/javascript/users/like/like_post.js +++ b/javascript/users/like/like_post.js @@ -91,7 +91,7 @@ const getQueryStringParams = (query) => { }); // Make the request using SDK - const response = await client.users.likePost(userId, {body: {tweet_id: postId}}); + const response = await client.users.likePost(userId, { tweetId: postId }); console.dir(response, { depth: null }); diff --git a/javascript/users/lists/follow_list.js b/javascript/users/lists/follow_list.js index dba9e36..5576abc 100644 --- a/javascript/users/lists/follow_list.js +++ b/javascript/users/lists/follow_list.js @@ -92,7 +92,7 @@ const getQueryStringParams = (query) => { }); // Make the request using SDK - const response = await client.users.followList(userId, {body: {list_id: listId}}); + const response = await client.users.followList(userId, { listId }); console.dir(response, { depth: null, }); diff --git a/javascript/users/lists/get_followed_lists.js b/javascript/users/lists/get_followed_lists.js index 57efeb3..c76f339 100644 --- a/javascript/users/lists/get_followed_lists.js +++ b/javascript/users/lists/get_followed_lists.js @@ -13,7 +13,7 @@ const id = "user-id"; // 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 + listFields: ['created_at', 'description', 'follower_count'], // 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 }); diff --git a/javascript/users/lists/get_list_memberships.js b/javascript/users/lists/get_list_memberships.js index 6ea2f7d..e06b0c7 100644 --- a/javascript/users/lists/get_list_memberships.js +++ b/javascript/users/lists/get_list_memberships.js @@ -13,7 +13,7 @@ const id = "user-id"; // 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 + listFields: ['created_at', 'description', 'follower_count'], // 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 }); diff --git a/javascript/users/lists/get_owned_lists.js b/javascript/users/lists/get_owned_lists.js index 465e238..9d4330f 100644 --- a/javascript/users/lists/get_owned_lists.js +++ b/javascript/users/lists/get_owned_lists.js @@ -13,7 +13,7 @@ const id = "user-id"; // 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 + listFields: ['created_at', 'description', 'follower_count'], // 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 }); diff --git a/javascript/users/lists/pin_list.js b/javascript/users/lists/pin_list.js index fb70c45..2276b4d 100644 --- a/javascript/users/lists/pin_list.js +++ b/javascript/users/lists/pin_list.js @@ -92,7 +92,7 @@ const getQueryStringParams = (query) => { }); // Make the request using SDK - const response = await client.users.pinList(userId, {list_id: listId}); + const response = await client.users.pinList(userId, { listId }); console.dir(response, { depth: null, }); diff --git a/javascript/users/mute/mute_user.js b/javascript/users/mute/mute_user.js index a0f0992..50f4002 100644 --- a/javascript/users/mute/mute_user.js +++ b/javascript/users/mute/mute_user.js @@ -93,7 +93,7 @@ const getQueryStringParams = (query) => { }); // Make the request using SDK - const response = await client.users.muteUser(userId, { body: { target_user_id: targetUserId } }); + const response = await client.users.muteUser(userId, { targetUserId }); console.dir(response, { depth: null }); diff --git a/javascript/users/repost/repost_post.js b/javascript/users/repost/repost_post.js index d740f62..dc696f5 100644 --- a/javascript/users/repost/repost_post.js +++ b/javascript/users/repost/repost_post.js @@ -91,7 +91,7 @@ const getQueryStringParams = (query) => { }); // Make the request using SDK - const response = await client.users.repostPost(userId, { body: { tweet_id: postId } }); + const response = await client.users.repostPost(userId, { tweetId: postId }); console.dir(response, { depth: null }); diff --git a/llms.txt b/llms.txt index a79dad4..8ee2cb0 100644 --- a/llms.txt +++ b/llms.txt @@ -4,12 +4,13 @@ ## Official XDK Packages Used -All four primary SDK sample suites use the official first-party **XDK** libraries generated from `https://api.x.com/2/openapi.json`: +All primary SDK sample suites use the official first-party **XDK** libraries generated from `https://api.x.com/2/openapi.json`: -| Language | Directory | Package | Install | Run | +| Language | Directory | Package | Install | Run / Typecheck | |---|---|---|---|---| | Python 3.10+ | `python/` (80 files) | `xdk` (PyPI) | `pip install xdk` | `python posts/search_recent.py` | -| JavaScript (Node 18+) | `javascript/` (84 files) | `@xdevplatform/xdk` (npm) | `cd javascript && npm install` | `node posts/search_recent.js` | +| TypeScript (Node 18+ ESM) | `typescript/` (84 files) | `@xdevplatform/xdk` (npm) | `cd typescript && npm install` | `npx tsx posts/search_recent.ts` / `npm run typecheck` | +| JavaScript (Node 18+ CJS) | `javascript/` (84 files) | `@xdevplatform/xdk` (npm) | `cd javascript && npm install` | `node posts/search_recent.js` | | Java 17+ | `java/` (80 files) | `com.x:xdk` (Maven Central) | `cd java && mvn compile` | `mvn compile exec:java -Dexec.mainClass="posts.SearchRecent"` | | C# / .NET 8+ | `csharp/` (80 files) | `XDevPlatform.Xdk` (NuGet) | `cd csharp && dotnet build` | `dotnet run -- posts/search_recent` | @@ -33,7 +34,8 @@ Every XDK language mirrors the same 11 top-level endpoint categories: Naming conventions per language: - **Python**: `snake_case.py` (e.g., `python/posts/search_recent.py`) -- **JavaScript**: `snake_case.js` (e.g., `javascript/posts/search_recent.js`) +- **TypeScript**: `snake_case.ts` ESM with strict `tsconfig.json` (e.g., `typescript/posts/search_recent.ts`) +- **JavaScript**: `snake_case.js` CommonJS (e.g., `javascript/posts/search_recent.js`) - **Java**: `PascalCase.java` with matching package declarations (e.g., `java/posts/SearchRecent.java`, `package posts;`) - **C#**: `PascalCase.cs` with `Samples.` namespaces and `SamplesRunner` CLI in `csharp/Program.cs` (e.g., `csharp/posts/SearchRecent.cs`) @@ -41,22 +43,23 @@ Naming conventions per language: ### 1. Client Initialization (Bearer Token) - **Python**: `from xdk import Client; client = Client(bearer_token=os.environ["BEARER_TOKEN"])` +- **TypeScript**: `import { Client } from '@xdevplatform/xdk'; const client = new Client({ bearerToken: process.env.BEARER_TOKEN });` - **JavaScript**: `const { Client } = require('@xdevplatform/xdk'); const client = new Client({ bearerToken: process.env.BEARER_TOKEN });` - **Java**: `XClient client = new XClient(XClientConfig.builder().bearerToken(bearerToken).build());` - **C#**: `using var client = new XClient(new XClientOptions { BearerToken = bearerToken });` ### 2. Cursor Pagination - **Python**: `for page in client.posts.search_recent(query="...", max_results=100): ...` -- **JavaScript**: `const paginator = new PostPaginator(async (token) => client.posts.searchRecent(query, { maxResults: 100, nextToken: token })); for await (const post of paginator) { ... }` +- **TypeScript / JavaScript**: `const paginator = new PostPaginator(async (token?: string) => client.posts.searchRecent(query, { maxResults: 100, nextToken: token })); for await (const post of paginator) { ... }` - **Java**: `for (var page : client.posts().searchRecentPages(query, options)) { ... }` - **C#**: `await foreach (var page in client.Posts.SearchRecentPages(query, options)) { ... }` ### 3. Real-Time Streaming - **Python**: `for event in client.stream.posts(tweet_fields=["id", "text"]): ...` -- **JavaScript**: `const stream = await client.stream.posts({ tweetFields: ['id', 'text'] }); stream.on('data', console.log);` +- **TypeScript / JavaScript**: `const stream = await client.stream.posts({ tweetFields: ['id', 'text'] }); stream.on('data', console.log);` - **Java**: `try (var stream = client.stream().posts(options)) { for (var event : stream) { ... } }` - **C#**: `await using var stream = client.Stream.PostsStream(options); await foreach (var event in stream) { ... }` ## Machine-Readable Index -See `api-index.json` at the repository root for an exact JSON mapping from every sample slug, HTTP method, and `/2/*` endpoint path to the corresponding files across `python`, `javascript`, `java`, `csharp`, `ruby`, and `r`. +See `api-index.json` at the repository root for an exact JSON mapping from every sample slug, HTTP method, and `/2/*` endpoint path to the corresponding files across `python`, `typescript`, `javascript`, `java`, `csharp`, `ruby`, and `r`. diff --git a/python/activity/stream_events.py b/python/activity/stream_events.py index 10ae6c9..6629eeb 100644 --- a/python/activity/stream_events.py +++ b/python/activity/stream_events.py @@ -25,9 +25,9 @@ def main(): print("Connecting to activity stream... (press Ctrl+C to stop)") - # The stream() method returns a generator that yields events as they arrive. + # The activity() stream method returns a generator that yields events as they arrive. # The SDK manages reconnection with exponential backoff automatically. - for event in client.activity.stream(): + for event in client.stream.activity(): # Access data attribute (model uses extra='allow' so data should be available) # Use getattr with fallback in case data field is missing from response event_data = getattr(event, 'data', None) diff --git a/python/compliance/create_jobs.py b/python/compliance/create_jobs.py index f91daaa..5f215bd 100644 --- a/python/compliance/create_jobs.py +++ b/python/compliance/create_jobs.py @@ -20,7 +20,7 @@ payload = {"type": "tweets", "name": "my_batch_compliance_job"} def main(): - response = client.compliance.create_job(body=payload) + response = client.compliance.create_jobs(body=payload) print(json.dumps(response.data, indent=4, sort_keys=True)) diff --git a/python/compliance/get_jobs_by_id.py b/python/compliance/get_jobs_by_id.py index 5a139d6..6eb42bc 100644 --- a/python/compliance/get_jobs_by_id.py +++ b/python/compliance/get_jobs_by_id.py @@ -19,7 +19,7 @@ job_id = '' def main(): - response = client.compliance.get_job(job_id) + response = client.compliance.get_jobs_by_id(job_id) print(json.dumps(response.data, indent=4, sort_keys=True)) diff --git a/python/lists/delete_list.py b/python/lists/delete_list.py index 927b67c..eb5c0ba 100644 --- a/python/lists/delete_list.py +++ b/python/lists/delete_list.py @@ -55,7 +55,7 @@ def main(): client = Client(access_token=access_token) # Step 6: Delete the list - response = client.lists.delete_list(list_id) + response = client.lists.delete(list_id) print("Response code: 200") print(json.dumps(response.data, indent=4, sort_keys=True)) diff --git a/python/lists/remove_member.py b/python/lists/remove_member.py index 5e80701..ede3102 100644 --- a/python/lists/remove_member.py +++ b/python/lists/remove_member.py @@ -58,7 +58,7 @@ def main(): client = Client(access_token=access_token) # Step 6: Remove member from list - response = client.lists.remove_member(list_id, user_id) + response = client.lists.remove_member_by_user_id(list_id, user_id) print("Response code: 200") print(json.dumps(response.data, indent=4, sort_keys=True)) diff --git a/python/media/upload.py b/python/media/upload.py index f3139bd..35171d4 100644 --- a/python/media/upload.py +++ b/python/media/upload.py @@ -1,7 +1,7 @@ """ Media Upload - X API v2 ======================= -Endpoint: POST https://upload.x.com/1.1/media/upload.json +Endpoint: POST https://api.x.com/2/media/upload Docs: https://developer.x.com/en/docs/twitter-api/media/upload-media/api-reference Authentication: OAuth 2.0 (User Context) @@ -27,7 +27,7 @@ redirect_uri = "https://example.com" # Set the scopes -scopes = ["tweet.read", "tweet.write", "users.read", "offline.access"] +scopes = ["media.write", "tweet.read", "tweet.write", "users.read", "offline.access"] # Path to the media file you want to upload media_path = "path/to/your/image.jpg" @@ -60,13 +60,13 @@ def main(): with open(media_path, "rb") as media_file: media_data = base64.b64encode(media_file.read()).decode("utf-8") - payload = {"media_data": media_data} - response = client.media.upload_media(body=payload) + payload = {"media": media_data, "media_category": "tweet_image"} + response = client.media.upload(body=payload) print("Response code: 200") - # Get the media_id to use when creating a post - media_id = response.data["media_id_string"] + # Get the media id to use when creating a post + media_id = response.data["id"] print("Media ID: {}".format(media_id)) print(json.dumps(response.data, indent=4, sort_keys=True)) diff --git a/typescript/README.md b/typescript/README.md new file mode 100644 index 0000000..c073239 --- /dev/null +++ b/typescript/README.md @@ -0,0 +1,133 @@ +# TypeScript Samples for X API v2 (`@xdevplatform/xdk`) + +Official TypeScript (Node.js 18+ ESM) sample code for the X API v2 powered by [**XDK for TypeScript** (`@xdevplatform/xdk`)](https://github.com/xdevplatform/xdk-typescript). + +All 84 samples are strictly type-checked (`tsc --noEmit` with `"strict": true`). + +## Setup + +### 1. Prerequisites + +- **Node.js 18+** (`node --version`) +- An [X Developer Account](https://console.x.com) with API credentials + +### 2. Install Dependencies + +```bash +cd typescript +npm install +``` + +### 3. Set Environment Variables + +**For App-only read operations (search, lookup, streams, webhooks, activity):** + +```bash +export BEARER_TOKEN="your_bearer_token" +``` + +**For User-context actions (create post, like, repost, bookmark, mute, follow, DMs, media upload):** + +```bash +export CLIENT_ID="your_oauth2_client_id" +export CLIENT_SECRET="your_oauth2_client_secret" # optional for public clients +export REDIRECT_URI="https://example.com" # must match your App settings +``` + +*(You can also set `ACCESS_TOKEN` directly if you already have a valid OAuth 2.0 user token.)* + +## Running & Type-Checking Samples + +```bash +cd typescript +npm install + +# Run any sample directly via tsx +npx tsx posts/search_recent.ts + +# Strictly type-check all 84 samples +npm run typecheck +``` + +## Examples by Category (84 Samples) + +### Activity (5) +- `activity/create_subscription.ts` - Subscribe to real-time X Activity events +- `activity/delete_subscription.ts` - Delete an Activity subscription +- `activity/list_subscriptions.ts` - List active Activity subscriptions +- `activity/stream_events.ts` - Stream real-time Activity events +- `activity/update_subscription.ts` - Update an Activity subscription tag / webhook + +### Compliance (5) +- `compliance/create_jobs.ts` - Create a batch compliance job +- `compliance/download_results.ts` - Download compliance results +- `compliance/get_jobs.ts` - List compliance jobs +- `compliance/get_jobs_by_id.ts` - Get compliance job status by ID +- `compliance/upload_ids.ts` - Upload Post/User IDs to a compliance job + +### Direct Messages (6) +- `direct_messages/get_events_by_conversation.ts` - Fetch DM events in a conversation +- `direct_messages/get_one_to_one_conversation_events.ts` - Fetch 1-to-1 DM events with a participant +- `direct_messages/get_user_conversation_events.ts` - Fetch recent DM events across conversations +- `direct_messages/post_dm_to_conversation.ts` - Send a message to an existing conversation +- `direct_messages/post_group_conversation_dm.ts` - Create a new group DM conversation +- `direct_messages/post_one_to_one_dm.ts` - Send a 1-to-1 Direct Message + +### Lists (9) +- `lists/add_member.ts` - Add a member to a List +- `lists/create_list.ts` - Create a new List +- `lists/delete_list.ts` - Delete a List +- `lists/get_list_by_id.ts` - Look up a List by ID +- `lists/get_list_followers.ts` - Get List followers +- `lists/get_list_members.ts` - Get List members +- `lists/get_list_posts.ts` - Get Posts from a List +- `lists/remove_member.ts` - Remove a member from a List +- `lists/update_list.ts` - Update a List + +### Media (2) +- `media/upload.ts` - Single-payload image upload (`POST /2/media/upload`) +- `media/media_upload_v2.ts` - Chunked video upload (`initialize` -> `append` -> `finalize` -> `STATUS` -> `posts.create`) + +### Posts (13) +- `posts/create_post.ts` - Create a Post +- `posts/delete_post.ts` - Delete a Post +- `posts/get_liking_users.ts` - Get users who liked a Post +- `posts/get_post_by_id.ts` - Look up a single Post by ID +- `posts/get_post_counts_all.ts` - Full-archive Post counts +- `posts/get_post_counts_recent.ts` - Recent Post counts (last 7 days) +- `posts/get_posts_by_ids.ts` - Look up multiple Posts by IDs (Bearer Token) +- `posts/get_posts_by_ids_user_context.ts` - Look up multiple Posts by IDs (OAuth 2.0 User Context) +- `posts/get_quoted_posts.ts` - Get Quote Posts for a Post +- `posts/get_reposted_by.ts` - Get users who reposted a Post +- `posts/hide_reply.ts` - Hide or unhide a reply +- `posts/search_all.ts` - Full-archive search +- `posts/search_recent.ts` - Recent search (last 7 days) + +### Spaces (2) +- `spaces/get_spaces_by_ids.ts` - Look up Spaces by IDs +- `spaces/search_spaces.ts` - Search live/scheduled Spaces + +### Streams (2) +- `streams/stream_posts_filtered.ts` - Filtered stream with rule management +- `streams/stream_posts_sample.ts` - 1% sampled volume stream + +### Usage (1) +- `usage/get_usage.ts` - Daily API Post usage metrics + +### Users (34) +- `users/get_users_by_usernames.ts`, `users/get_users_by_usernames_user_context.ts`, `users/get_users_me.ts` +- `users/block/get_blocking.ts` +- `users/bookmark/{create_bookmark,delete_bookmark,get_bookmarks}.ts` +- `users/follow/{follow_user,get_followers,get_followers_paginated,get_following,get_following_paginated,unfollow_user}.ts` +- `users/like/{get_liked_posts,like_post,unlike_post}.ts` +- `users/lists/{follow_list,get_followed_lists,get_list_memberships,get_owned_lists,get_pinned_lists,pin_list,unfollow_list,unpin_list}.ts` +- `users/mute/{get_muting,mute_user,unmute_user}.ts` +- `users/repost/{get_reposts_of_me,repost_post,unrepost_post}.ts` +- `users/timeline/{get_home_timeline,get_mentions,get_posts,get_posts_paginated}.ts` + +### Webhooks (5) +- `webhooks/register_webhook.ts` - Register a webhook URL +- `webhooks/list_webhooks.ts` - List registered webhooks +- `webhooks/validate_webhook.ts` - Trigger a CRC validation check +- `webhooks/delete_webhook.ts` - Delete a webhook +- `webhooks/webhook_server.ts` - Minimal Node.js HTTP server handling CRC (`HMAC-SHA256`) and POST deliveries diff --git a/typescript/activity/create_subscription.ts b/typescript/activity/create_subscription.ts new file mode 100644 index 0000000..9c1d23a --- /dev/null +++ b/typescript/activity/create_subscription.ts @@ -0,0 +1,29 @@ +/** + * Create Activity Subscription - X API v2 + * + * Endpoint: POST https://api.x.com/2/activity/subscriptions + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +import { Client } from '@xdevplatform/xdk'; + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const userId = '2244994945'; + const eventType = 'profile.update.bio'; + + const response = await client.activity.createSubscription({ + eventType, + filter: { userId }, + tag: `${eventType} for user ${userId}`, + }); + + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/activity/delete_subscription.ts b/typescript/activity/delete_subscription.ts new file mode 100644 index 0000000..215f85c --- /dev/null +++ b/typescript/activity/delete_subscription.ts @@ -0,0 +1,22 @@ +/** + * Delete Activity Subscription - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/activity/subscriptions/:id + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +import { Client } from '@xdevplatform/xdk'; + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const subscriptionId = 'your-subscription-id'; + const response = await client.activity.deleteSubscription(subscriptionId); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/activity/list_subscriptions.ts b/typescript/activity/list_subscriptions.ts new file mode 100644 index 0000000..803e55d --- /dev/null +++ b/typescript/activity/list_subscriptions.ts @@ -0,0 +1,21 @@ +/** + * List Activity Subscriptions - X API v2 + * + * Endpoint: GET https://api.x.com/2/activity/subscriptions + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +import { Client } from '@xdevplatform/xdk'; + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const response = await client.activity.getSubscriptions(); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/activity/stream_events.ts b/typescript/activity/stream_events.ts new file mode 100644 index 0000000..5fa9f1e --- /dev/null +++ b/typescript/activity/stream_events.ts @@ -0,0 +1,33 @@ +/** + * Activity Stream - X API v2 + * + * Endpoint: GET https://api.x.com/2/activity/stream + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +import { Client } from '@xdevplatform/xdk'; + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + console.log('Connecting to activity stream... (press Ctrl+C to stop)'); + const stream = await client.stream.activity(); + + stream.on('data', (event: unknown) => { + console.dir(event, { depth: null }); + }); + + stream.on('error', (err: any) => { + console.error('Stream error:', err); + }); + + stream.on('close', () => { + console.log('Activity stream closed'); + }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/activity/update_subscription.ts b/typescript/activity/update_subscription.ts new file mode 100644 index 0000000..65f3299 --- /dev/null +++ b/typescript/activity/update_subscription.ts @@ -0,0 +1,24 @@ +/** + * Update Activity Subscription - X API v2 + * + * Endpoint: PUT https://api.x.com/2/activity/subscriptions/:id + * Docs: https://docs.x.com/x-api/activity/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +import { Client } from '@xdevplatform/xdk'; + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const subscriptionId = 'your-subscription-id'; + const response = await client.activity.updateSubscription(subscriptionId, { + tag: 'updated-activity-tag', + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/compliance/create_jobs.ts b/typescript/compliance/create_jobs.ts new file mode 100644 index 0000000..42a4a7e --- /dev/null +++ b/typescript/compliance/create_jobs.ts @@ -0,0 +1,30 @@ +import { Client } from '@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' as const, + 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(); +})(); diff --git a/typescript/compliance/download_results.ts b/typescript/compliance/download_results.ts new file mode 100644 index 0000000..3630b17 --- /dev/null +++ b/typescript/compliance/download_results.ts @@ -0,0 +1,32 @@ +// Replace with your job download_url +const 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(); +})(); \ No newline at end of file diff --git a/typescript/compliance/get_jobs.ts b/typescript/compliance/get_jobs.ts new file mode 100644 index 0000000..60487bf --- /dev/null +++ b/typescript/compliance/get_jobs.ts @@ -0,0 +1,26 @@ +import { Client } from '@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 "tweets" with "users" +const jobType: 'tweets' | 'users' = 'tweets'; + +(async () => { + try { + // Make request + const response = await client.compliance.getJobs(jobType); + + console.dir(response, { + depth: null + }); + + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/compliance/get_jobs_by_id.ts b/typescript/compliance/get_jobs_by_id.ts new file mode 100644 index 0000000..156f2de --- /dev/null +++ b/typescript/compliance/get_jobs_by_id.ts @@ -0,0 +1,26 @@ +import { Client } from '@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(); +})(); diff --git a/typescript/compliance/upload_ids.ts b/typescript/compliance/upload_ids.ts new file mode 100644 index 0000000..1b01c96 --- /dev/null +++ b/typescript/compliance/upload_ids.ts @@ -0,0 +1,45 @@ +import * as fs from 'node: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: Buffer[] = []; + readStream.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))); + readStream.on('end', () => resolve(Buffer.concat(chunks))); + readStream.on('error', reject); + }); + + const res = await fetch(uploadUrl, { + method: 'PUT', + body: new Uint8Array(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(); +})(); diff --git a/typescript/direct_messages/get_events_by_conversation.ts b/typescript/direct_messages/get_events_by_conversation.ts new file mode 100644 index 0000000..c5041bc --- /dev/null +++ b/typescript/direct_messages/get_events_by_conversation.ts @@ -0,0 +1,96 @@ +/** + * Get Events by Conversation ID - X API v2 + * + * Endpoint: GET https://api.x.com/2/dm_conversations/:dm_conversation_id/dm_events + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-conversations-dm_conversation_id-dm_events + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +import * as readline from 'node:readline'; +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, +} from '@xdevplatform/xdk'; + +function promptLine(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput: string): string { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes: string[]): Promise { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['dm.read', 'tweet.read', 'users.read', 'offline.access']); + const dmConversationId = '1512210732774948865'; + + const paginator = new EventPaginator(async (token?: string) => { + const res = await client.directMessages.getEventsByConversationId(dmConversationId, { + maxResults: 100, + paginationToken: token, + }); + return { + data: res.data ?? [], + meta: res.meta, + includes: res.includes, + errors: res.errors, + }; + }); + + for await (const event of paginator) { + console.dir(event, { depth: null }); + } +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/direct_messages/get_one_to_one_conversation_events.ts b/typescript/direct_messages/get_one_to_one_conversation_events.ts new file mode 100644 index 0000000..d92ed88 --- /dev/null +++ b/typescript/direct_messages/get_one_to_one_conversation_events.ts @@ -0,0 +1,96 @@ +/** + * Get One-to-One Conversation Events - X API v2 + * + * Endpoint: GET https://api.x.com/2/dm_conversations/with/:participant_id/dm_events + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-conversations-with-participant_id-dm_events + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +import * as readline from 'node:readline'; +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, +} from '@xdevplatform/xdk'; + +function promptLine(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput: string): string { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes: string[]): Promise { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['dm.read', 'tweet.read', 'users.read', 'offline.access']); + const participantId = '1716450569358098432'; + + const paginator = new EventPaginator(async (token?: string) => { + const res = await client.directMessages.getEventsByParticipantId(participantId, { + maxResults: 100, + paginationToken: token, + }); + return { + data: res.data ?? [], + meta: res.meta, + includes: res.includes, + errors: res.errors, + }; + }); + + for await (const event of paginator) { + console.dir(event, { depth: null }); + } +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/direct_messages/get_user_conversation_events.ts b/typescript/direct_messages/get_user_conversation_events.ts new file mode 100644 index 0000000..8bceb1f --- /dev/null +++ b/typescript/direct_messages/get_user_conversation_events.ts @@ -0,0 +1,97 @@ +/** + * Get User Conversation Events - X API v2 + * + * Endpoint: GET https://api.x.com/2/dm_events + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-events + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +import * as readline from 'node:readline'; +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + EventPaginator, +} from '@xdevplatform/xdk'; + +function promptLine(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput: string): string { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes: string[]): Promise { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['dm.read', 'tweet.read', 'users.read', 'offline.access']); + + const paginator = new EventPaginator(async (token?: string) => { + const res = await client.directMessages.getEvents({ + maxResults: 100, + paginationToken: token, + dmEventFields: ['id', 'text', 'event_type', 'created_at', 'dm_conversation_id'], + expansions: ['sender_id'], + }); + return { + data: res.data ?? [], + meta: res.meta, + includes: res.includes, + errors: res.errors, + }; + }); + + for await (const event of paginator) { + console.dir(event, { depth: null }); + } +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/direct_messages/post_dm_to_conversation.ts b/typescript/direct_messages/post_dm_to_conversation.ts new file mode 100644 index 0000000..7001479 --- /dev/null +++ b/typescript/direct_messages/post_dm_to_conversation.ts @@ -0,0 +1,83 @@ +/** + * Post DM to Conversation - X API v2 + * + * Endpoint: POST https://api.x.com/2/dm_conversations/:dm_conversation_id/messages + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations-dm_conversation_id-messages + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +import * as readline from 'node:readline'; +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, +} from '@xdevplatform/xdk'; + +function promptLine(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput: string): string { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes: string[]): Promise { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['dm.read', 'dm.write', 'tweet.read', 'users.read', 'offline.access']); + const dmConversationId = '1856843062712176900'; + + const response = await client.directMessages.createByConversationId(dmConversationId, { + text: 'Hi, I am adding a message to an existing conversation using @xdevplatform/xdk.', + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/direct_messages/post_group_conversation_dm.ts b/typescript/direct_messages/post_group_conversation_dm.ts new file mode 100644 index 0000000..4800d56 --- /dev/null +++ b/typescript/direct_messages/post_group_conversation_dm.ts @@ -0,0 +1,86 @@ +/** + * Post Group Conversation Direct Message - X API v2 + * + * Endpoint: POST https://api.x.com/2/dm_conversations + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +import * as readline from 'node:readline'; +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, +} from '@xdevplatform/xdk'; + +function promptLine(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput: string): string { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes: string[]): Promise { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['dm.read', 'dm.write', 'tweet.read', 'users.read', 'offline.access']); + + const response = await client.directMessages.createConversation({ + conversationType: 'Group', + participantIds: ['2244994945', '1716450569358098432'], + message: { + text: 'Hi, creating a new group conversation via @xdevplatform/xdk.', + }, + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/direct_messages/post_one_to_one_dm.ts b/typescript/direct_messages/post_one_to_one_dm.ts new file mode 100644 index 0000000..0cf1a56 --- /dev/null +++ b/typescript/direct_messages/post_one_to_one_dm.ts @@ -0,0 +1,83 @@ +/** + * Post One-to-One Direct Message - X API v2 + * + * Endpoint: POST https://api.x.com/2/dm_conversations/with/:participant_id/messages + * Docs: https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations-with-participant_id-messages + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +import * as readline from 'node:readline'; +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, +} from '@xdevplatform/xdk'; + +function promptLine(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput: string): string { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes: string[]): Promise { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['dm.read', 'dm.write', 'tweet.read', 'users.read', 'offline.access']); + const participantId = '1716450569358098432'; + + const response = await client.directMessages.createByParticipantId(participantId, { + text: 'Hi, DMing you using the v2 one-to-one endpoint via @xdevplatform/xdk.', + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/lists/add_member.ts b/typescript/lists/add_member.ts new file mode 100644 index 0000000..6232f04 --- /dev/null +++ b/typescript/lists/add_member.ts @@ -0,0 +1,98 @@ +// 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 +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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, { userId }); + console.dir(response, { + depth: null, + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/lists/create_list.ts b/typescript/lists/create_list.ts new file mode 100644 index 0000000..50effa9 --- /dev/null +++ b/typescript/lists/create_list.ts @@ -0,0 +1,99 @@ +// 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 +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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(data); + console.dir(response, { + depth: null, + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/lists/delete_list.ts b/typescript/lists/delete_list.ts new file mode 100644 index 0000000..ecf7ac6 --- /dev/null +++ b/typescript/lists/delete_list.ts @@ -0,0 +1,94 @@ +// 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 +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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(); +})(); diff --git a/typescript/lists/get_list_by_id.ts b/typescript/lists/get_list_by_id.ts new file mode 100644 index 0000000..73dde02 --- /dev/null +++ b/typescript/lists/get_list_by_id.ts @@ -0,0 +1,32 @@ +/** + * 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 + */ + +import { Client } from '@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', 'description'], + expansions: ['owner_id'] + }); + + console.dir(response, { depth: null }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/lists/get_list_followers.ts b/typescript/lists/get_list_followers.ts new file mode 100644 index 0000000..d571420 --- /dev/null +++ b/typescript/lists/get_list_followers.ts @@ -0,0 +1,29 @@ +import { Client } from '@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: ['created_at', 'description'], // Edit optional query parameters here + expansions: ['pinned_post_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(); +})(); diff --git a/typescript/lists/get_list_members.ts b/typescript/lists/get_list_members.ts new file mode 100644 index 0000000..54ccc03 --- /dev/null +++ b/typescript/lists/get_list_members.ts @@ -0,0 +1,29 @@ +import { Client } from '@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: ['created_at', 'description'], // Edit optional query parameters here + expansions: ['pinned_post_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(); +})(); diff --git a/typescript/lists/get_list_posts.ts b/typescript/lists/get_list_posts.ts new file mode 100644 index 0000000..95439a7 --- /dev/null +++ b/typescript/lists/get_list_posts.ts @@ -0,0 +1,30 @@ +import { Client } from '@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(); +})(); + diff --git a/typescript/lists/remove_member.ts b/typescript/lists/remove_member.ts new file mode 100644 index 0000000..4aa1894 --- /dev/null +++ b/typescript/lists/remove_member.ts @@ -0,0 +1,98 @@ +// 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 +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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(); +})(); diff --git a/typescript/lists/update_list.ts b/typescript/lists/update_list.ts new file mode 100644 index 0000000..d8acc87 --- /dev/null +++ b/typescript/lists/update_list.ts @@ -0,0 +1,102 @@ +// 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 +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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, data); + console.dir(response, { + depth: null, + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/media/media_upload_v2.ts b/typescript/media/media_upload_v2.ts new file mode 100644 index 0000000..c67cbfc --- /dev/null +++ b/typescript/media/media_upload_v2.ts @@ -0,0 +1,121 @@ +/** + * Media Upload v2 (Chunked Video Upload) - X API v2 + * + * Endpoint: POST https://api.x.com/2/media/upload/initialize | append | finalize + * Docs: https://developer.x.com/en/docs/twitter-api/media/upload-media/api-reference + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +import * as fs from 'node:fs'; +import * as readline from 'node:readline'; +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, +} from '@xdevplatform/xdk'; + +function promptLine(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput: string): string { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes: string[]): Promise { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['media.write', 'users.read', 'tweet.read', 'tweet.write', 'offline.access']); + const videoPath = process.env.VIDEO_FILE || 'path/to/your/video.mp4'; + const allBytes = fs.readFileSync(videoPath); + + // 1. Initialize chunked upload + const initRes = await client.media.initializeUpload({ + mediaType: 'video/mp4', + mediaCategory: 'tweet_video', + totalBytes: allBytes.length, + }); + const mediaId = initRes.data?.id; + if (!mediaId) { + throw new Error('Media upload initialization did not return a media ID'); + } + console.log('Initialized upload for mediaId:', mediaId); + + // 2. Append 4 MiB chunks + const chunkSize = 4 * 1024 * 1024; + let segmentIndex = 0; + for (let offset = 0; offset < allBytes.length; offset += chunkSize) { + const chunk = allBytes.subarray(offset, Math.min(offset + chunkSize, allBytes.length)); + await client.media.appendUpload(mediaId, { + segmentIndex: segmentIndex++, + media: chunk.toString('base64'), + }); + console.log(`Uploaded ${Math.min(offset + chunkSize, allBytes.length)} / ${allBytes.length} bytes`); + } + + // 3. Finalize & poll processing status + const finRes = await client.media.finalizeUpload(mediaId); + let proc: any = finRes.data?.processingInfo; + while (proc && proc.state && proc.state !== 'succeeded' && proc.state !== 'failed') { + const waitSecs: number = proc.checkAfterSecs ?? proc.check_after_secs ?? 2; + await new Promise((r) => setTimeout(r, waitSecs * 1000)); + const statusRes = await client.media.getUploadStatus(mediaId, { command: 'STATUS' }); + proc = statusRes.data?.processingInfo; + } + + // 4. Create post with attached video + const postRes = await client.posts.create({ + text: 'Uploaded a video using @xdevplatform/xdk!', + media: { mediaIds: [mediaId] }, + }); + console.dir(postRes, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/media/upload.ts b/typescript/media/upload.ts new file mode 100644 index 0000000..863f0ec --- /dev/null +++ b/typescript/media/upload.ts @@ -0,0 +1,87 @@ +/** + * Media Upload (Single Payload) - X API v2 + * + * Endpoint: POST https://api.x.com/2/media/upload + * Docs: https://developer.x.com/en/docs/twitter-api/media/upload-media/api-reference + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +import * as fs from 'node:fs'; +import * as readline from 'node:readline'; +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, +} from '@xdevplatform/xdk'; + +function promptLine(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput: string): string { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes: string[]): Promise { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['media.write', 'tweet.read', 'tweet.write', 'users.read', 'offline.access']); + const mediaPath = process.env.MEDIA_FILE || 'path/to/your/image.jpg'; + const base64Media = fs.readFileSync(mediaPath).toString('base64'); + + const response = await client.media.upload({ + media: base64Media, + mediaCategory: 'tweet_image', + }); + console.log('Media ID:', response.data?.id); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/package.json b/typescript/package.json new file mode 100644 index 0000000..aa5581a --- /dev/null +++ b/typescript/package.json @@ -0,0 +1,21 @@ +{ + "name": "x-api-v2-typescript-samples", + "version": "1.0.0", + "private": true, + "type": "module", + "description": "Official TypeScript sample code for the X API v2 powered by @xdevplatform/xdk", + "engines": { + "node": ">=18.0.0" + }, + "scripts": { + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@xdevplatform/xdk": "^0.7.0" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "tsx": "^4.19.0", + "typescript": "^5.7.0" + } +} diff --git a/typescript/posts/create_post.ts b/typescript/posts/create_post.ts new file mode 100644 index 0000000..b769911 --- /dev/null +++ b/typescript/posts/create_post.ts @@ -0,0 +1,99 @@ +/** + * 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 + */ + +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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(); +})(); diff --git a/typescript/posts/delete_post.ts b/typescript/posts/delete_post.ts new file mode 100644 index 0000000..ba8868a --- /dev/null +++ b/typescript/posts/delete_post.ts @@ -0,0 +1,96 @@ +/** + * 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 + */ + +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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(); +})(); diff --git a/typescript/posts/get_liking_users.ts b/typescript/posts/get_liking_users.ts new file mode 100644 index 0000000..0f6ca04 --- /dev/null +++ b/typescript/posts/get_liking_users.ts @@ -0,0 +1,100 @@ +// 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 +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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(); +})(); diff --git a/typescript/posts/get_post_by_id.ts b/typescript/posts/get_post_by_id.ts new file mode 100644 index 0000000..42c66cc --- /dev/null +++ b/typescript/posts/get_post_by_id.ts @@ -0,0 +1,24 @@ +/** + * Single Post Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/tweets/:id + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets-id + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +import { Client } from '@xdevplatform/xdk'; + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const postId = 'post-id'; + const response = await client.posts.getById(postId, { + tweetFields: ['created_at', 'author_id', 'lang', 'source', 'public_metrics', 'entities'], + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/posts/get_post_counts_all.ts b/typescript/posts/get_post_counts_all.ts new file mode 100644 index 0000000..d0f6e2f --- /dev/null +++ b/typescript/posts/get_post_counts_all.ts @@ -0,0 +1,30 @@ +// Search for public posts across the whole Twitter archive +// https://developer.twitter.com/en/docs/twitter-api/tweets/search/quick-start/full-archive-search + +import { Client } from '@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(); +})(); \ No newline at end of file diff --git a/typescript/posts/get_post_counts_recent.ts b/typescript/posts/get_post_counts_recent.ts new file mode 100644 index 0000000..a88201c --- /dev/null +++ b/typescript/posts/get_post_counts_recent.ts @@ -0,0 +1,30 @@ +// Search for posts within the past seven days +// https://developer.twitter.com/en/docs/twitter-api/tweets/search/quick-start/recent-search + +import { Client } from '@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(); +})(); + diff --git a/typescript/posts/get_posts_by_ids.ts b/typescript/posts/get_posts_by_ids.ts new file mode 100644 index 0000000..9354ec5 --- /dev/null +++ b/typescript/posts/get_posts_by_ids.ts @@ -0,0 +1,37 @@ +/** + * 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 + */ + +import { Client } from '@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(); +})(); diff --git a/typescript/posts/get_posts_by_ids_user_context.ts b/typescript/posts/get_posts_by_ids_user_context.ts new file mode 100644 index 0000000..362e779 --- /dev/null +++ b/typescript/posts/get_posts_by_ids_user_context.ts @@ -0,0 +1,103 @@ +// Get Post objects by ID, using user authentication +// https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/quick-start + +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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(); +})(); + diff --git a/typescript/posts/get_quoted_posts.ts b/typescript/posts/get_quoted_posts.ts new file mode 100644 index 0000000..cec8773 --- /dev/null +++ b/typescript/posts/get_quoted_posts.ts @@ -0,0 +1,51 @@ +// Get Quote Posts by Post ID +// https://developer.twitter.com/en/docs/twitter-api/tweets/quote-tweets-lookup/quick-start + +import { Client, PostPaginator } from '@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?: string) => { + 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); +}); + diff --git a/typescript/posts/get_reposted_by.ts b/typescript/posts/get_reposted_by.ts new file mode 100644 index 0000000..c0c8796 --- /dev/null +++ b/typescript/posts/get_reposted_by.ts @@ -0,0 +1,54 @@ +// 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 + +import { Client, UserPaginator } from '@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?: string) => { + 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); +}); + diff --git a/typescript/posts/hide_reply.ts b/typescript/posts/hide_reply.ts new file mode 100644 index 0000000..f0cf3fc --- /dev/null +++ b/typescript/posts/hide_reply.ts @@ -0,0 +1,80 @@ +/** + * Hide Reply - X API v2 + * + * Endpoint: PUT https://api.x.com/2/tweets/:id/hidden + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/hide-replies/api-reference/put-tweets-id-hidden + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +import * as readline from 'node:readline'; +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, +} from '@xdevplatform/xdk'; + +function promptLine(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput: string): string { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes: string[]): Promise { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['tweet.read', 'tweet.write', 'users.read', 'offline.access']); + const replyPostId = 'reply-tweet-id-to-hide'; + const response = await client.posts.hideReply(replyPostId, { hidden: true }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/posts/search_all.ts b/typescript/posts/search_all.ts new file mode 100644 index 0000000..01afbee --- /dev/null +++ b/typescript/posts/search_all.ts @@ -0,0 +1,50 @@ +// Search for public posts across the whole Twitter archive +// https://developer.twitter.com/en/docs/twitter-api/tweets/search/quick-start/full-archive-search + +import { Client, PostPaginator } from '@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?: string) => { + 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); +}); diff --git a/typescript/posts/search_recent.ts b/typescript/posts/search_recent.ts new file mode 100644 index 0000000..de353e0 --- /dev/null +++ b/typescript/posts/search_recent.ts @@ -0,0 +1,58 @@ +/** + * 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. + */ + +import { Client, PostPaginator } from '@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?: string) => { + 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); +}); diff --git a/typescript/spaces/get_spaces_by_ids.ts b/typescript/spaces/get_spaces_by_ids.ts new file mode 100644 index 0000000..082b3cb --- /dev/null +++ b/typescript/spaces/get_spaces_by_ids.ts @@ -0,0 +1,32 @@ +/** + * 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 + */ + +import { Client } from '@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: ['created_at', 'participant_count', 'title', 'state'], + expansions: ['creator_id', 'host_ids'] + }); + + console.dir(response, { depth: null }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/spaces/search_spaces.ts b/typescript/spaces/search_spaces.ts new file mode 100644 index 0000000..e17affc --- /dev/null +++ b/typescript/spaces/search_spaces.ts @@ -0,0 +1,32 @@ +// Lookup Spaces by ID +// https://developer.twitter.com/en/docs/twitter-api/spaces/lookup + +import { Client } from '@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(); +})(); diff --git a/typescript/streams/stream_posts_filtered.ts b/typescript/streams/stream_posts_filtered.ts new file mode 100644 index 0000000..ca01df8 --- /dev/null +++ b/typescript/streams/stream_posts_filtered.ts @@ -0,0 +1,72 @@ +// Open a realtime stream of posts, filtered according to rules +// https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/quick-start + +import { Client } from '@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).filter((id): id is string => Boolean(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: unknown) => { + // event is the parsed JSON line (data/includes/matching_rules) + console.log('New data:', event); + }); + + stream.on('error', (e: any) => { + 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); + } +})(); diff --git a/typescript/streams/stream_posts_sample.ts b/typescript/streams/stream_posts_sample.ts new file mode 100644 index 0000000..375e0dc --- /dev/null +++ b/typescript/streams/stream_posts_sample.ts @@ -0,0 +1,47 @@ +// 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 + +import { Client } from '@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: unknown) => { + // event is the parsed JSON line (data/includes/matching_rules) + console.log('New data:', event); + }); + + stream.on('error', (e: any) => { + 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); + } +})(); diff --git a/typescript/tsconfig.json b/typescript/tsconfig.json new file mode 100644 index 0000000..aaa35a5 --- /dev/null +++ b/typescript/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2022"], + "types": ["node"], + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "esModuleInterop": true, + "isolatedModules": true, + "resolveJsonModule": true + }, + "include": ["**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/typescript/usage/get_usage.ts b/typescript/usage/get_usage.ts new file mode 100644 index 0000000..81688cc --- /dev/null +++ b/typescript/usage/get_usage.ts @@ -0,0 +1,27 @@ +// Get Posts Usage +// https://developer.twitter.com/en/docs/twitter-api/usage/tweets + +import { Client } from '@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(); +})(); + diff --git a/typescript/users/block/get_blocking.ts b/typescript/users/block/get_blocking.ts new file mode 100644 index 0000000..a03a718 --- /dev/null +++ b/typescript/users/block/get_blocking.ts @@ -0,0 +1,95 @@ +// Block a user, using user authentication +// https://developer.twitter.com/en/docs/twitter-api/users/blocks/quick-start +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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(); +})(); diff --git a/typescript/users/bookmark/create_bookmark.ts b/typescript/users/bookmark/create_bookmark.ts new file mode 100644 index 0000000..e24533b --- /dev/null +++ b/typescript/users/bookmark/create_bookmark.ts @@ -0,0 +1,101 @@ +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +//Helper function to parse callback +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +//Helper terminal input function +async function input(prompt: string): Promise { + 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: 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, { tweetId }); + console.dir(postBookmark, { + depth: null, + }); + process.exit(); + } catch (error) { + console.log(error); + process.exit(-1); + } +})(); diff --git a/typescript/users/bookmark/delete_bookmark.ts b/typescript/users/bookmark/delete_bookmark.ts new file mode 100644 index 0000000..ba31334 --- /dev/null +++ b/typescript/users/bookmark/delete_bookmark.ts @@ -0,0 +1,101 @@ +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +//Helper function to parse callback +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +//Helper terminal input function +async function input(prompt: string): Promise { + 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: 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); + } +})(); diff --git a/typescript/users/bookmark/get_bookmarks.ts b/typescript/users/bookmark/get_bookmarks.ts new file mode 100644 index 0000000..7712f3e --- /dev/null +++ b/typescript/users/bookmark/get_bookmarks.ts @@ -0,0 +1,105 @@ +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +//Helper function to parse callback +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +//Helper terminal input function +async function input(prompt: string): Promise { + 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: NonNullable[1]> = { + expansions: ['author_id'], + userFields: ['username', 'created_at'], + tweetFields: ['geo', 'entities', 'context_annotations'], +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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); + } +})(); diff --git a/typescript/users/follow/follow_user.ts b/typescript/users/follow/follow_user.ts new file mode 100644 index 0000000..c085f2c --- /dev/null +++ b/typescript/users/follow/follow_user.ts @@ -0,0 +1,86 @@ +/** + * Follow User - X API v2 + * + * Endpoint: POST https://api.x.com/2/users/:id/following + * Docs: https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/post-users-id-following + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +import * as readline from 'node:readline'; +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, +} from '@xdevplatform/xdk'; + +function promptLine(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput: string): string { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes: string[]): Promise { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['tweet.read', 'users.read', 'follows.write', 'offline.access']); + const me = await client.users.getMe(); + const myUserId = me.data?.id; + if (!myUserId) { + throw new Error('Could not resolve authenticated user ID'); + } + const targetUserId = 'user-id-to-follow'; + + const response = await client.users.followUser(myUserId, { targetUserId }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/users/follow/get_followers.ts b/typescript/users/follow/get_followers.ts new file mode 100644 index 0000000..621585c --- /dev/null +++ b/typescript/users/follow/get_followers.ts @@ -0,0 +1,44 @@ +// Fetch the followers of a user account, by ID +// https://developer.twitter.com/en/docs/twitter-api/users/follows/quick-start + +import { Client, UserPaginator } from '@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?: string) => { + 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); +}); diff --git a/typescript/users/follow/get_followers_paginated.ts b/typescript/users/follow/get_followers_paginated.ts new file mode 100644 index 0000000..688ee95 --- /dev/null +++ b/typescript/users/follow/get_followers_paginated.ts @@ -0,0 +1,56 @@ +/** + * 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 get_followers.ts + */ + +import { Client, UserPaginator } from '@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?: string) => { + 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); +}); + diff --git a/typescript/users/follow/get_following.ts b/typescript/users/follow/get_following.ts new file mode 100644 index 0000000..853337e --- /dev/null +++ b/typescript/users/follow/get_following.ts @@ -0,0 +1,25 @@ +/** + * User Following Lookup - 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) + * Required env vars: BEARER_TOKEN + */ + +import { Client } from '@xdevplatform/xdk'; + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const userId = '2244994945'; + const response = await client.users.getFollowing(userId, { + maxResults: 100, + userFields: ['created_at'], + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/users/follow/get_following_paginated.ts b/typescript/users/follow/get_following_paginated.ts new file mode 100644 index 0000000..7966af4 --- /dev/null +++ b/typescript/users/follow/get_following_paginated.ts @@ -0,0 +1,55 @@ +/** + * 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. + */ + +import { Client, UserPaginator } from '@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?: string) => { + 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); +}); + diff --git a/typescript/users/follow/unfollow_user.ts b/typescript/users/follow/unfollow_user.ts new file mode 100644 index 0000000..14b07fe --- /dev/null +++ b/typescript/users/follow/unfollow_user.ts @@ -0,0 +1,86 @@ +/** + * Unfollow User - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/users/:source_user_id/following/:target_user_id + * Docs: https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/delete-users-source_user_id-following + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +import * as readline from 'node:readline'; +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, +} from '@xdevplatform/xdk'; + +function promptLine(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput: string): string { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes: string[]): Promise { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['tweet.read', 'users.read', 'follows.write', 'offline.access']); + const me = await client.users.getMe(); + const myUserId = me.data?.id; + if (!myUserId) { + throw new Error('Could not resolve authenticated user ID'); + } + const targetUserId = 'user-id-to-unfollow'; + + const response = await client.users.unfollowUser(myUserId, targetUserId); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/users/get_users_by_usernames.ts b/typescript/users/get_users_by_usernames.ts new file mode 100644 index 0000000..83affc9 --- /dev/null +++ b/typescript/users/get_users_by_usernames.ts @@ -0,0 +1,31 @@ +/** + * 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 + */ + +import { Client } from '@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_post_id'] + }); + + console.dir(response, { depth: null }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/users/get_users_by_usernames_user_context.ts b/typescript/users/get_users_by_usernames_user_context.ts new file mode 100644 index 0000000..80e15b7 --- /dev/null +++ b/typescript/users/get_users_by_usernames_user_context.ts @@ -0,0 +1,102 @@ +// Get User objects by username, using user authentication +// https://developer.twitter.com/en/docs/twitter-api/users/lookup/quick-start + +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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_post_id'] + }); + + console.dir(response, { + depth: null + }); + + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/users/get_users_me.ts b/typescript/users/get_users_me.ts new file mode 100644 index 0000000..eba84e3 --- /dev/null +++ b/typescript/users/get_users_me.ts @@ -0,0 +1,94 @@ +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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_post_id'] + }); + + console.dir(response, { + depth: null + }); + + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/users/like/get_liked_posts.ts b/typescript/users/like/get_liked_posts.ts new file mode 100644 index 0000000..d44cd5f --- /dev/null +++ b/typescript/users/like/get_liked_posts.ts @@ -0,0 +1,124 @@ +// 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 + +import { + Client, + OAuth2, + PostPaginator, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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?: string) => { + 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(); +})(); + diff --git a/typescript/users/like/like_post.ts b/typescript/users/like/like_post.ts new file mode 100644 index 0000000..0dc2cf4 --- /dev/null +++ b/typescript/users/like/like_post.ts @@ -0,0 +1,98 @@ +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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, { tweetId: postId }); + console.dir(response, { + depth: null + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); + diff --git a/typescript/users/like/unlike_post.ts b/typescript/users/like/unlike_post.ts new file mode 100644 index 0000000..40b850b --- /dev/null +++ b/typescript/users/like/unlike_post.ts @@ -0,0 +1,98 @@ +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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(); +})(); + diff --git a/typescript/users/lists/follow_list.ts b/typescript/users/lists/follow_list.ts new file mode 100644 index 0000000..7852e07 --- /dev/null +++ b/typescript/users/lists/follow_list.ts @@ -0,0 +1,98 @@ +// Follow a list using OAuth 2.0 to authorize the user +// https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/quick-start +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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, { listId }); + console.dir(response, { + depth: null, + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/users/lists/get_followed_lists.ts b/typescript/users/lists/get_followed_lists.ts new file mode 100644 index 0000000..a81b18b --- /dev/null +++ b/typescript/users/lists/get_followed_lists.ts @@ -0,0 +1,29 @@ +import { Client } from '@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: ['created_at', 'description', 'follower_count'], // 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(); +})(); diff --git a/typescript/users/lists/get_list_memberships.ts b/typescript/users/lists/get_list_memberships.ts new file mode 100644 index 0000000..8b4eadf --- /dev/null +++ b/typescript/users/lists/get_list_memberships.ts @@ -0,0 +1,29 @@ +import { Client } from '@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: ['created_at', 'description', 'follower_count'], // 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(); +})(); diff --git a/typescript/users/lists/get_owned_lists.ts b/typescript/users/lists/get_owned_lists.ts new file mode 100644 index 0000000..3c0d29b --- /dev/null +++ b/typescript/users/lists/get_owned_lists.ts @@ -0,0 +1,29 @@ +import { Client } from '@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: ['created_at', 'description', 'follower_count'], // 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(); +})(); diff --git a/typescript/users/lists/get_pinned_lists.ts b/typescript/users/lists/get_pinned_lists.ts new file mode 100644 index 0000000..adaef91 --- /dev/null +++ b/typescript/users/lists/get_pinned_lists.ts @@ -0,0 +1,83 @@ +/** + * Pinned Lists Lookup - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/pinned_lists + * Docs: https://developer.x.com/en/docs/twitter-api/lists/pinned-lists/api-reference/get-users-id-pinned_lists + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +import * as readline from 'node:readline'; +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, +} from '@xdevplatform/xdk'; + +function promptLine(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput: string): string { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes: string[]): Promise { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['tweet.read', 'users.read', 'list.read', 'offline.access']); + const userId = 'your-user-id'; + + const response = await client.users.getPinnedLists(userId, { + listFields: ['created_at', 'description', 'private'], + }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/users/lists/pin_list.ts b/typescript/users/lists/pin_list.ts new file mode 100644 index 0000000..b25160a --- /dev/null +++ b/typescript/users/lists/pin_list.ts @@ -0,0 +1,98 @@ +// Pin a list using OAuth 2.0 to authorize the user +// https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/quick-start +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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.pinList(userId, { listId }); + console.dir(response, { + depth: null, + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/users/lists/unfollow_list.ts b/typescript/users/lists/unfollow_list.ts new file mode 100644 index 0000000..3e7965f --- /dev/null +++ b/typescript/users/lists/unfollow_list.ts @@ -0,0 +1,98 @@ +// Unfollow a list using OAuth 2.0 to authorize the user +// https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/quick-start +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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 replace list-id-to-unfollow with the list id you wish to unfollow. +const listId = "list-id-to-unfollow"; + +async function input(prompt: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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.unfollowList(userId, listId); + console.dir(response, { + depth: null, + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/users/lists/unpin_list.ts b/typescript/users/lists/unpin_list.ts new file mode 100644 index 0000000..e96d347 --- /dev/null +++ b/typescript/users/lists/unpin_list.ts @@ -0,0 +1,98 @@ +// Unpin a list using OAuth 2.0 to authorize the user +// https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/quick-start +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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 replace list-id-to-unpin with the list id you wish to unpin. +const listId = "list-id-to-unpin"; + +async function input(prompt: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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.unpinList(userId, listId); + console.dir(response, { + depth: null, + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/users/mute/get_muting.ts b/typescript/users/mute/get_muting.ts new file mode 100644 index 0000000..56996cc --- /dev/null +++ b/typescript/users/mute/get_muting.ts @@ -0,0 +1,95 @@ +// Retrieve accounts muted by authenticated user +// https://developer.twitter.com/en/docs/twitter-api/users/mutes/quick-start +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: OAuth2Config = { + clientId: clientId, + clientSecret: clientSecret, + redirectUri: 'https://example.com', + scope: ['tweet.read', 'users.read', 'tweet.write', 'offline.access', 'mute.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.getMuting(userId); + console.dir(response, { + depth: null, + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/users/mute/mute_user.ts b/typescript/users/mute/mute_user.ts new file mode 100644 index 0000000..5fb29e5 --- /dev/null +++ b/typescript/users/mute/mute_user.ts @@ -0,0 +1,99 @@ +// mute a user, using user authentication +// https://developer.twitter.com/en/docs/twitter-api/users/mutes/quick-start +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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 id-to-mute with the user id you wish to mute. +// You can find a user ID by using the user lookup endpoint +const targetUserId = "id-to-mute"; + +async function input(prompt: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: OAuth2Config = { + clientId: clientId, + clientSecret: clientSecret, + redirectUri: 'https://example.com', + scope: ['tweet.read', 'users.read', 'tweet.write', 'offline.access', 'mute.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.muteUser(userId, { targetUserId }); + console.dir(response, { + depth: null + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/users/mute/unmute_user.ts b/typescript/users/mute/unmute_user.ts new file mode 100644 index 0000000..8ad1a70 --- /dev/null +++ b/typescript/users/mute/unmute_user.ts @@ -0,0 +1,98 @@ +// Unmute a user, using user authentication +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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 sourceUserId = "your-user-id"; + +// Be sure to add replace the id-to-unmute with the user id of the you wish to unmute. +// You can find a user ID by using the user lookup endpoint +const targetUserId = "id-to-unmute"; + +async function input(prompt: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: OAuth2Config = { + clientId: clientId, + clientSecret: clientSecret, + redirectUri: 'https://example.com', + scope: ['tweet.read', 'users.read', 'tweet.write', 'offline.access', 'mute.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.unmuteUser(sourceUserId, targetUserId); + console.dir(response, { + depth: null + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/users/repost/get_reposts_of_me.ts b/typescript/users/repost/get_reposts_of_me.ts new file mode 100644 index 0000000..5dc1cb7 --- /dev/null +++ b/typescript/users/repost/get_reposts_of_me.ts @@ -0,0 +1,96 @@ +/** + * Reposts of Me - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/reposts_of_me + * Docs: https://docs.x.com/x-api/users/get-reposts-of-me + * + * Authentication: OAuth 2.0 PKCE (User Context) + * Required env vars: CLIENT_ID, CLIENT_SECRET (or ACCESS_TOKEN) + */ + +import * as readline from 'node:readline'; +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + PostPaginator, +} from '@xdevplatform/xdk'; + +function promptLine(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +function extractCode(callbackInput: string): string { + const trimmed = callbackInput.trim(); + if (!trimmed.includes('://') && !trimmed.includes('code=')) { + return trimmed; + } + const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://example.com?${trimmed}`); + const code = url.searchParams.get('code'); + if (!code) { + throw new Error("No 'code' query parameter found in callback URL"); + } + return code; +} + +async function createUserClient(scopes: string[]): Promise { + if (process.env.ACCESS_TOKEN) { + return new Client({ accessToken: process.env.ACCESS_TOKEN }); + } + const clientId = process.env.CLIENT_ID; + const clientSecret = process.env.CLIENT_SECRET; + if (!clientId) { + throw new Error('Set CLIENT_ID (and optionally CLIENT_SECRET) or ACCESS_TOKEN'); + } + const oauth2 = new OAuth2({ + clientId, + clientSecret, + redirectUri: process.env.REDIRECT_URI || 'https://example.com', + scope: scopes, + }); + const state = 'sample-state'; + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + oauth2.setPkceParameters(codeVerifier, codeChallenge); + + const authUrl = await oauth2.getAuthorizationUrl(state); + console.log('Visit the following URL to authorize your App:', authUrl); + const callbackUrl = await promptLine('Paste the redirected callback URL here: '); + const tokens = await oauth2.exchangeCode(extractCode(callbackUrl), codeVerifier); + return new Client({ accessToken: tokens.access_token }); +} + +(async () => { + const client = await createUserClient(['tweet.read', 'users.read', 'offline.access']); + + const paginator = new PostPaginator(async (token?: string) => { + const res = await client.users.getRepostsOfMe({ + maxResults: 100, + paginationToken: token, + tweetFields: ['created_at', 'public_metrics'], + }); + return { + data: res.data ?? [], + meta: res.meta, + includes: res.includes, + errors: res.errors, + }; + }); + + for await (const post of paginator) { + console.dir(post, { depth: null }); + } +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/users/repost/repost_post.ts b/typescript/users/repost/repost_post.ts new file mode 100644 index 0000000..5012c6a --- /dev/null +++ b/typescript/users/repost/repost_post.ts @@ -0,0 +1,98 @@ +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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"; + +// You can replace the given Post ID with the Post ID you want to repost +// You can find a Post ID by using the Post lookup endpoint +const postId = "1412865600439738368"; + +async function input(prompt: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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.users.repostPost(userId, { tweetId: postId }); + console.dir(response, { + depth: null + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); + diff --git a/typescript/users/repost/unrepost_post.ts b/typescript/users/repost/unrepost_post.ts new file mode 100644 index 0000000..ec4c9a5 --- /dev/null +++ b/typescript/users/repost/unrepost_post.ts @@ -0,0 +1,98 @@ +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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 the given Post ID with the Post ID you want to undo repost +// You can find a Post ID by using the Post lookup endpoint +const sourceTweetId = "1412865600439738368"; + +async function input(prompt: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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.users.unrepostPost(userId, sourceTweetId); + console.dir(response, { + depth: null + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); + diff --git a/typescript/users/timeline/get_home_timeline.ts b/typescript/users/timeline/get_home_timeline.ts new file mode 100644 index 0000000..5629b50 --- /dev/null +++ b/typescript/users/timeline/get_home_timeline.ts @@ -0,0 +1,95 @@ +// Get reverse chronological home timeline +// https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-reverse-chronological-timeline +import { + Client, + OAuth2, + generateCodeVerifier, + generateCodeChallenge, + type OAuth2Config, +} from '@xdevplatform/xdk'; + +import * as readlineModule from 'node:readline'; + +const readline = readlineModule.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: string): Promise { + return new Promise((resolve) => { + readline.question(prompt, (out) => { + readline.close(); + resolve(out); + }); + }); +} + +// Helper function to parse callback URL +const getQueryStringParams = (callbackInput: string): Record => { + const queryString = callbackInput.includes('?') ? callbackInput.split('?')[1] : callbackInput.replace(/^[?#]/, ''); + return Object.fromEntries(new URLSearchParams(queryString).entries()); +}; + +(async () => { + try { + // Configure OAuth 2.0 + const oauth2Config: 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.getTimeline(userId); + console.dir(response, { + depth: null, + }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/users/timeline/get_mentions.ts b/typescript/users/timeline/get_mentions.ts new file mode 100644 index 0000000..f1b406b --- /dev/null +++ b/typescript/users/timeline/get_mentions.ts @@ -0,0 +1,51 @@ +// Get User mentions timeline by user ID +// https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/quick-start + +import { Client, PostPaginator } from '@xdevplatform/xdk'; + +const userId = '2244994945'; + +// 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 }); + +// this is the ID for @TwitterDev +const getUserMentions = async () => { + console.log("Retrieving mentions..."); + + // Use paginator for automatic pagination + const userMentions = new PostPaginator( + async (token?: string) => { + const res = await client.users.getMentions(userId, { + maxResults: 100, + paginationToken: token, + tweetFields: ['created_at'] + }); + return { + data: res.data ?? [], + meta: res.meta, + includes: res.includes, + errors: res.errors + }; + } + ); + + // Fetch all pages + await userMentions.fetchNext(); + while (!userMentions.done) { + await userMentions.fetchNext(); + } + + console.dir(userMentions.posts, { + depth: null + }); + + console.log(`Got ${userMentions.posts.length} mentions for user ID ${userId}!`); +} + +getUserMentions().catch(err => { + console.error('Error:', err); + process.exit(-1); +}); diff --git a/typescript/users/timeline/get_posts.ts b/typescript/users/timeline/get_posts.ts new file mode 100644 index 0000000..1fc16c6 --- /dev/null +++ b/typescript/users/timeline/get_posts.ts @@ -0,0 +1,35 @@ +/** + * User Posts Timeline - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/posts + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-tweets + * + * Authentication: Bearer Token (App-only) or OAuth (User Context) + * Required env vars: BEARER_TOKEN + * + * This is a simple example that makes a single request. + * For automatic pagination, see user_posts_paginated.js + */ + +import { Client } from '@xdevplatform/xdk'; + +const token = process.env.BEARER_TOKEN; +const client = new Client({ bearerToken: token }); + +// Replace with the user ID you want to get posts for +const userId = "2244994945"; + +(async () => { + try { + const response = await client.users.getPosts(userId, { + tweetFields: ['created_at', 'public_metrics'], + maxResults: 10 + }); + + console.dir(response, { depth: null }); + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/typescript/users/timeline/get_posts_paginated.ts b/typescript/users/timeline/get_posts_paginated.ts new file mode 100644 index 0000000..050c07b --- /dev/null +++ b/typescript/users/timeline/get_posts_paginated.ts @@ -0,0 +1,69 @@ +/** + * User Posts Timeline (Paginated) - X API v2 + * + * Endpoint: GET https://api.x.com/2/users/:id/posts + * Docs: https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-tweets + * + * Authentication: Bearer Token (App-only) or OAuth (User Context) + * Required env vars: BEARER_TOKEN + * + * This example demonstrates automatic pagination using PostPaginator + * to fetch all pages of results. For a simple single-request example, + * see user_posts.js + */ + +import { Client, PostPaginator } from '@xdevplatform/xdk'; + +// this is the ID for @TwitterDev +const userId = "2244994945"; + +// 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 getUserTweets = async () => { + console.log("Retrieving Tweets..."); + + // Use paginator for automatic pagination + // we request the author_id expansion so that we can print out the user name later + const userTweets = new PostPaginator( + async (token?: string) => { + const res = await client.users.getPosts(userId, { + maxResults: 100, + paginationToken: token, + tweetFields: ['created_at'], + expansions: ['author_id'] + }); + return { + data: res.data ?? [], + meta: res.meta, + includes: res.includes, + errors: res.errors + }; + } + ); + + // Fetch all pages + await userTweets.fetchNext(); + while (!userTweets.done) { + await userTweets.fetchNext(); + } + + let userName; + if (userTweets.includes?.users && userTweets.includes.users.length > 0) { + userName = userTweets.includes.users[0].username; + } + + console.dir(userTweets.posts, { + depth: null + }); + console.log(`Got ${userTweets.posts.length} Tweets from ${userName || 'user'} (user ID ${userId})!`); +} + +getUserTweets().catch(err => { + console.error('Error:', err); + process.exit(-1); +}); + diff --git a/typescript/webhooks/delete_webhook.ts b/typescript/webhooks/delete_webhook.ts new file mode 100644 index 0000000..0037776 --- /dev/null +++ b/typescript/webhooks/delete_webhook.ts @@ -0,0 +1,22 @@ +/** + * Delete Webhook - X API v2 + * + * Endpoint: DELETE https://api.x.com/2/webhooks/:webhook_id + * Docs: https://docs.x.com/x-api/webhooks/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +import { Client } from '@xdevplatform/xdk'; + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const webhookId = 'your-webhook-id'; + const response = await client.webhooks.delete(webhookId); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/webhooks/list_webhooks.ts b/typescript/webhooks/list_webhooks.ts new file mode 100644 index 0000000..e07ea40 --- /dev/null +++ b/typescript/webhooks/list_webhooks.ts @@ -0,0 +1,21 @@ +/** + * List Webhooks - X API v2 + * + * Endpoint: GET https://api.x.com/2/webhooks + * Docs: https://docs.x.com/x-api/webhooks/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +import { Client } from '@xdevplatform/xdk'; + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const response = await client.webhooks.get(); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/webhooks/register_webhook.ts b/typescript/webhooks/register_webhook.ts new file mode 100644 index 0000000..1df771c --- /dev/null +++ b/typescript/webhooks/register_webhook.ts @@ -0,0 +1,22 @@ +/** + * Register Webhook - X API v2 + * + * Endpoint: POST https://api.x.com/2/webhooks + * Docs: https://docs.x.com/x-api/webhooks/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +import { Client } from '@xdevplatform/xdk'; + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const webhookUrl = 'https://your-domain.com/webhooks'; + const response = await client.webhooks.create({ url: webhookUrl }); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/webhooks/validate_webhook.ts b/typescript/webhooks/validate_webhook.ts new file mode 100644 index 0000000..8db93e7 --- /dev/null +++ b/typescript/webhooks/validate_webhook.ts @@ -0,0 +1,22 @@ +/** + * Validate Webhook (Trigger CRC) - X API v2 + * + * Endpoint: PUT https://api.x.com/2/webhooks/:webhook_id + * Docs: https://docs.x.com/x-api/webhooks/introduction + * + * Authentication: Bearer Token (App-only) + * Required env vars: BEARER_TOKEN + */ + +import { Client } from '@xdevplatform/xdk'; + +const client = new Client({ bearerToken: process.env.BEARER_TOKEN }); + +(async () => { + const webhookId = 'your-webhook-id'; + const response = await client.webhooks.validate(webhookId); + console.dir(response, { depth: null }); +})().catch((err) => { + console.error('Error:', err); + process.exit(1); +}); diff --git a/typescript/webhooks/webhook_server.ts b/typescript/webhooks/webhook_server.ts new file mode 100644 index 0000000..c68954d --- /dev/null +++ b/typescript/webhooks/webhook_server.ts @@ -0,0 +1,56 @@ +/** + * Webhook Server (CRC + Event Delivery) - X API v2 + * + * Docs: https://docs.x.com/x-api/webhooks/introduction + * Required env vars: CONSUMER_SECRET + */ + +import * as http from 'node:http'; +import * as crypto from 'node:crypto'; + +const consumerSecret = process.env.CONSUMER_SECRET; +if (!consumerSecret) { + throw new Error('CONSUMER_SECRET environment variable is not set'); +} + +const server = http.createServer((req, res) => { + const url = new URL(req.url ?? '/', `http://${req.headers.host || 'localhost:8080'}`); + if (url.pathname !== '/webhooks') { + res.writeHead(404); + res.end(); + return; + } + + if (req.method === 'GET') { + const crcToken = url.searchParams.get('crc_token'); + if (!crcToken) { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'No crc_token' })); + return; + } + const digest = crypto.createHmac('sha256', consumerSecret).update(crcToken).digest('base64'); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ response_token: `sha256=${digest}` })); + } else if (req.method === 'POST') { + let body = ''; + req.on('data', (chunk: Buffer) => { + body += chunk; + }); + req.on('end', () => { + try { + console.dir(JSON.parse(body), { depth: null }); + } catch { + console.log(body); + } + res.writeHead(200); + res.end(); + }); + } else { + res.writeHead(405); + res.end(); + } +}); + +server.listen(8080, '0.0.0.0', () => { + console.log('Listening on http://0.0.0.0:8080/webhooks'); +}); From 5d4f8749c8b1d61787340a9c72b1b4f4dc7e0636 Mon Sep 17 00:00:00 2001 From: Taylor Caldwell <169854908+tcaldwell-x@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:44:19 -0800 Subject: [PATCH 3/4] ci: use Microsoft.CodeAnalysis.CSharp NuGet package for pre-release C# AST check --- .github/workflows/ci.yml | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9c3c6c1..9dded3f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -204,18 +204,14 @@ jobs: echo "::notice::XDevPlatform.Xdk is awaiting initial NuGet.org publication; running Roslyn C# AST check until XDevPlatform.Xdk 0.1.0 is indexed on NuGet.org." python3 - <<'PY' import pathlib, subprocess, tempfile, textwrap - sdk_line = subprocess.check_output(["dotnet", "--list-sdks"], text=True).strip().splitlines()[-1] - ver, rest = sdk_line.split(" [", 1) - roslyn = pathlib.Path(rest.rstrip("]")) / ver / "Roslyn" / "bincore" - csproj = f""" + csproj = """ Exe net8.0 enable - {roslyn}/Microsoft.CodeAnalysis.dll - {roslyn}/Microsoft.CodeAnalysis.CSharp.dll + """ prog = textwrap.dedent("""\ From 10a599370c1c3a2a75b6ed678252d1c460f473f8 Mon Sep 17 00:00:00 2001 From: Taylor Caldwell <169854908+tcaldwell-x@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:23:40 -0800 Subject: [PATCH 4/4] chore(ci): run unconditional Maven & NuGet builds against published XDK 0.1.1 / 0.7.1 --- .github/workflows/ci.yml | 103 +++------------------------------------ java/README.md | 2 +- java/pom.xml | 2 +- javascript/package.json | 2 +- typescript/package.json | 2 +- 5 files changed, 10 insertions(+), 101 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9dded3f..24b98d2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -133,57 +133,11 @@ jobs: with: distribution: 'temurin' java-version: '21' + cache: 'maven' + cache-dependency-path: java/pom.xml - name: Compile Java samples - run: | - if curl -fsSI https://repo1.maven.org/maven2/com/x/xdk/maven-metadata.xml >/dev/null 2>&1; then - mvn -B -f java/pom.xml compile - else - echo "::notice::com.x:xdk is awaiting initial Maven Central publication; running JDK 17 AST syntax check until com.x:xdk 0.1.0 is indexed on Central." - python3 - <<'PY' - import pathlib, subprocess, tempfile - code = """ - import com.sun.source.util.JavacTask; - import java.io.File; - import java.nio.file.*; - import java.util.*; - import java.util.stream.*; - import javax.tools.*; - - public class ParseCheck { - public static void main(String[] args) throws Exception { - List files; - try (Stream walk = Files.walk(Paths.get("java"))) { - files = walk.filter(p -> p.toString().endsWith(".java")) - .map(Path::toFile) - .collect(Collectors.toList()); - } - if (files.size() < 80) { - throw new IllegalStateException("Expected >=80 Java files, found " + files.size()); - } - JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); - DiagnosticCollector diagnostics = new DiagnosticCollector<>(); - try (StandardJavaFileManager fm = compiler.getStandardFileManager(diagnostics, null, null)) { - Iterable units = fm.getJavaFileObjectsFromFiles(files); - JavacTask task = (JavacTask) compiler.getTask( - null, fm, diagnostics, List.of("--release", "17"), null, units); - task.parse(); - } - long errors = diagnostics.getDiagnostics().stream() - .filter(d -> d.getKind() == Diagnostic.Kind.ERROR) - .peek(System.err::println) - .count(); - System.out.println("Parsed " + files.size() + " Java files cleanly."); - if (errors > 0) System.exit(1); - } - } - """ - with tempfile.TemporaryDirectory() as d: - p = pathlib.Path(d) / "ParseCheck.java" - p.write_text(code) - subprocess.run(["java", str(p)], check=True) - PY - fi + run: mvn -B -f java/pom.xml compile csharp: name: C# / .NET 8 (XDevPlatform.Xdk) @@ -195,52 +149,7 @@ jobs: with: dotnet-version: '8.0.x' - - name: Build C# samples + - name: Build and verify C# samples run: | - if curl -fsSI https://api.nuget.org/v3-flatcontainer/xdevplatform.xdk/index.json >/dev/null 2>&1; then - dotnet build csharp/XdkSamples.csproj -warnaserror - dotnet run --project csharp/XdkSamples.csproj --no-build -- --help >/dev/null - else - echo "::notice::XDevPlatform.Xdk is awaiting initial NuGet.org publication; running Roslyn C# AST check until XDevPlatform.Xdk 0.1.0 is indexed on NuGet.org." - python3 - <<'PY' - import pathlib, subprocess, tempfile, textwrap - csproj = """ - - Exe - net8.0 - enable - - - - - """ - prog = textwrap.dedent("""\ - using Microsoft.CodeAnalysis; - using Microsoft.CodeAnalysis.CSharp; - - var csFiles = Directory.EnumerateFiles(args[0], "*.cs", SearchOption.AllDirectories) - .Where(p => !p.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}") - && !p.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}")) - .OrderBy(p => p) - .ToList(); - if (csFiles.Count < 81) throw new Exception($"Expected >=81 C# files, found {csFiles.Count}"); - var errors = 0; - foreach (var f in csFiles) - { - var tree = CSharpSyntaxTree.ParseText(File.ReadAllText(f), path: f); - foreach (var diag in tree.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error)) - { - Console.Error.WriteLine(diag); - errors++; - } - } - Console.WriteLine($"Parsed {csFiles.Count} C# files cleanly with Roslyn."); - return errors > 0 ? 1 : 0; - """) - with tempfile.TemporaryDirectory() as d: - dp = pathlib.Path(d) - (dp / "Check.csproj").write_text(csproj) - (dp / "Program.cs").write_text(prog) - subprocess.run(["dotnet", "run", "--project", str(dp / "Check.csproj"), "--", "csharp"], check=True) - PY - fi + dotnet build csharp/XdkSamples.csproj -warnaserror + dotnet run --project csharp/XdkSamples.csproj --no-build -- --help >/dev/null diff --git a/java/README.md b/java/README.md index c488078..9fcc75a 100644 --- a/java/README.md +++ b/java/README.md @@ -16,7 +16,7 @@ Add `com.x:xdk` to your `pom.xml` (already configured in [`java/pom.xml`](./pom. com.x xdk - [0.1.0,) + 0.1.1 ``` diff --git a/java/pom.xml b/java/pom.xml index 88bf9bc..d47d27e 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -15,7 +15,7 @@ UTF-8 17 - [0.1.0,) + [0.1.1,) diff --git a/javascript/package.json b/javascript/package.json index 2e43f2f..b192b98 100644 --- a/javascript/package.json +++ b/javascript/package.json @@ -7,6 +7,6 @@ "node": ">=18.0.0" }, "dependencies": { - "@xdevplatform/xdk": "^0.7.0" + "@xdevplatform/xdk": "^0.7.1" } } diff --git a/typescript/package.json b/typescript/package.json index aa5581a..91bcf37 100644 --- a/typescript/package.json +++ b/typescript/package.json @@ -11,7 +11,7 @@ "typecheck": "tsc --noEmit" }, "dependencies": { - "@xdevplatform/xdk": "^0.7.0" + "@xdevplatform/xdk": "^0.7.1" }, "devDependencies": { "@types/node": "^22.0.0",