diff --git a/Batch-Compliance/java/README.md b/Batch-Compliance/java/README.md
deleted file mode 100644
index b702cfe..0000000
--- a/Batch-Compliance/java/README.md
+++ /dev/null
@@ -1,64 +0,0 @@
-# Batch Compliance sample code
-
-This folder contains scripts to connect to the [Batch compliance endpoints](https://developer.twitter.com/en/docs/twitter-api/compliance/batch-compliance/introduction) in Python. Make sure you have your BEARER_TOKEN set up as an environment variable. Also, make sure you have the appropriate dependencies installed by running `mvn install` in the folder that you have the pom.xml in. Then, run the scripts in the following order:
-
-## 1. Create compliance job
-
-First, run the `CreateJob` file. In this file, make sure to specify your `type` as `tweets` or `users`, based on whether you will uploading a dataset with Tweet IDs or User IDs. This will give you a response like:
-
-```json
-{
- "data": {
- "resumable": false,
- "upload_url": "https://storage.googleapis.com/...",
- "download_expires_at": "2021-08-12T15:24:31.000Z",
- "download_url": "https://storage.googleapis.com/...",
- "status": "created",
- "name": "my_job",
- "upload_expires_at": "2021-08-05T15:39:31.000Z",
- "id": "XXXXX",
- "created_at": "2021-08-05T15:24:31.000Z",
- "type": "tweets"
- }
-}
-```
-
-Note the `id` from here as well as well as the upload_url, as this is the URL you will upload the file with Tweet IDs or User IDs to.
-
-## 2. Upload the Tweet IDs or User IDs to check for compliance
-
-Next, you will upload the file with Tweet IDs or User IDs to check for compliance. To do this, you will run the `UploadDataset` file. Make sure to replace the `uploadUrl` with your `upload_url` from the previous step and make sure to specify the path to your text file that contains the Tweet IDs or User IDs, one ID per line.
-
-## 3. Check the status of your compliance job
-
-Now that you have uploaded your dataset to check for compliance, your status will be in_progress. You can download the result of your compliance job, once the `status` is complete. To check for the status of your job, there are two options:
-
-### Get all jobs
-
-In order to get all your jobs, you can run `GetJobs`. Make sure to specify the appropriate job_type in this file i.e. tweets or users
-
-### Get job by job ID
-
-You can also get the job information for a job using the `id` from obtained in step 1. Run `GetJobById` and make sure to replace the jobId with your job id obtained in step 1. This will give you your job status and the `download_url`.
-
-```json
-{
- "data": {
- "resumable": false,
- "upload_url": "https://storage.googleapis.com/...",
- "download_expires_at": "2021-08-12T02:34:13.000Z",
- "download_url": "https://storage.googleapis.com/...",
- "status": "expired",
- "upload_expires_at": "2021-08-05T02:49:13.000Z",
- "id": "XXXXX",
- "created_at": "2021-08-05T02:34:13.000Z",
- "type": "tweets"
- }
-}
-```
-
-Once your `status` changes from `in_progress` to `complete`, note the `download_url` and go to the next step to download your results
-
-## 4. Download your results
-
-In order to download your results, you will need the `download_url` from the previous step (once the job status is complete). Run the `DownloadResult` file and make sure to replace the `downloadUrl` value with your appropriate value obtained from the previous step.
\ No newline at end of file
diff --git a/Batch-Compliance/java/pom.xml b/Batch-Compliance/java/pom.xml
deleted file mode 100644
index 9f16248..0000000
--- a/Batch-Compliance/java/pom.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
- 4.0.0
-
- org.example
- batch-compliance
- 1.0-SNAPSHOT
-
-
- org.apache.httpcomponents
- httpcore
- 4.4.11
-
-
- org.apache.httpcomponents
- httpclient
- 4.5.13
-
-
- org.apache.httpcomponents
- httpmime
- 4.5.2
-
-
-
-
- 8
- 8
-
-
-
\ No newline at end of file
diff --git a/Batch-Compliance/java/src/main/java/CreateJob.java b/Batch-Compliance/java/src/main/java/CreateJob.java
deleted file mode 100644
index e9d7b8d..0000000
--- a/Batch-Compliance/java/src/main/java/CreateJob.java
+++ /dev/null
@@ -1,61 +0,0 @@
-import java.io.IOException;
-
-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.HttpPost;
-import org.apache.http.entity.ByteArrayEntity;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.util.EntityUtils;
-
-/*
- * Sample code to create a batch compliance job
- * */
-public class CreateJob {
-
- // To set your enviornment variables in your terminal run the following line:
- // export 'BEARER_TOKEN'=''
-
- public static void main(String args[]) throws IOException {
- final String bearerToken = System.getenv("BEARER_TOKEN");
- if (null != bearerToken) {
- //Specify if you want to create a job for tweets or users
- String response = createJob("tweets", 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 batch compliance endpoint to create a new job
- * */
- private static String createJob(String type, String bearerToken) throws IOException {
- String jobResponse = null;
-
- HttpClient httpClient = HttpClients.custom()
- .setDefaultRequestConfig(RequestConfig.custom()
- .setCookieSpec(CookieSpecs.STANDARD).build())
- .build();
-
- HttpPost httpPost = new HttpPost("https://api.twitter.com/2/compliance/jobs");
- httpPost.setHeader("Authorization", String.format("Bearer %s", bearerToken));
- httpPost.setHeader("Content-Type", "application/json");
-
- String body = String.format("{\n" +
- " \"type\": \"%s\"\n" +
- "}", type);
- HttpEntity requestEntity = new ByteArrayEntity(body.getBytes("UTF-8"));
- httpPost.setEntity(requestEntity);
-
- HttpResponse response = httpClient.execute(httpPost);
- HttpEntity entity = response.getEntity();
- if (null != entity) {
- jobResponse = EntityUtils.toString(entity, "UTF-8");
- }
- return jobResponse;
- }
-
-}
\ No newline at end of file
diff --git a/Batch-Compliance/java/src/main/java/DownloadResult.java b/Batch-Compliance/java/src/main/java/DownloadResult.java
deleted file mode 100644
index 3b4cf94..0000000
--- a/Batch-Compliance/java/src/main/java/DownloadResult.java
+++ /dev/null
@@ -1,49 +0,0 @@
-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;
-
-/*
- * Sample code to download batch compliance result
- * */
-public class DownloadResult {
-
- public static void main(String args[]) throws IOException, URISyntaxException {
- // Replace with your job downloadUrl below
- String downloadUrl = "";
- String response = getResults(downloadUrl);
- System.out.println(response);
- }
-
- /*
- * This method gets the results for a batch compliance job
- * */
- private static String getResults(String downloadUrl) throws IOException, URISyntaxException {
- String jobResponse = null;
-
- HttpClient httpClient = HttpClients.custom()
- .setDefaultRequestConfig(RequestConfig.custom()
- .setCookieSpec(CookieSpecs.STANDARD).build())
- .build();
-
- URIBuilder uriBuilder = new URIBuilder(downloadUrl);
-
- HttpGet httpGet = new HttpGet(uriBuilder.build());
-
- HttpResponse response = httpClient.execute(httpGet);
- HttpEntity entity = response.getEntity();
- if (null != entity) {
- jobResponse = EntityUtils.toString(entity, "UTF-8");
- }
- return jobResponse;
- }
-
-}
\ No newline at end of file
diff --git a/Batch-Compliance/java/src/main/java/GetJobById.java b/Batch-Compliance/java/src/main/java/GetJobById.java
deleted file mode 100644
index ce8f131..0000000
--- a/Batch-Compliance/java/src/main/java/GetJobById.java
+++ /dev/null
@@ -1,59 +0,0 @@
-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;
-
-/*
- * Sample code to get batch compliance job by ID
- * */
-public class GetJobById {
-
- // To set your enviornment 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) {
- // Specify your job ID below
- String jobId = "";
- String response = getJobById(jobId, 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 batch compliance endpoint to get job by id
- * */
- private static String getJobById(String id, String bearerToken) throws IOException, URISyntaxException {
- String jobResponse = null;
-
- HttpClient httpClient = HttpClients.custom()
- .setDefaultRequestConfig(RequestConfig.custom()
- .setCookieSpec(CookieSpecs.STANDARD).build())
- .build();
-
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/compliance/jobs/" + id);
-
- 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) {
- jobResponse = EntityUtils.toString(entity, "UTF-8");
- }
- return jobResponse;
- }
-
-}
\ No newline at end of file
diff --git a/Batch-Compliance/java/src/main/java/GetJobs.java b/Batch-Compliance/java/src/main/java/GetJobs.java
deleted file mode 100644
index 1b5b9ad..0000000
--- a/Batch-Compliance/java/src/main/java/GetJobs.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 get all batch compliance jobs
- * */
-public class GetJobs {
-
- // To set your enviornment 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) {
- // Specify if you want to jobs for tweets or users
- String response = getJobs("tweets", 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 batch compliance endpoint to get all jobs
- * */
- private static String getJobs(String type, String bearerToken) throws IOException, URISyntaxException {
- String jobResponse = null;
-
- HttpClient httpClient = HttpClients.custom()
- .setDefaultRequestConfig(RequestConfig.custom()
- .setCookieSpec(CookieSpecs.STANDARD).build())
- .build();
-
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/compliance/jobs");
- ArrayList queryParameters;
- queryParameters = new ArrayList<>();
- queryParameters.add(new BasicNameValuePair("type", type));
- 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) {
- jobResponse = EntityUtils.toString(entity, "UTF-8");
- }
- return jobResponse;
- }
-
-}
\ No newline at end of file
diff --git a/Batch-Compliance/java/src/main/java/UploadDataset.java b/Batch-Compliance/java/src/main/java/UploadDataset.java
deleted file mode 100644
index a9aae85..0000000
--- a/Batch-Compliance/java/src/main/java/UploadDataset.java
+++ /dev/null
@@ -1,56 +0,0 @@
-import java.io.File;
-import java.io.IOException;
-
-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.HttpPut;
-import org.apache.http.entity.mime.MultipartEntityBuilder;
-import org.apache.http.entity.mime.content.FileBody;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.util.EntityUtils;
-
-/*
- * Sample code to upload a dataset for compliance
- * */
-public class UploadDataset {
-
- public static void main(String args[]) throws IOException {
- // Replace with your path to the file that contains the Tweet or User Ids
- String path = "";
- // Replace the upload url with the appropriate url
- String uploadUrl = "";
- String response = uploadDataset(uploadUrl, path);
- System.out.println(response);
- }
-
- /*
- * This method uploads a list of Tweet or User Ids to the upload_url
- * */
- private static String uploadDataset(String uploadUrl, String path) throws IOException {
- File file = new File(path);
-
- String jobResponse = null;
-
- HttpClient httpClient = HttpClients.custom()
- .setDefaultRequestConfig(RequestConfig.custom()
- .setCookieSpec(CookieSpecs.STANDARD).build())
- .build();
-
- HttpPut httpPut = new HttpPut(uploadUrl);
- httpPut.setHeader("Content-Type", "text/plain");
-
- HttpEntity body = MultipartEntityBuilder.create().addPart("file", new FileBody(file)).build();
- httpPut.setEntity(body);
-
- HttpResponse response = httpClient.execute(httpPut);
- HttpEntity entity = response.getEntity();
- if (null != entity) {
- jobResponse = EntityUtils.toString(entity, "UTF-8");
- }
- return jobResponse;
- }
-
-}
\ No newline at end of file
diff --git a/Batch-Compliance/js/README.md b/Batch-Compliance/js/README.md
deleted file mode 100644
index ab63abf..0000000
--- a/Batch-Compliance/js/README.md
+++ /dev/null
@@ -1,69 +0,0 @@
-# Batch Compliance sample code
-
-This folder contains scripts to connect to the [Batch compliance endpoints](https://developer.twitter.com/en/docs/twitter-api/compliance/batch-compliance/introduction) in Node.JS.
-
-- Make sure you have your BEARER_TOKEN set up as an environment variable.
-- Make sure you have `needle` installed by running `npm install needle`
-
-Run the scripts in the following order:
-
-## 1. Create compliance job
-
-First, run the `create_compliance_job.js` file. In this file, make sure to specify your `type` as `tweets` or `users`, based on whether you will uploading a dataset with Tweet IDs or User IDs. This will give you a response like:
-
-```json
-{
- "data": {
- "resumable": false,
- "upload_url": "https://storage.googleapis.com/...",
- "download_expires_at": "2021-08-12T15:24:31.000Z",
- "download_url": "https://storage.googleapis.com/...",
- "status": "created",
- "name": "my_job",
- "upload_expires_at": "2021-08-05T15:39:31.000Z",
- "id": "XXXXX",
- "created_at": "2021-08-05T15:24:31.000Z",
- "type": "tweets"
- }
-}
-```
-
-Note the `id` from here as well as well as the upload_url, as this is the URL you will upload the file with Tweet IDs or User IDs to.
-
-## 2. Upload the Tweet IDs or User IDs to check for compliance
-
-Next, you will upload the file with Tweet IDs or User IDs to check for compliance. To do this, you will run the `upload_ids.js` file. Make sure to replace the `uploadUrl` with your `upload_url` value from the previous step and make sure to specify the path to your text file that contains the Tweet IDs or User IDs, one ID per line.
-
-## 3. Check the status of your compliance job
-
-Now that you have uploaded your dataset to check for compliance, your status will be in_progress. You can download the result of your compliance job, once the `status` is complete. To check for the status of your job, there are two options:
-
-### Get all jobs
-
-In order to get all your jobs, you can run `get_list_of_compliance_jobs.js`. Make sure to specify the appropriate type in this file i.e. tweets or users
-
-### Get job by job ID
-
-You can also get the job information for a job using the `id` from obtained in step 1. Run `get_compliance_job_information_by_id.js` and make sure to replace the id with your job id obtained in step 1. This will give you the status and the `download_url`.
-
-```json
-{
- "data": {
- "resumable": false,
- "upload_url": "https://storage.googleapis.com/...",
- "download_expires_at": "2021-08-12T02:34:13.000Z",
- "download_url": "https://storage.googleapis.com/...",
- "status": "expired",
- "upload_expires_at": "2021-08-05T02:49:13.000Z",
- "id": "XXXXX",
- "created_at": "2021-08-05T02:34:13.000Z",
- "type": "tweets"
- }
-}
-```
-
-Once your `status` changes from `in_progress` to `complete`, note the `download_url` and go to the next step to download your results
-
-## 4. Download your results
-
-In order to download your results, you will need the `download_url` from the previous step (once the status is complete). Run the `download_compliance_results.js` file and make sure to replace the `downloadUrl` value in the code with your appropriate value obtained from the previous step.
diff --git a/Batch-Compliance/python/README.md b/Batch-Compliance/python/README.md
deleted file mode 100644
index 2314228..0000000
--- a/Batch-Compliance/python/README.md
+++ /dev/null
@@ -1,64 +0,0 @@
-# Batch Compliance sample code
-
-This folder contains scripts to connect to the [Batch compliance endpoints](https://developer.twitter.com/en/docs/twitter-api/compliance/batch-compliance/introduction) in Python. Make sure you have your BEARER_TOKEN set up as an environment variable. Run the scripts in the following order:
-
-## 1. Create compliance job
-
-First, run the `create_compliance_job.py` file. In this file, make sure to specify your `type` as `tweets` or `users`, based on whether you will uploading a dataset with Tweet IDs or User IDs. This will give you a response like:
-
-```json
-{
- "data": {
- "resumable": false,
- "upload_url": "https://storage.googleapis.com/...",
- "download_expires_at": "2021-08-12T15:24:31.000Z",
- "download_url": "https://storage.googleapis.com/...",
- "status": "created",
- "name": "my_job",
- "upload_expires_at": "2021-08-05T15:39:31.000Z",
- "id": "XXXXX",
- "created_at": "2021-08-05T15:24:31.000Z",
- "type": "tweets"
- }
-}
-```
-
-Note the `id` from here as well as well as the upload_url, as this is the URL you will upload the file with Tweet IDs or User IDs to.
-
-## 2. Upload the Tweet IDs or User IDs to check for compliance
-
-Next, you will upload the file with Tweet IDs or User IDs to check for compliance. To do this, you will run the `upload_ids.py` file. Make sure to replace the `upload_url` with your `upload_url` from the previous step and make sure to specify the path to your text file that contains the Tweet IDs or User IDs, one ID per line.
-
-## 3. Check the status of your compliance job
-
-Now that you have uploaded your dataset to check for compliance, your status will be in_progress. You can download the result of your compliance job, once the `status` is complete. To check for the status of your job, there are two options:
-
-### Get all jobs
-
-In order to get all your jobs, you can run `get_list_of_compliance_jobs.py`. Make sure to specify the appropriate type in this file i.e. tweets or users
-
-### Get job by job ID
-
-You can also get the job information for a job using the `id` from obtained in step 1. Run `get_compliance_job_information_by_id.py` and make sure to replace the id with your job id obtained in step 1. This will give you the status and the `download_url`.
-
-```json
-{
- "data": {
- "resumable": false,
- "upload_url": "https://storage.googleapis.com/...",
- "download_expires_at": "2021-08-12T02:34:13.000Z",
- "download_url": "https://storage.googleapis.com/...",
- "status": "expired",
- "upload_expires_at": "2021-08-05T02:49:13.000Z",
- "id": "XXXXX",
- "created_at": "2021-08-05T02:34:13.000Z",
- "type": "tweets"
- }
-}
-```
-
-Once your `status` changes from `in_progress` to `complete`, note the `download_url` and go to the next step to download your results
-
-## 4. Download your results
-
-In order to download your results, you will need the `download_url` from the previous step (once the status is complete). Run the `download_compliance_results.py` file and make sure to replace the `download_url` value with your appropriate value obtained from the previous step.
\ No newline at end of file
diff --git a/Manage-Bookmarks/create_bookmark.rb b/Manage-Bookmarks/create_bookmark.rb
deleted file mode 100644
index a13ed31..0000000
--- a/Manage-Bookmarks/create_bookmark.rb
+++ /dev/null
@@ -1,113 +0,0 @@
-require 'json'
-require 'typhoeus'
-require 'twitter_oauth2'
-
-# First, you will need to enable OAuth 2.0 in your App’s auth settings in the Developer Portal to get your client ID.
-# Inside your terminal you will need to set an enviornment variable
-# export CLIENT_ID='your-client-id'
-client_id = ENV["CLIENT_ID"]
-
-# If you have selected a type of App that is a confidential client you will need to set a client secret.
-# Confidential Clients securely authenticate with the authorization server.
-
-# Inside your terminal you will need to set an enviornment variable
-# export CLIENT_SECRET='your-client-secret'
-
-# Remove the comment on the following line if you are using a confidential client
-# client_secret = ENV["CLIENT_SECRET"]
-
-
-# Replace the following URL with your callback URL, which can be obtained from your App's auth settings.
-redirect_uri = "https://www.example.com"
-
-# Replace with a Tweet ID you want to Bookmark
-@json_payload = {"tweet_id": "1460323737035677698"}
-
-# Start an OAuth 2.0 session with a public client
-client = TwitterOAuth2::Client.new(
- identifier: "#{client_id}",
- redirect_uri: "#{redirect_uri}"
-)
-
-# Start an OAuth 2.0 session with a confidential client
-# Remove the comment on the following lines if you are using a confidential client
-# client = TwitterOAuth2::Client.new(
-# identifier: "#{client_id}",
-# secret: "#{client_secret}",
-# redirect_uri: "#{redirect_uri}"
-# )
-
-# Create your authorize url
-authorization_url = client.authorization_uri(
- scope: [
- :'users.read',
- :'tweet.read',
- :'bookmark.write',
- :'offline.access'
- ]
-)
-
-# Set code verifier and state
-code_verifier = client.code_verifier
-state = client.state
-
-# Visit the URL to authorize your App to make requests on behalf of a user
-print 'Visit the following URL to authorize your App on behalf of your Twitter handle in a browser'
-puts authorization_url
-`open "#{authorization_url}"`
-
-print 'Paste in the full URL after you authorized your App: ' and STDOUT.flush
-
-# Fetch your access token
-full_text = gets.chop
-new_code = full_text.split("code=")
-code = new_code[1]
-client.authorization_code = code
-
-# Your access token
-token_response = client.access_token! code_verifier
-
-# Make a request to the users/me endpoint to get your user ID
-def users_me(url, token_response)
- options = {
- method: 'get',
- headers: {
- "User-Agent": "BookmarksSampleCode",
- "Authorization": "Bearer #{token_response}"
- },
- }
-
- request = Typhoeus::Request.new(url, options)
- response = request.run
-
- return response
-end
-
-url = "https://api.twitter.com/2/users/me"
-me_response = users_me(url, token_response)
-
-json_s = JSON.parse(me_response.body)
-user_id = json_s["data"]["id"]
-
-# Make a request to the bookmarks url
-bookmarks_url = "https://api.twitter.com/2/users/#{user_id}/bookmarks"
-
-def bookmarked_tweets(bookmarks_url, token_response)
- options = {
- method: 'post',
- headers: {
- "User-Agent": "BookmarksSampleCode",
- "content-type": "application/json",
- "Authorization": "Bearer #{token_response}"
- },
- body: JSON.dump(@json_payload)
- }
-
- request = Typhoeus::Request.new(bookmarks_url, options)
- response = request.run
-
- return response
-end
-
-response = bookmarked_tweets(bookmarks_url, token_response)
-puts response.code, JSON.pretty_generate(JSON.parse(response.body))
diff --git a/Manage-Bookmarks/delete_bookmark.rb b/Manage-Bookmarks/delete_bookmark.rb
deleted file mode 100644
index 77b768c..0000000
--- a/Manage-Bookmarks/delete_bookmark.rb
+++ /dev/null
@@ -1,111 +0,0 @@
-require 'json'
-require 'typhoeus'
-require 'twitter_oauth2'
-
-# First, you will need to enable OAuth 2.0 in your App’s auth settings in the Developer Portal to get your client ID.
-# Inside your terminal you will need to set an enviornment variable
-# export CLIENT_ID='your-client-id'
-client_id = ENV["CLIENT_ID"]
-
-# If you have selected a type of App that is a confidential client you will need to set a client secret.
-# Confidential Clients securely authenticate with the authorization server.
-
-# Inside your terminal you will need to set an enviornment variable
-# export CLIENT_SECRET='your-client-secret'
-
-# Remove the comment on the following line if you are using a confidential client
-# client_secret = ENV["CLIENT_SECRET"]
-
-
-# Replace the following URL with your callback URL, which can be obtained from your App's auth settings.
-redirect_uri = "https://www.example.com"
-
-# Replace with a Tweet ID you want to remove a Bookmark of
-tweet_id = "1460323737035677698"
-
-# Start an OAuth 2.0 session with a public client
-client = TwitterOAuth2::Client.new(
- identifier: "#{client_id}",
- redirect_uri: "#{redirect_uri}"
-)
-
-# Start an OAuth 2.0 session with a confidential client
-# Remove the comment on the following lines if you are using a confidential client
-# client = TwitterOAuth2::Client.new(
-# identifier: "#{client_id}",
-# secret: "#{client_secret}",
-# redirect_uri: "#{redirect_uri}"
-# )
-
-# Create your authorize url
-authorization_url = client.authorization_uri(
- scope: [
- :'users.read',
- :'tweet.read',
- :'bookmark.write',
- :'offline.access'
- ]
-)
-
-# Set code verifier and state
-code_verifier = client.code_verifier
-state = client.state
-
-# Visit the URL to authorize your App to make requests on behalf of a user
-print 'Visit the following URL to authorize your App on behalf of your Twitter handle in a browser'
-puts authorization_url
-`open "#{authorization_url}"`
-
-print 'Paste in the full URL after you authorized your App: ' and STDOUT.flush
-
-# Fetch your access token
-full_text = gets.chop
-new_code = full_text.split("code=")
-code = new_code[1]
-client.authorization_code = code
-
-# Your access token
-token_response = client.access_token! code_verifier
-
-# Make a request to the users/me endpoint to get your user ID
-def users_me(url, token_response)
- options = {
- method: 'get',
- headers: {
- "User-Agent": "BookmarksSampleCode",
- "Authorization": "Bearer #{token_response}"
- },
- }
-
- request = Typhoeus::Request.new(url, options)
- response = request.run
-
- return response
-end
-
-url = "https://api.twitter.com/2/users/me"
-me_response = users_me(url, token_response)
-
-json_s = JSON.parse(me_response.body)
-user_id = json_s["data"]["id"]
-
-# Make a request to the bookmarks url
-bookmarks_url = "https://api.twitter.com/2/users/#{user_id}/bookmarks/#{tweet_id}"
-
-def bookmarked_tweets(bookmarks_url, token_response)
- options = {
- method: 'delete',
- headers: {
- "User-Agent": "BookmarksSampleCode",
- "Authorization": "Bearer #{token_response}"
- }
- }
-
- request = Typhoeus::Request.new(bookmarks_url, options)
- response = request.run
-
- return response
-end
-
-response = bookmarked_tweets(bookmarks_url, token_response)
-puts response.code, JSON.pretty_generate(JSON.parse(response.body))
diff --git a/Manage-Retweets/.#bearer_test.py b/Manage-Retweets/.#bearer_test.py
deleted file mode 120000
index cf1e1e2..0000000
--- a/Manage-Retweets/.#bearer_test.py
+++ /dev/null
@@ -1 +0,0 @@
-jgarson@tw-mbp-jgarson.9884
\ No newline at end of file
diff --git a/README.md b/README.md
index 8da353e..b1fbeff 100644
--- a/README.md
+++ b/README.md
@@ -1,102 +1,85 @@
-# Twitter API v2 sample code [](https://developer.twitter.com/en/docs/twitter-api)
+# X API v2 Sample Code
-Sample code for the Twitter API v2 endpoints.
-Individual API features have folders where you can find examples of usage in several coding languages (Java, Node.js, Python, R, and Ruby).
+[](https://developer.x.com/en/docs/twitter-api)
-* [Twitter API Documentation](https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api)
+Working code samples for the **X API v2** in Python, JavaScript, Ruby, Java, and R.
-## Prerequisites
+## 📁 Repository Structure
-* Twitter API Essential Access ([sign up here](https://t.co/signup))
-* A Project and an App created [in the dashboard](https://developer.twitter.com/en/portal/dashboard)
-
-## Using the code samples
-
-In order to run the samples in this repository you will need to set up some environment variables. You can find your credentials and bearer token in the App inside of your Project in the [dashboard of the developer portal](https://developer.twitter.com/en/portal/projects-and-apps).
-
-For OAuth 1.0a samples, you will need to export your consumer key and secret in your terminal. Be sure to replace `` and `` with your own credentials without the `< >`.
-
-```bash
-export CONSUMER_KEY=''
-export CONSUMER_SECRET=''
-```
-
-For samples which use bearer token authentication, you will need to export the bearer token. Be sure to replace `` with your own bearer token without the `< >`.
-
-```bash
-export BEARER_TOKEN=''
```
-
-## Language-specific requirements
-
-### Java environment set up
-
-If you use Homebrew, you can install a Java runtime using:
-
-```bash
-brew cask install java
+├── python/ # 108 Python examples
+├── javascript/ # 70 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
```
-You will also need to download the relevant JAR files referenced in the individual samples in order to build and run the code. If you use an IDE, it may be able to do this automatically for you.
-
-### JavaScript (Node.js) environment set up
-
-You will need to have Node.js installed to run this code. All Node.js examples use `needle` as the HTTP client, which needs to be npm installed. For OAuth with user context requests, you'll need to install the `got` and `oauth-1.0a` packages.
-
-```bash
-npm install needle
-npm install got
-npm install oauth-1.0a
-```
+## 🚀 Quick Start
-### Python environment set up
+### 1. Get API Credentials
-You will need to have Python 3 installed to run this code. The Python samples use `requests==2.24.0` which uses `requests-oauthlib==1.3.0`.
+Sign up at the [X Developer Portal](https://developer.x.com/en/portal/dashboard).
-(Optionally) It is common and recommended not to install required package globally, but locally under project subfolder using `venv`:
+### 2. Set Environment Variables
```bash
-python3 -m venv venv
-source venv/bin/activate
+export BEARER_TOKEN='your_bearer_token'
+export CONSUMER_KEY='your_consumer_key'
+export CONSUMER_SECRET='your_consumer_secret'
```
-You can install these packages as follows:
+### 3. Run an Example
```bash
-pip install requests
-pip install requests-oauthlib
-```
-
-### Ruby environment set up
+# Python
+cd python && pip install -r requirements.txt
+python posts/recent_search.py
-You will need to have Ruby (recommended: >= 2.0.0) installed in order to run the code. The Ruby examples use `typhoeus` as the HTTP client, which needs to be gem installed. For OAuth with user context requests, you'll also need to install the `oauth` gem (see below).
+# JavaScript
+cd javascript && npm install
+node posts/recent_search.js
-```bash
-gem install typhoeus
-gem install oauth
+# Ruby
+cd ruby && bundle install
+ruby posts/recent_search.rb
```
-## Additional resources
-
-We maintain a [Postman](https://getpostman.com) Collection which you can use for exercising individual API endpoints.
-
-* [Using Postman with the Twitter API](https://developer.twitter.com/en/docs/tutorials/postman-getting-started)
-* [Twitter API v2 on the Postman website](https://t.co/twitter-api-postman)
+## 📚 Examples by Category
-## Support
+| Category | Python | JavaScript | Ruby | Java | R |
+|----------|--------|------------|------|------|---|
+| Posts (search, create, delete, likes, retweets) | ✅ | ✅ | ✅ | ✅ | ✅ |
+| Users (lookup, followers, blocks, mutes) | ✅ | ✅ | ✅ | ✅ | ✅ |
+| Timelines (user, mentions, home) | ✅ | ✅ | ✅ | ✅ | |
+| Streams (filtered, sampled) | ✅ | ✅ | ✅ | ✅ | |
+| Lists (lookup, manage, members) | ✅ | ✅ | ✅ | | |
+| Spaces (lookup, search) | ✅ | ✅ | ✅ | ✅ | |
+| Bookmarks | ✅ | ✅ | ✅ | | |
+| Direct Messages | ✅ | | | | |
+| Media Upload | ✅ | | | | |
+| Compliance | ✅ | ✅ | | ✅ | |
+| Usage | ✅ | ✅ | | ✅ | |
-* For general questions related to the API and features, please use the v2 section of our [developer community forums](https://twittercommunity.com/c/twitter-api/twitter-api-v2/65).
+## 🔐 Authentication
-* If there's an bug or issue with the sample code itself, please create a [new issue](https://github.com/twitterdev/Twitter-API-v2-sample-code/issues) here on GitHub.
+| Type | Use Case | Env Vars |
+|------|----------|----------|
+| Bearer Token | Read-only (search, lookup) | `BEARER_TOKEN` |
+| OAuth 1.0a | User actions (post, like) | `CONSUMER_KEY`, `CONSUMER_SECRET` |
+| OAuth 2.0 PKCE | Bookmarks, newer endpoints | OAuth flow |
-## Contributing
+## 🤖 For LLMs
-We welcome pull requests that add meaningful additions to these code samples, particularly for languages that are not yet represented here.
+- **`llms.txt`** - Context file for AI assistants
+- **`api-index.json`** - Machine-readable endpoint catalog
-We feel that a welcoming community is important and we ask that you follow Twitter's [Open Source Code of Conduct](https://github.com/twitter/.github/blob/main/code-of-conduct.md) in all interactions with the community.
+## 🔗 Resources
-## License
+- [X API Documentation](https://developer.x.com/en/docs/twitter-api)
+- [Developer Portal](https://developer.x.com/en/portal/dashboard)
-Copyright 2021 Twitter, Inc.
+## 📄 License
-Licensed under the Apache License, Version 2.0: https://www.apache.org/licenses/LICENSE-2.0
+Apache 2.0
diff --git a/Reverse-Chron-Home-Timeline/OAuth1a-user/reverse-chron-home-timeline.rb b/Reverse-Chron-Home-Timeline/OAuth1a-user/reverse-chron-home-timeline.rb
deleted file mode 100644
index 36cdf3b..0000000
--- a/Reverse-Chron-Home-Timeline/OAuth1a-user/reverse-chron-home-timeline.rb
+++ /dev/null
@@ -1,80 +0,0 @@
-# This script implements the PIN-based OAuth flow to obtain access tokens for a user context request
-# It then makes a Mutes lookup request (by usernames) with OAuth 1.0a authentication (user context)
-require 'oauth'
-require 'json'
-require 'typhoeus'
-require 'oauth/request_proxy/typhoeus_request'
-
-# The code below sets the consumer key and secret from your environment variables
-# To set environment variables on Mac OS X, run the export command below from the terminal:
-# export CONSUMER_KEY='YOUR-KEY', CONSUMER_SECRET='YOUR-SECRET'
-consumer_key = ENV["CONSUMER_KEY"]
-consumer_secret = ENV["CONSUMER_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
-id = "your-user-id"
-
-url = "https://api.twitter.com/2/users/#{id}/timelines/reverse_chronological"
-
-consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
- :authorize_path => '/oauth/authenticate',
- :debug_output => false)
-
-def get_request_token(consumer)
-
- request_token = consumer.get_request_token()
-
- return request_token
-end
-
-def get_user_authorization(request_token)
- puts "Follow this URL to have a user authorize your app: #{request_token.authorize_url()}"
- puts "Enter PIN: "
- pin = gets.strip
-
- return pin
-end
-
-def obtain_access_token(consumer, request_token, pin)
- token = request_token.token
- token_secret = request_token.secret
- hash = { :oauth_token => token, :oauth_token_secret => token_secret }
- request_token = OAuth::RequestToken.from_hash(consumer, hash)
-
- # Get access token
- access_token = request_token.get_access_token({:oauth_verifier => pin})
-
- return access_token
-end
-
-
-def reverse_chron_home_timeline(url, oauth_params)
- options = {
- :method => :get,
- headers: {
- "User-Agent": "v2ReverseChronHomeTimelineRuby"
- }
- }
- request = Typhoeus::Request.new(url, options)
- oauth_helper = OAuth::Client::Helper.new(request, oauth_params.merge(:request_uri => url))
- request.options[:headers].merge!({"Authorization" => oauth_helper.header}) # Signs the request
- response = request.run
-
- return response
-end
-
-
-
-# PIN-based OAuth flow - Step 1
-request_token = get_request_token(consumer)
-# PIN-based OAuth flow - Step 2
-pin = get_user_authorization(request_token)
-# PIN-based OAuth flow - Step 3
-access_token = obtain_access_token(consumer, request_token, pin)
-
-oauth_params = {:consumer => consumer, :token => access_token}
-
-response = reverse_chron_home_timeline(url, oauth_params)
-puts response.code, JSON.pretty_generate(JSON.parse(response.body))
diff --git a/Tweet-Lookup/get_tweets_with_bearer_token.r b/Tweet-Lookup/get_tweets_with_bearer_token.r
deleted file mode 100644
index 62221cb..0000000
--- a/Tweet-Lookup/get_tweets_with_bearer_token.r
+++ /dev/null
@@ -1,21 +0,0 @@
-require(httr)
-
-bearer_token <- ""
-
-headers <- c(`Authorization` = sprintf('Bearer %s', bearer_token))
-
-params <- list(`tweet.fields` = 'created_at')
-
-ids <- '1293593516040269825'
-
-url_ids <-
- sprintf('https://api.twitter.com/2/tweets?ids=%s', ids)
-
-response <-
- httr::GET(url = url_ids,
- httr::add_headers(.headers = headers),
- query = params)
-
-
-obj <- httr::content(response, as = "text")
-print(obj)
diff --git a/Usage Tweets/get_usage_tweets.rb b/Usage Tweets/get_usage_tweets.rb
deleted file mode 100644
index 6bd93bb..0000000
--- a/Usage Tweets/get_usage_tweets.rb
+++ /dev/null
@@ -1,29 +0,0 @@
-# This script uses your bearer token to authenticate and retrieve the Usage
-
-require 'json'
-require 'typhoeus'
-
-# The code below sets the bearer token from your environment variables
-# To set environment variables on Mac OS X, run the export command below from the terminal:
-# export BEARER_TOKEN='YOUR-TOKEN'
-bearer_token = ENV["BEARER_TOKEN"]
-
-usage_tweets_url = "https://api.twitter.com/2/usage/tweets"
-
-def usage_tweets(url, bearer_token)
- options = {
- method: 'get',
- headers: {
- "User-Agent": "v2UsageTweetsRuby",
- "Authorization": "Bearer #{bearer_token}"
- }
- }
-
- request = Typhoeus::Request.new(url, options)
- response = request.run
-
- return response
-end
-
-response = usage_tweets(usage_tweets_url, bearer_token)
-puts response.code, JSON.pretty_generate(JSON.parse(response.body))
diff --git a/api-index.json b/api-index.json
new file mode 100644
index 0000000..bd17e8d
--- /dev/null
+++ b/api-index.json
@@ -0,0 +1,489 @@
+{
+ "name": "X API v2 Sample Code",
+ "version": "2.0",
+ "base_url": "https://api.x.com/2",
+ "languages": ["python", "javascript", "ruby", "java"],
+ "endpoints": [
+ {
+ "name": "Create Post",
+ "path": "/tweets",
+ "method": "POST",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "posts",
+ "files": {
+ "python": "create_post.py",
+ "javascript": "create_post.js"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets"
+ },
+ {
+ "name": "Delete Post",
+ "path": "/tweets/:id",
+ "method": "DELETE",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "posts",
+ "files": {
+ "python": "delete_post.py",
+ "javascript": "delete_post.js"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/delete-tweets-id"
+ },
+ {
+ "name": "Post Lookup",
+ "path": "/tweets",
+ "method": "GET",
+ "auth": ["bearer", "oauth1", "oauth2-user"],
+ "folder": "posts",
+ "files": {
+ "python": "lookup.py",
+ "javascript": "lookup.js",
+ "ruby": "lookup.rb"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets"
+ },
+ {
+ "name": "Recent Search",
+ "path": "/tweets/search/recent",
+ "method": "GET",
+ "auth": ["bearer", "oauth2-user"],
+ "folder": "posts",
+ "files": {
+ "python": "search_recent.py",
+ "javascript": "search_recent.js",
+ "ruby": "search_recent.rb",
+ "java": "SearchRecent.java"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent"
+ },
+ {
+ "name": "Full Archive Search",
+ "path": "/tweets/search/all",
+ "method": "GET",
+ "auth": ["bearer"],
+ "folder": "posts",
+ "files": {
+ "python": "search_full_archive.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-all",
+ "note": "Requires Academic Research access"
+ },
+ {
+ "name": "Recent Post Counts",
+ "path": "/tweets/counts/recent",
+ "method": "GET",
+ "auth": ["bearer"],
+ "folder": "posts",
+ "files": {
+ "python": "counts_recent.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/counts/api-reference/get-tweets-counts-recent"
+ },
+ {
+ "name": "Quote Posts",
+ "path": "/tweets/:id/quote_tweets",
+ "method": "GET",
+ "auth": ["bearer", "oauth2-user"],
+ "folder": "posts",
+ "files": {
+ "python": "quote_posts.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/quote-tweets/api-reference/get-tweets-id-quote_tweets"
+ },
+ {
+ "name": "Repost",
+ "path": "/users/:id/retweets",
+ "method": "POST",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "posts",
+ "files": {
+ "python": "repost.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/post-users-id-retweets"
+ },
+ {
+ "name": "Undo Repost",
+ "path": "/users/:id/retweets/:source_tweet_id",
+ "method": "DELETE",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "posts",
+ "files": {
+ "python": "undo_repost.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/delete-users-id-retweets-tweet_id"
+ },
+ {
+ "name": "Reposted By",
+ "path": "/tweets/:id/retweeted_by",
+ "method": "GET",
+ "auth": ["bearer", "oauth2-user"],
+ "folder": "posts",
+ "files": {
+ "python": "reposted_by.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/retweets/api-reference/get-tweets-id-retweeted_by"
+ },
+ {
+ "name": "Like Post",
+ "path": "/users/:id/likes",
+ "method": "POST",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "posts",
+ "files": {
+ "python": "like.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/post-users-id-likes"
+ },
+ {
+ "name": "Unlike Post",
+ "path": "/users/:id/likes/:tweet_id",
+ "method": "DELETE",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "posts",
+ "files": {
+ "python": "unlike.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/delete-users-id-likes-tweet_id"
+ },
+ {
+ "name": "Liking Users",
+ "path": "/tweets/:id/liking_users",
+ "method": "GET",
+ "auth": ["bearer", "oauth2-user"],
+ "folder": "posts",
+ "files": {
+ "python": "liking_users.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/get-tweets-id-liking_users"
+ },
+ {
+ "name": "Liked Posts",
+ "path": "/users/:id/liked_tweets",
+ "method": "GET",
+ "auth": ["bearer", "oauth2-user"],
+ "folder": "posts",
+ "files": {
+ "python": "liked_posts.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/likes/api-reference/get-users-id-liked_tweets"
+ },
+ {
+ "name": "User Lookup",
+ "path": "/users/by",
+ "method": "GET",
+ "auth": ["bearer", "oauth1", "oauth2-user"],
+ "folder": "users",
+ "files": {
+ "python": "lookup.py",
+ "javascript": "lookup.js",
+ "ruby": "lookup.rb",
+ "java": "Lookup.java"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-by"
+ },
+ {
+ "name": "Authenticated User (Me)",
+ "path": "/users/me",
+ "method": "GET",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "users",
+ "files": {
+ "python": "me.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-me"
+ },
+ {
+ "name": "User Followers",
+ "path": "/users/:id/followers",
+ "method": "GET",
+ "auth": ["bearer", "oauth2-user"],
+ "folder": "users",
+ "files": {
+ "python": "followers.py",
+ "javascript": "followers.js",
+ "ruby": "followers.rb"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/get-users-id-followers"
+ },
+ {
+ "name": "User Following",
+ "path": "/users/:id/following",
+ "method": "GET",
+ "auth": ["bearer", "oauth2-user"],
+ "folder": "users",
+ "files": {
+ "python": "following.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/get-users-id-following"
+ },
+ {
+ "name": "Block User",
+ "path": "/users/:id/blocking",
+ "method": "POST",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "users",
+ "files": {
+ "python": "block.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/users/blocks/api-reference/post-users-user_id-blocking"
+ },
+ {
+ "name": "Unblock User",
+ "path": "/users/:source_user_id/blocking/:target_user_id",
+ "method": "DELETE",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "users",
+ "files": {
+ "python": "unblock.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/users/blocks/api-reference/delete-users-user_id-blocking"
+ },
+ {
+ "name": "Blocked Users",
+ "path": "/users/:id/blocking",
+ "method": "GET",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "users",
+ "files": {
+ "python": "blocked.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/users/blocks/api-reference/get-users-blocking"
+ },
+ {
+ "name": "Mute User",
+ "path": "/users/:id/muting",
+ "method": "POST",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "users",
+ "files": {
+ "python": "mute.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/post-users-user_id-muting"
+ },
+ {
+ "name": "Unmute User",
+ "path": "/users/:source_user_id/muting/:target_user_id",
+ "method": "DELETE",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "users",
+ "files": {
+ "python": "unmute.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/delete-users-user_id-muting"
+ },
+ {
+ "name": "Muted Users",
+ "path": "/users/:id/muting",
+ "method": "GET",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "users",
+ "files": {
+ "python": "muted.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/users/mutes/api-reference/get-users-muting"
+ },
+ {
+ "name": "User Posts Timeline",
+ "path": "/users/:id/tweets",
+ "method": "GET",
+ "auth": ["bearer", "oauth2-user"],
+ "folder": "timelines",
+ "files": {
+ "python": "user_posts.py",
+ "javascript": "user_posts.js",
+ "ruby": "user_posts.rb"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-tweets"
+ },
+ {
+ "name": "User Mentions Timeline",
+ "path": "/users/:id/mentions",
+ "method": "GET",
+ "auth": ["bearer", "oauth2-user"],
+ "folder": "timelines",
+ "files": {
+ "python": "user_mentions.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-mentions"
+ },
+ {
+ "name": "Home Timeline",
+ "path": "/users/:id/reverse_chronological_timeline",
+ "method": "GET",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "timelines",
+ "files": {
+ "python": "home_timeline.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-reverse-chronological-timeline"
+ },
+ {
+ "name": "Filtered Stream",
+ "path": "/tweets/search/stream",
+ "method": "GET",
+ "auth": ["bearer"],
+ "folder": "streams",
+ "files": {
+ "python": "filtered_stream.py",
+ "javascript": "filtered_stream.js"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/filtered-stream/api-reference/get-tweets-search-stream"
+ },
+ {
+ "name": "Sampled Stream",
+ "path": "/tweets/sample/stream",
+ "method": "GET",
+ "auth": ["bearer"],
+ "folder": "streams",
+ "files": {
+ "python": "sampled_stream.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/volume-streams/api-reference/get-tweets-sample-stream"
+ },
+ {
+ "name": "Bookmarks Lookup",
+ "path": "/users/:id/bookmarks",
+ "method": "GET",
+ "auth": ["oauth2-user"],
+ "folder": "bookmarks",
+ "files": {
+ "python": "lookup.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/get-users-id-bookmarks"
+ },
+ {
+ "name": "Create Bookmark",
+ "path": "/users/:id/bookmarks",
+ "method": "POST",
+ "auth": ["oauth2-user"],
+ "folder": "bookmarks",
+ "files": {
+ "python": "create.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/post-users-id-bookmarks"
+ },
+ {
+ "name": "Delete Bookmark",
+ "path": "/users/:id/bookmarks/:tweet_id",
+ "method": "DELETE",
+ "auth": ["oauth2-user"],
+ "folder": "bookmarks",
+ "files": {
+ "python": "delete.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/delete-users-id-bookmarks-tweet_id"
+ },
+ {
+ "name": "Spaces Lookup",
+ "path": "/spaces",
+ "method": "GET",
+ "auth": ["bearer", "oauth2-user"],
+ "folder": "spaces",
+ "files": {
+ "python": "lookup.py",
+ "javascript": "lookup.js"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/spaces/lookup/api-reference/get-spaces"
+ },
+ {
+ "name": "Spaces Search",
+ "path": "/spaces/search",
+ "method": "GET",
+ "auth": ["bearer", "oauth2-user"],
+ "folder": "spaces",
+ "files": {
+ "python": "search.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/spaces/search/api-reference/get-spaces-search"
+ },
+ {
+ "name": "List Lookup",
+ "path": "/lists/:id",
+ "method": "GET",
+ "auth": ["bearer", "oauth2-user"],
+ "folder": "lists",
+ "files": {
+ "python": "lookup.py",
+ "javascript": "lookup.js",
+ "ruby": "lookup.rb"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/lists/list-lookup/api-reference/get-lists-id"
+ },
+ {
+ "name": "Create List",
+ "path": "/lists",
+ "method": "POST",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "lists",
+ "files": {
+ "python": "create.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/post-lists"
+ },
+ {
+ "name": "Delete List",
+ "path": "/lists/:id",
+ "method": "DELETE",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "lists",
+ "files": {
+ "python": "delete.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/lists/manage-lists/api-reference/delete-lists-id"
+ },
+ {
+ "name": "DM Events Lookup",
+ "path": "/dm_events",
+ "method": "GET",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "direct_messages",
+ "files": {
+ "python": "lookup.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/direct-messages/lookup/api-reference/get-dm-events"
+ },
+ {
+ "name": "Send DM",
+ "path": "/dm_conversations/with/:participant_id/messages",
+ "method": "POST",
+ "auth": ["oauth1", "oauth2-user"],
+ "folder": "direct_messages",
+ "files": {
+ "python": "send.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/direct-messages/manage/api-reference/post-dm-conversations-with-participant_id-messages"
+ },
+ {
+ "name": "Create Compliance Job",
+ "path": "/compliance/jobs",
+ "method": "POST",
+ "auth": ["bearer"],
+ "folder": "compliance",
+ "files": {
+ "python": "create_job.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/post-compliance-jobs"
+ },
+ {
+ "name": "Get Compliance Jobs",
+ "path": "/compliance/jobs",
+ "method": "GET",
+ "auth": ["bearer"],
+ "folder": "compliance",
+ "files": {
+ "python": "get_jobs.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/compliance/batch-compliance/api-reference/get-compliance-jobs"
+ },
+ {
+ "name": "API Usage",
+ "path": "/usage/tweets",
+ "method": "GET",
+ "auth": ["bearer"],
+ "folder": "usage",
+ "files": {
+ "python": "get_usage.py"
+ },
+ "docs": "https://developer.x.com/en/docs/twitter-api/usage/api-reference/get-usage-tweets"
+ }
+ ]
+}
diff --git a/java/README.md b/java/README.md
new file mode 100644
index 0000000..44fbe43
--- /dev/null
+++ b/java/README.md
@@ -0,0 +1,64 @@
+# X API v2 - Java Examples
+
+Working Java code samples for the X (formerly Twitter) API v2.
+
+## Setup
+
+### 1. Install Java 11+
+
+```bash
+java --version
+```
+
+### 2. Add dependencies
+
+Using Maven, add to your `pom.xml`:
+
+```xml
+
+
+ org.apache.httpcomponents
+ httpclient
+ 4.5.13
+
+
+ com.google.code.gson
+ gson
+ 2.9.1
+
+
+```
+
+### 3. Set environment variables
+
+For **Bearer Token** authentication (app-only):
+```bash
+export BEARER_TOKEN='your_bearer_token'
+```
+
+## Examples by Category
+
+### Posts
+| File | Description | Auth |
+|------|-------------|------|
+| `posts/SearchRecent.java` | Search recent posts (7 days) | Bearer |
+
+### Users
+| File | Description | Auth |
+|------|-------------|------|
+| `users/Lookup.java` | Look up users by username | Bearer |
+
+## Building and Running
+
+```bash
+# Compile
+javac -cp ".:lib/*" posts/SearchRecent.java
+
+# Run
+java -cp ".:lib/*" SearchRecent
+```
+
+## 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/Full-Archive-Search/FullArchiveSearchDemo.java b/java/posts/FullArchiveSearchDemo.java
similarity index 96%
rename from Full-Archive-Search/FullArchiveSearchDemo.java
rename to java/posts/FullArchiveSearchDemo.java
index 90b9b32..9f058c2 100644
--- a/Full-Archive-Search/FullArchiveSearchDemo.java
+++ b/java/posts/FullArchiveSearchDemo.java
@@ -44,7 +44,7 @@ private static String search(String searchString, String bearerToken) throws IOE
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/tweets/search/all");
+ URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/search/all");
ArrayList queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("query", searchString));
diff --git a/Full-Archive-Tweet-Counts/FullArchiveTweetCountsDemo.java b/java/posts/FullArchiveTweetCountsDemo.java
similarity index 96%
rename from Full-Archive-Tweet-Counts/FullArchiveTweetCountsDemo.java
rename to java/posts/FullArchiveTweetCountsDemo.java
index 0c62c8b..65bb037 100644
--- a/Full-Archive-Tweet-Counts/FullArchiveTweetCountsDemo.java
+++ b/java/posts/FullArchiveTweetCountsDemo.java
@@ -44,7 +44,7 @@ private static String getTweetCounts(String searchString, String bearerToken) th
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/tweets/counts/all");
+ URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/counts/all");
ArrayList queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("query", searchString));
diff --git a/Quote-Tweets/QuoteTweetsDemo.java b/java/posts/QuoteTweetsDemo.java
similarity index 97%
rename from Quote-Tweets/QuoteTweetsDemo.java
rename to java/posts/QuoteTweetsDemo.java
index e83a971..e9fc858 100644
--- a/Quote-Tweets/QuoteTweetsDemo.java
+++ b/java/posts/QuoteTweetsDemo.java
@@ -44,7 +44,7 @@ private static String getTweets(int tweetId, String bearerToken) throws IOExcept
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder(String.format("https://api.twitter.com/2/tweets/%s/quote_tweets", tweetId));
+ 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"));
diff --git a/Recent-Search/RecentSearchDemo.java b/java/posts/RecentSearchDemo.java
similarity index 96%
rename from Recent-Search/RecentSearchDemo.java
rename to java/posts/RecentSearchDemo.java
index 9072908..e504b46 100644
--- a/Recent-Search/RecentSearchDemo.java
+++ b/java/posts/RecentSearchDemo.java
@@ -44,7 +44,7 @@ private static String search(String searchString, String bearerToken) throws IOE
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/tweets/search/recent");
+ URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/search/recent");
ArrayList queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("query", searchString));
diff --git a/Recent-Tweet-Counts/RecentTweetCountsDemo.java b/java/posts/RecentTweetCountsDemo.java
similarity index 96%
rename from Recent-Tweet-Counts/RecentTweetCountsDemo.java
rename to java/posts/RecentTweetCountsDemo.java
index 09723cf..1735b9c 100644
--- a/Recent-Tweet-Counts/RecentTweetCountsDemo.java
+++ b/java/posts/RecentTweetCountsDemo.java
@@ -44,7 +44,7 @@ private static String getTweetCounts(String searchString, String bearerToken) th
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/tweets/counts/recent");
+ URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/counts/recent");
ArrayList queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("query", searchString));
diff --git a/java/posts/SearchRecent.java b/java/posts/SearchRecent.java
new file mode 100644
index 0000000..9540c56
--- /dev/null
+++ b/java/posts/SearchRecent.java
@@ -0,0 +1,64 @@
+/**
+ * Recent Search - X API v2
+ *
+ * Endpoint: GET https://api.x.com/2/tweets/search/recent
+ * Docs: https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent
+ *
+ * Authentication: Bearer Token (App-only)
+ * Required env vars: BEARER_TOKEN
+ *
+ * Dependencies: org.apache.httpcomponents:httpclient, com.google.code.gson:gson
+ */
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.config.CookieSpecs;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.utils.URIBuilder;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+
+public class SearchRecent {
+
+ public static void main(String[] args) throws IOException, URISyntaxException {
+ String bearerToken = System.getenv("BEARER_TOKEN");
+
+ if (bearerToken == null) {
+ System.err.println("BEARER_TOKEN environment variable not set");
+ System.exit(1);
+ }
+
+ String response = search("from:XDevelopers -is:retweet", bearerToken);
+ System.out.println(response);
+ }
+
+ private static String search(String query, String bearerToken) throws IOException, URISyntaxException {
+ String searchUrl = "https://api.x.com/2/tweets/search/recent";
+
+ HttpClient httpClient = HttpClients.custom()
+ .setDefaultRequestConfig(RequestConfig.custom()
+ .setCookieSpec(CookieSpecs.STANDARD).build())
+ .build();
+
+ URIBuilder uriBuilder = new URIBuilder(searchUrl);
+ uriBuilder.addParameter("query", query);
+ uriBuilder.addParameter("tweet.fields", "author_id,created_at");
+
+ HttpGet httpGet = new HttpGet(uriBuilder.build());
+ httpGet.setHeader("Authorization", "Bearer " + bearerToken);
+ httpGet.setHeader("User-Agent", "v2RecentSearchJava");
+
+ HttpResponse response = httpClient.execute(httpGet);
+ HttpEntity entity = response.getEntity();
+
+ if (entity != null) {
+ return EntityUtils.toString(entity, "UTF-8");
+ } else {
+ return "No response";
+ }
+ }
+}
diff --git a/Tweet-Lookup/TweetsDemo.java b/java/posts/TweetsDemo.java
similarity index 96%
rename from Tweet-Lookup/TweetsDemo.java
rename to java/posts/TweetsDemo.java
index c197ca4..60c41e6 100644
--- a/Tweet-Lookup/TweetsDemo.java
+++ b/java/posts/TweetsDemo.java
@@ -44,7 +44,7 @@ private static String getTweets(String ids, String bearerToken) throws IOExcepti
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/tweets");
+ URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets");
ArrayList queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("ids", ids));
diff --git a/Search-Spaces/SearchSpacesDemo.java b/java/spaces/SearchSpacesDemo.java
similarity index 96%
rename from Search-Spaces/SearchSpacesDemo.java
rename to java/spaces/SearchSpacesDemo.java
index bcde135..2e92b2a 100644
--- a/Search-Spaces/SearchSpacesDemo.java
+++ b/java/spaces/SearchSpacesDemo.java
@@ -44,7 +44,7 @@ private static String getSpaceById(String spaceId, String bearerToken) throws IO
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/spaces");
+ URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/spaces");
ArrayList queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("ids", spaceId));
diff --git a/Spaces-Lookup/SpacesLookupDemo.java b/java/spaces/SpacesLookupDemo.java
similarity index 96%
rename from Spaces-Lookup/SpacesLookupDemo.java
rename to java/spaces/SpacesLookupDemo.java
index bcde135..2e92b2a 100644
--- a/Spaces-Lookup/SpacesLookupDemo.java
+++ b/java/spaces/SpacesLookupDemo.java
@@ -44,7 +44,7 @@ private static String getSpaceById(String spaceId, String bearerToken) throws IO
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/spaces");
+ URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/spaces");
ArrayList queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("ids", spaceId));
diff --git a/Filtered-Stream/FilteredStreamDemo.java b/java/streams/FilteredStreamDemo.java
similarity index 94%
rename from Filtered-Stream/FilteredStreamDemo.java
rename to java/streams/FilteredStreamDemo.java
index ea23fb1..6a30c85 100644
--- a/Filtered-Stream/FilteredStreamDemo.java
+++ b/java/streams/FilteredStreamDemo.java
@@ -46,7 +46,7 @@ private static void connectStream(String bearerToken) throws IOException, URISyn
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/tweets/search/stream");
+ 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));
@@ -84,7 +84,7 @@ private static void createRules(String bearerToken, Map rules) t
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/tweets/search/stream/rules");
+ 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));
@@ -108,7 +108,7 @@ private static List getRules(String bearerToken) throws URISyntaxExcepti
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/tweets/search/stream/rules");
+ 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));
@@ -137,7 +137,7 @@ private static void deleteRules(String bearerToken, List existingRules)
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/tweets/search/stream/rules");
+ 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));
diff --git a/Sampled-Stream/SampledStream.java b/java/streams/SampledStream.java
similarity index 95%
rename from Sampled-Stream/SampledStream.java
rename to java/streams/SampledStream.java
index 001cb95..4d0444e 100644
--- a/Sampled-Stream/SampledStream.java
+++ b/java/streams/SampledStream.java
@@ -40,7 +40,7 @@ private static void connectStream(String bearerToken) throws IOException, URISyn
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/tweets/sample/stream");
+ 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));
diff --git a/User-Mention-Timeline/UserMentionsDemo.java b/java/timelines/UserMentionsDemo.java
similarity index 97%
rename from User-Mention-Timeline/UserMentionsDemo.java
rename to java/timelines/UserMentionsDemo.java
index ea36b4a..efff5a3 100644
--- a/User-Mention-Timeline/UserMentionsDemo.java
+++ b/java/timelines/UserMentionsDemo.java
@@ -44,7 +44,7 @@ private static String getTweets(String userId, String bearerToken) throws IOExce
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder(String.format("https://api.twitter.com/2/users/%s/mentions", userId));
+ 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"));
diff --git a/User-Tweet-Timeline/UserTweetsDemo.java b/java/timelines/UserTweetsDemo.java
similarity index 98%
rename from User-Tweet-Timeline/UserTweetsDemo.java
rename to java/timelines/UserTweetsDemo.java
index 19df235..d0b1edb 100644
--- a/User-Tweet-Timeline/UserTweetsDemo.java
+++ b/java/timelines/UserTweetsDemo.java
@@ -44,7 +44,7 @@ private static String getTweets(String userId, String bearerToken) throws IOExce
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder(String.format("https://api.twitter.com/2/users/%s/tweets", userId));
+ 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"));
diff --git a/Reverse-Chron-Home-Timeline/OAuth2-user/reverse-chron-home-timeline-java-sdk.java b/java/timelines/reverse-chron-home-timeline-java-sdk.java
similarity index 100%
rename from Reverse-Chron-Home-Timeline/OAuth2-user/reverse-chron-home-timeline-java-sdk.java
rename to java/timelines/reverse-chron-home-timeline-java-sdk.java
diff --git a/Usage Tweets/UsageTweetsDemo.java b/java/usage/UsageTweetsDemo.java
similarity index 96%
rename from Usage Tweets/UsageTweetsDemo.java
rename to java/usage/UsageTweetsDemo.java
index 38f588f..ecae4b7 100644
--- a/Usage Tweets/UsageTweetsDemo.java
+++ b/java/usage/UsageTweetsDemo.java
@@ -43,7 +43,7 @@ private static String getUsageTweets(String bearerToken) throws IOException, URI
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/usage/tweets");
+ 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");
diff --git a/Follows-Lookup/FollowersLookupDemo.java b/java/users/FollowersLookupDemo.java
similarity index 97%
rename from Follows-Lookup/FollowersLookupDemo.java
rename to java/users/FollowersLookupDemo.java
index aa99ba1..015d8f8 100644
--- a/Follows-Lookup/FollowersLookupDemo.java
+++ b/java/users/FollowersLookupDemo.java
@@ -44,7 +44,7 @@ private static String getFollowers(String userId, String bearerToken) throws IOE
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder(String.format("https://api.twitter.com/2/users/%s/followers", userId));
+ 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"));
diff --git a/Follows-Lookup/FollowingLookupDemo.java b/java/users/FollowingLookupDemo.java
similarity index 97%
rename from Follows-Lookup/FollowingLookupDemo.java
rename to java/users/FollowingLookupDemo.java
index 12c9867..6b1d453 100644
--- a/Follows-Lookup/FollowingLookupDemo.java
+++ b/java/users/FollowingLookupDemo.java
@@ -44,7 +44,7 @@ private static String getFollowing(String userId, String bearerToken) throws IOE
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder(String.format("https://api.twitter.com/2/users/%s/following", userId));
+ 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"));
diff --git a/java/users/Lookup.java b/java/users/Lookup.java
new file mode 100644
index 0000000..ff0d781
--- /dev/null
+++ b/java/users/Lookup.java
@@ -0,0 +1,64 @@
+/**
+ * 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/User-Lookup/UsersDemo.java b/java/users/UsersDemo.java
similarity index 96%
rename from User-Lookup/UsersDemo.java
rename to java/users/UsersDemo.java
index 51826a1..f9fd8c9 100644
--- a/User-Lookup/UsersDemo.java
+++ b/java/users/UsersDemo.java
@@ -44,7 +44,7 @@ private static String getUsers(String usernames, String bearerToken) throws IOEx
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
- URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/users/by");
+ URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/users/by");
ArrayList queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("usernames", usernames));
diff --git a/javascript/README.md b/javascript/README.md
new file mode 100644
index 0000000..216afe5
--- /dev/null
+++ b/javascript/README.md
@@ -0,0 +1,78 @@
+# X API v2 - JavaScript (Node.js) Examples
+
+Working JavaScript code samples for the X (formerly Twitter) API v2.
+
+## Setup
+
+### 1. Install Node.js 14+
+
+```bash
+node --version
+```
+
+### 2. Install dependencies
+
+```bash
+npm install
+```
+
+### 3. Set environment variables
+
+For **Bearer Token** authentication (app-only):
+```bash
+export BEARER_TOKEN='your_bearer_token'
+```
+
+For **OAuth 1.0a** authentication (user context):
+```bash
+export CONSUMER_KEY='your_consumer_key'
+export CONSUMER_SECRET='your_consumer_secret'
+```
+
+## Examples by Category
+
+### Posts
+| File | Description | Auth |
+|------|-------------|------|
+| `posts/create_post.js` | Create a new post | OAuth 1.0a |
+| `posts/delete_post.js` | Delete a post | OAuth 1.0a |
+| `posts/lookup.js` | Look up posts by ID | Bearer |
+| `posts/search_recent.js` | Search recent posts (7 days) | Bearer |
+
+### Users
+| File | Description | Auth |
+|------|-------------|------|
+| `users/lookup.js` | Look up users by username | Bearer |
+| `users/followers.js` | Get user's followers | Bearer |
+
+### Timelines
+| File | Description | Auth |
+|------|-------------|------|
+| `timelines/user_posts.js` | User's posts timeline | Bearer |
+
+### Streams
+| File | Description | Auth |
+|------|-------------|------|
+| `streams/filtered_stream.js` | Filtered stream with rules | Bearer |
+
+### Lists
+| File | Description | Auth |
+|------|-------------|------|
+| `lists/lookup.js` | Look up a list | Bearer |
+
+### Spaces
+| File | Description | Auth |
+|------|-------------|------|
+| `spaces/lookup.js` | Look up Spaces | Bearer |
+
+## Running Examples
+
+```bash
+# Make sure environment variables are set
+node posts/search_recent.js
+```
+
+## More Information
+
+- [X API Documentation](https://developer.x.com/en/docs/twitter-api)
+- [X Developer Portal](https://developer.x.com/en/portal/dashboard)
diff --git a/Bookmarks-lookup/bookmarks-lookup-js-sdk.js b/javascript/bookmarks/bookmarks-lookup-js-sdk.js
similarity index 100%
rename from Bookmarks-lookup/bookmarks-lookup-js-sdk.js
rename to javascript/bookmarks/bookmarks-lookup-js-sdk.js
diff --git a/Manage-Bookmarks/create-bookmark-js-sdk.js b/javascript/bookmarks/create-bookmark-js-sdk.js
similarity index 100%
rename from Manage-Bookmarks/create-bookmark-js-sdk.js
rename to javascript/bookmarks/create-bookmark-js-sdk.js
diff --git a/Manage-Bookmarks/delete-bookmark-js-sdk.js b/javascript/bookmarks/delete-bookmark-js-sdk.js
similarity index 100%
rename from Manage-Bookmarks/delete-bookmark-js-sdk.js
rename to javascript/bookmarks/delete-bookmark-js-sdk.js
diff --git a/Batch-Compliance/js/create_compliance_job.js b/javascript/compliance/create_compliance_job.js
similarity index 94%
rename from Batch-Compliance/js/create_compliance_job.js
rename to javascript/compliance/create_compliance_job.js
index 4d8c170..14e6dee 100644
--- a/Batch-Compliance/js/create_compliance_job.js
+++ b/javascript/compliance/create_compliance_job.js
@@ -5,7 +5,7 @@ const needle = require('needle');
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
-const endpointUrl = 'https://api.twitter.com/2/compliance/jobs'
+const endpointUrl = 'https://api.x.com/2/compliance/jobs'
// For User Compliance Job, replace type value with users instead of tweets
// Also replace the name value with your desired job name
diff --git a/Batch-Compliance/js/download_compliance_results.js b/javascript/compliance/download_compliance_results.js
similarity index 100%
rename from Batch-Compliance/js/download_compliance_results.js
rename to javascript/compliance/download_compliance_results.js
diff --git a/Batch-Compliance/js/get_compliance_job_information_by_id.js b/javascript/compliance/get_compliance_job_information_by_id.js
similarity index 92%
rename from Batch-Compliance/js/get_compliance_job_information_by_id.js
rename to javascript/compliance/get_compliance_job_information_by_id.js
index 93bbd29..18e85a9 100644
--- a/Batch-Compliance/js/get_compliance_job_information_by_id.js
+++ b/javascript/compliance/get_compliance_job_information_by_id.js
@@ -8,7 +8,7 @@ const token = process.env.BEARER_TOKEN;
// Replace with your job ID
jobId = ''
-const endpointUrl = `https://api.twitter.com/2/compliance/jobs/${jobId}`
+const endpointUrl = `https://api.x.com/2/compliance/jobs/${jobId}`
async function getRequest() {
diff --git a/Batch-Compliance/js/get_list_of_compliance_jobs.js b/javascript/compliance/get_list_of_compliance_jobs.js
similarity index 93%
rename from Batch-Compliance/js/get_list_of_compliance_jobs.js
rename to javascript/compliance/get_list_of_compliance_jobs.js
index b878559..b52e55e 100644
--- a/Batch-Compliance/js/get_list_of_compliance_jobs.js
+++ b/javascript/compliance/get_list_of_compliance_jobs.js
@@ -5,7 +5,7 @@ const needle = require('needle');
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
-const endpointUrl = 'https://api.twitter.com/2/compliance/jobs'
+const endpointUrl = 'https://api.x.com/2/compliance/jobs'
// For User Compliance job, replace the value for type with users
const params = {
diff --git a/Batch-Compliance/js/upload_ids.js b/javascript/compliance/upload_ids.js
similarity index 100%
rename from Batch-Compliance/js/upload_ids.js
rename to javascript/compliance/upload_ids.js
diff --git a/List-lookup/List-Tweets-lookup/List-tweets.js b/javascript/lists/List-tweets.js
similarity index 94%
rename from List-lookup/List-Tweets-lookup/List-tweets.js
rename to javascript/lists/List-tweets.js
index 06a4b03..57783fc 100644
--- a/List-lookup/List-Tweets-lookup/List-tweets.js
+++ b/javascript/lists/List-tweets.js
@@ -6,7 +6,7 @@ const needle = require("needle");
const token = process.env.BEARER_TOKEN;
const id = "list-id";
-const endpointURL = `https://api.twitter.com/2/lists/${id}/tweets`;
+const endpointURL = `https://api.x.com/2/lists/${id}/tweets`;
async function getRequest() {
// These are the parameters for the API request
diff --git a/List-lookup/Pinned-Lists-lookup/Pinned-List.js b/javascript/lists/Pinned-List.js
similarity index 90%
rename from List-lookup/Pinned-Lists-lookup/Pinned-List.js
rename to javascript/lists/Pinned-List.js
index 1f52c40..d11de05 100644
--- a/List-lookup/Pinned-Lists-lookup/Pinned-List.js
+++ b/javascript/lists/Pinned-List.js
@@ -28,13 +28,13 @@ const params = {
"user.fields": `created_at,verified`, // Edit optional query parameters here
};
-const endpointURL = `https://api.twitter.com/2/users/${id}/pinned_lists`;
+const endpointURL = `https://api.x.com/2/users/${id}/pinned_lists`;
// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
- "https://api.twitter.com/oauth/request_token?oauth_callback=oob";
-const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
-const accessTokenURL = "https://api.twitter.com/oauth/access_token";
+ "https://api.x.com/oauth/request_token?oauth_callback=oob";
+const authorizeURL = new URL("https://api.x.com/oauth/authorize");
+const accessTokenURL = "https://api.x.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -81,7 +81,7 @@ async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
method: "POST",
})
);
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
diff --git a/Manage-Lists/Manage-List-Members/add_member.js b/javascript/lists/add_member.js
similarity index 90%
rename from Manage-Lists/Manage-List-Members/add_member.js
rename to javascript/lists/add_member.js
index 37458c3..0c5befa 100644
--- a/Manage-Lists/Manage-List-Members/add_member.js
+++ b/javascript/lists/add_member.js
@@ -26,13 +26,13 @@ const data = {
user_id: "user-id-to-add",
};
-const endpointURL = `https://api.twitter.com/2/lists/${id}/members`;
+const endpointURL = `https://api.x.com/2/lists/${id}/members`;
// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
- "https://api.twitter.com/oauth/request_token?oauth_callback=oob";
-const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
-const accessTokenURL = "https://api.twitter.com/oauth/access_token";
+ "https://api.x.com/oauth/request_token?oauth_callback=oob";
+const authorizeURL = new URL("https://api.x.com/oauth/authorize");
+const accessTokenURL = "https://api.x.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -79,7 +79,7 @@ async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
method: "POST",
})
);
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
diff --git a/Manage-Lists/create_a_list.js b/javascript/lists/create_a_list.js
similarity index 90%
rename from Manage-Lists/create_a_list.js
rename to javascript/lists/create_a_list.js
index d4ac6e1..4a60525 100644
--- a/Manage-Lists/create_a_list.js
+++ b/javascript/lists/create_a_list.js
@@ -25,13 +25,13 @@ const data = {
private: false,
};
-const endpointURL = `https://api.twitter.com/2/lists`;
+const endpointURL = `https://api.x.com/2/lists`;
// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
- "https://api.twitter.com/oauth/request_token?oauth_callback=oob";
-const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
-const accessTokenURL = "https://api.twitter.com/oauth/access_token";
+ "https://api.x.com/oauth/request_token?oauth_callback=oob";
+const authorizeURL = new URL("https://api.x.com/oauth/authorize");
+const accessTokenURL = "https://api.x.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -78,7 +78,7 @@ async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
method: "POST",
})
);
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
diff --git a/Manage-Lists/delete_a_list.js b/javascript/lists/delete_a_list.js
similarity index 90%
rename from Manage-Lists/delete_a_list.js
rename to javascript/lists/delete_a_list.js
index 918a625..75d55de 100644
--- a/Manage-Lists/delete_a_list.js
+++ b/javascript/lists/delete_a_list.js
@@ -20,13 +20,13 @@ const consumer_secret = process.env.CONSUMER_SECRET;
// Be sure to add replace the your-list-id with the id of the list you wish to delete.
const target_list_id = "your-list-id";
-const endpointURL = `https://api.twitter.com/2/lists/${target_list_id}`;
+const endpointURL = `https://api.x.com/2/lists/${target_list_id}`;
// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
- "https://api.twitter.com/oauth/request_token?oauth_callback=oob";
-const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
-const accessTokenURL = "https://api.twitter.com/oauth/access_token";
+ "https://api.x.com/oauth/request_token?oauth_callback=oob";
+const authorizeURL = new URL("https://api.x.com/oauth/authorize");
+const accessTokenURL = "https://api.x.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -73,7 +73,7 @@ async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
method: "POST",
})
);
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
diff --git a/Manage-Lists/Manage-Followed-Lists/follow_list.js b/javascript/lists/follow_list.js
similarity index 90%
rename from Manage-Lists/Manage-Followed-Lists/follow_list.js
rename to javascript/lists/follow_list.js
index a4ec8d0..ed0cc4b 100644
--- a/Manage-Lists/Manage-Followed-Lists/follow_list.js
+++ b/javascript/lists/follow_list.js
@@ -27,13 +27,13 @@ const data = {
list_id: "list-id-to-follow",
};
-const endpointURL = `https://api.twitter.com/2/users/${id}/followed_lists`;
+const endpointURL = `https://api.x.com/2/users/${id}/followed_lists`;
// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
- "https://api.twitter.com/oauth/request_token?oauth_callback=oob";
-const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
-const accessTokenURL = "https://api.twitter.com/oauth/access_token";
+ "https://api.x.com/oauth/request_token?oauth_callback=oob";
+const authorizeURL = new URL("https://api.x.com/oauth/authorize");
+const accessTokenURL = "https://api.x.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -80,7 +80,7 @@ async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
method: "POST",
})
);
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
diff --git a/List-lookup/List-follows-lookup/list-followers-lookup.js b/javascript/lists/list-followers-lookup.js
similarity index 94%
rename from List-lookup/List-follows-lookup/list-followers-lookup.js
rename to javascript/lists/list-followers-lookup.js
index cac4f15..abae1a7 100644
--- a/List-lookup/List-follows-lookup/list-followers-lookup.js
+++ b/javascript/lists/list-followers-lookup.js
@@ -6,7 +6,7 @@ const needle = require("needle");
const token = process.env.BEARER_TOKEN;
const id = "list-id";
-const endpointURL = `https://api.twitter.com/2/lists/${id}/followers`;
+const endpointURL = `https://api.x.com/2/lists/${id}/followers`;
async function getRequest() {
// These are the parameters for the API request
diff --git a/List-lookup/list-lookup-by-id.js b/javascript/lists/list-lookup-by-id.js
similarity index 95%
rename from List-lookup/list-lookup-by-id.js
rename to javascript/lists/list-lookup-by-id.js
index 8c562ac..1a04544 100644
--- a/List-lookup/list-lookup-by-id.js
+++ b/javascript/lists/list-lookup-by-id.js
@@ -6,7 +6,7 @@ const needle = require("needle");
const token = process.env.BEARER_TOKEN;
const id = "list-id";
-const endpointURL = `https://api.twitter.com/2/lists/${id}`;
+const endpointURL = `https://api.x.com/2/lists/${id}`;
async function getRequest() {
// These are the parameters for the API request
diff --git a/List-lookup/List-members-lookup/list-member-lookup.js b/javascript/lists/list-member-lookup.js
similarity index 94%
rename from List-lookup/List-members-lookup/list-member-lookup.js
rename to javascript/lists/list-member-lookup.js
index bab37fb..ebd86a9 100644
--- a/List-lookup/List-members-lookup/list-member-lookup.js
+++ b/javascript/lists/list-member-lookup.js
@@ -6,7 +6,7 @@ const needle = require("needle");
const token = process.env.BEARER_TOKEN;
const id = "list-id";
-const endpointURL = `https://api.twitter.com/2/lists/${id}/members`;
+const endpointURL = `https://api.x.com/2/lists/${id}/members`;
async function getRequest() {
// These are the parameters for the API request
diff --git a/javascript/lists/lookup.js b/javascript/lists/lookup.js
new file mode 100644
index 0000000..868e8d3
--- /dev/null
+++ b/javascript/lists/lookup.js
@@ -0,0 +1,47 @@
+/**
+ * List Lookup - X API v2
+ *
+ * Endpoint: GET https://api.x.com/2/lists/:id
+ * Docs: https://developer.x.com/en/docs/twitter-api/lists/list-lookup/api-reference/get-lists-id
+ *
+ * Authentication: Bearer Token (App-only) or OAuth (User Context)
+ * Required env vars: BEARER_TOKEN
+ */
+
+const needle = require('needle');
+
+const token = process.env.BEARER_TOKEN;
+
+// Replace with the list ID you want to look up
+const listId = "84839422";
+const endpointURL = `https://api.x.com/2/lists/${listId}`;
+
+async function getRequest() {
+ const params = {
+ "list.fields": "created_at,follower_count,member_count,owner_id,description"
+ };
+
+ const res = await needle('get', endpointURL, params, {
+ headers: {
+ "User-Agent": "v2ListLookupJS",
+ "authorization": `Bearer ${token}`
+ }
+ });
+
+ if (res.body) {
+ return res.body;
+ } else {
+ throw new Error('Unsuccessful request');
+ }
+}
+
+(async () => {
+ try {
+ const response = await getRequest();
+ console.dir(response, { depth: null });
+ } catch (e) {
+ console.log(e);
+ process.exit(-1);
+ }
+ process.exit();
+})();
diff --git a/Manage-Lists/Manage-Pinned-Lists/pin_list.js b/javascript/lists/pin_list.js
similarity index 90%
rename from Manage-Lists/Manage-Pinned-Lists/pin_list.js
rename to javascript/lists/pin_list.js
index 8430e61..a2a2ac6 100644
--- a/Manage-Lists/Manage-Pinned-Lists/pin_list.js
+++ b/javascript/lists/pin_list.js
@@ -27,13 +27,13 @@ const data = {
list_id: "list-id-to-pin",
};
-const endpointURL = `https://api.twitter.com/2/users/${id}/pinned_lists`;
+const endpointURL = `https://api.x.com/2/users/${id}/pinned_lists`;
// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
- "https://api.twitter.com/oauth/request_token?oauth_callback=oob";
-const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
-const accessTokenURL = "https://api.twitter.com/oauth/access_token";
+ "https://api.x.com/oauth/request_token?oauth_callback=oob";
+const authorizeURL = new URL("https://api.x.com/oauth/authorize");
+const accessTokenURL = "https://api.x.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -80,7 +80,7 @@ async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
method: "POST",
})
);
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
diff --git a/Manage-Lists/Manage-List-Members/remove_member.js b/javascript/lists/remove_member.js
similarity index 90%
rename from Manage-Lists/Manage-List-Members/remove_member.js
rename to javascript/lists/remove_member.js
index 2ec42e2..0059a2b 100644
--- a/Manage-Lists/Manage-List-Members/remove_member.js
+++ b/javascript/lists/remove_member.js
@@ -25,13 +25,13 @@ const id = "your-list-id";
const user_id = "user-id-to-remove";
-const endpointURL = `https://api.twitter.com/2/lists/${id}/members/${user_id}`;
+const endpointURL = `https://api.x.com/2/lists/${id}/members/${user_id}`;
// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
- "https://api.twitter.com/oauth/request_token?oauth_callback=oob";
-const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
-const accessTokenURL = "https://api.twitter.com/oauth/access_token";
+ "https://api.x.com/oauth/request_token?oauth_callback=oob";
+const authorizeURL = new URL("https://api.x.com/oauth/authorize");
+const accessTokenURL = "https://api.x.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -78,7 +78,7 @@ async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
method: "POST",
})
);
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
diff --git a/Manage-Lists/Manage-Followed-Lists/unfollow_list.js b/javascript/lists/unfollow_list.js
similarity index 90%
rename from Manage-Lists/Manage-Followed-Lists/unfollow_list.js
rename to javascript/lists/unfollow_list.js
index 7138fc9..7d47e23 100644
--- a/Manage-Lists/Manage-Followed-Lists/unfollow_list.js
+++ b/javascript/lists/unfollow_list.js
@@ -25,13 +25,13 @@ const id = "your-user-id";
const list_id = "list-id-to-unfollow";
-const endpointURL = `https://api.twitter.com/2/users/${id}/followed_lists/${list_id}`;
+const endpointURL = `https://api.x.com/2/users/${id}/followed_lists/${list_id}`;
// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
- "https://api.twitter.com/oauth/request_token?oauth_callback=oob";
-const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
-const accessTokenURL = "https://api.twitter.com/oauth/access_token";
+ "https://api.x.com/oauth/request_token?oauth_callback=oob";
+const authorizeURL = new URL("https://api.x.com/oauth/authorize");
+const accessTokenURL = "https://api.x.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -78,7 +78,7 @@ async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
method: "POST",
})
);
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
diff --git a/Manage-Lists/Manage-Pinned-Lists/unpin_list.js b/javascript/lists/unpin_list.js
similarity index 90%
rename from Manage-Lists/Manage-Pinned-Lists/unpin_list.js
rename to javascript/lists/unpin_list.js
index a7db4ca..1cfdc8c 100644
--- a/Manage-Lists/Manage-Pinned-Lists/unpin_list.js
+++ b/javascript/lists/unpin_list.js
@@ -25,13 +25,13 @@ const id = "your-user-id";
const list_id = "list-id-to-unpin";
-const endpointURL = `https://api.twitter.com/2/users/${id}/pinned_lists/${list_id}`;
+const endpointURL = `https://api.x.com/2/users/${id}/pinned_lists/${list_id}`;
// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
- "https://api.twitter.com/oauth/request_token?oauth_callback=oob";
-const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
-const accessTokenURL = "https://api.twitter.com/oauth/access_token";
+ "https://api.x.com/oauth/request_token?oauth_callback=oob";
+const authorizeURL = new URL("https://api.x.com/oauth/authorize");
+const accessTokenURL = "https://api.x.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -78,7 +78,7 @@ async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
method: "POST",
})
);
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
diff --git a/Manage-Lists/update_a_list.js b/javascript/lists/update_a_list.js
similarity index 90%
rename from Manage-Lists/update_a_list.js
rename to javascript/lists/update_a_list.js
index 58196f6..7c6d428 100644
--- a/Manage-Lists/update_a_list.js
+++ b/javascript/lists/update_a_list.js
@@ -28,13 +28,13 @@ const data = {
// Be sure to add replace the your-list-id with the list id of the list you wish to update.
const target_list_id = "your-list-id";
-const endpointURL = `https://api.twitter.com/2/lists/${target_list_id}`;
+const endpointURL = `https://api.x.com/2/lists/${target_list_id}`;
// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
- "https://api.twitter.com/oauth/request_token?oauth_callback=oob";
-const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
-const accessTokenURL = "https://api.twitter.com/oauth/access_token";
+ "https://api.x.com/oauth/request_token?oauth_callback=oob";
+const authorizeURL = new URL("https://api.x.com/oauth/authorize");
+const accessTokenURL = "https://api.x.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -81,7 +81,7 @@ async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
method: "POST",
})
);
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
diff --git a/List-lookup/List-follows-lookup/user-list-followed.js b/javascript/lists/user-list-followed.js
similarity index 94%
rename from List-lookup/List-follows-lookup/user-list-followed.js
rename to javascript/lists/user-list-followed.js
index 57b151b..7bf4a52 100644
--- a/List-lookup/List-follows-lookup/user-list-followed.js
+++ b/javascript/lists/user-list-followed.js
@@ -6,7 +6,7 @@ const needle = require("needle");
const token = process.env.BEARER_TOKEN;
const id = "user-id";
-const endpointURL = `https://api.twitter.com/2/users/${id}/followed_lists`;
+const endpointURL = `https://api.x.com/2/users/${id}/followed_lists`;
async function getRequest() {
// These are the parameters for the API request
diff --git a/List-lookup/List-members-lookup/user-list-memberships.js b/javascript/lists/user-list-memberships.js
similarity index 94%
rename from List-lookup/List-members-lookup/user-list-memberships.js
rename to javascript/lists/user-list-memberships.js
index 5bdf590..fa196c4 100644
--- a/List-lookup/List-members-lookup/user-list-memberships.js
+++ b/javascript/lists/user-list-memberships.js
@@ -6,7 +6,7 @@ const needle = require("needle");
const token = process.env.BEARER_TOKEN;
const id = "user-id";
-const endpointURL = `https://api.twitter.com/2/users/${id}/list_memberships`;
+const endpointURL = `https://api.x.com/2/users/${id}/list_memberships`;
async function getRequest() {
// These are the parameters for the API request
diff --git a/List-lookup/user-owned-list-lookup.js b/javascript/lists/user-owned-list-lookup.js
similarity index 94%
rename from List-lookup/user-owned-list-lookup.js
rename to javascript/lists/user-owned-list-lookup.js
index e36444c..f695cf8 100644
--- a/List-lookup/user-owned-list-lookup.js
+++ b/javascript/lists/user-owned-list-lookup.js
@@ -6,7 +6,7 @@ const needle = require("needle");
const token = process.env.BEARER_TOKEN;
const id = "user-id";
-const endpointURL = `https://api.twitter.com/2/users/${id}/owned_lists`;
+const endpointURL = `https://api.x.com/2/users/${id}/owned_lists`;
async function getRequest() {
// These are the parameters for the API request
diff --git a/Manage-Blocks/block_a_user.js b/javascript/posts/block_a_user.js
similarity index 89%
rename from Manage-Blocks/block_a_user.js
rename to javascript/posts/block_a_user.js
index 08e4a6c..626b027 100644
--- a/Manage-Blocks/block_a_user.js
+++ b/javascript/posts/block_a_user.js
@@ -29,12 +29,12 @@ const data = {
"target_user_id": "id-to-block"
}
-const endpointURL = `https://api.twitter.com/2/users/${id}/blocking`;
+const endpointURL = `https://api.x.com/2/users/${id}/blocking`;
// this example uses PIN-based OAuth to authorize the user
-const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob';
-const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
-const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -80,7 +80,7 @@ async function accessToken({
url: accessTokenURL,
method: 'POST'
}));
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"]
diff --git a/javascript/posts/create_post.js b/javascript/posts/create_post.js
new file mode 100644
index 0000000..956efd1
--- /dev/null
+++ b/javascript/posts/create_post.js
@@ -0,0 +1,134 @@
+/**
+ * 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 1.0a (User Context)
+ * Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+ */
+
+const got = require('got');
+const crypto = require('crypto');
+const OAuth = require('oauth-1.0a');
+const qs = require('querystring');
+const readline = require('readline').createInterface({
+ input: process.stdin,
+ output: process.stdout
+});
+
+const consumer_key = process.env.CONSUMER_KEY;
+const consumer_secret = process.env.CONSUMER_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!"
+};
+
+const endpointURL = 'https://api.x.com/2/tweets';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
+
+const oauth = OAuth({
+ consumer: {
+ key: consumer_key,
+ secret: consumer_secret
+ },
+ signature_method: 'HMAC-SHA1',
+ hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
+});
+
+async function input(prompt) {
+ return new Promise(async (resolve, reject) => {
+ readline.question(prompt, (out) => {
+ readline.close();
+ resolve(out);
+ });
+ });
+}
+
+async function requestToken() {
+ const authHeader = oauth.toHeader(oauth.authorize({
+ url: requestTokenURL,
+ method: 'POST'
+ }));
+
+ const req = await got.post(requestTokenURL, {
+ headers: {
+ Authorization: authHeader["Authorization"]
+ }
+ });
+ if (req.body) {
+ return qs.parse(req.body);
+ } else {
+ throw new Error('Cannot get an OAuth request token');
+ }
+}
+
+async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
+ const authHeader = oauth.toHeader(oauth.authorize({
+ url: accessTokenURL,
+ method: 'POST'
+ }));
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const req = await got.post(path, {
+ headers: {
+ Authorization: authHeader["Authorization"]
+ }
+ });
+ if (req.body) {
+ return qs.parse(req.body);
+ } else {
+ throw new Error('Cannot get an OAuth request token');
+ }
+}
+
+async function createPost({ oauth_token, oauth_token_secret }) {
+ const token = {
+ key: oauth_token,
+ secret: oauth_token_secret
+ };
+
+ const authHeader = oauth.toHeader(oauth.authorize({
+ url: endpointURL,
+ method: 'POST'
+ }, token));
+
+ const req = await got.post(endpointURL, {
+ json: data,
+ responseType: 'json',
+ headers: {
+ Authorization: authHeader["Authorization"],
+ 'user-agent': "v2CreatePostJS",
+ 'content-type': "application/json",
+ 'accept': "application/json"
+ }
+ });
+ if (req.body) {
+ return req.body;
+ } else {
+ throw new Error('Unsuccessful request');
+ }
+}
+
+(async () => {
+ try {
+ // Get request token
+ const oAuthRequestToken = await requestToken();
+ // Get authorization
+ authorizeURL.searchParams.append('oauth_token', oAuthRequestToken.oauth_token);
+ console.log('Please go here and authorize:', authorizeURL.href);
+ const pin = await input('Paste the PIN here: ');
+ // Get the access token
+ const oAuthAccessToken = await accessToken(oAuthRequestToken, pin.trim());
+ // Make the request
+ const response = await createPost(oAuthAccessToken);
+ console.dir(response, { depth: null });
+ } catch (e) {
+ console.log(e);
+ process.exit(-1);
+ }
+ process.exit();
+})();
diff --git a/Manage-Tweets/create_tweet.js b/javascript/posts/create_tweet.js
similarity index 89%
rename from Manage-Tweets/create_tweet.js
rename to javascript/posts/create_tweet.js
index 64de55a..eb15cec 100644
--- a/Manage-Tweets/create_tweet.js
+++ b/javascript/posts/create_tweet.js
@@ -23,12 +23,12 @@ const data = {
"text": "Hello world!"
};
-const endpointURL = `https://api.twitter.com/2/tweets`;
+const endpointURL = `https://api.x.com/2/tweets`;
// this example uses PIN-based OAuth to authorize the user
-const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write';
-const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
-const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -74,7 +74,7 @@ async function accessToken({
url: accessTokenURL,
method: 'POST'
}));
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"]
diff --git a/javascript/posts/delete_post.js b/javascript/posts/delete_post.js
new file mode 100644
index 0000000..3d36b84
--- /dev/null
+++ b/javascript/posts/delete_post.js
@@ -0,0 +1,124 @@
+/**
+ * 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 1.0a (User Context)
+ * Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+ */
+
+const got = require('got');
+const crypto = require('crypto');
+const OAuth = require('oauth-1.0a');
+const qs = require('querystring');
+const readline = require('readline').createInterface({
+ input: process.stdin,
+ output: process.stdout
+});
+
+const consumer_key = process.env.CONSUMER_KEY;
+const consumer_secret = process.env.CONSUMER_SECRET;
+
+// Replace with the post ID you want to delete
+const postId = "post-id-to-delete";
+const endpointURL = `https://api.x.com/2/tweets/${postId}`;
+
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
+
+const oauth = OAuth({
+ consumer: {
+ key: consumer_key,
+ secret: consumer_secret
+ },
+ signature_method: 'HMAC-SHA1',
+ hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
+});
+
+async function input(prompt) {
+ return new Promise(async (resolve, reject) => {
+ readline.question(prompt, (out) => {
+ readline.close();
+ resolve(out);
+ });
+ });
+}
+
+async function requestToken() {
+ const authHeader = oauth.toHeader(oauth.authorize({
+ url: requestTokenURL,
+ method: 'POST'
+ }));
+
+ const req = await got.post(requestTokenURL, {
+ headers: {
+ Authorization: authHeader["Authorization"]
+ }
+ });
+ if (req.body) {
+ return qs.parse(req.body);
+ } else {
+ throw new Error('Cannot get an OAuth request token');
+ }
+}
+
+async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
+ const authHeader = oauth.toHeader(oauth.authorize({
+ url: accessTokenURL,
+ method: 'POST'
+ }));
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const req = await got.post(path, {
+ headers: {
+ Authorization: authHeader["Authorization"]
+ }
+ });
+ if (req.body) {
+ return qs.parse(req.body);
+ } else {
+ throw new Error('Cannot get an OAuth request token');
+ }
+}
+
+async function deletePost({ oauth_token, oauth_token_secret }) {
+ const token = {
+ key: oauth_token,
+ secret: oauth_token_secret
+ };
+
+ const authHeader = oauth.toHeader(oauth.authorize({
+ url: endpointURL,
+ method: 'DELETE'
+ }, token));
+
+ const req = await got.delete(endpointURL, {
+ responseType: 'json',
+ headers: {
+ Authorization: authHeader["Authorization"],
+ 'user-agent': "v2DeletePostJS"
+ }
+ });
+ if (req.body) {
+ return req.body;
+ } else {
+ throw new Error('Unsuccessful request');
+ }
+}
+
+(async () => {
+ try {
+ const oAuthRequestToken = await requestToken();
+ authorizeURL.searchParams.append('oauth_token', oAuthRequestToken.oauth_token);
+ console.log('Please go here and authorize:', authorizeURL.href);
+ const pin = await input('Paste the PIN here: ');
+ const oAuthAccessToken = await accessToken(oAuthRequestToken, pin.trim());
+ const response = await deletePost(oAuthAccessToken);
+ console.dir(response, { depth: null });
+ } catch (e) {
+ console.log(e);
+ process.exit(-1);
+ }
+ process.exit();
+})();
diff --git a/Manage-Tweets/delete_tweet.js b/javascript/posts/delete_tweet.js
similarity index 89%
rename from Manage-Tweets/delete_tweet.js
rename to javascript/posts/delete_tweet.js
index a62a913..ea6bfbd 100644
--- a/Manage-Tweets/delete_tweet.js
+++ b/javascript/posts/delete_tweet.js
@@ -18,13 +18,13 @@ const consumer_secret = process.env.CONSUMER_SECRET;
// Be sure to replace your-tweet-id with the id of the Tweet you wish to delete.
const id = "your-tweet-id";
-const endpointURL = `https://api.twitter.com/2/tweets/${id}`;
+const endpointURL = `https://api.x.com/2/tweets/${id}`;
// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
- "https://api.twitter.com/oauth/request_token?oauth_callback=oob";
-const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
-const accessTokenURL = "https://api.twitter.com/oauth/access_token";
+ "https://api.x.com/oauth/request_token?oauth_callback=oob";
+const authorizeURL = new URL("https://api.x.com/oauth/authorize");
+const accessTokenURL = "https://api.x.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -71,7 +71,7 @@ async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
method: "POST",
})
);
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
diff --git a/Full-Archive-Search/full-archive-search.js b/javascript/posts/full-archive-search.js
similarity index 95%
rename from Full-Archive-Search/full-archive-search.js
rename to javascript/posts/full-archive-search.js
index f3fd13d..c76d67e 100644
--- a/Full-Archive-Search/full-archive-search.js
+++ b/javascript/posts/full-archive-search.js
@@ -8,7 +8,7 @@ const needle = require('needle');
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
-const endpointUrl = 'https://api.twitter.com/2/tweets/search/all'
+const endpointUrl = 'https://api.x.com/2/tweets/search/all'
async function getRequest() {
diff --git a/Full-Archive-Tweet-Counts/full_archive_tweet_counts.js b/javascript/posts/full_archive_tweet_counts.js
similarity index 95%
rename from Full-Archive-Tweet-Counts/full_archive_tweet_counts.js
rename to javascript/posts/full_archive_tweet_counts.js
index f1c2b82..8ac536f 100644
--- a/Full-Archive-Tweet-Counts/full_archive_tweet_counts.js
+++ b/javascript/posts/full_archive_tweet_counts.js
@@ -8,7 +8,7 @@ const needle = require('needle');
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
-const endpointUrl = 'https://api.twitter.com/2/tweets/counts/all'
+const endpointUrl = 'https://api.x.com/2/tweets/counts/all'
async function getRequest() {
diff --git a/Tweet-Lookup/get_tweets_with_bearer_token.js b/javascript/posts/get_tweets_with_bearer_token.js
similarity index 96%
rename from Tweet-Lookup/get_tweets_with_bearer_token.js
rename to javascript/posts/get_tweets_with_bearer_token.js
index 6a1635c..fcdf694 100644
--- a/Tweet-Lookup/get_tweets_with_bearer_token.js
+++ b/javascript/posts/get_tweets_with_bearer_token.js
@@ -8,7 +8,7 @@ const needle = require('needle');
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
-const endpointURL = "https://api.twitter.com/2/tweets?ids=";
+const endpointURL = "https://api.x.com/2/tweets?ids=";
async function getRequest() {
diff --git a/Tweet-Lookup/get_tweets_with_user_context.js b/javascript/posts/get_tweets_with_user_context.js
similarity index 89%
rename from Tweet-Lookup/get_tweets_with_user_context.js
rename to javascript/posts/get_tweets_with_user_context.js
index 06b875c..c769f6f 100644
--- a/Tweet-Lookup/get_tweets_with_user_context.js
+++ b/javascript/posts/get_tweets_with_user_context.js
@@ -23,12 +23,12 @@ const consumer_secret = process.env.CONSUMER_SECRET;
const tweetIDs = '1278747501642657792,1275828087666679809'; // Edit the Tweet IDs to look up
const params = 'tweet.fields=lang,author_id&user.fields=created_at'; // Edit optional query parameters here
-const endpointURL = `https://api.twitter.com/2/tweets?ids=${tweetIDs}&${params}`;
+const endpointURL = `https://api.x.com/2/tweets?ids=${tweetIDs}&${params}`;
// this example uses PIN-based OAuth to authorize the user
-const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob';
-const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
-const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
const oauth = OAuth({
consumer: {
@@ -78,7 +78,7 @@ async function accessToken({
method: 'POST'
}));
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await got.post(path, {
headers: {
diff --git a/Manage-Likes/like_a_tweet.js b/javascript/posts/like_a_tweet.js
similarity index 89%
rename from Manage-Likes/like_a_tweet.js
rename to javascript/posts/like_a_tweet.js
index 638a36a..9ff9203 100644
--- a/Manage-Likes/like_a_tweet.js
+++ b/javascript/posts/like_a_tweet.js
@@ -27,12 +27,12 @@ const data = {
"tweet_id": "1354143047324299264"
};
-const endpointURL = `https://api.twitter.com/2/users/${id}/likes`;
+const endpointURL = `https://api.x.com/2/users/${id}/likes`;
// this example uses PIN-based OAuth to authorize the user
-const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob';
-const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
-const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -78,7 +78,7 @@ async function accessToken({
url: accessTokenURL,
method: 'POST'
}));
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"]
diff --git a/Likes-Lookup/liked_tweets.js b/javascript/posts/liked_tweets.js
similarity index 94%
rename from Likes-Lookup/liked_tweets.js
rename to javascript/posts/liked_tweets.js
index 2b0f668..ea65a93 100644
--- a/Likes-Lookup/liked_tweets.js
+++ b/javascript/posts/liked_tweets.js
@@ -6,7 +6,7 @@ const needle = require("needle");
const token = process.env.BEARER_TOKEN;
const id = "your-user-id";
-const endpointURL = `https://api.twitter.com/2/users/${id}/liked_tweets`;
+const endpointURL = `https://api.x.com/2/users/${id}/liked_tweets`;
async function getRequest() {
// These are the parameters for the API request
diff --git a/Likes-Lookup/liking_users.js b/javascript/posts/liking_users.js
similarity index 94%
rename from Likes-Lookup/liking_users.js
rename to javascript/posts/liking_users.js
index d79d9b0..406025d 100644
--- a/Likes-Lookup/liking_users.js
+++ b/javascript/posts/liking_users.js
@@ -9,7 +9,7 @@ const token = process.env.BEARER_TOKEN;
// You can find an ID by using the Tweet lookup endpoint
const id = "1354143047324299264";
-const endpointURL = `https://api.twitter.com/2/tweets/${id}/liking_users`;
+const endpointURL = `https://api.x.com/2/tweets/${id}/liking_users`;
async function getRequest() {
// These are the parameters for the API request
diff --git a/javascript/posts/lookup.js b/javascript/posts/lookup.js
new file mode 100644
index 0000000..51f7880
--- /dev/null
+++ b/javascript/posts/lookup.js
@@ -0,0 +1,47 @@
+/**
+ * Post Lookup - 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) or OAuth (User Context)
+ * Required env vars: BEARER_TOKEN
+ */
+
+const needle = require('needle');
+
+const token = process.env.BEARER_TOKEN;
+const endpointURL = "https://api.x.com/2/tweets";
+
+async function getRequest() {
+ // Post IDs to look up (comma-separated, up to 100)
+ const params = {
+ "ids": "1278747501642657792,1255542774432063488",
+ "tweet.fields": "created_at,author_id,lang,source,public_metrics",
+ "expansions": "author_id"
+ };
+
+ const res = await needle('get', endpointURL, params, {
+ headers: {
+ "User-Agent": "v2PostLookupJS",
+ "authorization": `Bearer ${token}`
+ }
+ });
+
+ if (res.body) {
+ return res.body;
+ } else {
+ throw new Error('Unsuccessful request');
+ }
+}
+
+(async () => {
+ try {
+ const response = await getRequest();
+ console.dir(response, { depth: null });
+ } catch (e) {
+ console.log(e);
+ process.exit(-1);
+ }
+ process.exit();
+})();
diff --git a/Quote-Tweets/quote_tweets.js b/javascript/posts/quote_tweets.js
similarity index 96%
rename from Quote-Tweets/quote_tweets.js
rename to javascript/posts/quote_tweets.js
index 5b66272..ccc4230 100644
--- a/Quote-Tweets/quote_tweets.js
+++ b/javascript/posts/quote_tweets.js
@@ -4,7 +4,7 @@
const needle = require('needle');
const tweetId = 20;
-const url = `https://api.twitter.com/2/tweets/${tweetId}/quote_tweets`;
+const url = `https://api.x.com/2/tweets/${tweetId}/quote_tweets`;
// 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:
diff --git a/Recent-Search/recent_search.js b/javascript/posts/recent_search.js
similarity index 94%
rename from Recent-Search/recent_search.js
rename to javascript/posts/recent_search.js
index 97a9bf6..1d82ed4 100644
--- a/Recent-Search/recent_search.js
+++ b/javascript/posts/recent_search.js
@@ -8,7 +8,7 @@ const needle = require('needle');
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
-const endpointUrl = "https://api.twitter.com/2/tweets/search/recent";
+const endpointUrl = "https://api.x.com/2/tweets/search/recent";
async function getRequest() {
diff --git a/Recent-Tweet-Counts/recent_tweet_counts.js b/javascript/posts/recent_tweet_counts.js
similarity index 94%
rename from Recent-Tweet-Counts/recent_tweet_counts.js
rename to javascript/posts/recent_tweet_counts.js
index 623ea20..73b981f 100644
--- a/Recent-Tweet-Counts/recent_tweet_counts.js
+++ b/javascript/posts/recent_tweet_counts.js
@@ -8,7 +8,7 @@ const needle = require('needle');
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
-const endpointUrl = "https://api.twitter.com/2/tweets/counts/recent";
+const endpointUrl = "https://api.x.com/2/tweets/counts/recent";
async function getRequest() {
diff --git a/Manage-Retweets/retweet_a_tweet.js b/javascript/posts/retweet_a_tweet.js
similarity index 89%
rename from Manage-Retweets/retweet_a_tweet.js
rename to javascript/posts/retweet_a_tweet.js
index b4ede7f..875b67b 100644
--- a/Manage-Retweets/retweet_a_tweet.js
+++ b/javascript/posts/retweet_a_tweet.js
@@ -27,12 +27,12 @@ const data = {
"tweet_id": "1412865600439738368"
}
-const endpointURL = `https://api.twitter.com/2/users/${id}/retweets`;
+const endpointURL = `https://api.x.com/2/users/${id}/retweets`;
// this example uses PIN-based OAuth to authorize the user
-const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob';
-const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
-const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -78,7 +78,7 @@ async function accessToken({
url: accessTokenURL,
method: 'POST'
}));
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"]
diff --git a/Retweets-Lookup/retweeted_by.js b/javascript/posts/retweeted_by.js
similarity index 94%
rename from Retweets-Lookup/retweeted_by.js
rename to javascript/posts/retweeted_by.js
index 1a48587..3d25df8 100644
--- a/Retweets-Lookup/retweeted_by.js
+++ b/javascript/posts/retweeted_by.js
@@ -9,7 +9,7 @@ const token = process.env.BEARER_TOKEN;
// You can find an ID by using the Tweet lookup endpoint
const id = "1354143047324299264";
-const endpointURL = `https://api.twitter.com/2/tweets/${id}/retweeted_by`;
+const endpointURL = `https://api.x.com/2/tweets/${id}/retweeted_by`;
async function getRequest() {
// These are the parameters for the API request
diff --git a/javascript/posts/search_recent.js b/javascript/posts/search_recent.js
new file mode 100644
index 0000000..1315dc2
--- /dev/null
+++ b/javascript/posts/search_recent.js
@@ -0,0 +1,49 @@
+/**
+ * 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
+ *
+ * Note: Returns posts from the last 7 days.
+ */
+
+const needle = require('needle');
+
+const token = process.env.BEARER_TOKEN;
+const endpointUrl = "https://api.x.com/2/tweets/search/recent";
+
+async function getRequest() {
+ // Edit query parameters below
+ // By default, only the post ID and text fields are returned
+ const params = {
+ 'query': 'from:XDevelopers -is:retweet',
+ 'tweet.fields': 'author_id,created_at'
+ };
+
+ const res = await needle('get', endpointUrl, params, {
+ headers: {
+ "User-Agent": "v2RecentSearchJS",
+ "authorization": `Bearer ${token}`
+ }
+ });
+
+ if (res.body) {
+ return res.body;
+ } else {
+ throw new Error('Unsuccessful request');
+ }
+}
+
+(async () => {
+ try {
+ const response = await getRequest();
+ console.dir(response, { depth: null });
+ } catch (e) {
+ console.log(e);
+ process.exit(-1);
+ }
+ process.exit();
+})();
diff --git a/Manage-Blocks/unblock_a_user.js b/javascript/posts/unblock_a_user.js
similarity index 89%
rename from Manage-Blocks/unblock_a_user.js
rename to javascript/posts/unblock_a_user.js
index bd59d18..d8d5081 100644
--- a/Manage-Blocks/unblock_a_user.js
+++ b/javascript/posts/unblock_a_user.js
@@ -28,13 +28,13 @@ const source_user_id = "your-user-id";
// You can find a user ID by using the user lookup endpoint
const target_user_id = "id-to-unblock"
-const endpointURL = `https://api.twitter.com/2/users/${source_user_id}/blocking/${target_user_id}`;
+const endpointURL = `https://api.x.com/2/users/${source_user_id}/blocking/${target_user_id}`;
// this example uses PIN-based OAuth to authorize the user
-const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob';
-const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
-const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -80,7 +80,7 @@ async function accessToken({
url: accessTokenURL,
method: 'POST'
}));
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"]
diff --git a/Manage-Retweets/undo_a_retweet.js b/javascript/posts/undo_a_retweet.js
similarity index 88%
rename from Manage-Retweets/undo_a_retweet.js
rename to javascript/posts/undo_a_retweet.js
index 0b70840..1d0029f 100644
--- a/Manage-Retweets/undo_a_retweet.js
+++ b/javascript/posts/undo_a_retweet.js
@@ -26,13 +26,13 @@ const id = "your-user-id";
// You can find a Tweet ID by using the Tweet lookup endpoint
const source_tweet_id = "1354143047324299264";
-const endpointURL = `https://api.twitter.com/2/users/${id}/retweets/${source_tweet_id}`;
+const endpointURL = `https://api.x.com/2/users/${id}/retweets/${source_tweet_id}`;
// this example uses PIN-based OAuth to authorize the user
-const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob';
-const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
-const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -78,7 +78,7 @@ async function accessToken({
url: accessTokenURL,
method: 'POST'
}));
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"]
diff --git a/Manage-Likes/unlike_a_tweet.js b/javascript/posts/unlike_a_tweet.js
similarity index 89%
rename from Manage-Likes/unlike_a_tweet.js
rename to javascript/posts/unlike_a_tweet.js
index c5ad508..f7c5905 100644
--- a/Manage-Likes/unlike_a_tweet.js
+++ b/javascript/posts/unlike_a_tweet.js
@@ -26,13 +26,13 @@ const id = "your-user-id";
// You can find a Tweet ID by using the Tweet lookup endpoint
const tweet_id = "1354143047324299264";
-const endpointURL = `https://api.twitter.com/2/users/${id}/likes/${tweet_id}`;
+const endpointURL = `https://api.x.com/2/users/${id}/likes/${tweet_id}`;
// this example uses PIN-based OAuth to authorize the user
-const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob';
-const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
-const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -78,7 +78,7 @@ async function accessToken({
url: accessTokenURL,
method: 'POST'
}));
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"]
diff --git a/javascript/spaces/lookup.js b/javascript/spaces/lookup.js
new file mode 100644
index 0000000..6d8b2a6
--- /dev/null
+++ b/javascript/spaces/lookup.js
@@ -0,0 +1,45 @@
+/**
+ * Spaces Lookup - X API v2
+ *
+ * Endpoint: GET https://api.x.com/2/spaces
+ * Docs: https://developer.x.com/en/docs/twitter-api/spaces/lookup/api-reference/get-spaces
+ *
+ * Authentication: Bearer Token (App-only) or OAuth (User Context)
+ * Required env vars: BEARER_TOKEN
+ */
+
+const needle = require('needle');
+
+const token = process.env.BEARER_TOKEN;
+const endpointURL = "https://api.x.com/2/spaces";
+
+async function getRequest() {
+ const params = {
+ "ids": "1DXxyRYNejbKM",
+ "space.fields": "host_ids,created_at,creator_id,participant_count,title,state"
+ };
+
+ const res = await needle('get', endpointURL, params, {
+ headers: {
+ "User-Agent": "v2SpacesLookupJS",
+ "authorization": `Bearer ${token}`
+ }
+ });
+
+ if (res.body) {
+ return res.body;
+ } else {
+ throw new Error('Unsuccessful request');
+ }
+}
+
+(async () => {
+ try {
+ const response = await getRequest();
+ console.dir(response, { depth: null });
+ } catch (e) {
+ console.log(e);
+ process.exit(-1);
+ }
+ process.exit();
+})();
diff --git a/Search-Spaces/search_spaces.js b/javascript/spaces/search_spaces.js
similarity index 95%
rename from Search-Spaces/search_spaces.js
rename to javascript/spaces/search_spaces.js
index f7876a9..eb58ed3 100644
--- a/Search-Spaces/search_spaces.js
+++ b/javascript/spaces/search_spaces.js
@@ -8,7 +8,7 @@ const needle = require('needle');
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
-const endpointUrl = `https://api.twitter.com/2/spaces/search`;
+const endpointUrl = `https://api.x.com/2/spaces/search`;
async function getRequest() {
diff --git a/Spaces-Lookup/spaces_lookup.js b/javascript/spaces/spaces_lookup.js
similarity index 94%
rename from Spaces-Lookup/spaces_lookup.js
rename to javascript/spaces/spaces_lookup.js
index 623ea20..73b981f 100644
--- a/Spaces-Lookup/spaces_lookup.js
+++ b/javascript/spaces/spaces_lookup.js
@@ -8,7 +8,7 @@ const needle = require('needle');
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
-const endpointUrl = "https://api.twitter.com/2/tweets/counts/recent";
+const endpointUrl = "https://api.x.com/2/tweets/counts/recent";
async function getRequest() {
diff --git a/Filtered-Stream/filtered_stream.js b/javascript/streams/filtered_stream.js
similarity index 96%
rename from Filtered-Stream/filtered_stream.js
rename to javascript/streams/filtered_stream.js
index d998d87..3926e98 100644
--- a/Filtered-Stream/filtered_stream.js
+++ b/javascript/streams/filtered_stream.js
@@ -8,8 +8,8 @@ const needle = require('needle');
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
-const rulesURL = 'https://api.twitter.com/2/tweets/search/stream/rules';
-const streamURL = 'https://api.twitter.com/2/tweets/search/stream';
+const rulesURL = 'https://api.x.com/2/tweets/search/stream/rules';
+const streamURL = 'https://api.x.com/2/tweets/search/stream';
// 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 Tweets return to show which rule they matched
diff --git a/Sampled-Stream/sampled_stream.js b/javascript/streams/sampled_stream.js
similarity index 96%
rename from Sampled-Stream/sampled_stream.js
rename to javascript/streams/sampled_stream.js
index 4a0d5d8..533f747 100644
--- a/Sampled-Stream/sampled_stream.js
+++ b/javascript/streams/sampled_stream.js
@@ -8,7 +8,7 @@ const needle = require('needle');
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
-const streamURL = 'https://api.twitter.com/2/tweets/sample/stream';
+const streamURL = 'https://api.x.com/2/tweets/sample/stream';
function streamConnect(retryAttempt) {
diff --git a/Reverse-Chron-Home-Timeline/OAuth2-user/reverse-chron-home-timeline-js-sdk.js b/javascript/timelines/reverse-chron-home-timeline-js-sdk.js
similarity index 100%
rename from Reverse-Chron-Home-Timeline/OAuth2-user/reverse-chron-home-timeline-js-sdk.js
rename to javascript/timelines/reverse-chron-home-timeline-js-sdk.js
diff --git a/Reverse-Chron-Home-Timeline/OAuth1a-user/reverse-chron-home-timeline.js b/javascript/timelines/reverse-chron-home-timeline.js
similarity index 89%
rename from Reverse-Chron-Home-Timeline/OAuth1a-user/reverse-chron-home-timeline.js
rename to javascript/timelines/reverse-chron-home-timeline.js
index a9c7702..51d4dbd 100644
--- a/Reverse-Chron-Home-Timeline/OAuth1a-user/reverse-chron-home-timeline.js
+++ b/javascript/timelines/reverse-chron-home-timeline.js
@@ -20,13 +20,13 @@ const consumer_secret = process.env.CONSUMER_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 id = "your-user-id";
-const endpointURL = `https://api.twitter.com/2/users/${id}/timelines/reverse_chronological`;
+const endpointURL = `https://api.x.com/2/users/${id}/timelines/reverse_chronological`;
// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
- "https://api.twitter.com/oauth/request_token?oauth_callback=oob";
-const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
-const accessTokenURL = "https://api.twitter.com/oauth/access_token";
+ "https://api.x.com/oauth/request_token?oauth_callback=oob";
+const authorizeURL = new URL("https://api.x.com/oauth/authorize");
+const accessTokenURL = "https://api.x.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -73,7 +73,7 @@ async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
method: "POST",
})
);
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
diff --git a/User-Mention-Timeline/user_mentions.js b/javascript/timelines/user_mentions.js
similarity index 96%
rename from User-Mention-Timeline/user_mentions.js
rename to javascript/timelines/user_mentions.js
index cfd5c08..98a4fd7 100644
--- a/User-Mention-Timeline/user_mentions.js
+++ b/javascript/timelines/user_mentions.js
@@ -4,7 +4,7 @@
const needle = require('needle');
const userId = 2244994945;
-const url = `https://api.twitter.com/2/users/${userId}/mentions`;
+const url = `https://api.x.com/2/users/${userId}/mentions`;
// 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:
diff --git a/javascript/timelines/user_posts.js b/javascript/timelines/user_posts.js
new file mode 100644
index 0000000..100f443
--- /dev/null
+++ b/javascript/timelines/user_posts.js
@@ -0,0 +1,48 @@
+/**
+ * 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) or OAuth (User Context)
+ * Required env vars: BEARER_TOKEN
+ */
+
+const needle = require('needle');
+
+const token = process.env.BEARER_TOKEN;
+
+// Replace with the user ID you want to get posts for
+const userId = "2244994945";
+const endpointURL = `https://api.x.com/2/users/${userId}/tweets`;
+
+async function getRequest() {
+ const params = {
+ "tweet.fields": "created_at,public_metrics",
+ "max_results": 10
+ };
+
+ const res = await needle('get', endpointURL, params, {
+ headers: {
+ "User-Agent": "v2UserPostsJS",
+ "authorization": `Bearer ${token}`
+ }
+ });
+
+ if (res.body) {
+ return res.body;
+ } else {
+ throw new Error('Unsuccessful request');
+ }
+}
+
+(async () => {
+ try {
+ const response = await getRequest();
+ console.dir(response, { depth: null });
+ } catch (e) {
+ console.log(e);
+ process.exit(-1);
+ }
+ process.exit();
+})();
diff --git a/User-Tweet-Timeline/user_tweets.js b/javascript/timelines/user_tweets.js
similarity index 97%
rename from User-Tweet-Timeline/user_tweets.js
rename to javascript/timelines/user_tweets.js
index 7324d6f..2576822 100644
--- a/User-Tweet-Timeline/user_tweets.js
+++ b/javascript/timelines/user_tweets.js
@@ -5,7 +5,7 @@ const needle = require('needle');
// this is the ID for @TwitterDev
const userId = "2244994945";
-const url = `https://api.twitter.com/2/users/${userId}/tweets`;
+const url = `https://api.x.com/2/users/${userId}/tweets`;
// 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:
diff --git a/Usage Tweets/get_usage_tweets.js b/javascript/usage/get_usage_tweets.js
similarity index 94%
rename from Usage Tweets/get_usage_tweets.js
rename to javascript/usage/get_usage_tweets.js
index 53df3be..31ec211 100644
--- a/Usage Tweets/get_usage_tweets.js
+++ b/javascript/usage/get_usage_tweets.js
@@ -8,7 +8,7 @@ const needle = require('needle');
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
-const endpointURL = "https://api.twitter.com/2/usage/tweets";
+const endpointURL = "https://api.x.com/2/usage/tweets";
async function getRequest() {
diff --git a/javascript/users/followers.js b/javascript/users/followers.js
new file mode 100644
index 0000000..7605b47
--- /dev/null
+++ b/javascript/users/followers.js
@@ -0,0 +1,48 @@
+/**
+ * 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) or OAuth (User Context)
+ * Required env vars: BEARER_TOKEN
+ */
+
+const needle = require('needle');
+
+const token = process.env.BEARER_TOKEN;
+
+// Replace with the user ID you want to get followers for
+const userId = "2244994945";
+const endpointURL = `https://api.x.com/2/users/${userId}/followers`;
+
+async function getRequest() {
+ const params = {
+ "user.fields": "created_at,description",
+ "max_results": 100
+ };
+
+ const res = await needle('get', endpointURL, params, {
+ headers: {
+ "User-Agent": "v2FollowersJS",
+ "authorization": `Bearer ${token}`
+ }
+ });
+
+ if (res.body) {
+ return res.body;
+ } else {
+ throw new Error('Unsuccessful request');
+ }
+}
+
+(async () => {
+ try {
+ const response = await getRequest();
+ console.dir(response, { depth: null });
+ } catch (e) {
+ console.log(e);
+ process.exit(-1);
+ }
+ process.exit();
+})();
diff --git a/Follows-Lookup/followers_lookup.js b/javascript/users/followers_lookup.js
similarity index 96%
rename from Follows-Lookup/followers_lookup.js
rename to javascript/users/followers_lookup.js
index 2fea9e7..cf93eb1 100644
--- a/Follows-Lookup/followers_lookup.js
+++ b/javascript/users/followers_lookup.js
@@ -5,7 +5,7 @@ const needle = require('needle');
// this is the ID for @TwitterDev
const userId = 2244994945;
-const url = `https://api.twitter.com/2/users/${userId}/followers`;
+const url = `https://api.x.com/2/users/${userId}/followers`;
const bearerToken = process.env.BEARER_TOKEN;
const getFollowers = async () => {
diff --git a/Follows-Lookup/following_lookup.js b/javascript/users/following_lookup.js
similarity index 96%
rename from Follows-Lookup/following_lookup.js
rename to javascript/users/following_lookup.js
index 8892f45..f5c76db 100644
--- a/Follows-Lookup/following_lookup.js
+++ b/javascript/users/following_lookup.js
@@ -5,7 +5,7 @@ const needle = require('needle');
// this is the ID for @TwitterDev
const userId = 2244994945;
-const url = `https://api.twitter.com/2/users/${userId}/following`;
+const url = `https://api.x.com/2/users/${userId}/following`;
const bearerToken = process.env.BEARER_TOKEN;
const getFollowing = async () => {
diff --git a/User-Lookup/get_users_me_with_user_context.js b/javascript/users/get_users_me_with_user_context.js
similarity index 89%
rename from User-Lookup/get_users_me_with_user_context.js
rename to javascript/users/get_users_me_with_user_context.js
index 10e4bb9..5166717 100644
--- a/User-Lookup/get_users_me_with_user_context.js
+++ b/javascript/users/get_users_me_with_user_context.js
@@ -19,12 +19,12 @@ const consumer_secret = process.env.CONSUMER_SECRET;
// by default, only the Tweet ID and text are returned
const params = 'user.fields=created_at,description&expansions=pinned_tweet_id' // Edit optional query parameters here
-const endpointURL = `https://api.twitter.com/2/users/me?{params}`;
+const endpointURL = `https://api.x.com/2/users/me?{params}`;
// this example uses PIN-based OAuth to authorize the user
-const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob';
-const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
-const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
const oauth = OAuth({
consumer: {
@@ -74,7 +74,7 @@ async function accessToken({
method: 'POST'
}));
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await got.post(path, {
headers: {
diff --git a/User-Lookup/get_users_with_bearer_token.js b/javascript/users/get_users_with_bearer_token.js
similarity index 95%
rename from User-Lookup/get_users_with_bearer_token.js
rename to javascript/users/get_users_with_bearer_token.js
index 66136a7..56c4414 100644
--- a/User-Lookup/get_users_with_bearer_token.js
+++ b/javascript/users/get_users_with_bearer_token.js
@@ -8,7 +8,7 @@ const needle = require('needle');
// export BEARER_TOKEN='YOUR-TOKEN'
const token = process.env.BEARER_TOKEN;
-const endpointURL = "https://api.twitter.com/2/users/by?usernames="
+const endpointURL = "https://api.x.com/2/users/by?usernames="
async function getRequest() {
diff --git a/User-Lookup/get_users_with_user_context.js b/javascript/users/get_users_with_user_context.js
similarity index 89%
rename from User-Lookup/get_users_with_user_context.js
rename to javascript/users/get_users_with_user_context.js
index c451c65..4cceedb 100644
--- a/User-Lookup/get_users_with_user_context.js
+++ b/javascript/users/get_users_with_user_context.js
@@ -23,12 +23,12 @@ const consumer_secret = process.env.CONSUMER_SECRET;
const usernames = 'TwitterDev,TwitterAPI' // Edit usernames to look up
const params = 'user.fields=created_at,description&expansions=pinned_tweet_id' // Edit optional query parameters here
-const endpointURL = `https://api.twitter.com/2/users/by?usernames=${usernames}&${params}`;
+const endpointURL = `https://api.x.com/2/users/by?usernames=${usernames}&${params}`;
// this example uses PIN-based OAuth to authorize the user
-const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob';
-const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
-const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
const oauth = OAuth({
consumer: {
@@ -78,7 +78,7 @@ async function accessToken({
method: 'POST'
}));
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await got.post(path, {
headers: {
diff --git a/javascript/users/lookup.js b/javascript/users/lookup.js
new file mode 100644
index 0000000..3cfbed9
--- /dev/null
+++ b/javascript/users/lookup.js
@@ -0,0 +1,46 @@
+/**
+ * User Lookup - X API v2
+ *
+ * Endpoint: GET https://api.x.com/2/users/by
+ * Docs: https://developer.x.com/en/docs/twitter-api/users/lookup/api-reference/get-users-by
+ *
+ * Authentication: Bearer Token (App-only) or OAuth (User Context)
+ * Required env vars: BEARER_TOKEN
+ */
+
+const needle = require('needle');
+
+const token = process.env.BEARER_TOKEN;
+const endpointURL = "https://api.x.com/2/users/by";
+
+async function getRequest() {
+ // Usernames to look up (up to 100 comma-separated)
+ const params = {
+ "usernames": "XDevelopers,X",
+ "user.fields": "created_at,description,public_metrics"
+ };
+
+ const res = await needle('get', endpointURL, params, {
+ headers: {
+ "User-Agent": "v2UserLookupJS",
+ "authorization": `Bearer ${token}`
+ }
+ });
+
+ if (res.body) {
+ return res.body;
+ } else {
+ throw new Error('Unsuccessful request');
+ }
+}
+
+(async () => {
+ try {
+ const response = await getRequest();
+ console.dir(response, { depth: null });
+ } catch (e) {
+ console.log(e);
+ process.exit(-1);
+ }
+ process.exit();
+})();
diff --git a/Blocks-Lookup/lookup_blocks.js b/javascript/users/lookup_blocks.js
similarity index 89%
rename from Blocks-Lookup/lookup_blocks.js
rename to javascript/users/lookup_blocks.js
index a29bc0c..a9ff459 100644
--- a/Blocks-Lookup/lookup_blocks.js
+++ b/javascript/users/lookup_blocks.js
@@ -22,12 +22,12 @@ const consumer_secret = process.env.CONSUMER_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 id = "your-user-id";
-const endpointURL = `https://api.twitter.com/2/users/${id}/blocking`;
+const endpointURL = `https://api.x.com/2/users/${id}/blocking`;
// this example uses PIN-based OAuth to authorize the user
-const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob';
-const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
-const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -73,7 +73,7 @@ async function accessToken({
url: accessTokenURL,
method: 'POST'
}));
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"]
diff --git a/Mutes-Lookup/lookup_mutes.js b/javascript/users/lookup_mutes.js
similarity index 89%
rename from Mutes-Lookup/lookup_mutes.js
rename to javascript/users/lookup_mutes.js
index 5177153..d8c9d39 100644
--- a/Mutes-Lookup/lookup_mutes.js
+++ b/javascript/users/lookup_mutes.js
@@ -20,13 +20,13 @@ const consumer_secret = process.env.CONSUMER_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 id = "your-user-id";
-const endpointURL = `https://api.twitter.com/2/users/${id}/muting`;
+const endpointURL = `https://api.x.com/2/users/${id}/muting`;
// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
- "https://api.twitter.com/oauth/request_token?oauth_callback=oob";
-const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
-const accessTokenURL = "https://api.twitter.com/oauth/access_token";
+ "https://api.x.com/oauth/request_token?oauth_callback=oob";
+const authorizeURL = new URL("https://api.x.com/oauth/authorize");
+const accessTokenURL = "https://api.x.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -73,7 +73,7 @@ async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
method: "POST",
})
);
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
diff --git a/Manage-Mutes/mute_a_user.js b/javascript/users/mute_a_user.js
similarity index 89%
rename from Manage-Mutes/mute_a_user.js
rename to javascript/users/mute_a_user.js
index b912920..73d12f2 100644
--- a/Manage-Mutes/mute_a_user.js
+++ b/javascript/users/mute_a_user.js
@@ -29,12 +29,12 @@ const data = {
"target_user_id": "id-to-mute"
}
-const endpointURL = `https://api.twitter.com/2/users/${id}/muting`;
+const endpointURL = `https://api.x.com/2/users/${id}/muting`;
// this example uses PIN-based OAuth to authorize the user
-const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob';
-const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
-const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -80,7 +80,7 @@ async function accessToken({
url: accessTokenURL,
method: 'POST'
}));
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"]
diff --git a/Manage-Mutes/unmute_a_user.js b/javascript/users/unmute_a_user.js
similarity index 88%
rename from Manage-Mutes/unmute_a_user.js
rename to javascript/users/unmute_a_user.js
index fa0785f..ddd421c 100644
--- a/Manage-Mutes/unmute_a_user.js
+++ b/javascript/users/unmute_a_user.js
@@ -27,13 +27,13 @@ const source_user_id = "your-user-id";
// You can find a user ID by using the user lookup endpoint
const target_user_id = "id-to-unmute"
-const endpointURL = `https://api.twitter.com/2/users/${source_user_id}/muting/${target_user_id}`;
+const endpointURL = `https://api.x.com/2/users/${source_user_id}/muting/${target_user_id}`;
// this example uses PIN-based OAuth to authorize the user
-const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob';
-const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
-const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
+const requestTokenURL = 'https://api.x.com/oauth/request_token?oauth_callback=oob';
+const authorizeURL = new URL('https://api.x.com/oauth/authorize');
+const accessTokenURL = 'https://api.x.com/oauth/access_token';
const oauth = OAuth({
consumer: {
key: consumer_key,
@@ -79,7 +79,7 @@ async function accessToken({
url: accessTokenURL,
method: 'POST'
}));
- const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
+ const path = `https://api.x.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
const req = await got.post(path, {
: {
Authorization: authHeader["Authorization"]
diff --git a/llms.txt b/llms.txt
new file mode 100644
index 0000000..254197a
--- /dev/null
+++ b/llms.txt
@@ -0,0 +1,156 @@
+# 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
diff --git a/python/README.md b/python/README.md
new file mode 100644
index 0000000..0f21f15
--- /dev/null
+++ b/python/README.md
@@ -0,0 +1,150 @@
+# X API v2 - Python Examples
+
+Working Python examples for the X API v2.
+
+## Setup
+
+```bash
+pip install requests requests-oauthlib
+```
+
+## Environment Variables
+
+```bash
+export BEARER_TOKEN='your_bearer_token'
+export CONSUMER_KEY='your_consumer_key'
+export CONSUMER_SECRET='your_consumer_secret'
+```
+
+## Examples
+
+### Posts
+- posts/counts_full_archive.py
+- posts/counts_recent.py
+- posts/create_post.py
+- posts/create_tweet.py
+- posts/delete_post.py
+- posts/delete_tweet.py
+- posts/full_archive_tweet_counts.py
+- posts/full-archive-search.py
+- posts/get_tweets_with_bearer_token.py
+- posts/get_tweets_with_user_context.py
+- posts/like_a_tweet.py
+- posts/like.py
+- posts/liked_posts.py
+- posts/liked_tweets.py
+- posts/liking_users.py
+- posts/lookup.py
+- posts/quote_posts.py
+- posts/quote_tweets.py
+- posts/recent_search.py
+- posts/recent_tweet_counts.py
+- posts/repost.py
+- posts/reposted_by.py
+- posts/retweet_a_tweet.py
+- posts/retweeted_by.py
+- posts/search_full_archive.py
+- posts/search_recent.py
+- posts/undo_a_retweet.py
+- posts/undo_repost.py
+- posts/unlike_a_tweet.py
+- posts/unlike.py
+
+### Users
+- users/block_a_user.py
+- users/block.py
+- users/blocked.py
+- users/followers_lookup.py
+- users/followers.py
+- users/following_lookup.py
+- users/following.py
+- users/get_users_me_user_context.py
+- users/get_users_with_bearer_token.py
+- users/get_users_with_user_context.py
+- users/lookup_blocks.py
+- users/lookup_mutes.py
+- users/lookup.py
+- users/me.py
+- users/mute_a_user.py
+- users/mute.py
+- users/muted.py
+- users/unblock_a_user.py
+- users/unblock.py
+- users/unmute_a_user.py
+- users/unmute.py
+
+### Timelines
+- timelines/home_timeline.py
+- timelines/reverse-chron-home-timeline.py
+- timelines/user_mentions.py
+- timelines/user_posts.py
+- timelines/user_tweets.py
+
+### Streams
+- streams/filtered_stream.py
+- streams/sampled_stream.py
+- streams/sampled-stream.py
+
+### Lists
+- lists/add_member.py
+- lists/create_a_list.py
+- lists/create.py
+- lists/delete_a_list.py
+- lists/delete.py
+- lists/follow_list.py
+- lists/list-followers-lookup.py
+- lists/list-lookup-by-id.py
+- lists/list-member-lookup.py
+- lists/List-Tweets.py
+- lists/lookup.py
+- lists/pin_list.py
+- lists/Pinned-List.py
+- lists/remove_member.py
+- lists/unfollow_list.py
+- lists/unpin_list.py
+- lists/update_a_list.py
+- lists/user-list-followed.py
+- lists/user-list-memberships.py
+- lists/user-owned-list-lookup.py
+
+### Bookmarks
+- bookmarks/bookmarks_lookup.py
+- bookmarks/create_bookmark.py
+- bookmarks/create.py
+- bookmarks/delete_bookmark.py
+- bookmarks/delete.py
+- bookmarks/lookup.py
+
+### Spaces
+- spaces/lookup.py
+- spaces/search_spaces.py
+- spaces/search.py
+- spaces/spaces_lookup.py
+
+### Direct Messages
+- direct_messages/get_events_by_conversation.py
+- direct_messages/get_one_to_one_conversation_events.py
+- direct_messages/get_user_conversation_events.py
+- direct_messages/lookup.py
+- direct_messages/post_dm_to_conversation.py
+- direct_messages/post_group_conversation_dm.py
+- direct_messages/post_one_to_one_dm.py
+- direct_messages/send.py
+
+### Media
+- media/media_upload_v2.py
+- media/upload.py
+
+### Compliance
+- compliance/create_compliance_job.py
+- compliance/create_job.py
+- compliance/download_compliance_results.py
+- compliance/get_compliance_job_information_by_id.py
+- compliance/get_jobs.py
+- compliance/get_list_of_compliance_jobs.py
+- compliance/upload_ids.py
+
+### Usage
+- usage/get_usage_tweets.py
+- usage/get_usage.py
+
diff --git a/Bookmarks-lookup/bookmarks_lookup.py b/python/bookmarks/bookmarks_lookup.py
similarity index 95%
rename from Bookmarks-lookup/bookmarks_lookup.py
rename to python/bookmarks/bookmarks_lookup.py
index 4cb2dae..e864e22 100644
--- a/Bookmarks-lookup/bookmarks_lookup.py
+++ b/python/bookmarks/bookmarks_lookup.py
@@ -57,7 +57,7 @@
)
# Fetch your access token
-token_url = "https://api.twitter.com/2/oauth2/token"
+token_url = "https://api.x.com/2/oauth2/token"
# The following line of code will only work if you are using a type of App that is a public client
auth = False
@@ -82,13 +82,13 @@
# Make a request to the users/me endpoint to get your user ID
user_me = requests.request(
"GET",
- "https://api.twitter.com/2/users/me",
+ "https://api.x.com/2/users/me",
headers={"Authorization": "Bearer {}".format(access)},
).json()
user_id = user_me["data"]["id"]
# Make a request to the bookmarks url
-url = "https://api.twitter.com/2/users/{}/bookmarks".format(user_id)
+url = "https://api.x.com/2/users/{}/bookmarks".format(user_id)
headers = {
"Authorization": "Bearer {}".format(access),
"User-Agent": "BookmarksSampleCode",
diff --git a/python/bookmarks/create.py b/python/bookmarks/create.py
new file mode 100644
index 0000000..0499013
--- /dev/null
+++ b/python/bookmarks/create.py
@@ -0,0 +1,54 @@
+"""
+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 with PKCE (User Context)
+Required env vars: BEARER_TOKEN (OAuth 2.0 user access token)
+"""
+
+import requests
+import os
+import json
+
+# Note: This endpoint requires OAuth 2.0 User Context
+# The bearer_token here should be the user's access token from OAuth 2.0 PKCE flow
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url(user_id):
+ return "https://api.x.com/2/users/{}/bookmarks".format(user_id)
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2CreateBookmarkPython"
+ return r
+
+
+def connect_to_endpoint(url, payload):
+ response = requests.post(url, auth=bearer_oauth, json=payload)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ # Replace with the authenticated user's ID
+ user_id = "your-user-id"
+
+ # Replace with the post ID you want to bookmark
+ payload = {"tweet_id": "post-id-to-bookmark"}
+
+ url = create_url(user_id)
+ json_response = connect_to_endpoint(url, payload)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Manage-Bookmarks/create_bookmark.py b/python/bookmarks/create_bookmark.py
similarity index 95%
rename from Manage-Bookmarks/create_bookmark.py
rename to python/bookmarks/create_bookmark.py
index d998cd1..56346d9 100644
--- a/Manage-Bookmarks/create_bookmark.py
+++ b/python/bookmarks/create_bookmark.py
@@ -60,7 +60,7 @@
)
# Fetch your access token
-token_url = "https://api.twitter.com/2/oauth2/token"
+token_url = "https://api.x.com/2/oauth2/token"
# The following line of code will only work if you are using a type of App that is a public client
auth = False
@@ -85,13 +85,13 @@
# Make a request to the users/me endpoint to get your user ID
user_me = requests.request(
"GET",
- "https://api.twitter.com/2/users/me",
+ "https://api.x.com/2/users/me",
headers={"Authorization": "Bearer {}".format(access)},
).json()
user_id = user_me["data"]["id"]
# Make a request to the bookmarks url
-url = "https://api.twitter.com/2/users/{}/bookmarks".format(user_id)
+url = "https://api.x.com/2/users/{}/bookmarks".format(user_id)
headers = {
"Authorization": "Bearer {}".format(access),
"Content-Type": "application/json",
diff --git a/python/bookmarks/delete.py b/python/bookmarks/delete.py
new file mode 100644
index 0000000..d962f16
--- /dev/null
+++ b/python/bookmarks/delete.py
@@ -0,0 +1,54 @@
+"""
+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 with PKCE (User Context)
+Required env vars: BEARER_TOKEN (OAuth 2.0 user access token)
+"""
+
+import requests
+import os
+import json
+
+# Note: This endpoint requires OAuth 2.0 User Context
+# The bearer_token here should be the user's access token from OAuth 2.0 PKCE flow
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url(user_id, post_id):
+ return "https://api.x.com/2/users/{}/bookmarks/{}".format(user_id, post_id)
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2DeleteBookmarkPython"
+ return r
+
+
+def connect_to_endpoint(url):
+ response = requests.delete(url, auth=bearer_oauth)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ # Replace with the authenticated user's ID
+ user_id = "your-user-id"
+
+ # Replace with the post ID you want to remove from bookmarks
+ post_id = "post-id-to-unbookmark"
+
+ url = create_url(user_id, post_id)
+ json_response = connect_to_endpoint(url)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Manage-Bookmarks/delete_bookmark.py b/python/bookmarks/delete_bookmark.py
similarity index 95%
rename from Manage-Bookmarks/delete_bookmark.py
rename to python/bookmarks/delete_bookmark.py
index 7bd2d49..fae427b 100644
--- a/Manage-Bookmarks/delete_bookmark.py
+++ b/python/bookmarks/delete_bookmark.py
@@ -61,7 +61,7 @@
)
# Fetch your access token
-token_url = "https://api.twitter.com/2/oauth2/token"
+token_url = "https://api.x.com/2/oauth2/token"
# The following line of code will only work if you are using a type of App that is a public client
auth = False
@@ -86,13 +86,13 @@
# Make a request to the users/me endpoint to get the user ID of the authenticated user
user_me = requests.request(
"GET",
- "https://api.twitter.com/2/users/me",
+ "https://api.x.com/2/users/me",
headers={"Authorization": "Bearer {}".format(access)},
).json()
user_id = user_me["data"]["id"]
# Make a request to the bookmarks url
-url = "https://api.twitter.com/2/users/{}/bookmarks/{}".format(
+url = "https://api.x.com/2/users/{}/bookmarks/{}".format(
user_id, bookmarked_tweet_id
)
headers = {
diff --git a/python/bookmarks/lookup.py b/python/bookmarks/lookup.py
new file mode 100644
index 0000000..6af4463
--- /dev/null
+++ b/python/bookmarks/lookup.py
@@ -0,0 +1,55 @@
+"""
+Bookmarks Lookup - X API v2
+===========================
+Endpoint: GET https://api.x.com/2/users/:id/bookmarks
+Docs: https://developer.x.com/en/docs/twitter-api/tweets/bookmarks/api-reference/get-users-id-bookmarks
+
+Authentication: OAuth 2.0 with PKCE (User Context)
+Required env vars: BEARER_TOKEN (OAuth 2.0 user access token)
+"""
+
+import requests
+import os
+import json
+
+# Note: This endpoint requires OAuth 2.0 User Context
+# The bearer_token here should be the user's access token from OAuth 2.0 PKCE flow
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url(user_id):
+ return "https://api.x.com/2/users/{}/bookmarks".format(user_id)
+
+
+def get_params():
+ return {"tweet.fields": "created_at"}
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2BookmarksLookupPython"
+ return r
+
+
+def connect_to_endpoint(url, params):
+ response = requests.request("GET", url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ # Replace with the authenticated user's ID
+ user_id = "your-user-id"
+ url = create_url(user_id)
+ params = get_params()
+ json_response = connect_to_endpoint(url, params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Batch-Compliance/python/create_compliance_job.py b/python/compliance/create_compliance_job.py
similarity index 94%
rename from Batch-Compliance/python/create_compliance_job.py
rename to python/compliance/create_compliance_job.py
index e856c47..f0ceca4 100644
--- a/Batch-Compliance/python/create_compliance_job.py
+++ b/python/compliance/create_compliance_job.py
@@ -6,7 +6,7 @@
# export 'BEARER_TOKEN'=''
bearer_token = os.environ.get("BEARER_TOKEN")
-compliance_job_url = "https://api.twitter.com/2/compliance/jobs"
+compliance_job_url = "https://api.x.com/2/compliance/jobs"
# For User Compliance Job, replace the type value with users instead of tweets
# Also replace the name value with your desired job name
diff --git a/python/compliance/create_job.py b/python/compliance/create_job.py
new file mode 100644
index 0000000..ba7ce03
--- /dev/null
+++ b/python/compliance/create_job.py
@@ -0,0 +1,56 @@
+"""
+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
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url():
+ return "https://api.x.com/2/compliance/jobs"
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2ComplianceJobPython"
+ return r
+
+
+def connect_to_endpoint(url, payload):
+ response = requests.post(url, auth=bearer_oauth, json=payload)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = create_url()
+
+ # Type can be "tweets" or "users"
+ payload = {
+ "type": "tweets",
+ "name": "my_compliance_job"
+ }
+
+ json_response = connect_to_endpoint(url, payload)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+ # Note the job id and upload_url from the response
+ # You'll need these to upload your dataset and download results
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Batch-Compliance/python/download_compliance_results.py b/python/compliance/download_compliance_results.py
similarity index 100%
rename from Batch-Compliance/python/download_compliance_results.py
rename to python/compliance/download_compliance_results.py
diff --git a/Batch-Compliance/python/get_compliance_job_information_by_id.py b/python/compliance/get_compliance_job_information_by_id.py
similarity index 90%
rename from Batch-Compliance/python/get_compliance_job_information_by_id.py
rename to python/compliance/get_compliance_job_information_by_id.py
index 474585a..5d46e72 100644
--- a/Batch-Compliance/python/get_compliance_job_information_by_id.py
+++ b/python/compliance/get_compliance_job_information_by_id.py
@@ -9,7 +9,7 @@
# Replace with your job ID below
job_id = ''
-compliance_job_url = f"https://api.twitter.com/2/compliance/jobs/{job_id}".format(job_id)
+compliance_job_url = f"https://api.x.com/2/compliance/jobs/{job_id}".format(job_id)
def bearer_oauth(r):
diff --git a/python/compliance/get_jobs.py b/python/compliance/get_jobs.py
new file mode 100644
index 0000000..de65383
--- /dev/null
+++ b/python/compliance/get_jobs.py
@@ -0,0 +1,52 @@
+"""
+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
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url():
+ return "https://api.x.com/2/compliance/jobs"
+
+
+def get_params():
+ # Type can be "tweets" or "users"
+ return {"type": "tweets"}
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2ComplianceJobsPython"
+ return r
+
+
+def connect_to_endpoint(url, params):
+ response = requests.get(url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = create_url()
+ params = get_params()
+ json_response = connect_to_endpoint(url, params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Batch-Compliance/python/get_list_of_compliance_jobs.py b/python/compliance/get_list_of_compliance_jobs.py
similarity index 93%
rename from Batch-Compliance/python/get_list_of_compliance_jobs.py
rename to python/compliance/get_list_of_compliance_jobs.py
index 1fcb80f..54a9c01 100644
--- a/Batch-Compliance/python/get_list_of_compliance_jobs.py
+++ b/python/compliance/get_list_of_compliance_jobs.py
@@ -6,7 +6,7 @@
# export 'BEARER_TOKEN'=''
bearer_token = os.environ.get("BEARER_TOKEN")
-compliance_job_url = "https://api.twitter.com/2/compliance/jobs"
+compliance_job_url = "https://api.x.com/2/compliance/jobs"
# For User Compliance job, replace the value for type with users
query_params = {"type": "tweets"}
diff --git a/Batch-Compliance/python/upload_ids.py b/python/compliance/upload_ids.py
similarity index 100%
rename from Batch-Compliance/python/upload_ids.py
rename to python/compliance/upload_ids.py
diff --git a/Direct-Messages-lookup/get_events_by_conversation.py b/python/direct_messages/get_events_by_conversation.py
similarity index 96%
rename from Direct-Messages-lookup/get_events_by_conversation.py
rename to python/direct_messages/get_events_by_conversation.py
index 19f1888..93515f7 100644
--- a/Direct-Messages-lookup/get_events_by_conversation.py
+++ b/python/direct_messages/get_events_by_conversation.py
@@ -8,7 +8,7 @@
# This example is set up to retrieve Direct Message events by conversation ID. This supports both
# one-to-one and group conversations.
-GET_DMS_EVENTS_URL = "https://api.twitter.com/2/dm_conversations/:dm_conversation_id/dm_events"
+GET_DMS_EVENTS_URL = "https://api.x.com/2/dm_conversations/:dm_conversation_id/dm_events"
#-----------------------------------------------------------------------------------------------------------------------
# These variables need to be updated to the setting that match how your Twitter App is set-up at
@@ -58,7 +58,7 @@ def handle_oauth():
)
# Fetch your access token
- token_url = "https://api.twitter.com/2/oauth2/token"
+ token_url = "https://api.x.com/2/oauth2/token"
# The following line of code will only work if you are using a type of App that is a public client
auth = False
diff --git a/Direct-Messages-lookup/get_one_to_one_conversation_events.py b/python/direct_messages/get_one_to_one_conversation_events.py
similarity index 96%
rename from Direct-Messages-lookup/get_one_to_one_conversation_events.py
rename to python/direct_messages/get_one_to_one_conversation_events.py
index 73d17ef..b03f552 100644
--- a/Direct-Messages-lookup/get_one_to_one_conversation_events.py
+++ b/python/direct_messages/get_one_to_one_conversation_events.py
@@ -9,7 +9,7 @@
# This example is set up to retrieve Direct Message conversation events associated with a one-to-one message.
# Currently, the v2 DM endpoints support three conversation event types: MessageCreate, ParticipantsJoin, and
# ParticipantsLeave.
-GET_DM_EVENTS_URL = "https://api.twitter.com/2/dm_conversations/with/:participant_id/dm_events"
+GET_DM_EVENTS_URL = "https://api.x.com/2/dm_conversations/with/:participant_id/dm_events"
#-----------------------------------------------------------------------------------------------------------------------
# These variables need to be updated to the setting that match how your Twitter App is set-up at
@@ -59,7 +59,7 @@ def handle_oauth():
)
# Fetch your access token
- token_url = "https://api.twitter.com/2/oauth2/token"
+ token_url = "https://api.x.com/2/oauth2/token"
# The following line of code will only work if you are using a type of App that is a public client
auth = False
diff --git a/Direct-Messages-lookup/get_user_conversation_events.py b/python/direct_messages/get_user_conversation_events.py
similarity index 96%
rename from Direct-Messages-lookup/get_user_conversation_events.py
rename to python/direct_messages/get_user_conversation_events.py
index 6f272f6..b5bc8c5 100644
--- a/Direct-Messages-lookup/get_user_conversation_events.py
+++ b/python/direct_messages/get_user_conversation_events.py
@@ -8,7 +8,7 @@
# This example is set up to retrieve Direct Message events of the authenticating user. This supports both
# one-to-one and group conversations.
-GET_DM_EVENTS_URL = "https://api.twitter.com/2/dm_events"
+GET_DM_EVENTS_URL = "https://api.x.com/2/dm_events"
#-----------------------------------------------------------------------------------------------------------------------
# These variables need to be updated to the setting that match how your Twitter App is set-up at
@@ -53,7 +53,7 @@ def handle_oauth():
)
# Fetch your access token.
- token_url = "https://api.twitter.com/2/oauth2/token"
+ token_url = "https://api.x.com/2/oauth2/token"
# The following line of code will only work if you are using a type of App that is a public client.
auth = False
diff --git a/python/direct_messages/lookup.py b/python/direct_messages/lookup.py
new file mode 100644
index 0000000..3ba8f24
--- /dev/null
+++ b/python/direct_messages/lookup.py
@@ -0,0 +1,78 @@
+"""
+Direct Messages Lookup - 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 1.0a or OAuth 2.0 (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# DM event fields are adjustable. Options include:
+# id, text, event_type, created_at, dm_conversation_id,
+# sender_id, participant_ids, referenced_tweets, attachments
+params = {"dm_event.fields": "id,text,event_type,created_at,sender_id"}
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.get("https://api.x.com/2/dm_events", params=params)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/Manage-Direct-Messages/post_dm_to_conversation.py b/python/direct_messages/post_dm_to_conversation.py
similarity index 96%
rename from Manage-Direct-Messages/post_dm_to_conversation.py
rename to python/direct_messages/post_dm_to_conversation.py
index f257231..18d6af3 100644
--- a/Manage-Direct-Messages/post_dm_to_conversation.py
+++ b/python/direct_messages/post_dm_to_conversation.py
@@ -7,7 +7,7 @@
from requests_oauthlib import OAuth2Session
#This example is set up to add a DM to a specified conversation by referencing its ID.
-POST_DM_URL = "https://api.twitter.com/2/dm_conversations/:dm_conversation_id/messages"
+POST_DM_URL = "https://api.x.com/2/dm_conversations/:dm_conversation_id/messages"
#-----------------------------------------------------------------------------------------------------------------------
# These variables need to be updated to the setting that match how your Twitter App is set-up at
@@ -59,7 +59,7 @@ def handle_oauth():
)
# Fetch your access token.
- token_url = "https://api.twitter.com/2/oauth2/token"
+ token_url = "https://api.x.com/2/oauth2/token"
# The following line of code will only work if you are using a type of App that is a public client
auth = False
diff --git a/Manage-Direct-Messages/post_group_conversation_dm.py b/python/direct_messages/post_group_conversation_dm.py
similarity index 97%
rename from Manage-Direct-Messages/post_group_conversation_dm.py
rename to python/direct_messages/post_group_conversation_dm.py
index 0cb0082..135a9e5 100644
--- a/Manage-Direct-Messages/post_group_conversation_dm.py
+++ b/python/direct_messages/post_group_conversation_dm.py
@@ -7,7 +7,7 @@
from requests_oauthlib import OAuth2Session
#This example is set up to create a new group conversation and add a new DM to it.
-POST_DM_URL = "https://api.twitter.com/2/dm_conversations"
+POST_DM_URL = "https://api.x.com/2/dm_conversations"
#-----------------------------------------------------------------------------------------------------------------------
# These variables need to be updated to the setting that match how your Twitter App is set-up at
@@ -59,7 +59,7 @@ def handle_oauth():
)
# Fetch your access token.
- token_url = "https://api.twitter.com/2/oauth2/token"
+ token_url = "https://api.x.com/2/oauth2/token"
# The following line of code will only work if you are using a type of App that is a public client.
auth = False
diff --git a/Manage-Direct-Messages/post_one_to_one_dm.py b/python/direct_messages/post_one_to_one_dm.py
similarity index 96%
rename from Manage-Direct-Messages/post_one_to_one_dm.py
rename to python/direct_messages/post_one_to_one_dm.py
index 582a43e..da59ba4 100644
--- a/Manage-Direct-Messages/post_one_to_one_dm.py
+++ b/python/direct_messages/post_one_to_one_dm.py
@@ -7,7 +7,7 @@
from requests_oauthlib import OAuth2Session
#This example is set up to add a new DM to a one-to-one conversation.
-POST_DM_URL = "https://api.twitter.com/2/dm_conversations/with/:participant_id/messages"
+POST_DM_URL = "https://api.x.com/2/dm_conversations/with/:participant_id/messages"
#-----------------------------------------------------------------------------------------------------------------------
# These variables need to be updated to the setting that match how your Twitter App is set-up at
@@ -59,7 +59,7 @@ def handle_oauth():
)
# Fetch your access token
- token_url = "https://api.twitter.com/2/oauth2/token"
+ token_url = "https://api.x.com/2/oauth2/token"
# The following line of code will only work if you are using a type of App that is a public client
auth = False
diff --git a/python/direct_messages/send.py b/python/direct_messages/send.py
new file mode 100644
index 0000000..9299385
--- /dev/null
+++ b/python/direct_messages/send.py
@@ -0,0 +1,82 @@
+"""
+Send 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 1.0a or OAuth 2.0 (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# Replace with the user ID you want to send a DM to
+participant_id = "recipient-user-id"
+
+# Message content
+payload = {"text": "Hello! This is a test message."}
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.post(
+ "https://api.x.com/2/dm_conversations/with/{}/messages".format(participant_id),
+ json=payload
+)
+
+if response.status_code != 201:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/List-lookup/List-Tweets-lookup/List-Tweets.py b/python/lists/List-Tweets.py
similarity index 95%
rename from List-lookup/List-Tweets-lookup/List-Tweets.py
rename to python/lists/List-Tweets.py
index 847d917..dca8430 100644
--- a/List-lookup/List-Tweets-lookup/List-Tweets.py
+++ b/python/lists/List-Tweets.py
@@ -18,7 +18,7 @@ def create_url():
tweet_fields = "tweet.fields=lang,author_id"
# Be sure to replace list-id with any List ID
id = "list-id"
- url = "https://api.twitter.com/2/lists/{}/tweets".format(id)
+ url = "https://api.x.com/2/lists/{}/tweets".format(id)
return url, tweet_fields
diff --git a/List-lookup/Pinned-Lists-lookup/Pinned-List.py b/python/lists/Pinned-List.py
similarity index 89%
rename from List-lookup/Pinned-Lists-lookup/Pinned-List.py
rename to python/lists/Pinned-List.py
index a27fd4c..898d63f 100644
--- a/List-lookup/Pinned-Lists-lookup/Pinned-List.py
+++ b/python/lists/Pinned-List.py
@@ -20,7 +20,7 @@
list_fields = "list.fields=created_at,description,private"
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -35,13 +35,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -64,7 +64,7 @@
# Making the request
response = oauth.get(
- "https://api.twitter.com/2/users/{}/pinned_lists".format(id), params=list_fields)
+ "https://api.x.com/2/users/{}/pinned_lists".format(id), params=list_fields)
if response.status_code != 200:
raise Exception(
diff --git a/Manage-Lists/Manage-List-Members/add_member.py b/python/lists/add_member.py
similarity index 88%
rename from Manage-Lists/Manage-List-Members/add_member.py
rename to python/lists/add_member.py
index 4f542ab..fe985f1 100644
--- a/Manage-Lists/Manage-List-Members/add_member.py
+++ b/python/lists/add_member.py
@@ -18,7 +18,7 @@
payload = {"user_id": "user-id-to-add"}
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -33,13 +33,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -62,7 +62,7 @@
# Making the request
response = oauth.post(
- "https://api.twitter.com/2/lists/{}/members".format(id), json=payload
+ "https://api.x.com/2/lists/{}/members".format(id), json=payload
)
if response.status_code != 200:
diff --git a/Reverse-Chron-Home-Timeline/OAuth1a-user/reverse-chron-home-timeline.py b/python/lists/create.py
similarity index 64%
rename from Reverse-Chron-Home-Timeline/OAuth1a-user/reverse-chron-home-timeline.py
rename to python/lists/create.py
index 6d6c5a6..cd51ff4 100644
--- a/Reverse-Chron-Home-Timeline/OAuth1a-user/reverse-chron-home-timeline.py
+++ b/python/lists/create.py
@@ -1,20 +1,29 @@
+"""
+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 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
from requests_oauthlib import OAuth1Session
import os
import json
-# To set your enviornment variables in your terminal run the following line:
-# export 'CONSUMER_KEY'=''
-# export 'CONSUMER_SECRET'=''
consumer_key = os.environ.get("CONSUMER_KEY")
consumer_secret = os.environ.get("CONSUMER_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
-id = "your-user-id"
-
-params = {"tweet.fields": "created_at"} # Tweet ID and text are included by default.
+# List parameters
+payload = {
+ "name": "My new list",
+ "description": "A description for my list",
+ "private": False
+}
-request_token_url = "https://api.twitter.com/oauth/request_token"
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -29,13 +38,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -56,16 +65,16 @@
resource_owner_secret=access_token_secret,
)
-response = oauth.get(
- "https://api.twitter.com/2/users/{}/timelines/reverse_chronological".format(id),params=params
-)
+# Making the request
+response = oauth.post("https://api.x.com/2/lists", json=payload)
if response.status_code != 200:
raise Exception(
- "Request returned an error: {} {}".format(
- response.status_code, response.text)
+ "Request returned an error: {} {}".format(response.status_code, response.text)
)
print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
json_response = response.json()
print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/Manage-Lists/create_a_list.py b/python/lists/create_a_list.py
similarity index 89%
rename from Manage-Lists/create_a_list.py
rename to python/lists/create_a_list.py
index a4ece50..cb4d5b0 100644
--- a/Manage-Lists/create_a_list.py
+++ b/python/lists/create_a_list.py
@@ -17,7 +17,7 @@
"private": False}
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -32,13 +32,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -61,7 +61,7 @@
# Making the request
response = oauth.post(
- "https://api.twitter.com/2/lists", json=payload
+ "https://api.x.com/2/lists", json=payload
)
if response.status_code != 201:
diff --git a/python/lists/delete.py b/python/lists/delete.py
new file mode 100644
index 0000000..6d0b4ec
--- /dev/null
+++ b/python/lists/delete.py
@@ -0,0 +1,76 @@
+"""
+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 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# Replace with the list ID you want to delete
+list_id = "list-id-to-delete"
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.delete("https://api.x.com/2/lists/{}".format(list_id))
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/Manage-Lists/delete_a_list.py b/python/lists/delete_a_list.py
similarity index 89%
rename from Manage-Lists/delete_a_list.py
rename to python/lists/delete_a_list.py
index 9edaa89..c00bded 100644
--- a/Manage-Lists/delete_a_list.py
+++ b/python/lists/delete_a_list.py
@@ -16,7 +16,7 @@
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -31,13 +31,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -60,7 +60,7 @@
# Making the request
response = oauth.delete(
- "https://api.twitter.com/2/lists/{}".format(id)
+ "https://api.x.com/2/lists/{}".format(id)
)
if response.status_code != 200:
diff --git a/Manage-Lists/Manage-Followed-Lists/follow_list.py b/python/lists/follow_list.py
similarity index 88%
rename from Manage-Lists/Manage-Followed-Lists/follow_list.py
rename to python/lists/follow_list.py
index 827ae8c..d52adc0 100644
--- a/Manage-Lists/Manage-Followed-Lists/follow_list.py
+++ b/python/lists/follow_list.py
@@ -18,7 +18,7 @@
payload = {"list_id": "list-id-to-follow"}
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -33,13 +33,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -62,7 +62,7 @@
# Making the request
response = oauth.post(
- "https://api.twitter.com/2/users/{}/followed_lists".format(id), json=payload
+ "https://api.x.com/2/users/{}/followed_lists".format(id), json=payload
)
if response.status_code != 200:
diff --git a/List-lookup/List-follows-lookup/list-followers-lookup.py b/python/lists/list-followers-lookup.py
similarity index 95%
rename from List-lookup/List-follows-lookup/list-followers-lookup.py
rename to python/lists/list-followers-lookup.py
index db36cae..85566d0 100644
--- a/List-lookup/List-follows-lookup/list-followers-lookup.py
+++ b/python/lists/list-followers-lookup.py
@@ -15,7 +15,7 @@ def create_url():
user_fields = "user.fields=created_at,description,verified"
# You can replace list-id with the List ID you wish to find followers of.
id = "list-id"
- url = "https://api.twitter.com/2/lists/{}/followers".format(id)
+ url = "https://api.x.com/2/lists/{}/followers".format(id)
return url, user_fields
diff --git a/List-lookup/list-lookup-by-id.py b/python/lists/list-lookup-by-id.py
similarity index 95%
rename from List-lookup/list-lookup-by-id.py
rename to python/lists/list-lookup-by-id.py
index abbee5f..6f47eff 100644
--- a/List-lookup/list-lookup-by-id.py
+++ b/python/lists/list-lookup-by-id.py
@@ -14,7 +14,7 @@ def create_url():
list_fields = "list.fields=created_at,follower_count"
# You can replace the ID given with the List ID you wish to lookup.
id = "list-id"
- url = "https://api.twitter.com/2/lists/{}".format(id)
+ url = "https://api.x.com/2/lists/{}".format(id)
return url, list_fields
diff --git a/List-lookup/List-members-lookup/list-member-lookup.py b/python/lists/list-member-lookup.py
similarity index 95%
rename from List-lookup/List-members-lookup/list-member-lookup.py
rename to python/lists/list-member-lookup.py
index a10fca3..0f10dd3 100644
--- a/List-lookup/List-members-lookup/list-member-lookup.py
+++ b/python/lists/list-member-lookup.py
@@ -15,7 +15,7 @@ def create_url():
user_fields = "user.fields=created_at,description,verified"
# You can replace list-id with the List ID you wish to find members of.
id = "list-id"
- url = "https://api.twitter.com/2/lists/{}/members".format(id)
+ url = "https://api.x.com/2/lists/{}/members".format(id)
return url, user_fields
def bearer_oauth(r):
diff --git a/python/lists/lookup.py b/python/lists/lookup.py
new file mode 100644
index 0000000..b736289
--- /dev/null
+++ b/python/lists/lookup.py
@@ -0,0 +1,55 @@
+"""
+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 requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url():
+ # Replace with the list ID you want to look up
+ list_id = "84839422"
+ return "https://api.x.com/2/lists/{}".format(list_id)
+
+
+def get_params():
+ # List fields are adjustable. Options include:
+ # created_at, follower_count, member_count, private, description, owner_id
+ return {"list.fields": "created_at,follower_count,member_count,owner_id,description"}
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2ListLookupPython"
+ return r
+
+
+def connect_to_endpoint(url, params):
+ response = requests.request("GET", url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = create_url()
+ params = get_params()
+ json_response = connect_to_endpoint(url, params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Manage-Lists/Manage-Pinned-Lists/pin_list.py b/python/lists/pin_list.py
similarity index 88%
rename from Manage-Lists/Manage-Pinned-Lists/pin_list.py
rename to python/lists/pin_list.py
index 127b2c0..20a03b4 100644
--- a/Manage-Lists/Manage-Pinned-Lists/pin_list.py
+++ b/python/lists/pin_list.py
@@ -18,7 +18,7 @@
payload = {"list_id": "list-id-to-pin"}
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -33,13 +33,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -62,7 +62,7 @@
# Making the request
response = oauth.post(
- "https://api.twitter.com/2/users/{}/pinned_lists".format(id), json=payload
+ "https://api.x.com/2/users/{}/pinned_lists".format(id), json=payload
)
if response.status_code != 200:
diff --git a/Manage-Lists/Manage-List-Members/remove_member.py b/python/lists/remove_member.py
similarity index 89%
rename from Manage-Lists/Manage-List-Members/remove_member.py
rename to python/lists/remove_member.py
index 01a1f8e..cf51b34 100644
--- a/Manage-Lists/Manage-List-Members/remove_member.py
+++ b/python/lists/remove_member.py
@@ -19,7 +19,7 @@
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -34,13 +34,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -63,7 +63,7 @@
# Making the request
response = oauth.delete(
- "https://api.twitter.com/2/lists/{}/members/{}".format(id, user_id)
+ "https://api.x.com/2/lists/{}/members/{}".format(id, user_id)
)
if response.status_code != 200:
diff --git a/Manage-Lists/Manage-Followed-Lists/unfollow_list.py b/python/lists/unfollow_list.py
similarity index 89%
rename from Manage-Lists/Manage-Followed-Lists/unfollow_list.py
rename to python/lists/unfollow_list.py
index ac5f779..d28b62a 100644
--- a/Manage-Lists/Manage-Followed-Lists/unfollow_list.py
+++ b/python/lists/unfollow_list.py
@@ -19,7 +19,7 @@
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -34,13 +34,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -63,7 +63,7 @@
# Making the request
response = oauth.delete(
- "https://api.twitter.com/2/users/{}/followed_lists/{}".format(id, list_id)
+ "https://api.x.com/2/users/{}/followed_lists/{}".format(id, list_id)
)
if response.status_code != 200:
diff --git a/Manage-Lists/Manage-Pinned-Lists/unpin_list.py b/python/lists/unpin_list.py
similarity index 89%
rename from Manage-Lists/Manage-Pinned-Lists/unpin_list.py
rename to python/lists/unpin_list.py
index dab8620..03e76d7 100644
--- a/Manage-Lists/Manage-Pinned-Lists/unpin_list.py
+++ b/python/lists/unpin_list.py
@@ -19,7 +19,7 @@
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -34,13 +34,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -63,7 +63,7 @@
# Making the request
response = oauth.delete(
- "https://api.twitter.com/2/users/{}/pinned_lists/{}".format(id, list_id)
+ "https://api.x.com/2/users/{}/pinned_lists/{}".format(id, list_id)
)
if response.status_code != 200:
diff --git a/Manage-Lists/update_a_list.py b/python/lists/update_a_list.py
similarity index 89%
rename from Manage-Lists/update_a_list.py
rename to python/lists/update_a_list.py
index fe27f87..8abf2ba 100644
--- a/Manage-Lists/update_a_list.py
+++ b/python/lists/update_a_list.py
@@ -22,7 +22,7 @@
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -37,13 +37,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -66,7 +66,7 @@
# Making the request
response = oauth.put(
- "https://api.twitter.com/2/lists/{}".format(id), json=payload
+ "https://api.x.com/2/lists/{}".format(id), json=payload
)
if response.status_code != 200:
diff --git a/List-lookup/List-follows-lookup/user-list-followed.py b/python/lists/user-list-followed.py
similarity index 95%
rename from List-lookup/List-follows-lookup/user-list-followed.py
rename to python/lists/user-list-followed.py
index 448efb5..f28b3be 100644
--- a/List-lookup/List-follows-lookup/user-list-followed.py
+++ b/python/lists/user-list-followed.py
@@ -14,7 +14,7 @@ def create_url():
list_fields = "list.fields=created_at,follower_count"
# You can replace the user-id with any valid User ID you wish to find what Lists they are following.
id = "user-id"
- url = "https://api.twitter.com/2/users/{}/followed_lists".format(id)
+ url = "https://api.x.com/2/users/{}/followed_lists".format(id)
return url, list_fields
diff --git a/List-lookup/List-members-lookup/user-list-memberships.py b/python/lists/user-list-memberships.py
similarity index 94%
rename from List-lookup/List-members-lookup/user-list-memberships.py
rename to python/lists/user-list-memberships.py
index a8440db..3455aaa 100644
--- a/List-lookup/List-members-lookup/user-list-memberships.py
+++ b/python/lists/user-list-memberships.py
@@ -14,7 +14,7 @@ def create_url():
list_fields = "list.fields=created_at,follower_count"
# You can replace the user-id with any valid User ID you wish to find what Lists they are members of.
id = "user-id"
- url = "https://api.twitter.com/2/users/{}/list_memberships".format(id)
+ url = "https://api.x.com/2/users/{}/list_memberships".format(id)
return url, list_fields
diff --git a/List-lookup/user-owned-list-lookup.py b/python/lists/user-owned-list-lookup.py
similarity index 95%
rename from List-lookup/user-owned-list-lookup.py
rename to python/lists/user-owned-list-lookup.py
index 0b49b7b..3bbcd99 100644
--- a/List-lookup/user-owned-list-lookup.py
+++ b/python/lists/user-owned-list-lookup.py
@@ -14,7 +14,7 @@ def create_url():
list_fields = "list.fields=created_at,follower_count"
# You can replace user-id with any valid User ID to see if they own any Lists.
id = "user-id"
- url = "https://api.twitter.com/2/users/{}/owned_lists".format(id)
+ url = "https://api.x.com/2/users/{}/owned_lists".format(id)
return url, list_fields
diff --git a/Media Upload/media_upload_v2.py b/python/media/media_upload_v2.py
similarity index 100%
rename from Media Upload/media_upload_v2.py
rename to python/media/media_upload_v2.py
diff --git a/python/media/upload.py b/python/media/upload.py
new file mode 100644
index 0000000..130fa5b
--- /dev/null
+++ b/python/media/upload.py
@@ -0,0 +1,91 @@
+"""
+Media Upload - 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 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+
+This example demonstrates uploading an image to attach to a post.
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+import base64
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# Path to the media file you want to upload
+media_path = "path/to/your/image.jpg"
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Read and encode the media file
+with open(media_path, "rb") as media_file:
+ media_data = base64.b64encode(media_file.read()).decode("utf-8")
+
+# Upload the media (using v1.1 endpoint as v2 media upload is similar)
+upload_url = "https://upload.twitter.com/1.1/media/upload.json"
+payload = {"media_data": media_data}
+
+response = oauth.post(upload_url, data=payload)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Get the media_id to use when creating a post
+json_response = response.json()
+media_id = json_response["media_id_string"]
+print("Media ID: {}".format(media_id))
+print(json.dumps(json_response, indent=4, sort_keys=True))
+
+# You can now use this media_id when creating a post:
+# payload = {"text": "My post with media!", "media": {"media_ids": [media_id]}}
diff --git a/python/posts/counts_full_archive.py b/python/posts/counts_full_archive.py
new file mode 100644
index 0000000..963c026
--- /dev/null
+++ b/python/posts/counts_full_archive.py
@@ -0,0 +1,52 @@
+"""
+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
+
+Note: Requires Academic Research access. Returns counts from the entire archive.
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2FullArchivePostCountsPython"
+ return r
+
+
+def get_params():
+ return {
+ "query": "from:XDevelopers",
+ "granularity": "day"
+ }
+
+
+def connect_to_endpoint(url, params):
+ response = requests.request("GET", url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = "https://api.x.com/2/tweets/counts/all"
+ params = get_params()
+ json_response = connect_to_endpoint(url, params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/python/posts/counts_recent.py b/python/posts/counts_recent.py
new file mode 100644
index 0000000..8f51666
--- /dev/null
+++ b/python/posts/counts_recent.py
@@ -0,0 +1,52 @@
+"""
+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
+
+Note: Returns count of posts from the last 7 days matching your query.
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2PostCountsPython"
+ return r
+
+
+def get_params():
+ return {
+ "query": "from:XDevelopers",
+ "granularity": "day"
+ }
+
+
+def connect_to_endpoint(url, params):
+ response = requests.request("GET", url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = "https://api.x.com/2/tweets/counts/recent"
+ params = get_params()
+ json_response = connect_to_endpoint(url, params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/python/posts/create_post.py b/python/posts/create_post.py
new file mode 100644
index 0000000..63cf6fd
--- /dev/null
+++ b/python/posts/create_post.py
@@ -0,0 +1,80 @@
+"""
+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 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# The text content of the post. You can also add parameters for polls,
+# quote posts, reply settings, and more.
+payload = {"text": "Hello world!"}
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.post(
+ "https://api.x.com/2/tweets",
+ json=payload,
+)
+
+if response.status_code != 201:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/Manage-Tweets/create_tweet.py b/python/posts/create_tweet.py
similarity index 88%
rename from Manage-Tweets/create_tweet.py
rename to python/posts/create_tweet.py
index a8efc85..92c570b 100644
--- a/Manage-Tweets/create_tweet.py
+++ b/python/posts/create_tweet.py
@@ -13,7 +13,7 @@
payload = {"text": "Hello world!"}
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write"
+request_token_url = "https://api.x.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -28,13 +28,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -57,7 +57,7 @@
# Making the request
response = oauth.post(
- "https://api.twitter.com/2/tweets",
+ "https://api.x.com/2/tweets",
json=payload,
)
diff --git a/python/posts/delete_post.py b/python/posts/delete_post.py
new file mode 100644
index 0000000..0199ab0
--- /dev/null
+++ b/python/posts/delete_post.py
@@ -0,0 +1,77 @@
+"""
+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 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# Replace with the ID of the post you wish to delete.
+# The authenticated user must own the post.
+post_id = "post-id-to-delete"
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.delete("https://api.x.com/2/tweets/{}".format(post_id))
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json_response)
diff --git a/Manage-Tweets/delete_tweet.py b/python/posts/delete_tweet.py
similarity index 88%
rename from Manage-Tweets/delete_tweet.py
rename to python/posts/delete_tweet.py
index 5aff4bc..2184284 100644
--- a/Manage-Tweets/delete_tweet.py
+++ b/python/posts/delete_tweet.py
@@ -16,7 +16,7 @@
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -31,13 +31,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -59,7 +59,7 @@
)
# Making the request
-response = oauth.delete("https://api.twitter.com/2/tweets/{}".format(id))
+response = oauth.delete("https://api.x.com/2/tweets/{}".format(id))
if response.status_code != 200:
raise Exception(
diff --git a/Full-Archive-Search/full-archive-search.py b/python/posts/full-archive-search.py
similarity index 95%
rename from Full-Archive-Search/full-archive-search.py
rename to python/posts/full-archive-search.py
index acb0a95..785c487 100644
--- a/Full-Archive-Search/full-archive-search.py
+++ b/python/posts/full-archive-search.py
@@ -6,7 +6,7 @@
# export 'BEARER_TOKEN'=''
bearer_token = os.environ.get("BEARER_TOKEN")
-search_url = "https://api.twitter.com/2/tweets/search/all"
+search_url = "https://api.x.com/2/tweets/search/all"
# Optional params: start_time,end_time,since_id,until_id,max_results,next_token,
# expansions,tweet.fields,media.fields,poll.fields,place.fields,user.fields
diff --git a/Full-Archive-Tweet-Counts/full_archive_tweet_counts.py b/python/posts/full_archive_tweet_counts.py
similarity index 94%
rename from Full-Archive-Tweet-Counts/full_archive_tweet_counts.py
rename to python/posts/full_archive_tweet_counts.py
index 0476e03..697a0be 100644
--- a/Full-Archive-Tweet-Counts/full_archive_tweet_counts.py
+++ b/python/posts/full_archive_tweet_counts.py
@@ -6,7 +6,7 @@
# export 'BEARER_TOKEN'=''
bearer_token = os.environ.get("BEARER_TOKEN")
-search_url = "https://api.twitter.com/2/tweets/counts/all"
+search_url = "https://api.x.com/2/tweets/counts/all"
# Optional params: start_time,end_time,since_id,until_id,next_token,granularity
query_params = {'query': 'from:twitterdev','granularity': 'day', 'start_time': '2021-01-01T00:00:00Z'}
diff --git a/Tweet-Lookup/get_tweets_with_bearer_token.py b/python/posts/get_tweets_with_bearer_token.py
similarity index 95%
rename from Tweet-Lookup/get_tweets_with_bearer_token.py
rename to python/posts/get_tweets_with_bearer_token.py
index 5f1cafa..e646f70 100644
--- a/Tweet-Lookup/get_tweets_with_bearer_token.py
+++ b/python/posts/get_tweets_with_bearer_token.py
@@ -19,7 +19,7 @@ def create_url():
ids = "ids=1278747501642657792,1255542774432063488"
# You can adjust ids to include a single Tweets.
# Or you can add to up to 100 comma-separated IDs
- url = "https://api.twitter.com/2/tweets?{}&{}".format(ids, tweet_fields)
+ url = "https://api.x.com/2/tweets?{}&{}".format(ids, tweet_fields)
return url
diff --git a/Tweet-Lookup/get_tweets_with_user_context.py b/python/posts/get_tweets_with_user_context.py
similarity index 90%
rename from Tweet-Lookup/get_tweets_with_user_context.py
rename to python/posts/get_tweets_with_user_context.py
index e66becb..8ab866e 100644
--- a/Tweet-Lookup/get_tweets_with_user_context.py
+++ b/python/posts/get_tweets_with_user_context.py
@@ -20,7 +20,7 @@
# possibly_sensitive, promoted_metrics, public_metrics, referenced_tweets,
# source, text, and withheld
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -35,13 +35,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -64,7 +64,7 @@
)
response = oauth.get(
- "https://api.twitter.com/2/tweets", params=params
+ "https://api.x.com/2/tweets", params=params
)
if response.status_code != 200:
diff --git a/python/posts/like.py b/python/posts/like.py
new file mode 100644
index 0000000..5bcb4d6
--- /dev/null
+++ b/python/posts/like.py
@@ -0,0 +1,81 @@
+"""
+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 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# Replace with your own user ID
+user_id = "your-user-id"
+
+# Replace with the post ID you want to like
+payload = {"tweet_id": "1354143047324299264"}
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.post(
+ "https://api.x.com/2/users/{}/likes".format(user_id), json=payload
+)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/Manage-Likes/like_a_tweet.py b/python/posts/like_a_tweet.py
similarity index 89%
rename from Manage-Likes/like_a_tweet.py
rename to python/posts/like_a_tweet.py
index abe8818..00a24ce 100644
--- a/Manage-Likes/like_a_tweet.py
+++ b/python/posts/like_a_tweet.py
@@ -18,7 +18,7 @@
payload = {"tweet_id": "1354143047324299264"}
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -33,13 +33,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -62,7 +62,7 @@
# Making the request
response = oauth.post(
- "https://api.twitter.com/2/users/{}/likes".format(id), json=payload
+ "https://api.x.com/2/users/{}/likes".format(id), json=payload
)
if response.status_code != 200:
diff --git a/python/posts/liked_posts.py b/python/posts/liked_posts.py
new file mode 100644
index 0000000..cfafbf5
--- /dev/null
+++ b/python/posts/liked_posts.py
@@ -0,0 +1,53 @@
+"""
+Posts Liked by User - 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: Bearer Token (App-only) or OAuth (User Context)
+Required env vars: BEARER_TOKEN
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url():
+ # Replace with the user ID you want to get liked posts for
+ user_id = "2244994945"
+ return "https://api.x.com/2/users/{}/liked_tweets".format(user_id)
+
+
+def get_params():
+ return {"tweet.fields": "created_at"}
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2LikedPostsPython"
+ return r
+
+
+def connect_to_endpoint(url, params):
+ response = requests.request("GET", url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = create_url()
+ params = get_params()
+ json_response = connect_to_endpoint(url, params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Likes-Lookup/liked_tweets.py b/python/posts/liked_tweets.py
similarity index 96%
rename from Likes-Lookup/liked_tweets.py
rename to python/posts/liked_tweets.py
index 5b05cc2..b668621 100644
--- a/Likes-Lookup/liked_tweets.py
+++ b/python/posts/liked_tweets.py
@@ -21,7 +21,7 @@ def create_url():
id = "your-user-id"
# You can adjust ids to include a single Tweets.
# Or you can add to up to 100 comma-separated IDs
- url = "https://api.twitter.com/2/users/{}/liked_tweets".format(id)
+ url = "https://api.x.com/2/users/{}/liked_tweets".format(id)
return url, tweet_fields
diff --git a/Likes-Lookup/liking_users.py b/python/posts/liking_users.py
similarity index 95%
rename from Likes-Lookup/liking_users.py
rename to python/posts/liking_users.py
index 01079d5..1b08116 100644
--- a/Likes-Lookup/liking_users.py
+++ b/python/posts/liking_users.py
@@ -18,7 +18,7 @@ def create_url():
id = "1354143047324299264"
# You can adjust ids to include a single Tweets.
# Or you can add to up to 100 comma-separated IDs
- url = "https://api.twitter.com/2/tweets/{}/liking_users".format(id)
+ url = "https://api.x.com/2/tweets/{}/liking_users".format(id)
return url, user_fields
diff --git a/python/posts/lookup.py b/python/posts/lookup.py
new file mode 100644
index 0000000..802a466
--- /dev/null
+++ b/python/posts/lookup.py
@@ -0,0 +1,61 @@
+"""
+Post Lookup - 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) or OAuth (User Context)
+Required env vars: BEARER_TOKEN
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url():
+ # Post IDs to look up (comma-separated, up to 100)
+ post_ids = "ids=1278747501642657792,1255542774432063488"
+
+ # Post fields are adjustable. Options include:
+ # attachments, author_id, context_annotations, conversation_id,
+ # created_at, entities, geo, id, in_reply_to_user_id, lang,
+ # non_public_metrics, organic_metrics, possibly_sensitive,
+ # promoted_metrics, public_metrics, referenced_tweets,
+ # source, text, and withheld
+ post_fields = "tweet.fields=created_at,author_id,lang,source,public_metrics,context_annotations,entities"
+ url = "https://api.x.com/2/tweets?{}&{}".format(post_ids, post_fields)
+ return url
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2PostLookupPython"
+ return r
+
+
+def connect_to_endpoint(url):
+ response = requests.request("GET", url, auth=bearer_oauth)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(
+ response.status_code, response.text
+ )
+ )
+ return response.json()
+
+
+def main():
+ url = create_url()
+ json_response = connect_to_endpoint(url)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/python/posts/quote_posts.py b/python/posts/quote_posts.py
new file mode 100644
index 0000000..038ebea
--- /dev/null
+++ b/python/posts/quote_posts.py
@@ -0,0 +1,54 @@
+"""
+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) or OAuth (User Context)
+Required env vars: BEARER_TOKEN
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+# Replace with the post ID you want to get quotes for
+post_id = "1409931481552543749"
+
+
+def get_params():
+ return {"tweet.fields": "created_at"}
+
+
+def create_url():
+ return "https://api.x.com/2/tweets/{}/quote_tweets".format(post_id)
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2QuotePostsPython"
+ return r
+
+
+def connect_to_endpoint(url, params):
+ response = requests.request("GET", url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = create_url()
+ params = get_params()
+ json_response = connect_to_endpoint(url, params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Quote-Tweets/quote_tweets.py b/python/posts/quote_tweets.py
similarity index 94%
rename from Quote-Tweets/quote_tweets.py
rename to python/posts/quote_tweets.py
index 509b656..a56204c 100644
--- a/Quote-Tweets/quote_tweets.py
+++ b/python/posts/quote_tweets.py
@@ -13,7 +13,7 @@ def auth():
def create_url():
# Replace with Tweet ID below
tweet_id = 20
- return "https://api.twitter.com/2/tweets/{}/quote_tweets".format(tweet_id)
+ return "https://api.x.com/2/tweets/{}/quote_tweets".format(tweet_id)
def get_params():
diff --git a/Recent-Search/recent_search.py b/python/posts/recent_search.py
similarity index 94%
rename from Recent-Search/recent_search.py
rename to python/posts/recent_search.py
index cb97511..58b19a9 100644
--- a/Recent-Search/recent_search.py
+++ b/python/posts/recent_search.py
@@ -6,7 +6,7 @@
# export 'BEARER_TOKEN'=''
bearer_token = os.environ.get("BEARER_TOKEN")
-search_url = "https://api.twitter.com/2/tweets/search/recent"
+search_url = "https://api.x.com/2/tweets/search/recent"
# Optional params: start_time,end_time,since_id,until_id,max_results,next_token,
# expansions,tweet.fields,media.fields,poll.fields,place.fields,user.fields
diff --git a/Recent-Tweet-Counts/recent_tweet_counts.py b/python/posts/recent_tweet_counts.py
similarity index 94%
rename from Recent-Tweet-Counts/recent_tweet_counts.py
rename to python/posts/recent_tweet_counts.py
index 6ceafba..2b94f03 100644
--- a/Recent-Tweet-Counts/recent_tweet_counts.py
+++ b/python/posts/recent_tweet_counts.py
@@ -6,7 +6,7 @@
# export 'BEARER_TOKEN'=''
bearer_token = os.environ.get("BEARER_TOKEN")
-search_url = "https://api.twitter.com/2/tweets/counts/recent"
+search_url = "https://api.x.com/2/tweets/counts/recent"
# Optional params: start_time,end_time,since_id,until_id,next_token,granularity
query_params = {'query': 'from:twitterdev','granularity': 'day'}
diff --git a/python/posts/repost.py b/python/posts/repost.py
new file mode 100644
index 0000000..e5cd46e
--- /dev/null
+++ b/python/posts/repost.py
@@ -0,0 +1,81 @@
+"""
+Repost (Retweet) - 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 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# Replace with your own user ID (find using user lookup endpoint)
+user_id = "your-user-id"
+
+# Replace with the post ID you want to repost
+payload = {"tweet_id": "1412865600439738368"}
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.post(
+ "https://api.x.com/2/users/{}/retweets".format(user_id), json=payload
+)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/python/posts/reposted_by.py b/python/posts/reposted_by.py
new file mode 100644
index 0000000..c2ff4fc
--- /dev/null
+++ b/python/posts/reposted_by.py
@@ -0,0 +1,53 @@
+"""
+Reposted By (Users who retweeted) - 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) or OAuth (User Context)
+Required env vars: BEARER_TOKEN
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url():
+ # Replace with the post ID you want to get reposters for
+ post_id = "1354143047324299264"
+ return "https://api.x.com/2/tweets/{}/retweeted_by".format(post_id)
+
+
+def get_params():
+ return {"user.fields": "created_at"}
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2RepostedByPython"
+ return r
+
+
+def connect_to_endpoint(url, params):
+ response = requests.request("GET", url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = create_url()
+ params = get_params()
+ json_response = connect_to_endpoint(url, params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Manage-Retweets/retweet_a_tweet.py b/python/posts/retweet_a_tweet.py
similarity index 89%
rename from Manage-Retweets/retweet_a_tweet.py
rename to python/posts/retweet_a_tweet.py
index 449f386..40c218b 100644
--- a/Manage-Retweets/retweet_a_tweet.py
+++ b/python/posts/retweet_a_tweet.py
@@ -19,7 +19,7 @@
payload = {"tweet_id": "1412865600439738368"}
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -34,13 +34,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -63,7 +63,7 @@
# Making the request
response = oauth.post(
- "https://api.twitter.com/2/users/{}/retweets".format(id), json=payload
+ "https://api.x.com/2/users/{}/retweets".format(id), json=payload
)
if response.status_code != 200:
diff --git a/Retweets-Lookup/retweeted_by.py b/python/posts/retweeted_by.py
similarity index 95%
rename from Retweets-Lookup/retweeted_by.py
rename to python/posts/retweeted_by.py
index f171bc4..9876a36 100644
--- a/Retweets-Lookup/retweeted_by.py
+++ b/python/posts/retweeted_by.py
@@ -20,7 +20,7 @@ def create_url():
id = "1354143047324299264"
# You can adjust ids to include a single Tweets.
# Or you can add to up to 100 comma-separated IDs
- url = "https://api.twitter.com/2/tweets/{}/retweeted_by".format(id)
+ url = "https://api.x.com/2/tweets/{}/retweeted_by".format(id)
return url, user_fields
diff --git a/python/posts/search_full_archive.py b/python/posts/search_full_archive.py
new file mode 100644
index 0000000..e9c9bc8
--- /dev/null
+++ b/python/posts/search_full_archive.py
@@ -0,0 +1,53 @@
+"""
+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
+
+Note: Requires Academic Research access. Returns posts from the entire archive.
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+search_url = "https://api.x.com/2/tweets/search/all"
+
+# Optional params: start_time, end_time, since_id, until_id, max_results,
+# next_token, expansions, tweet.fields, media.fields, poll.fields,
+# place.fields, user.fields
+query_params = {
+ 'query': '(from:XDevelopers -is:retweet) OR #xapi',
+ 'tweet.fields': 'author_id'
+}
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2FullArchiveSearchPython"
+ return r
+
+
+def connect_to_endpoint(url, params):
+ response = requests.get(url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ json_response = connect_to_endpoint(search_url, query_params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/python/posts/search_recent.py b/python/posts/search_recent.py
new file mode 100644
index 0000000..9538a83
--- /dev/null
+++ b/python/posts/search_recent.py
@@ -0,0 +1,52 @@
+"""
+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) or OAuth (User Context)
+Required env vars: BEARER_TOKEN
+
+Note: Returns posts from the last 7 days.
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+search_url = "https://api.x.com/2/tweets/search/recent"
+
+# Optional params: start_time, end_time, since_id, until_id, max_results, next_token,
+# expansions, tweet.fields, media.fields, poll.fields, place.fields, user.fields
+query_params = {
+ 'query': '(from:XDevelopers -is:retweet) OR #xapi',
+ 'tweet.fields': 'author_id'
+}
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2RecentSearchPython"
+ return r
+
+
+def connect_to_endpoint(url, params):
+ response = requests.get(url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ json_response = connect_to_endpoint(search_url, query_params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Manage-Retweets/undo_a_retweet.py b/python/posts/undo_a_retweet.py
similarity index 89%
rename from Manage-Retweets/undo_a_retweet.py
rename to python/posts/undo_a_retweet.py
index 7c427c6..51fe32d 100644
--- a/Manage-Retweets/undo_a_retweet.py
+++ b/python/posts/undo_a_retweet.py
@@ -20,7 +20,7 @@
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -35,13 +35,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -64,7 +64,7 @@
# Making the request
response = oauth.delete(
- "https://api.twitter.com/2/users/{}/retweets/{}".format(id, source_tweet_id)
+ "https://api.x.com/2/users/{}/retweets/{}".format(id, source_tweet_id)
)
if response.status_code != 200:
diff --git a/python/posts/undo_repost.py b/python/posts/undo_repost.py
new file mode 100644
index 0000000..fb87599
--- /dev/null
+++ b/python/posts/undo_repost.py
@@ -0,0 +1,81 @@
+"""
+Undo Repost (Unretweet) - 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 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# Replace with your own user ID
+user_id = "your-user-id"
+
+# Replace with the post ID you want to undo repost for
+source_post_id = "post-id-to-unrepost"
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.delete(
+ "https://api.x.com/2/users/{}/retweets/{}".format(user_id, source_post_id)
+)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/python/posts/unlike.py b/python/posts/unlike.py
new file mode 100644
index 0000000..4691558
--- /dev/null
+++ b/python/posts/unlike.py
@@ -0,0 +1,81 @@
+"""
+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 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# Replace with your own user ID
+user_id = "your-user-id"
+
+# Replace with the post ID you want to unlike
+post_id = "post-id-to-unlike"
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.delete(
+ "https://api.x.com/2/users/{}/likes/{}".format(user_id, post_id)
+)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/Manage-Likes/unlike_a_tweet.py b/python/posts/unlike_a_tweet.py
similarity index 89%
rename from Manage-Likes/unlike_a_tweet.py
rename to python/posts/unlike_a_tweet.py
index 33151af..91ff611 100644
--- a/Manage-Likes/unlike_a_tweet.py
+++ b/python/posts/unlike_a_tweet.py
@@ -17,7 +17,7 @@
tweet_id = "1354143047324299264"
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -32,13 +32,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -61,7 +61,7 @@
# Making the request
response = oauth.delete(
- "https://api.twitter.com/2/users/{}/likes/{}".format(id, tweet_id)
+ "https://api.x.com/2/users/{}/likes/{}".format(id, tweet_id)
)
if response.status_code != 200:
diff --git a/python/requirements.txt b/python/requirements.txt
new file mode 100644
index 0000000..a85ab73
--- /dev/null
+++ b/python/requirements.txt
@@ -0,0 +1,2 @@
+requests>=2.28.0
+requests-oauthlib>=1.3.0
diff --git a/python/spaces/lookup.py b/python/spaces/lookup.py
new file mode 100644
index 0000000..5a0f185
--- /dev/null
+++ b/python/spaces/lookup.py
@@ -0,0 +1,55 @@
+"""
+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 requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url():
+ # Space IDs to look up (comma-separated)
+ space_ids = "ids=1DXxyRYNejbKM"
+
+ # Space fields are adjustable. Options include:
+ # host_ids, created_at, creator_id, id, lang, invited_user_ids,
+ # participant_count, speaker_ids, started_at, ended_at, subscriber_count,
+ # topic_ids, state, title, updated_at, scheduled_start, is_ticketed
+ space_fields = "space.fields=host_ids,created_at,creator_id,participant_count,title,state"
+ url = "https://api.x.com/2/spaces?{}&{}".format(space_ids, space_fields)
+ return url
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2SpacesLookupPython"
+ return r
+
+
+def connect_to_endpoint(url):
+ response = requests.request("GET", url, auth=bearer_oauth)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = create_url()
+ json_response = connect_to_endpoint(url)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/python/spaces/search.py b/python/spaces/search.py
new file mode 100644
index 0000000..7678e2e
--- /dev/null
+++ b/python/spaces/search.py
@@ -0,0 +1,55 @@
+"""
+Spaces Search - 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) or OAuth (User Context)
+Required env vars: BEARER_TOKEN
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url():
+ query = "query=crypto"
+ state = "state=live"
+
+ # Space fields are adjustable. Options include:
+ # host_ids, created_at, creator_id, id, lang, invited_user_ids,
+ # participant_count, speaker_ids, started_at, ended_at, subscriber_count,
+ # topic_ids, state, title, updated_at, scheduled_start, is_ticketed
+ space_fields = "space.fields=host_ids,created_at,participant_count,title"
+ url = "https://api.x.com/2/spaces/search?{}&{}&{}".format(query, state, space_fields)
+ return url
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2SpacesSearchPython"
+ return r
+
+
+def connect_to_endpoint(url):
+ response = requests.request("GET", url, auth=bearer_oauth)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = create_url()
+ json_response = connect_to_endpoint(url)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Search-Spaces/search_spaces.py b/python/spaces/search_spaces.py
similarity index 95%
rename from Search-Spaces/search_spaces.py
rename to python/spaces/search_spaces.py
index 430825e..d0c6340 100644
--- a/Search-Spaces/search_spaces.py
+++ b/python/spaces/search_spaces.py
@@ -6,7 +6,7 @@
# export 'BEARER_TOKEN'=''
bearer_token = os.environ.get("BEARER_TOKEN")
-search_url = "https://api.twitter.com/2/spaces/search"
+search_url = "https://api.x.com/2/spaces/search"
search_term = 'NBA' # Replace this value with your search term
diff --git a/Spaces-Lookup/spaces_lookup.py b/python/spaces/spaces_lookup.py
similarity index 96%
rename from Spaces-Lookup/spaces_lookup.py
rename to python/spaces/spaces_lookup.py
index 20b586e..7c576d7 100644
--- a/Spaces-Lookup/spaces_lookup.py
+++ b/python/spaces/spaces_lookup.py
@@ -6,7 +6,7 @@
# export 'BEARER_TOKEN'=''
bearer_token = os.environ.get("BEARER_TOKEN")
-search_url = "https://api.twitter.com/2/spaces"
+search_url = "https://api.x.com/2/spaces"
# 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
query_params = {'ids': 'SPACE_ID', 'space.fields': 'title,created_at', 'expansions': 'creator_id'}
diff --git a/Filtered-Stream/filtered_stream.py b/python/streams/filtered_stream.py
similarity index 88%
rename from Filtered-Stream/filtered_stream.py
rename to python/streams/filtered_stream.py
index 346ca32..88d578b 100644
--- a/Filtered-Stream/filtered_stream.py
+++ b/python/streams/filtered_stream.py
@@ -19,7 +19,7 @@ def bearer_oauth(r):
def get_rules():
response = requests.get(
- "https://api.twitter.com/2/tweets/search/stream/rules", auth=bearer_oauth
+ "https://api.x.com/2/tweets/search/stream/rules", auth=bearer_oauth
)
if response.status_code != 200:
raise Exception(
@@ -36,7 +36,7 @@ def delete_all_rules(rules):
ids = list(map(lambda rule: rule["id"], rules["data"]))
payload = {"delete": {"ids": ids}}
response = requests.post(
- "https://api.twitter.com/2/tweets/search/stream/rules",
+ "https://api.x.com/2/tweets/search/stream/rules",
auth=bearer_oauth,
json=payload
)
@@ -57,7 +57,7 @@ def set_rules(delete):
]
payload = {"add": sample_rules}
response = requests.post(
- "https://api.twitter.com/2/tweets/search/stream/rules",
+ "https://api.x.com/2/tweets/search/stream/rules",
auth=bearer_oauth,
json=payload,
)
@@ -70,7 +70,7 @@ def set_rules(delete):
def get_stream(set):
response = requests.get(
- "https://api.twitter.com/2/tweets/search/stream", auth=bearer_oauth, stream=True,
+ "https://api.x.com/2/tweets/search/stream", auth=bearer_oauth, stream=True,
)
print(response.status_code)
if response.status_code != 200:
diff --git a/Sampled-Stream/sampled-stream.py b/python/streams/sampled-stream.py
similarity index 94%
rename from Sampled-Stream/sampled-stream.py
rename to python/streams/sampled-stream.py
index 4b28641..ef0eb9d 100644
--- a/Sampled-Stream/sampled-stream.py
+++ b/python/streams/sampled-stream.py
@@ -8,7 +8,7 @@
def create_url():
- return "https://api.twitter.com/2/tweets/sample/stream"
+ return "https://api.x.com/2/tweets/sample/stream"
def bearer_oauth(r):
diff --git a/python/streams/sampled_stream.py b/python/streams/sampled_stream.py
new file mode 100644
index 0000000..456b31b
--- /dev/null
+++ b/python/streams/sampled_stream.py
@@ -0,0 +1,51 @@
+"""
+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
+
+Note: Returns approximately 1% of all public posts in real-time.
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2SampledStreamPython"
+ return r
+
+
+def get_stream():
+ response = requests.get(
+ "https://api.x.com/2/tweets/sample/stream", auth=bearer_oauth, stream=True,
+ )
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(
+ "Cannot get stream (HTTP {}): {}".format(
+ response.status_code, response.text
+ )
+ )
+ for response_line in response.iter_lines():
+ if response_line:
+ json_response = json.loads(response_line)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+def main():
+ get_stream()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/python/timelines/home_timeline.py b/python/timelines/home_timeline.py
new file mode 100644
index 0000000..f8a8d23
--- /dev/null
+++ b/python/timelines/home_timeline.py
@@ -0,0 +1,83 @@
+"""
+Reverse Chronological Home Timeline - X API v2
+==============================================
+Endpoint: GET https://api.x.com/2/users/:id/reverse_chronological_timeline
+Docs: https://developer.x.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-reverse-chronological-timeline
+
+Authentication: OAuth 1.0a or OAuth 2.0 (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# Post fields are adjustable. Options include:
+# attachments, author_id, context_annotations, conversation_id,
+# created_at, entities, geo, id, in_reply_to_user_id, lang,
+# possibly_sensitive, public_metrics, referenced_tweets, source, text
+params = {"tweet.fields": "created_at"}
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+user_id = oauth_tokens["user_id"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.get(
+ "https://api.x.com/2/users/{}/reverse_chronological_timeline".format(user_id),
+ params=params
+)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/Reverse-Chron-Home-Timeline/OAuth2-user/reverse-chron-home-timeline.py b/python/timelines/reverse-chron-home-timeline.py
similarity index 95%
rename from Reverse-Chron-Home-Timeline/OAuth2-user/reverse-chron-home-timeline.py
rename to python/timelines/reverse-chron-home-timeline.py
index ed6e2f8..7b09c66 100644
--- a/Reverse-Chron-Home-Timeline/OAuth2-user/reverse-chron-home-timeline.py
+++ b/python/timelines/reverse-chron-home-timeline.py
@@ -57,7 +57,7 @@
)
# Fetch your access token
-token_url = "https://api.twitter.com/2/oauth2/token"
+token_url = "https://api.x.com/2/oauth2/token"
# The following line of code will only work if you are using a type of App that is a public client
auth = False
@@ -82,7 +82,7 @@
# Make a request to the users/me endpoint to get your user ID
user_me = requests.request(
"GET",
- "https://api.twitter.com/2/users/me",
+ "https://api.x.com/2/users/me",
headers={"Authorization": "Bearer {}".format(access)},
).json()
@@ -96,7 +96,7 @@
user_id = user_me["data"]["id"]
# Set the url.
-url = "https://api.twitter.com/2/users/{}/timelines/reverse_chronological".format(user_id)
+url = "https://api.x.com/2/users/{}/timelines/reverse_chronological".format(user_id)
headers = {
"Authorization": "Bearer {}".format(access),
diff --git a/User-Mention-Timeline/user_mentions.py b/python/timelines/user_mentions.py
similarity index 95%
rename from User-Mention-Timeline/user_mentions.py
rename to python/timelines/user_mentions.py
index fbf94c1..4b9aca8 100644
--- a/User-Mention-Timeline/user_mentions.py
+++ b/python/timelines/user_mentions.py
@@ -10,7 +10,7 @@
def create_url():
# Replace with user ID below
user_id = 2244994945
- return "https://api.twitter.com/2/users/{}/mentions".format(user_id)
+ return "https://api.x.com/2/users/{}/mentions".format(user_id)
def get_params():
diff --git a/python/timelines/user_posts.py b/python/timelines/user_posts.py
new file mode 100644
index 0000000..a691277
--- /dev/null
+++ b/python/timelines/user_posts.py
@@ -0,0 +1,57 @@
+"""
+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) or OAuth (User Context)
+Required env vars: BEARER_TOKEN
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url():
+ # Replace with the user ID you want to get posts for
+ user_id = "2244994945"
+ return "https://api.x.com/2/users/{}/tweets".format(user_id)
+
+
+def get_params():
+ # Post fields are adjustable. Options include:
+ # attachments, author_id, context_annotations, conversation_id,
+ # created_at, entities, geo, id, in_reply_to_user_id, lang,
+ # possibly_sensitive, public_metrics, referenced_tweets, source, text
+ return {"tweet.fields": "created_at"}
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2UserPostsPython"
+ return r
+
+
+def connect_to_endpoint(url, params):
+ response = requests.request("GET", url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = create_url()
+ params = get_params()
+ json_response = connect_to_endpoint(url, params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/User-Tweet-Timeline/user_tweets.py b/python/timelines/user_tweets.py
similarity index 95%
rename from User-Tweet-Timeline/user_tweets.py
rename to python/timelines/user_tweets.py
index 625172c..8f547ea 100644
--- a/User-Tweet-Timeline/user_tweets.py
+++ b/python/timelines/user_tweets.py
@@ -10,7 +10,7 @@
def create_url():
# Replace with user ID below
user_id = 2244994945
- return "https://api.twitter.com/2/users/{}/tweets".format(user_id)
+ return "https://api.x.com/2/users/{}/tweets".format(user_id)
def get_params():
diff --git a/python/usage/get_usage.py b/python/usage/get_usage.py
new file mode 100644
index 0000000..7042699
--- /dev/null
+++ b/python/usage/get_usage.py
@@ -0,0 +1,53 @@
+"""
+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
+
+Returns the number of posts read from the API.
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url():
+ return "https://api.x.com/2/usage/tweets"
+
+
+def get_params():
+ return {"days": 7}
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2UsagePython"
+ return r
+
+
+def connect_to_endpoint(url, params):
+ response = requests.get(url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = create_url()
+ params = get_params()
+ json_response = connect_to_endpoint(url, params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Usage Tweets/get_usage_tweets.py b/python/usage/get_usage_tweets.py
similarity index 94%
rename from Usage Tweets/get_usage_tweets.py
rename to python/usage/get_usage_tweets.py
index e2842aa..23ad0d8 100644
--- a/Usage Tweets/get_usage_tweets.py
+++ b/python/usage/get_usage_tweets.py
@@ -29,7 +29,7 @@ def connect_to_endpoint(url):
def main():
- url = "https://api.twitter.com/2/usage/tweets"
+ url = "https://api.x.com/2/usage/tweets"
json_response = connect_to_endpoint(url)
print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/python/users/block.py b/python/users/block.py
new file mode 100644
index 0000000..77da5db
--- /dev/null
+++ b/python/users/block.py
@@ -0,0 +1,81 @@
+"""
+Block User - X API v2
+=====================
+Endpoint: POST https://api.x.com/2/users/:id/blocking
+Docs: https://developer.x.com/en/docs/twitter-api/users/blocks/api-reference/post-users-user_id-blocking
+
+Authentication: OAuth 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# Replace with your own user ID
+user_id = "your-user-id"
+
+# Replace with the user ID you want to block
+payload = {"target_user_id": "target-user-id"}
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.post(
+ "https://api.x.com/2/users/{}/blocking".format(user_id), json=payload
+)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/Manage-Blocks/block_a_user.py b/python/users/block_a_user.py
similarity index 89%
rename from Manage-Blocks/block_a_user.py
rename to python/users/block_a_user.py
index 92e1fdb..2523aa6 100644
--- a/Manage-Blocks/block_a_user.py
+++ b/python/users/block_a_user.py
@@ -18,7 +18,7 @@
payload = {"target_user_id": "id-to-block"}
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -33,13 +33,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -62,7 +62,7 @@
# Making the request
response = oauth.post(
- "https://api.twitter.com/2/users/{}/blocking".format(id), json=payload
+ "https://api.x.com/2/users/{}/blocking".format(id), json=payload
)
if response.status_code != 200:
diff --git a/python/users/blocked.py b/python/users/blocked.py
new file mode 100644
index 0000000..7bb4a0c
--- /dev/null
+++ b/python/users/blocked.py
@@ -0,0 +1,84 @@
+"""
+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 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# User fields are adjustable. Options include:
+# created_at, description, entities, id, location, name,
+# pinned_tweet_id, profile_image_url, protected,
+# public_metrics, url, username, verified, and withheld
+fields = "user.fields=created_at,description"
+params = {"user.fields": fields}
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+user_id = oauth_tokens["user_id"]
+
+# Making the request
+response = oauth.get(
+ "https://api.x.com/2/users/{}/blocking".format(user_id), params=params
+)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/python/users/followers.py b/python/users/followers.py
new file mode 100644
index 0000000..35f87de
--- /dev/null
+++ b/python/users/followers.py
@@ -0,0 +1,53 @@
+"""
+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) or OAuth (User Context)
+Required env vars: BEARER_TOKEN
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url():
+ # Replace with the user ID you want to get followers for
+ user_id = "2244994945"
+ return "https://api.x.com/2/users/{}/followers".format(user_id)
+
+
+def get_params():
+ return {"user.fields": "created_at"}
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2FollowersLookupPython"
+ return r
+
+
+def connect_to_endpoint(url, params):
+ response = requests.request("GET", url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = create_url()
+ params = get_params()
+ json_response = connect_to_endpoint(url, params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Follows-Lookup/followers_lookup.py b/python/users/followers_lookup.py
similarity index 93%
rename from Follows-Lookup/followers_lookup.py
rename to python/users/followers_lookup.py
index 314baad..ea51170 100644
--- a/Follows-Lookup/followers_lookup.py
+++ b/python/users/followers_lookup.py
@@ -10,7 +10,7 @@
def create_url():
# Replace with user ID below
user_id = 2244994945
- return "https://api.twitter.com/2/users/{}/followers".format(user_id)
+ return "https://api.x.com/2/users/{}/followers".format(user_id)
def get_params():
diff --git a/python/users/following.py b/python/users/following.py
new file mode 100644
index 0000000..dba3fb3
--- /dev/null
+++ b/python/users/following.py
@@ -0,0 +1,53 @@
+"""
+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) or OAuth (User Context)
+Required env vars: BEARER_TOKEN
+"""
+
+import requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url():
+ # Replace with the user ID you want to get following for
+ user_id = "2244994945"
+ return "https://api.x.com/2/users/{}/following".format(user_id)
+
+
+def get_params():
+ return {"user.fields": "created_at"}
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2FollowingLookupPython"
+ return r
+
+
+def connect_to_endpoint(url, params):
+ response = requests.request("GET", url, auth=bearer_oauth, params=params)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(response.status_code, response.text)
+ return response.json()
+
+
+def main():
+ url = create_url()
+ params = get_params()
+ json_response = connect_to_endpoint(url, params)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Follows-Lookup/following_lookup.py b/python/users/following_lookup.py
similarity index 93%
rename from Follows-Lookup/following_lookup.py
rename to python/users/following_lookup.py
index 1dd0c21..be136e5 100644
--- a/Follows-Lookup/following_lookup.py
+++ b/python/users/following_lookup.py
@@ -10,7 +10,7 @@
def create_url():
# Replace with user ID below
user_id = 2244994945
- return "https://api.twitter.com/2/users/{}/following".format(user_id)
+ return "https://api.x.com/2/users/{}/following".format(user_id)
def get_params():
diff --git a/User-Lookup/get_users_me_user_context.py b/python/users/get_users_me_user_context.py
similarity index 88%
rename from User-Lookup/get_users_me_user_context.py
rename to python/users/get_users_me_user_context.py
index f4a3bd4..95cdafa 100644
--- a/User-Lookup/get_users_me_user_context.py
+++ b/python/users/get_users_me_user_context.py
@@ -17,7 +17,7 @@
params = {"user.fields": fields}
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -32,13 +32,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# # Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -59,7 +59,7 @@
resource_owner_secret=access_token_secret,
)
-response = oauth.get("https://api.twitter.com/2/users/me", params=params)
+response = oauth.get("https://api.x.com/2/users/me", params=params)
if response.status_code != 200:
raise Exception(
diff --git a/User-Lookup/get_users_with_bearer_token.py b/python/users/get_users_with_bearer_token.py
similarity index 94%
rename from User-Lookup/get_users_with_bearer_token.py
rename to python/users/get_users_with_bearer_token.py
index c751f58..4bc7c91 100644
--- a/User-Lookup/get_users_with_bearer_token.py
+++ b/python/users/get_users_with_bearer_token.py
@@ -16,7 +16,7 @@ def create_url():
# created_at, description, entities, id, location, name,
# pinned_tweet_id, profile_image_url, protected,
# public_metrics, url, username, verified, and withheld
- url = "https://api.twitter.com/2/users/by?{}&{}".format(usernames, user_fields)
+ url = "https://api.x.com/2/users/by?{}&{}".format(usernames, user_fields)
return url
diff --git a/User-Lookup/get_users_with_user_context.py b/python/users/get_users_with_user_context.py
similarity index 89%
rename from User-Lookup/get_users_with_user_context.py
rename to python/users/get_users_with_user_context.py
index c295d4b..295e285 100644
--- a/User-Lookup/get_users_with_user_context.py
+++ b/python/users/get_users_with_user_context.py
@@ -17,7 +17,7 @@
params = {"usernames": "TwitterDev,TwitterAPI", "user.fields": fields}
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -32,13 +32,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# # Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -60,7 +60,7 @@
)
response = oauth.get(
- "https://api.twitter.com/2/users/by", params=params
+ "https://api.x.com/2/users/by", params=params
)
if response.status_code != 200:
diff --git a/python/users/lookup.py b/python/users/lookup.py
new file mode 100644
index 0000000..fb984e6
--- /dev/null
+++ b/python/users/lookup.py
@@ -0,0 +1,59 @@
+"""
+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 requests
+import os
+import json
+
+bearer_token = os.environ.get("BEARER_TOKEN")
+
+
+def create_url():
+ # Specify the usernames to lookup (up to 100 comma-separated)
+ usernames = "usernames=XDevelopers,X"
+
+ # User fields are adjustable. Options include:
+ # created_at, description, entities, id, location, name,
+ # pinned_tweet_id, profile_image_url, protected,
+ # public_metrics, url, username, verified, and withheld
+ user_fields = "user.fields=description,created_at"
+ url = "https://api.x.com/2/users/by?{}&{}".format(usernames, user_fields)
+ return url
+
+
+def bearer_oauth(r):
+ """
+ Method required by bearer token authentication.
+ """
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
+ r.headers["User-Agent"] = "v2UserLookupPython"
+ return r
+
+
+def connect_to_endpoint(url):
+ response = requests.request("GET", url, auth=bearer_oauth)
+ print(response.status_code)
+ if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(
+ response.status_code, response.text
+ )
+ )
+ return response.json()
+
+
+def main():
+ url = create_url()
+ json_response = connect_to_endpoint(url)
+ print(json.dumps(json_response, indent=4, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Blocks-Lookup/lookup_blocks.py b/python/users/lookup_blocks.py
similarity index 89%
rename from Blocks-Lookup/lookup_blocks.py
rename to python/users/lookup_blocks.py
index 84a2ba3..623c13a 100644
--- a/Blocks-Lookup/lookup_blocks.py
+++ b/python/users/lookup_blocks.py
@@ -19,7 +19,7 @@
# pinned_tweet_id, profile_image_url, protected,
# public_metrics, url, username, verified, and withheld
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -34,13 +34,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -63,7 +63,7 @@
)
response = oauth.get(
- "https://api.twitter.com/2/users/{}/blocking".format(id), params=params
+ "https://api.x.com/2/users/{}/blocking".format(id), params=params
)
if response.status_code != 200:
diff --git a/Mutes-Lookup/lookup_mutes.py b/python/users/lookup_mutes.py
similarity index 89%
rename from Mutes-Lookup/lookup_mutes.py
rename to python/users/lookup_mutes.py
index 89f313c..298bb58 100644
--- a/Mutes-Lookup/lookup_mutes.py
+++ b/python/users/lookup_mutes.py
@@ -21,7 +21,7 @@
# pinned_tweet_id, profile_image_url, protected,
# public_metrics, url, username, verified, and withheld
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -36,13 +36,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -65,7 +65,7 @@
)
response = oauth.get(
- "https://api.twitter.com/2/users/{}/muting".format(id),params=params
+ "https://api.x.com/2/users/{}/muting".format(id),params=params
)
if response.status_code != 200:
diff --git a/python/users/me.py b/python/users/me.py
new file mode 100644
index 0000000..819ea46
--- /dev/null
+++ b/python/users/me.py
@@ -0,0 +1,80 @@
+"""
+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 1.0a or OAuth 2.0 (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# User fields are adjustable. Options include:
+# created_at, description, entities, id, location, name,
+# pinned_tweet_id, profile_image_url, protected,
+# public_metrics, url, username, verified, and withheld
+fields = "user.fields=description,created_at"
+params = {"user.fields": fields}
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.get("https://api.x.com/2/users/me", params=params)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/python/users/mute.py b/python/users/mute.py
new file mode 100644
index 0000000..ce37e70
--- /dev/null
+++ b/python/users/mute.py
@@ -0,0 +1,81 @@
+"""
+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 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# Replace with your own user ID
+user_id = "your-user-id"
+
+# Replace with the user ID you want to mute
+payload = {"target_user_id": "target-user-id"}
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.post(
+ "https://api.x.com/2/users/{}/muting".format(user_id), json=payload
+)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/Manage-Mutes/mute_a_user.py b/python/users/mute_a_user.py
similarity index 89%
rename from Manage-Mutes/mute_a_user.py
rename to python/users/mute_a_user.py
index de9fec6..7a664a7 100644
--- a/Manage-Mutes/mute_a_user.py
+++ b/python/users/mute_a_user.py
@@ -18,7 +18,7 @@
payload = {"target_user_id": "id-to-mute"}
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -33,13 +33,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -62,7 +62,7 @@
# Making the request
response = oauth.post(
- "https://api.twitter.com/2/users/{}/muting".format(id), json=payload
+ "https://api.x.com/2/users/{}/muting".format(id), json=payload
)
if response.status_code != 200:
diff --git a/python/users/muted.py b/python/users/muted.py
new file mode 100644
index 0000000..01aaa29
--- /dev/null
+++ b/python/users/muted.py
@@ -0,0 +1,84 @@
+"""
+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 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# User fields are adjustable. Options include:
+# created_at, description, entities, id, location, name,
+# pinned_tweet_id, profile_image_url, protected,
+# public_metrics, url, username, verified, and withheld
+fields = "user.fields=created_at,description"
+params = {"user.fields": fields}
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+user_id = oauth_tokens["user_id"]
+
+# Making the request
+response = oauth.get(
+ "https://api.x.com/2/users/{}/muting".format(user_id), params=params
+)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/python/users/unblock.py b/python/users/unblock.py
new file mode 100644
index 0000000..be374b8
--- /dev/null
+++ b/python/users/unblock.py
@@ -0,0 +1,81 @@
+"""
+Unblock User - X API v2
+=======================
+Endpoint: DELETE https://api.x.com/2/users/:source_user_id/blocking/:target_user_id
+Docs: https://developer.x.com/en/docs/twitter-api/users/blocks/api-reference/delete-users-user_id-blocking
+
+Authentication: OAuth 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# Replace with your own user ID
+user_id = "your-user-id"
+
+# Replace with the user ID you want to unblock
+target_user_id = "target-user-id"
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.delete(
+ "https://api.x.com/2/users/{}/blocking/{}".format(user_id, target_user_id)
+)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/Manage-Blocks/unblock_a_user.py b/python/users/unblock_a_user.py
similarity index 89%
rename from Manage-Blocks/unblock_a_user.py
rename to python/users/unblock_a_user.py
index b76c756..62ea052 100644
--- a/Manage-Blocks/unblock_a_user.py
+++ b/python/users/unblock_a_user.py
@@ -20,7 +20,7 @@
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -35,13 +35,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -64,7 +64,7 @@
# Making the request
response = oauth.delete(
- "https://api.twitter.com/2/users/{}/blocking/{}".format(id, target_user_id)
+ "https://api.x.com/2/users/{}/blocking/{}".format(id, target_user_id)
)
if response.status_code != 200:
diff --git a/python/users/unmute.py b/python/users/unmute.py
new file mode 100644
index 0000000..b1d607f
--- /dev/null
+++ b/python/users/unmute.py
@@ -0,0 +1,81 @@
+"""
+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 1.0a (User Context)
+Required env vars: CONSUMER_KEY, CONSUMER_SECRET
+"""
+
+from requests_oauthlib import OAuth1Session
+import os
+import json
+
+consumer_key = os.environ.get("CONSUMER_KEY")
+consumer_secret = os.environ.get("CONSUMER_SECRET")
+
+# Replace with your own user ID
+user_id = "your-user-id"
+
+# Replace with the user ID you want to unmute
+target_user_id = "target-user-id"
+
+# Get request token
+request_token_url = "https://api.x.com/oauth/request_token"
+oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
+
+try:
+ fetch_response = oauth.fetch_request_token(request_token_url)
+except ValueError:
+ print(
+ "There may have been an issue with the consumer_key or consumer_secret you entered."
+ )
+
+resource_owner_key = fetch_response.get("oauth_token")
+resource_owner_secret = fetch_response.get("oauth_token_secret")
+print("Got OAuth token: %s" % resource_owner_key)
+
+# Get authorization
+base_authorization_url = "https://api.x.com/oauth/authorize"
+authorization_url = oauth.authorization_url(base_authorization_url)
+print("Please go here and authorize: %s" % authorization_url)
+verifier = input("Paste the PIN here: ")
+
+# Get the access token
+access_token_url = "https://api.x.com/oauth/access_token"
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=resource_owner_key,
+ resource_owner_secret=resource_owner_secret,
+ verifier=verifier,
+)
+oauth_tokens = oauth.fetch_access_token(access_token_url)
+
+access_token = oauth_tokens["oauth_token"]
+access_token_secret = oauth_tokens["oauth_token_secret"]
+
+# Make the request
+oauth = OAuth1Session(
+ consumer_key,
+ client_secret=consumer_secret,
+ resource_owner_key=access_token,
+ resource_owner_secret=access_token_secret,
+)
+
+# Making the request
+response = oauth.delete(
+ "https://api.x.com/2/users/{}/muting/{}".format(user_id, target_user_id)
+)
+
+if response.status_code != 200:
+ raise Exception(
+ "Request returned an error: {} {}".format(response.status_code, response.text)
+ )
+
+print("Response code: {}".format(response.status_code))
+
+# Saving the response as JSON
+json_response = response.json()
+print(json.dumps(json_response, indent=4, sort_keys=True))
diff --git a/Manage-Mutes/unmute_a_user.py b/python/users/unmute_a_user.py
similarity index 89%
rename from Manage-Mutes/unmute_a_user.py
rename to python/users/unmute_a_user.py
index 518072a..268e545 100644
--- a/Manage-Mutes/unmute_a_user.py
+++ b/python/users/unmute_a_user.py
@@ -20,7 +20,7 @@
# Get request token
-request_token_url = "https://api.twitter.com/oauth/request_token"
+request_token_url = "https://api.x.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
@@ -35,13 +35,13 @@
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
-base_authorization_url = "https://api.twitter.com/oauth/authorize"
+base_authorization_url = "https://api.x.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
-access_token_url = "https://api.twitter.com/oauth/access_token"
+access_token_url = "https://api.x.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
@@ -64,7 +64,7 @@
# Making the request
response = oauth.delete(
- "https://api.twitter.com/2/users/{}/muting/{}".format(id, target_user_id)
+ "https://api.x.com/2/users/{}/muting/{}".format(id, target_user_id)
)
if response.status_code != 200:
diff --git a/Full-Archive-Search/full-archive-search.r b/r/posts/full-archive-search.r
similarity index 76%
rename from Full-Archive-Search/full-archive-search.r
rename to r/posts/full-archive-search.r
index e08d7d8..666953f 100644
--- a/Full-Archive-Search/full-archive-search.r
+++ b/r/posts/full-archive-search.r
@@ -13,7 +13,7 @@ params = list(
`tweet.fields` = 'created_at,lang,context_annotations'
)
-response <- httr::GET(url = 'https://api.twitter.com/2/tweets/search/all', httr::add_headers(.headers=headers), query = params)
+response <- httr::GET(url = 'https://api.x.com/2/tweets/search/all', httr::add_headers(.headers=headers), query = params)
fas_body <-
content(
diff --git a/Full-Archive-Tweet-Counts/full_archive_tweet_counts.r b/r/posts/full_archive_tweet_counts.r
similarity index 73%
rename from Full-Archive-Tweet-Counts/full_archive_tweet_counts.r
rename to r/posts/full_archive_tweet_counts.r
index 421f79f..0c82bde 100644
--- a/Full-Archive-Tweet-Counts/full_archive_tweet_counts.r
+++ b/r/posts/full_archive_tweet_counts.r
@@ -12,7 +12,7 @@ params = list(
`granularity` = 'day'
)
-response <- httr::GET(url = 'https://api.twitter.com/2/tweets/counts/all', httr::add_headers(.headers=headers), query = params)
+response <- httr::GET(url = 'https://api.x.com/2/tweets/counts/all', httr::add_headers(.headers=headers), query = params)
body <-
content(
diff --git a/Recent-Search/recent-search.r b/r/posts/recent-search.r
similarity index 75%
rename from Recent-Search/recent-search.r
rename to r/posts/recent-search.r
index 7c388e5..d01c9b3 100644
--- a/Recent-Search/recent-search.r
+++ b/r/posts/recent-search.r
@@ -14,7 +14,7 @@ params = list(
)
-response <- httr::GET(url = 'https://api.twitter.com/2/tweets/search/recent', httr::add_headers(.headers=headers), query = params)
+response <- httr::GET(url = 'https://api.x.com/2/tweets/search/recent', httr::add_headers(.headers=headers), query = params)
recent_search_body <-
diff --git a/Recent-Tweet-Counts/recent_tweet_counts.r b/r/posts/recent_tweet_counts.r
similarity index 72%
rename from Recent-Tweet-Counts/recent_tweet_counts.r
rename to r/posts/recent_tweet_counts.r
index 48df1cb..179f1bc 100644
--- a/Recent-Tweet-Counts/recent_tweet_counts.r
+++ b/r/posts/recent_tweet_counts.r
@@ -12,7 +12,7 @@ params = list(
`granularity` = 'day'
)
-response <- httr::GET(url = 'https://api.twitter.com/2/tweets/counts/recent', httr::add_headers(.headers=headers), query = params)
+response <- httr::GET(url = 'https://api.x.com/2/tweets/counts/recent', httr::add_headers(.headers=headers), query = params)
body <-
content(
diff --git a/User-Lookup/get_users_with_bearer_token.r b/r/users/get_users_with_bearer_token.r
similarity index 83%
rename from User-Lookup/get_users_with_bearer_token.r
rename to r/users/get_users_with_bearer_token.r
index 9585655..e0582a3 100644
--- a/User-Lookup/get_users_with_bearer_token.r
+++ b/r/users/get_users_with_bearer_token.r
@@ -9,7 +9,7 @@ params <- list(`user.fields` = 'description')
handle <- 'TwitterDev'
url_handle <-
- sprintf('https://api.twitter.com/2/users/by?usernames=%s', handle)
+ sprintf('https://api.x.com/2/users/by?usernames=%s', handle)
response <-
httr::GET(url = url_handle,
diff --git a/ruby/Gemfile b/ruby/Gemfile
new file mode 100644
index 0000000..79e382d
--- /dev/null
+++ b/ruby/Gemfile
@@ -0,0 +1,3 @@
+source 'https://rubygems.org'
+gem 'typhoeus', '~> 1.4'
+gem 'oauth', '~> 1.1'
diff --git a/ruby/README.md b/ruby/README.md
new file mode 100644
index 0000000..c8cb19c
--- /dev/null
+++ b/ruby/README.md
@@ -0,0 +1,67 @@
+# X API v2 - Ruby Examples
+
+Working Ruby code samples for the X (formerly Twitter) API v2.
+
+## Setup
+
+### 1. Install Ruby 2.7+
+
+```bash
+ruby --version
+```
+
+### 2. Install dependencies
+
+```bash
+gem install typhoeus
+gem install oauth # For OAuth 1.0a examples
+```
+
+### 3. Set environment variables
+
+For **Bearer Token** authentication (app-only):
+```bash
+export BEARER_TOKEN='your_bearer_token'
+```
+
+For **OAuth 1.0a** authentication (user context):
+```bash
+export CONSUMER_KEY='your_consumer_key'
+export CONSUMER_SECRET='your_consumer_secret'
+```
+
+## Examples by Category
+
+### Posts
+| File | Description | Auth |
+|------|-------------|------|
+| `posts/search_recent.rb` | Search recent posts (7 days) | Bearer |
+| `posts/lookup.rb` | Look up posts by ID | Bearer |
+
+### Users
+| File | Description | Auth |
+|------|-------------|------|
+| `users/lookup.rb` | Look up users by username | Bearer |
+| `users/followers.rb` | Get user's followers | Bearer |
+
+### Timelines
+| File | Description | Auth |
+|------|-------------|------|
+| `timelines/user_posts.rb` | User's posts timeline | Bearer |
+
+### Lists
+| File | Description | Auth |
+|------|-------------|------|
+| `lists/lookup.rb` | Look up a list | Bearer |
+
+## Running Examples
+
+```bash
+# Make sure environment variables are set
+ruby posts/search_recent.rb
+```
+
+## 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/Bookmarks-lookup/bookmarks_lookup.rb b/ruby/bookmarks/bookmarks_lookup.rb
similarity index 96%
rename from Bookmarks-lookup/bookmarks_lookup.rb
rename to ruby/bookmarks/bookmarks_lookup.rb
index 89fc4cf..e529019 100644
--- a/Bookmarks-lookup/bookmarks_lookup.rb
+++ b/ruby/bookmarks/bookmarks_lookup.rb
@@ -82,14 +82,14 @@ def users_me(url, token_response)
return response
end
-url = "https://api.twitter.com/2/users/me"
+url = "https://api.x.com/2/users/me"
me_response = users_me(url, token_response)
json_s = JSON.parse(me_response.body)
user_id = json_s["data"]["id"]
# Make a request to the bookmarks url
-bookmarks_url = "https://api.twitter.com/2/users/#{user_id}/bookmarks"
+bookmarks_url = "https://api.x.com/2/users/#{user_id}/bookmarks"
def bookmarked_tweets(bookmarks_url, token_response)
options = {
diff --git a/List-lookup/List-Tweets-lookup/List-Tweets.rb b/ruby/lists/List-Tweets.rb
similarity index 95%
rename from List-lookup/List-Tweets-lookup/List-Tweets.rb
rename to ruby/lists/List-Tweets.rb
index 80f309b..5d2c2ee 100644
--- a/List-lookup/List-Tweets-lookup/List-Tweets.rb
+++ b/ruby/lists/List-Tweets.rb
@@ -10,7 +10,7 @@
# Be sure to replace list-id with any List ID
id = "list-id"
-url = "https://api.twitter.com/2/lists/#{id}/tweets"
+url = "https://api.x.com/2/lists/#{id}/tweets"
params = {
diff --git a/List-lookup/Pinned-Lists-lookup/Pinned-List.rb b/ruby/lists/Pinned-List.rb
similarity index 95%
rename from List-lookup/Pinned-Lists-lookup/Pinned-List.rb
rename to ruby/lists/Pinned-List.rb
index d858449..e1e7645 100644
--- a/List-lookup/Pinned-Lists-lookup/Pinned-List.rb
+++ b/ruby/lists/Pinned-List.rb
@@ -14,7 +14,7 @@
# You can find a user ID by using the user lookup endpoint
id = "your-user-id"
-url = "https://api.twitter.com/2/users/#{id}/pinned_lists"
+url = "https://api.x.com/2/users/#{id}/pinned_lists"
@params = {
# List fields are adjustable, options include:
@@ -24,7 +24,7 @@
}
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Lists/Manage-List-Members/add_member.rb b/ruby/lists/add_member.rb
similarity index 95%
rename from Manage-Lists/Manage-List-Members/add_member.rb
rename to ruby/lists/add_member.rb
index 6d6668a..8c5888b 100644
--- a/Manage-Lists/Manage-List-Members/add_member.rb
+++ b/ruby/lists/add_member.rb
@@ -13,13 +13,13 @@
# Be sure to replace your-list-id with your own list ID or one of an authenticating user
id = "your-list-id"
-member_url = "https://api.twitter.com/2/lists/#{id}/members"
+member_url = "https://api.x.com/2/lists/#{id}/members"
# Be sure to replace user-id-to-add with the user id you wish to add.
@user_id = { "user_id": "user-id-to-add" }
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Lists/create_a_list.rb b/ruby/lists/create_a_list.rb
similarity index 95%
rename from Manage-Lists/create_a_list.rb
rename to ruby/lists/create_a_list.rb
index d61822f..96e3dc0 100644
--- a/Manage-Lists/create_a_list.rb
+++ b/ruby/lists/create_a_list.rb
@@ -12,7 +12,7 @@
consumer_secret = ENV["CONSUMER_SECRET"]
-create_list_url = "https://api.twitter.com/2/lists"
+create_list_url = "https://api.x.com/2/lists"
# Be sure to add replace name-of-list with the name you wish to call the list.
# description and private keys are optional
@@ -21,7 +21,7 @@
"private": false}
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Lists/delete_a_list.rb b/ruby/lists/delete_a_list.rb
similarity index 95%
rename from Manage-Lists/delete_a_list.rb
rename to ruby/lists/delete_a_list.rb
index 3ae36dc..af8cef2 100644
--- a/Manage-Lists/delete_a_list.rb
+++ b/ruby/lists/delete_a_list.rb
@@ -15,11 +15,11 @@
id = "your-list-id"
-delete_list_url = "https://api.twitter.com/2/lists/#{id}"
+delete_list_url = "https://api.x.com/2/lists/#{id}"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Lists/Manage-Followed-Lists/follow_list.rb b/ruby/lists/follow_list.rb
similarity index 94%
rename from Manage-Lists/Manage-Followed-Lists/follow_list.rb
rename to ruby/lists/follow_list.rb
index 57c1bed..0e5efe9 100644
--- a/Manage-Lists/Manage-Followed-Lists/follow_list.rb
+++ b/ruby/lists/follow_list.rb
@@ -14,13 +14,13 @@
# You can find a user ID by using the user lookup endpoint
id = "your-user-id"
-following_url = "https://api.twitter.com/2/users/#{id}/followed_lists"
+following_url = "https://api.x.com/2/users/#{id}/followed_lists"
# Be sure to add replace list-id-to-follow with the list id you wish to follow.
@list_id = { "list_id": "list-id-to-follow" }
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/List-lookup/List-follows-lookup/list-followers-lookup.rb b/ruby/lists/list-followers-lookup.rb
similarity index 95%
rename from List-lookup/List-follows-lookup/list-followers-lookup.rb
rename to ruby/lists/list-followers-lookup.rb
index 0e2b2d7..70538e0 100644
--- a/List-lookup/List-follows-lookup/list-followers-lookup.rb
+++ b/ruby/lists/list-followers-lookup.rb
@@ -10,7 +10,7 @@
# Be sure to replace list-id with any List ID
id = "list-id"
-url = "https://api.twitter.com/2/lists/#{id}/followers"
+url = "https://api.x.com/2/lists/#{id}/followers"
params = {
diff --git a/List-lookup/list-lookup-by-id.rb b/ruby/lists/list-lookup-by-id.rb
similarity index 95%
rename from List-lookup/list-lookup-by-id.rb
rename to ruby/lists/list-lookup-by-id.rb
index 66b529b..4aaaba3 100644
--- a/List-lookup/list-lookup-by-id.rb
+++ b/ruby/lists/list-lookup-by-id.rb
@@ -10,7 +10,7 @@
# Be sure to replace list-id with any List ID
id = "list-id"
-url = "https://api.twitter.com/2/lists/#{id}"
+url = "https://api.x.com/2/lists/#{id}"
params = {
diff --git a/List-lookup/List-members-lookup/list-member-lookup.rb b/ruby/lists/list-member-lookup.rb
similarity index 95%
rename from List-lookup/List-members-lookup/list-member-lookup.rb
rename to ruby/lists/list-member-lookup.rb
index 7ba4029..f00cc9c 100644
--- a/List-lookup/List-members-lookup/list-member-lookup.rb
+++ b/ruby/lists/list-member-lookup.rb
@@ -10,7 +10,7 @@
# Be sure to replace list-id with any List ID
id = "list-id"
-url = "https://api.twitter.com/2/lists/#{id}/members"
+url = "https://api.x.com/2/lists/#{id}/members"
params = {
diff --git a/ruby/lists/lookup.rb b/ruby/lists/lookup.rb
new file mode 100644
index 0000000..e8d4174
--- /dev/null
+++ b/ruby/lists/lookup.rb
@@ -0,0 +1,39 @@
+# 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
+
+require 'json'
+require 'typhoeus'
+
+bearer_token = ENV["BEARER_TOKEN"]
+
+# Replace with the list ID you want to look up
+list_id = "84839422"
+url = "https://api.x.com/2/lists/#{list_id}"
+
+query_params = {
+ "list.fields": "created_at,follower_count,member_count,owner_id,description"
+}
+
+def lookup_list(url, bearer_token, query_params)
+ options = {
+ method: 'get',
+ headers: {
+ "User-Agent": "v2ListLookupRuby",
+ "Authorization": "Bearer #{bearer_token}"
+ },
+ params: query_params
+ }
+
+ request = Typhoeus::Request.new(url, options)
+ response = request.run
+
+ return response
+end
+
+response = lookup_list(url, bearer_token, query_params)
+puts response.code, JSON.pretty_generate(JSON.parse(response.body))
diff --git a/Manage-Lists/Manage-Pinned-Lists/pin_list.rb b/ruby/lists/pin_list.rb
similarity index 95%
rename from Manage-Lists/Manage-Pinned-Lists/pin_list.rb
rename to ruby/lists/pin_list.rb
index 9bf5617..c32f5db 100644
--- a/Manage-Lists/Manage-Pinned-Lists/pin_list.rb
+++ b/ruby/lists/pin_list.rb
@@ -14,13 +14,13 @@
# You can find a user ID by using the user lookup endpoint
id = "your-user-id"
-pin_url = "https://api.twitter.com/2/users/#{id}/pinned_lists"
+pin_url = "https://api.x.com/2/users/#{id}/pinned_lists"
# Be sure to add replace list-id-to-pin with the list id you wish to pin.
@list_id = { "list_id": "list-id-to-pin" }
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Lists/Manage-List-Members/remove_member.rb b/ruby/lists/remove_member.rb
similarity index 94%
rename from Manage-Lists/Manage-List-Members/remove_member.rb
rename to ruby/lists/remove_member.rb
index a4fa4c6..3c51687 100644
--- a/Manage-Lists/Manage-List-Members/remove_member.rb
+++ b/ruby/lists/remove_member.rb
@@ -16,10 +16,10 @@
# Be sure to replace user-id-to-remove with the user id you wish to remove.
user_id = "user-id-to-remove"
-member_url = "https://api.twitter.com/2/lists/#{id}/members/#{user_id}"
+member_url = "https://api.x.com/2/lists/#{id}/members/#{user_id}"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Lists/Manage-Followed-Lists/unfollow_list.rb b/ruby/lists/unfollow_list.rb
similarity index 94%
rename from Manage-Lists/Manage-Followed-Lists/unfollow_list.rb
rename to ruby/lists/unfollow_list.rb
index 2d3535f..adf937b 100644
--- a/Manage-Lists/Manage-Followed-Lists/unfollow_list.rb
+++ b/ruby/lists/unfollow_list.rb
@@ -18,10 +18,10 @@
list_id = "list-id-to-unfollow"
# Returns a user object for one or more users specified by the requested usernames
-unfollow_url = "https://api.twitter.com/2/users/#{id}/followed_lists/#{list_id}"
+unfollow_url = "https://api.x.com/2/users/#{id}/followed_lists/#{list_id}"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Lists/Manage-Pinned-Lists/unpin_list.rb b/ruby/lists/unpin_list.rb
similarity index 94%
rename from Manage-Lists/Manage-Pinned-Lists/unpin_list.rb
rename to ruby/lists/unpin_list.rb
index f800997..0524ac6 100644
--- a/Manage-Lists/Manage-Pinned-Lists/unpin_list.rb
+++ b/ruby/lists/unpin_list.rb
@@ -18,10 +18,10 @@
list_id = "list-id-to-unpin"
# Returns a user object for one or more users specified by the requested usernames
-unpin_url = "https://api.twitter.com/2/users/#{id}/pinned_lists/#{list_id}"
+unpin_url = "https://api.x.com/2/users/#{id}/pinned_lists/#{list_id}"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Lists/update_a_list.rb b/ruby/lists/update_a_list.rb
similarity index 95%
rename from Manage-Lists/update_a_list.rb
rename to ruby/lists/update_a_list.rb
index 9d5d97b..b9c2a8f 100644
--- a/Manage-Lists/update_a_list.rb
+++ b/ruby/lists/update_a_list.rb
@@ -20,11 +20,11 @@
# Be sure to replace your-list-id with the id of the list you wish to update. The authenticated user must own the list in order to update
id = "your-list-id"
-update_list_url = "https://api.twitter.com/2/lists/#{id}"
+update_list_url = "https://api.x.com/2/lists/#{id}"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/List-lookup/List-follows-lookup/user-list-followed.rb b/ruby/lists/user-list-followed.rb
similarity index 94%
rename from List-lookup/List-follows-lookup/user-list-followed.rb
rename to ruby/lists/user-list-followed.rb
index e4bd02d..f8acd26 100644
--- a/List-lookup/List-follows-lookup/user-list-followed.rb
+++ b/ruby/lists/user-list-followed.rb
@@ -10,7 +10,7 @@
# Be sure to replace user-id with any User ID
id = "user-id"
-url = "https://api.twitter.com/2/users/#{id}/followed_lists"
+url = "https://api.x.com/2/users/#{id}/followed_lists"
params = {
diff --git a/List-lookup/List-members-lookup/user-list-memberships.rb b/ruby/lists/user-list-memberships.rb
similarity index 94%
rename from List-lookup/List-members-lookup/user-list-memberships.rb
rename to ruby/lists/user-list-memberships.rb
index 5d065a6..373d2bd 100644
--- a/List-lookup/List-members-lookup/user-list-memberships.rb
+++ b/ruby/lists/user-list-memberships.rb
@@ -10,7 +10,7 @@
# Be sure to replace user-id with any User ID
id = "user-id"
-url = "https://api.twitter.com/2/users/#{id}/list_memberships"
+url = "https://api.x.com/2/users/#{id}/list_memberships"
params = {
diff --git a/List-lookup/user-owned-list-lookup.rb b/ruby/lists/user-owned-list-lookup.rb
similarity index 94%
rename from List-lookup/user-owned-list-lookup.rb
rename to ruby/lists/user-owned-list-lookup.rb
index a447f34..c05936b 100644
--- a/List-lookup/user-owned-list-lookup.rb
+++ b/ruby/lists/user-owned-list-lookup.rb
@@ -10,7 +10,7 @@
# You can replace the ID with the User ID to see if they own any Lists.
id = "user-id"
-url = "https://api.twitter.com/2/users/#{id}/owned_lists"
+url = "https://api.x.com/2/users/#{id}/owned_lists"
params = {
diff --git a/Manage-Tweets/create_tweet.rb b/ruby/posts/create_tweet.rb
similarity index 95%
rename from Manage-Tweets/create_tweet.rb
rename to ruby/posts/create_tweet.rb
index 4fdb071..9fb8c0e 100644
--- a/Manage-Tweets/create_tweet.rb
+++ b/ruby/posts/create_tweet.rb
@@ -10,14 +10,14 @@
consumer_secret = ENV["CONSUMER_SECRET"]
-create_tweet_url = "https://api.twitter.com/2/tweets"
+create_tweet_url = "https://api.x.com/2/tweets"
# Be sure to add replace the text of the with the text you wish to Tweet.
# You can also add parameters to post polls, quote Tweets, Tweet with reply settings, and Tweet to Super Followers in addition to other features.
@json_payload = {"text": "Hello world!"}
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Tweets/delete_tweet.rb b/ruby/posts/delete_tweet.rb
similarity index 94%
rename from Manage-Tweets/delete_tweet.rb
rename to ruby/posts/delete_tweet.rb
index 294407e..2a0ad3b 100644
--- a/Manage-Tweets/delete_tweet.rb
+++ b/ruby/posts/delete_tweet.rb
@@ -12,11 +12,11 @@
# Be sure to replace your-tweet-id with the id of the Tweet you wish to delete.
id = "your-tweet-id"
-delete_tweet_url = "https://api.twitter.com/2/tweets/#{id}"
+delete_tweet_url = "https://api.x.com/2/tweets/#{id}"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Full-Archive-Search/full-archive-search.rb b/ruby/posts/full-archive-search.rb
similarity index 96%
rename from Full-Archive-Search/full-archive-search.rb
rename to ruby/posts/full-archive-search.rb
index 6dc9cd1..854f04a 100644
--- a/Full-Archive-Search/full-archive-search.rb
+++ b/ruby/posts/full-archive-search.rb
@@ -9,7 +9,7 @@
bearer_token = ENV["BEARER_TOKEN"]
# Endpoint URL for the Full-archive Search API
-search_url = "https://api.twitter.com/2/tweets/search/all"
+search_url = "https://api.x.com/2/tweets/search/all"
# Set the query value here. Value can be up to 512 characters
query = "from:Twitter OR from:TwitterDev OR from:DailyNasa"
diff --git a/Full-Archive-Tweet-Counts/full_archive_tweet_counts.rb b/ruby/posts/full_archive_tweet_counts.rb
similarity index 95%
rename from Full-Archive-Tweet-Counts/full_archive_tweet_counts.rb
rename to ruby/posts/full_archive_tweet_counts.rb
index 7bed9d5..4e9c85c 100644
--- a/Full-Archive-Tweet-Counts/full_archive_tweet_counts.rb
+++ b/ruby/posts/full_archive_tweet_counts.rb
@@ -9,7 +9,7 @@
bearer_token = ENV["BEARER_TOKEN"]
# Endpoint URL for the Full-archive Search API
-search_url = "https://api.twitter.com/2/tweets/counts/all"
+search_url = "https://api.x.com/2/tweets/counts/all"
# Set the query value here. Value can be up to 1024 characters
query = "from:TwitterDev"
diff --git a/Tweet-Lookup/get_tweets_with_bearer_token.rb b/ruby/posts/get_tweets_with_bearer_token.rb
similarity index 96%
rename from Tweet-Lookup/get_tweets_with_bearer_token.rb
rename to ruby/posts/get_tweets_with_bearer_token.rb
index c4e5973..8f95b47 100644
--- a/Tweet-Lookup/get_tweets_with_bearer_token.rb
+++ b/ruby/posts/get_tweets_with_bearer_token.rb
@@ -8,7 +8,7 @@
# export BEARER_TOKEN='YOUR-TOKEN'
bearer_token = ENV["BEARER_TOKEN"]
-tweet_lookup_url = "https://api.twitter.com/2/tweets"
+tweet_lookup_url = "https://api.x.com/2/tweets"
# Specify the Tweet IDs that you want to lookup below (to 100 per request)
tweet_ids = "1261326399320715264,1278347468690915330"
diff --git a/Tweet-Lookup/get_tweets_with_user_context.rb b/ruby/posts/get_tweets_with_user_context.rb
similarity index 96%
rename from Tweet-Lookup/get_tweets_with_user_context.rb
rename to ruby/posts/get_tweets_with_user_context.rb
index e900296..06aa9f5 100644
--- a/Tweet-Lookup/get_tweets_with_user_context.rb
+++ b/ruby/posts/get_tweets_with_user_context.rb
@@ -13,7 +13,7 @@
consumer_secret = ENV["CONSUMER_SECRET"]
# Returns a Tweet object for one or more Tweets IDs as specified by the request
-tweet_lookup_url = "https://api.twitter.com/2/tweets"
+tweet_lookup_url = "https://api.x.com/2/tweets"
# Specify the Tweet IDs that you want to lookup below (to 100 per request)
tweet_ids = "1261326399320715264,1278347468690915330"
@@ -31,7 +31,7 @@
}
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Likes/like_a_tweet.rb b/ruby/posts/like_a_tweet.rb
similarity index 95%
rename from Manage-Likes/like_a_tweet.rb
rename to ruby/posts/like_a_tweet.rb
index a07abcd..d44c241 100644
--- a/Manage-Likes/like_a_tweet.rb
+++ b/ruby/posts/like_a_tweet.rb
@@ -14,14 +14,14 @@
# 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
id = "your-user-id"
-likes_url = "https://api.twitter.com/2/users/#{id}/likes"
+likes_url = "https://api.x.com/2/users/#{id}/likes"
# You can replace Tweet ID given with the Tweet ID you wish to like.
# You can find a Tweet ID by using the Tweet lookup endpoint
@tweet_id = { "tweet_id": "1354143047324299264" }
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Likes-Lookup/liked_tweets.rb b/ruby/posts/liked_tweets.rb
similarity index 95%
rename from Likes-Lookup/liked_tweets.rb
rename to ruby/posts/liked_tweets.rb
index be3a9a9..4cc4e3a 100644
--- a/Likes-Lookup/liked_tweets.rb
+++ b/ruby/posts/liked_tweets.rb
@@ -11,7 +11,7 @@
# 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
id = "your-user-id"
-url = "https://api.twitter.com/2/users/#{id}/liked_tweets"
+url = "https://api.x.com/2/users/#{id}/liked_tweets"
params = {
diff --git a/Likes-Lookup/liking_users.rb b/ruby/posts/liking_users.rb
similarity index 95%
rename from Likes-Lookup/liking_users.rb
rename to ruby/posts/liking_users.rb
index e4133fb..d879e6f 100644
--- a/Likes-Lookup/liking_users.rb
+++ b/ruby/posts/liking_users.rb
@@ -13,7 +13,7 @@
# You can find an ID by using the Tweet lookup endpoint
id = "1354143047324299264"
-url = "https://api.twitter.com/2/tweets/#{id}/liking_users"
+url = "https://api.x.com/2/tweets/#{id}/liking_users"
params = {
# User fields are adjustable, options include:
diff --git a/ruby/posts/lookup.rb b/ruby/posts/lookup.rb
new file mode 100644
index 0000000..293d5ea
--- /dev/null
+++ b/ruby/posts/lookup.rb
@@ -0,0 +1,40 @@
+# Post Lookup - 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) or OAuth (User Context)
+# Required env vars: BEARER_TOKEN
+
+require 'json'
+require 'typhoeus'
+
+bearer_token = ENV["BEARER_TOKEN"]
+
+# Post IDs to look up (comma-separated, up to 100)
+post_ids = "1278747501642657792,1255542774432063488"
+url = "https://api.x.com/2/tweets"
+
+query_params = {
+ "ids": post_ids,
+ "tweet.fields": "created_at,author_id,lang,source,public_metrics"
+}
+
+def lookup_posts(url, bearer_token, query_params)
+ options = {
+ method: 'get',
+ headers: {
+ "User-Agent": "v2PostLookupRuby",
+ "Authorization": "Bearer #{bearer_token}"
+ },
+ params: query_params
+ }
+
+ request = Typhoeus::Request.new(url, options)
+ response = request.run
+
+ return response
+end
+
+response = lookup_posts(url, bearer_token, query_params)
+puts response.code, JSON.pretty_generate(JSON.parse(response.body))
diff --git a/Quote-Tweets/quote_tweets.rb b/ruby/posts/quote_tweets.rb
similarity index 95%
rename from Quote-Tweets/quote_tweets.rb
rename to ruby/posts/quote_tweets.rb
index 8bb5d2b..77d1f9c 100644
--- a/Quote-Tweets/quote_tweets.rb
+++ b/ruby/posts/quote_tweets.rb
@@ -8,7 +8,7 @@
bearer_token = ENV["BEARER_TOKEN"]
# Endpoint URL for the Quote Tweets endpoint.
-endpoint_url = "https://api.twitter.com/2/tweets/:id/quote_tweets"
+endpoint_url = "https://api.x.com/2/tweets/:id/quote_tweets"
# Specify the Tweet ID for this request.
id = 20
diff --git a/Recent-Search/recent_search.rb b/ruby/posts/recent_search.rb
similarity index 96%
rename from Recent-Search/recent_search.rb
rename to ruby/posts/recent_search.rb
index 3f025ef..ada35fb 100644
--- a/Recent-Search/recent_search.rb
+++ b/ruby/posts/recent_search.rb
@@ -9,7 +9,7 @@
bearer_token = ENV["BEARER_TOKEN"]
# Endpoint URL for the Recent Search API
-search_url = "https://api.twitter.com/2/tweets/search/recent"
+search_url = "https://api.x.com/2/tweets/search/recent"
# Set the query value here. Value can be up to 512 characters
query = "from:Twitter OR from:TwitterDev OR from:DailyNasa"
diff --git a/Recent-Tweet-Counts/recent_tweet_counts.rb b/ruby/posts/recent_tweet_counts.rb
similarity index 95%
rename from Recent-Tweet-Counts/recent_tweet_counts.rb
rename to ruby/posts/recent_tweet_counts.rb
index 52bc7bc..beff26e 100644
--- a/Recent-Tweet-Counts/recent_tweet_counts.rb
+++ b/ruby/posts/recent_tweet_counts.rb
@@ -9,7 +9,7 @@
bearer_token = ENV["BEARER_TOKEN"]
# Endpoint URL for the Recent Search API
-search_url = "https://api.twitter.com/2/tweets/counts/recent"
+search_url = "https://api.x.com/2/tweets/counts/recent"
# Set the query value here. Value can be up to 512 characters
query = "from:TwitterDev"
diff --git a/Manage-Retweets/retweet_a_tweet.rb b/ruby/posts/retweet_a_tweet.rb
similarity index 95%
rename from Manage-Retweets/retweet_a_tweet.rb
rename to ruby/posts/retweet_a_tweet.rb
index a707930..f02586a 100644
--- a/Manage-Retweets/retweet_a_tweet.rb
+++ b/ruby/posts/retweet_a_tweet.rb
@@ -14,14 +14,14 @@
# Be sure to add replace id of the user you wish to retweet on behalf of.
# You can find a user ID by using the user lookup endpoint
id = "your-user-id"
-retweets_url = "https://api.twitter.com/2/users/#{id}/retweets"
+retweets_url = "https://api.x.com/2/users/#{id}/retweets"
# Be sure to replace tweet-id with your the Tweet ID you want to retweet
# You can find a Tweet ID by using the Tweet lookup endpoint
@tweet_id = { "tweet_id": "1412865600439738368" }
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Retweets-Lookup/retweeted_by.rb b/ruby/posts/retweeted_by.rb
similarity index 95%
rename from Retweets-Lookup/retweeted_by.rb
rename to ruby/posts/retweeted_by.rb
index 5f80461..14d1b4d 100644
--- a/Retweets-Lookup/retweeted_by.rb
+++ b/ruby/posts/retweeted_by.rb
@@ -13,7 +13,7 @@
# You can find an ID by using the Tweet lookup endpoint
id = "1412865600439738368"
-url = "https://api.twitter.com/2/tweets/#{id}/retweeted_by"
+url = "https://api.x.com/2/tweets/#{id}/retweeted_by"
params = {
# User fields are adjustable, options include:
diff --git a/ruby/posts/search_recent.rb b/ruby/posts/search_recent.rb
new file mode 100644
index 0000000..e5e99ec
--- /dev/null
+++ b/ruby/posts/search_recent.rb
@@ -0,0 +1,47 @@
+# 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
+#
+# Note: Returns posts from the last 7 days.
+
+require 'json'
+require 'typhoeus'
+
+bearer_token = ENV["BEARER_TOKEN"]
+
+search_url = "https://api.x.com/2/tweets/search/recent"
+
+# Set the query value here. Value can be up to 512 characters
+query = "from:XDevelopers -is:retweet"
+
+# See docs for list of param options:
+# https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent
+query_params = {
+ "query": query,
+ "max_results": 10,
+ "tweet.fields": "attachments,author_id,conversation_id,created_at,entities,id,lang",
+ "user.fields": "description"
+}
+
+def search_posts(url, bearer_token, query_params)
+ options = {
+ method: 'get',
+ headers: {
+ "User-Agent": "v2RecentSearchRuby",
+ "Authorization": "Bearer #{bearer_token}"
+ },
+ params: query_params
+ }
+
+ request = Typhoeus::Request.new(url, options)
+ response = request.run
+
+ return response
+end
+
+response = search_posts(search_url, bearer_token, query_params)
+puts response.code, JSON.pretty_generate(JSON.parse(response.body))
diff --git a/Manage-Retweets/undo_a_retweet.rb b/ruby/posts/undo_a_retweet.rb
similarity index 94%
rename from Manage-Retweets/undo_a_retweet.rb
rename to ruby/posts/undo_a_retweet.rb
index 6358152..33e14a3 100644
--- a/Manage-Retweets/undo_a_retweet.rb
+++ b/ruby/posts/undo_a_retweet.rb
@@ -21,10 +21,10 @@
source_tweet_id = "1412865600439738368"
# Returns a user object for one or more users specified by the requested usernames
-user_unretweet_url = "https://api.twitter.com/2/users/#{id}/retweets/#{source_tweet_id}"
+user_unretweet_url = "https://api.x.com/2/users/#{id}/retweets/#{source_tweet_id}"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Likes/unlike_a_tweet.rb b/ruby/posts/unlike_a_tweet.rb
similarity index 94%
rename from Manage-Likes/unlike_a_tweet.rb
rename to ruby/posts/unlike_a_tweet.rb
index d1351a2..f4cb59c 100644
--- a/Manage-Likes/unlike_a_tweet.rb
+++ b/ruby/posts/unlike_a_tweet.rb
@@ -21,10 +21,10 @@
tweet_id = "1354143047324299264"
# Returns a user object for one or more users specified by the requested usernames
-tweet_unlike_url = "https://api.twitter.com/2/users/#{id}/likes/#{tweet_id}"
+tweet_unlike_url = "https://api.x.com/2/users/#{id}/likes/#{tweet_id}"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Search-Spaces/search_spaces.rb b/ruby/spaces/search_spaces.rb
similarity index 95%
rename from Search-Spaces/search_spaces.rb
rename to ruby/spaces/search_spaces.rb
index 228c8dd..2980ad7 100644
--- a/Search-Spaces/search_spaces.rb
+++ b/ruby/spaces/search_spaces.rb
@@ -9,7 +9,7 @@
bearer_token = ENV["BEARER_TOKEN"]
# Endpoint URL
-spaces_search_url = "https://api.twitter.com/2/spaces/search"
+spaces_search_url = "https://api.x.com/2/spaces/search"
# Replace this value with your search term
query = "NBA"
diff --git a/Spaces-Lookup/spaces_lookup.rb b/ruby/spaces/spaces_lookup.rb
similarity index 95%
rename from Spaces-Lookup/spaces_lookup.rb
rename to ruby/spaces/spaces_lookup.rb
index b64340c..2c900cb 100644
--- a/Spaces-Lookup/spaces_lookup.rb
+++ b/ruby/spaces/spaces_lookup.rb
@@ -9,7 +9,7 @@
bearer_token = ENV["BEARER_TOKEN"]
# Endpoint URL for Spaces lookup
-spaces_lookup_url = "https://api.twitter.com/2/spaces"
+spaces_lookup_url = "https://api.x.com/2/spaces"
# Replace SPACE_ID with the ID of a Space
id = "SPACE_ID"
diff --git a/Filtered-Stream/filtered_stream.rb b/ruby/streams/filtered_stream.rb
similarity index 97%
rename from Filtered-Stream/filtered_stream.rb
rename to ruby/streams/filtered_stream.rb
index 64d1965..d1cf889 100644
--- a/Filtered-Stream/filtered_stream.rb
+++ b/ruby/streams/filtered_stream.rb
@@ -10,8 +10,8 @@
# export BEARER_TOKEN='YOUR-TOKEN'
@bearer_token = ENV["BEARER_TOKEN"]
-@stream_url = "https://api.twitter.com/2/tweets/search/stream"
-@rules_url = "https://api.twitter.com/2/tweets/search/stream/rules"
+@stream_url = "https://api.x.com/2/tweets/search/stream"
+@rules_url = "https://api.x.com/2/tweets/search/stream/rules"
@sample_rules = [
{ 'value': 'dog has:images', 'tag': 'dog pictures' },
diff --git a/Sampled-Stream/sampled_stream.rb b/ruby/streams/sampled_stream.rb
similarity index 96%
rename from Sampled-Stream/sampled_stream.rb
rename to ruby/streams/sampled_stream.rb
index f1c356d..6a8c29d 100644
--- a/Sampled-Stream/sampled_stream.rb
+++ b/ruby/streams/sampled_stream.rb
@@ -8,7 +8,7 @@
# export BEARER_TOKEN='YOUR-TOKEN'
bearer_token = ENV["BEARER_TOKEN"]
-stream_url = "https://api.twitter.com/2/tweets/sample/stream"
+stream_url = "https://api.x.com/2/tweets/sample/stream"
# Add or remove optional parameters values from the params object below. Full list of parameters and their values can be found in the docs:
# https://developer.twitter.com/en/docs/twitter-api/tweets/volume-streams/api-reference/get-tweets-sample-stream
diff --git a/Reverse-Chron-Home-Timeline/OAuth2-user/reverse-chron-home-timeline.rb b/ruby/timelines/reverse-chron-home-timeline.rb
similarity index 96%
rename from Reverse-Chron-Home-Timeline/OAuth2-user/reverse-chron-home-timeline.rb
rename to ruby/timelines/reverse-chron-home-timeline.rb
index aeedb1a..4b7ba40 100644
--- a/Reverse-Chron-Home-Timeline/OAuth2-user/reverse-chron-home-timeline.rb
+++ b/ruby/timelines/reverse-chron-home-timeline.rb
@@ -81,14 +81,14 @@ def users_me(url, token_response)
return response
end
-url = "https://api.twitter.com/2/users/me"
+url = "https://api.x.com/2/users/me"
me_response = users_me(url, token_response)
json_s = JSON.parse(me_response.body)
user_id = json_s["data"]["id"]
# Make a request to the reverse chronological home timeline endpoint
-url = "https://api.twitter.com/2/users/#{user_id}/timelines/reverse_chronological"
+url = "https://api.x.com/2/users/#{user_id}/timelines/reverse_chronological"
def reverse_chron_timeline(url, token_response)
diff --git a/User-Mention-Timeline/user-mentions.rb b/ruby/timelines/user-mentions.rb
similarity index 96%
rename from User-Mention-Timeline/user-mentions.rb
rename to ruby/timelines/user-mentions.rb
index 49274d1..cce22f3 100644
--- a/User-Mention-Timeline/user-mentions.rb
+++ b/ruby/timelines/user-mentions.rb
@@ -8,7 +8,7 @@
bearer_token = ENV["BEARER_TOKEN"]
# Endpoint URL for the User mentions timelines.
-endpoint_url = "https://api.twitter.com/2/users/:id/mentions"
+endpoint_url = "https://api.x.com/2/users/:id/mentions"
# Specify the User ID for this request.
id = 2244994945 #@TwitterDev's numeric User ID.
diff --git a/User-Tweet-Timeline/user-tweets.rb b/ruby/timelines/user-tweets.rb
similarity index 96%
rename from User-Tweet-Timeline/user-tweets.rb
rename to ruby/timelines/user-tweets.rb
index a652263..68ac34c 100644
--- a/User-Tweet-Timeline/user-tweets.rb
+++ b/ruby/timelines/user-tweets.rb
@@ -14,7 +14,7 @@
bearer_token = ENV["BEARER_TOKEN"]
# Endpoint URL for the Recent Search API
-endpoint_url = "https://api.twitter.com/2/users/:id/tweets"
+endpoint_url = "https://api.x.com/2/users/:id/tweets"
# Specify the User ID for this request.
id = 2244994945 #@TwitterDev's numeric User ID.
diff --git a/ruby/timelines/user_posts.rb b/ruby/timelines/user_posts.rb
new file mode 100644
index 0000000..181acf7
--- /dev/null
+++ b/ruby/timelines/user_posts.rb
@@ -0,0 +1,40 @@
+# 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) or OAuth (User Context)
+# Required env vars: BEARER_TOKEN
+
+require 'json'
+require 'typhoeus'
+
+bearer_token = ENV["BEARER_TOKEN"]
+
+# Replace with the user ID you want to get posts for
+user_id = "2244994945"
+url = "https://api.x.com/2/users/#{user_id}/tweets"
+
+query_params = {
+ "tweet.fields": "created_at,public_metrics",
+ "max_results": 10
+}
+
+def get_user_posts(url, bearer_token, query_params)
+ options = {
+ method: 'get',
+ headers: {
+ "User-Agent": "v2UserPostsRuby",
+ "Authorization": "Bearer #{bearer_token}"
+ },
+ params: query_params
+ }
+
+ request = Typhoeus::Request.new(url, options)
+ response = request.run
+
+ return response
+end
+
+response = get_user_posts(url, bearer_token, query_params)
+puts response.code, JSON.pretty_generate(JSON.parse(response.body))
diff --git a/Manage-Blocks/block_a_user.rb b/ruby/users/block_a_user.rb
similarity index 95%
rename from Manage-Blocks/block_a_user.rb
rename to ruby/users/block_a_user.rb
index 399b0b0..07e0b2b 100644
--- a/Manage-Blocks/block_a_user.rb
+++ b/ruby/users/block_a_user.rb
@@ -14,14 +14,14 @@
# 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
id = "your-user-id"
-blocking_url = "https://api.twitter.com/2/users/#{id}/blocking"
+blocking_url = "https://api.x.com/2/users/#{id}/blocking"
# Be sure to add replace id-to-block with the id of the user you wish to block.
# You can find a user ID by using the user lookup endpoint
@target_user_id = { "target_user_id": "id-to-block" }
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Follows-Lookup/followers-lookup.rb b/ruby/users/followers-lookup.rb
similarity index 94%
rename from Follows-Lookup/followers-lookup.rb
rename to ruby/users/followers-lookup.rb
index 4d7fd62..6464a7e 100644
--- a/Follows-Lookup/followers-lookup.rb
+++ b/ruby/users/followers-lookup.rb
@@ -7,7 +7,7 @@
bearer_token = ENV["BEARER_TOKEN"]
# Endpoint URL for the user followers
-endpoint_url = "https://api.twitter.com/2/users/:id/followers"
+endpoint_url = "https://api.x.com/2/users/:id/followers"
# Specify the User ID for this request.
id = 2244994945
diff --git a/ruby/users/followers.rb b/ruby/users/followers.rb
new file mode 100644
index 0000000..68a284f
--- /dev/null
+++ b/ruby/users/followers.rb
@@ -0,0 +1,40 @@
+# 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) or OAuth (User Context)
+# Required env vars: BEARER_TOKEN
+
+require 'json'
+require 'typhoeus'
+
+bearer_token = ENV["BEARER_TOKEN"]
+
+# Replace with the user ID you want to get followers for
+user_id = "2244994945"
+url = "https://api.x.com/2/users/#{user_id}/followers"
+
+query_params = {
+ "user.fields": "created_at,description",
+ "max_results": 100
+}
+
+def get_followers(url, bearer_token, query_params)
+ options = {
+ method: 'get',
+ headers: {
+ "User-Agent": "v2FollowersRuby",
+ "Authorization": "Bearer #{bearer_token}"
+ },
+ params: query_params
+ }
+
+ request = Typhoeus::Request.new(url, options)
+ response = request.run
+
+ return response
+end
+
+response = get_followers(url, bearer_token, query_params)
+puts response.code, JSON.pretty_generate(JSON.parse(response.body))
diff --git a/Follows-Lookup/following-lookup.rb b/ruby/users/following-lookup.rb
similarity index 94%
rename from Follows-Lookup/following-lookup.rb
rename to ruby/users/following-lookup.rb
index f5719ea..a912298 100644
--- a/Follows-Lookup/following-lookup.rb
+++ b/ruby/users/following-lookup.rb
@@ -7,7 +7,7 @@
bearer_token = ENV["BEARER_TOKEN"]
# Endpoint URL for the user following API
-endpoint_url = "https://api.twitter.com/2/users/:id/following"
+endpoint_url = "https://api.x.com/2/users/:id/following"
# Specify the User ID for this request.
id = 2244994945
diff --git a/User-Lookup/get_users_me_with_user_context.rb b/ruby/users/get_users_me_with_user_context.rb
similarity index 95%
rename from User-Lookup/get_users_me_with_user_context.rb
rename to ruby/users/get_users_me_with_user_context.rb
index 103bec5..24a9e14 100644
--- a/User-Lookup/get_users_me_with_user_context.rb
+++ b/ruby/users/get_users_me_with_user_context.rb
@@ -9,10 +9,10 @@
consumer_key = ENV["CONSUMER_KEY"]
consumer_secret = ENV["CONSUMER_SECRET"]
-user_lookup_url = "https://api.twitter.com/2/users/me"
+user_lookup_url = "https://api.x.com/2/users/me"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/User-Lookup/get_users_with_bearer_token.rb b/ruby/users/get_users_with_bearer_token.rb
similarity index 96%
rename from User-Lookup/get_users_with_bearer_token.rb
rename to ruby/users/get_users_with_bearer_token.rb
index 5386f7e..eb3cedf 100644
--- a/User-Lookup/get_users_with_bearer_token.rb
+++ b/ruby/users/get_users_with_bearer_token.rb
@@ -8,7 +8,7 @@
# export BEARER_TOKEN='YOUR-TOKEN'
bearer_token = ENV["BEARER_TOKEN"]
-user_lookup_url = "https://api.twitter.com/2/users"
+user_lookup_url = "https://api.x.com/2/users"
# Specify the User IDs that you want to lookup below (to 100 per request)
user_ids = "2244994945,783214"
diff --git a/User-Lookup/get_users_with_user_context.rb b/ruby/users/get_users_with_user_context.rb
similarity index 96%
rename from User-Lookup/get_users_with_user_context.rb
rename to ruby/users/get_users_with_user_context.rb
index 003e630..3cc2c32 100644
--- a/User-Lookup/get_users_with_user_context.rb
+++ b/ruby/users/get_users_with_user_context.rb
@@ -13,13 +13,13 @@
consumer_secret = ENV["CONSUMER_SECRET"]
# Returns a user object for one or more users specified by the requested usernames
-user_lookup_url = "https://api.twitter.com/2/users/by"
+user_lookup_url = "https://api.x.com/2/users/by"
# Specify the usernames that you want to lookup below (to 100 per request)
usernames = "Twitter,TwitterDev"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/ruby/users/lookup.rb b/ruby/users/lookup.rb
new file mode 100644
index 0000000..c5f3cf9
--- /dev/null
+++ b/ruby/users/lookup.rb
@@ -0,0 +1,39 @@
+# 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
+
+require 'json'
+require 'typhoeus'
+
+bearer_token = ENV["BEARER_TOKEN"]
+
+url = "https://api.x.com/2/users/by"
+
+# Usernames to look up (up to 100 comma-separated)
+query_params = {
+ "usernames": "XDevelopers,X",
+ "user.fields": "created_at,description,public_metrics"
+}
+
+def lookup_users(url, bearer_token, query_params)
+ options = {
+ method: 'get',
+ headers: {
+ "User-Agent": "v2UserLookupRuby",
+ "Authorization": "Bearer #{bearer_token}"
+ },
+ params: query_params
+ }
+
+ request = Typhoeus::Request.new(url, options)
+ response = request.run
+
+ return response
+end
+
+response = lookup_users(url, bearer_token, query_params)
+puts response.code, JSON.pretty_generate(JSON.parse(response.body))
diff --git a/Blocks-Lookup/lookup_blocks.rb b/ruby/users/lookup_blocks.rb
similarity index 94%
rename from Blocks-Lookup/lookup_blocks.rb
rename to ruby/users/lookup_blocks.rb
index 1fb62f1..e174634 100644
--- a/Blocks-Lookup/lookup_blocks.rb
+++ b/ruby/users/lookup_blocks.rb
@@ -15,10 +15,10 @@
# You can find a user ID by using the user lookup endpoint
id = "your-user-id"
-blocking_url = "https://api.twitter.com/2/users/#{id}/blocking"
+blocking_url = "https://api.x.com/2/users/#{id}/blocking"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Mutes-Lookup/lookup_mutes.rb b/ruby/users/lookup_mutes.rb
similarity index 95%
rename from Mutes-Lookup/lookup_mutes.rb
rename to ruby/users/lookup_mutes.rb
index 0c83fdd..7c766ae 100644
--- a/Mutes-Lookup/lookup_mutes.rb
+++ b/ruby/users/lookup_mutes.rb
@@ -15,10 +15,10 @@
# You can find a user ID by using the user lookup endpoint
id = "your-user-id"
-muting_url = "https://api.twitter.com/2/users/#{id}/muting"
+muting_url = "https://api.x.com/2/users/#{id}/muting"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Mutes/mute_a_user.rb b/ruby/users/mute_a_user.rb
similarity index 95%
rename from Manage-Mutes/mute_a_user.rb
rename to ruby/users/mute_a_user.rb
index 5ea974d..2670452 100644
--- a/Manage-Mutes/mute_a_user.rb
+++ b/ruby/users/mute_a_user.rb
@@ -13,14 +13,14 @@
# 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
id = "your-user-id"
-muting_url = "https://api.twitter.com/2/users/#{id}/muting"
+muting_url = "https://api.x.com/2/users/#{id}/muting"
# Be sure to add replace id-to-mute with the id of the user you wish to mute.
# You can find a user ID by using the user lookup endpoint
@target_user_id = { "target_user_id": "id-to-mute" }
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Blocks/unblock_a_user.rb b/ruby/users/unblock_a_user.rb
similarity index 94%
rename from Manage-Blocks/unblock_a_user.rb
rename to ruby/users/unblock_a_user.rb
index 68a8710..3491dc3 100644
--- a/Manage-Blocks/unblock_a_user.rb
+++ b/ruby/users/unblock_a_user.rb
@@ -21,10 +21,10 @@
target_user_id = "id-to-unblock"
# Returns a user object for one or more users specified by the requested usernames
-user_unblock_url = "https://api.twitter.com/2/users/#{source_user_id}/blocking/#{target_user_id}"
+user_unblock_url = "https://api.x.com/2/users/#{source_user_id}/blocking/#{target_user_id}"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)
diff --git a/Manage-Mutes/unmute_a_user.rb b/ruby/users/unmute_a_user.rb
similarity index 94%
rename from Manage-Mutes/unmute_a_user.rb
rename to ruby/users/unmute_a_user.rb
index 7fac9d9..6c02da4 100644
--- a/Manage-Mutes/unmute_a_user.rb
+++ b/ruby/users/unmute_a_user.rb
@@ -19,10 +19,10 @@
target_user_id = "id-to-unmute"
# Returns a user object for one or more users specified by the requested usernames
-user_unmute_url = "https://api.twitter.com/2/users/#{source_user_id}/muting/#{target_user_id}"
+user_unmute_url = "https://api.x.com/2/users/#{source_user_id}/muting/#{target_user_id}"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => 'https://api.twitter.com',
+ :site => 'https://api.x.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)