|
| 1 | +""" |
| 2 | +Follow User - X API v2 |
| 3 | +====================== |
| 4 | +Endpoint: POST https://api.x.com/2/users/:id/following |
| 5 | +Docs: https://developer.x.com/en/docs/twitter-api/users/follows/api-reference/post-users-id-following |
| 6 | +
|
| 7 | +Authentication: OAuth 2.0 (User Context) |
| 8 | +Required env vars: CLIENT_ID, CLIENT_SECRET |
| 9 | +""" |
| 10 | + |
| 11 | +import os |
| 12 | +import json |
| 13 | +from xdk import Client |
| 14 | +from xdk.oauth2_auth import OAuth2PKCEAuth |
| 15 | + |
| 16 | +# The code below sets the client ID and client secret from your environment variables |
| 17 | +# To set environment variables on macOS or Linux, run the export commands below from the terminal: |
| 18 | +# export CLIENT_ID='YOUR-CLIENT-ID' |
| 19 | +# export CLIENT_SECRET='YOUR-CLIENT-SECRET' |
| 20 | +client_id = os.environ.get("CLIENT_ID") |
| 21 | +client_secret = os.environ.get("CLIENT_SECRET") |
| 22 | + |
| 23 | +# Replace the following URL with your callback URL, which can be obtained from your App's auth settings. |
| 24 | +redirect_uri = "https://example.com" |
| 25 | + |
| 26 | +# Set the scopes |
| 27 | +scopes = ["tweet.read", "users.read", "follows.write", "offline.access"] |
| 28 | + |
| 29 | +# Be sure to replace user-id-to-follow with the user id you wish to follow. |
| 30 | +# You can find a user ID by using the user lookup endpoint |
| 31 | +target_user_id = "user-id-to-follow" |
| 32 | + |
| 33 | +def main(): |
| 34 | + # Step 1: Create PKCE instance |
| 35 | + auth = OAuth2PKCEAuth( |
| 36 | + client_id=client_id, |
| 37 | + client_secret=client_secret, |
| 38 | + redirect_uri=redirect_uri, |
| 39 | + scope=scopes |
| 40 | + ) |
| 41 | + |
| 42 | + # Step 2: Get authorization URL |
| 43 | + auth_url = auth.get_authorization_url() |
| 44 | + print("Visit the following URL to authorize your App on behalf of your X handle in a browser:") |
| 45 | + print(auth_url) |
| 46 | + |
| 47 | + # Step 3: Handle callback |
| 48 | + callback_url = input("Paste the full callback URL here: ") |
| 49 | + |
| 50 | + # Step 4: Exchange code for tokens |
| 51 | + tokens = auth.fetch_token(authorization_response=callback_url) |
| 52 | + access_token = tokens["access_token"] |
| 53 | + |
| 54 | + # Step 5: Create client |
| 55 | + client = Client(access_token=access_token) |
| 56 | + |
| 57 | + # Step 6: Get the authenticated user's ID |
| 58 | + me_response = client.users.get_me() |
| 59 | + user_id = me_response.data["id"] |
| 60 | + |
| 61 | + # Step 7: Follow the user |
| 62 | + payload = {"target_user_id": target_user_id} |
| 63 | + response = client.users.follow_user(user_id, body=payload) |
| 64 | + |
| 65 | + print("Response code: 200") |
| 66 | + print(json.dumps(response.data, indent=4, sort_keys=True)) |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + main() |
0 commit comments