Giter Site home page Giter Site logo

twitterdev / twitter-api-v2-sample-code Goto Github PK

View Code? Open in Web Editor NEW
2.6K 63.0 964.0 150 KB

Sample code for the Twitter API v2 endpoints

Home Page: https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api

License: Apache License 2.0

Java 12.17% JavaScript 32.59% Python 29.74% Ruby 24.92% R 0.58%
twitter twitter-api ruby java python nodejs javascript twitter-api-v2

twitter-api-v2-sample-code's Introduction

Twitter API v2 sample code v2

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).

Prerequisites

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.

For OAuth 1.0a samples, you will need to export your consumer key and secret in your terminal. Be sure to replace <your_consumer_key> and <your_consumer_secret> with your own credentials without the < >.

export CONSUMER_KEY='<your_consumer_key>'
export CONSUMER_SECRET='<your_consumer_secret>'

For samples which use bearer token authentication, you will need to export the bearer token. Be sure to replace <your_bearer_token> with your own bearer token without the < >.

export BEARER_TOKEN='<your_bearer_token>'

Language-specific requirements

Java environment set up

If you use Homebrew, you can install a Java runtime using:

brew cask install java

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.

npm install needle
npm install got
npm install oauth-1.0a

Python environment set up

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.

(Optionally) It is common and recommended not to install required package globally, but locally under project subfolder using venv:

python3 -m venv venv
source venv/bin/activate

You can install these packages as follows:

pip install requests
pip install requests-oauthlib

Ruby environment set up

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).

gem install typhoeus
gem install oauth

Additional resources

We maintain a Postman Collection which you can use for exercising individual API endpoints.

Support

  • For general questions related to the API and features, please use the v2 section of our developer community forums.

  • If there's an bug or issue with the sample code itself, please create a new issue here on GitHub.

Contributing

We welcome pull requests that add meaningful additions to these code samples, particularly for languages that are not yet represented here.

We feel that a welcoming community is important and we ask that you follow Twitter's Open Source Code of Conduct in all interactions with the community.

License

Copyright 2021 Twitter, Inc.

Licensed under the Apache License, Version 2.0: https://www.apache.org/licenses/LICENSE-2.0

twitter-api-v2-sample-code's People

Contributors

ajayhubs avatar alanblee avatar andypiper avatar aureliaspecker avatar dependabot[bot] avatar ethanjwright avatar fukkuro avatar iamdaniele avatar iamrobertduda avatar jimmoffitt avatar lennde avatar lofieth avatar niphint avatar ryanwi avatar sparack avatar twitter-service avatar viktor992 avatar virgildotcodes avatar wing328 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

twitter-api-v2-sample-code's Issues

js sample needs more parameter if that obtains user.fields

Hi experts

I'm so helpful that samples.
However I found the small issue , so I would like to write it.

js sample parameter is below:

    const params = {
        "ids": "1278747501642657792,1255542774432063488", // Edit Tweet IDs to look up
        "tweet.fields": "lang,author_id", // Edit optional query parameters here
        "user.fields": "created_at" // Edit optional query parameters here
    }

But when we specify user.fields parameter, we also must specify "expansions" parameter.
It is written by https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets-id

Actually I couldn't get user.fields response,and I added following parameter then it worked.

    const params = {
        "ids": "1278747501642657792,1255542774432063488", // Edit Tweet IDs to look up
        "tweet.fields": "lang,author_id", // Edit optional query parameters here
        "user.fields": "created_at" // Edit optional query parameters here
        "expansions": "author_id" // ** add here **
    }

Please check above.

Thank you

[question]Is authorization response necessary?

https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/54b161835fc7fb7c16e358f1c46ec12b4c0ec418/Bookmarks-lookup/bookmarks_lookup.py#L55

I'm referencing both the bookmarks lookup code and this code for my project(I'm a total noob), and I noticed that the latter isn't using any authorization response for their twitter authentication but the former is. This has gotten me confused and wondering, is the authorization response necessary for the authentication or is it just used there for demo purposes and better explanation?

I can't use StreamingClient in API v2.

Describe the bug
Hello.
I paid $100 and get Basic access level.
And I tried to use StreamingClient and got error like followings.

{"client_id":"xxxxxxxx","detail":"When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App 
that is attached to a Project. You can create a project via the developer portal.","registration_url":"https://developer.twitter.com/en/docs/projects/overview","title":"Client Forbidden","required_enrollment":"Appropriate Level of API Access","reason":"client-not-enrolled","type":"https://api.twitter.com/2/problems/client-forbidden"}

But all endpoints except of StreamingClient work well.
I'm not sure why this error was happened.
Users can't use Streaming functionality in Basic level?
Or Is there any issue in API v2?

Getting client forbidden error in twitter api with endpoint /2/users/1669301955590778880?user.fields=profile_image_url from 5 days

error :{
“client_id”: “27316216”,
“detail”: “When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.”,
“registration_url”: “twitter registration url”,
“title”: “Client Forbidden”,
“required_enrollment”: “Appropriate Level of API Access”,
“reason”: “client-not-enrolled”,
“type”: “twitter error demonstrating page”
}
getting same error for 3 accounts checked

Authentication Error (403 Forbidden) when Running Twitter Bot

Description:

I am facing an authentication issue with the Twitter bot using the code from the repository https://github.com/vedicscriptures/twitter_bot/blob/main/main.py. Previously, it used to work without any problems, but now I am encountering a 403 Forbidden error during authentication.

Steps to Reproduce:

  1. Clone the repository: https://github.com/vedicscriptures/twitter_bot.git
  2. Run the command: python main.py
  3. Observe the authentication error mentioned below:
Run python main.py
  python main.py
  shell: /usr/bin/bash -e {0}
  env:
    pythonLocation: /opt/hostedtoolcache/Python/3.8.17/x64
    LD_LIBRARY_PATH: /opt/hostedtoolcache/Python/3.8.17/x64/lib
    APIKey: ***
    APISecretKey: ***
    AccessToken: ***
    AccessTokenSecret: ***
    BearerToken: ***
2021-10-14
2023-07-31 18:09:40.196412
Error during authentication :
403 Forbidden
When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.

Links to Runs with the Issue:

  1. Successful Run URL: https://github.com/vedicscriptures/twitter_bot/actions/runs/5681881040/job/15398990021
  2. Failing Run URL: https://github.com/vedicscriptures/twitter_bot/actions/runs/5718104707/job/15493234567

Additional Information:
I have confirmed that the code being used is the same as provided in the repository, and it was previously functional. However, after the recent run at the URL mentioned above, the authentication issue started occurring. Any assistance in resolving this problem would be greatly appreciated.

Cannot get rules (HTTP 401)

The bug occurs when using the code example for Filtered-Stream. I have set the bearer token through the console as it mentions but I still receive a 401 which would hint towards me not being authorized. I don't know if I have done something wrong regarding the setting of the token, but I did this through the console in VSCode.

The actual error message I received was the one below. I'm not fabulous with Python or the API so I'm a little stuck.

Exception has occurred: Exception Cannot get rules (HTTP 401): {"title":"Unauthorized","detail":"Unauthorized","type":"about:blank","status":401} File "C:\Users\Rhys\OneDrive\Documents\TwitterCrawl.py", line 25, in get_rules raise Exception( File "C:\Users\Rhys\OneDrive\Documents\TwitterCrawl.py", line 89, in main rules = get_rules() File "C:\Users\Rhys\OneDrive\Documents\TwitterCrawl.py", line 96, in <module> main()

NameError: name 'fetch_response' is not defined

Getting this error when launching sample tweet post script:
esource_owner_key = fetch_response.get("oauth_token")
^^^^^^^^^^^^^^
NameError: name 'fetch_response' is not defined

My keys are correct and my account should have the relevant access, can anyone please help me find out what is causing this issue I would be very appreciative, thank you.

Add version to `got` dependency

If we just copy the dependencies installation code from JavaScript (Node.js) environment set up, we'll get the following

npm install needle
npm install got
npm install oauth-1.0a

This means we are installing the latest version of got. Since v12.0.0 the package is pure ESM, so we must use import to load it or we'll get the following error

~/index.js:3
const got = require('got');
            ^

Error [ERR_REQUIRE_ESM]: require() of ES Module ~/node_modules/got/dist/source/index.js from ~/index.js not supported.
Instead change the require of ~/node_modules/got/dist/source/index.js in ~/index.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (~/index.js:3:13) {
  code: 'ERR_REQUIRE_ESM'
}

To reproduce the error, you need to install the dependencies the way the README.md says and try to run any example that requires got package.

There are two solutions as I see, we could rewrite all the scripts that fail or we could install a previous version to v12.0.0. So in order to run the examples as they are without any script change, I suggest adding a version range with a "less than" symbol.

npm install got@'<12.0.0'

Recent search not working in browser. I am constantly getting CORS error

`getTweets(){

var myHeaders = new HttpHeaders();
myHeaders.append("Authorization", "Bearer "+this.token);
// myHeaders.append("Cookie", "guest_id=v1%3A161908241149107957; personalization_id="v1_ejJZ4HGUOXH10orpNKx4xQ=="");

var requestOptions = {
method: 'GET',

headers: myHeaders,
redirect: 'follow'

};

fetch("https://api.twitter.com/1.1/search/tweets.json?q==ECONOMICTIMES&max_results=10&tweet.fields=author_id,created_at,entities,geo,in_reply_to_user_id,lang,possibly_sensitive,referenced_tweets,source", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
`

ValueError: Only unicode objects are escapable. Got None of type <class 'NoneType'>.

Describe the bug
When I run this code on python 3.7, it will always say: "There may have been an issue with the consumer_key or consumer_secret you entered." But I'm pretty sure they are right.

The error is this:

/usr/local/lib/python3.7/dist-packages/oauthlib/oauth1/rfc5849/utils.py in escape(u)
     48     if not isinstance(u, str):
     49         raise ValueError('Only unicode objects are escapable. ' +
---> 50                          'Got {!r} of type {}.'.format(u, type(u)))
     51     # Letters, digits, and the characters '_.-' are already treated as safe
     52     # by urllib.quote(). We need to add '~' to fully support rfc5849.

ValueError: Only unicode objects are escapable. Got None of type <class 'NoneType'>.

When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal

When i try to search tweets (v2.search) i got this error "When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal"

but if i try to post a tweet using v2.tweet i get no errors.

Python and Javascript stream examples break after 5 minutes

Describe the bug
Both Python and Javascript example code for streaming break after 5 minutes of retrieving tweets. Javascript just hangs/ends without message, Python throws the following error:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/urllib3/response.py", line 543, in _update_chunk_length
    self.chunk_left = int(line, 16)
ValueError: invalid literal for int() with base 16: b''

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/urllib3/response.py", line 302, in _error_catcher
    yield
  File "/usr/lib/python3/dist-packages/urllib3/response.py", line 598, in read_chunked
    self._update_chunk_length()
  File "/usr/lib/python3/dist-packages/urllib3/response.py", line 547, in _update_chunk_length
    raise httplib.IncompleteRead(line)
http.client.IncompleteRead: IncompleteRead(0 bytes read)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/xxx/.local/lib/python3.6/site-packages/requests/models.py", line 753, in generate
    for chunk in self.raw.stream(chunk_size, decode_content=True):
  File "/usr/lib/python3/dist-packages/urllib3/response.py", line 432, in stream
    for line in self.read_chunked(amt, decode_content=decode_content):
  File "/usr/lib/python3/dist-packages/urllib3/response.py", line 626, in read_chunked
    self._original_response.close()
  File "/usr/lib/python3.6/contextlib.py", line 99, in __exit__
    self.gen.throw(type, value, traceback)
  File "/usr/lib/python3/dist-packages/urllib3/response.py", line 320, in _error_catcher
    raise ProtocolError('Connection broken: %r' % e, e)
urllib3.exceptions.ProtocolError: ('Connection broken: IncompleteRead(0 bytes read)', IncompleteRead(0 bytes read))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "twitter-sample-python.py", line 93, in <module>
    main()
  File "twitter-sample-python.py", line 89, in main
    get_stream(headers, set, bearer_token)
  File "twitter-sample-python.py", line 76, in get_stream
    for response_line in response.iter_lines():
  File "/home/xxx/.local/lib/python3.6/site-packages/requests/models.py", line 797, in iter_lines
    for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):
  File "/home/xxx/.local/lib/python3.6/site-packages/requests/models.py", line 756, in generate
    raise ChunkedEncodingError(e)
requests.exceptions.ChunkedEncodingError: ('Connection broken: IncompleteRead(0 bytes read)', IncompleteRead(0 bytes read))

To Reproduce
Download example code, set bearer token, run example code. Each time the code is executed, it will stop receiving tweets after the same amount of time, i.e. ~5 minutes. I could reproduce this on two different machines, os (ubuntu+osx), twitter accounts, and three different internet connections.

Expected behavior
Stream should not stop.

Getting "Bad request" when trying to post a tweet [nodejs]

I'm exploring the Twitter API integrated with Nodejs, currently trying to post a tweet using the example provided "Twitter-API-v2-sample-code/Manage-Tweets/create_tweet.js" but getting error "Bad request".
I only changed the consumer_key and consumer_secret with mine.

To Reproduce

  1. Use "Twitter-API-v2-sample-code/Manage-Tweets/create_tweet.js" file code.
  2. replace consumer_key and consumer_secret with the needed values.
  3. run.

Expected behavior
get the "Hello World" tweet posted successfully.

Output
GotError [HTTPError]: Response code 400 (Bad Request)
at EventEmitter. (/Users/samaael-komy/IBM Unify LC2/git/Emma-General-BE/node_modules/got/source/as-promise.js:74:19)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
host: 'api.twitter.com',
hostname: 'api.twitter.com',
method: 'POST',
path: '/2/tweets',
socketPath: undefined,
protocol: 'https:',
url: 'https://api.twitter.com/2/tweets',
gotOptions: {
path: '/2/tweets',
protocol: 'https:',
slashes: true,
auth: null,
host: 'api.twitter.com',
port: null,
hostname: 'api.twitter.com',
hash: null,
search: null,
query: null,
pathname: '/2/tweets',
href: 'https://api.twitter.com/2/tweets',
retry: {
retries: [Function (anonymous)],
methods: [Set],
statusCodes: [Set],
errorCodes: [Set]
},
headers: {
'user-agent': 'v2CreateTweetJS',
authorization: 'OAuth oauth_consumer_key="XXX", oauth_nonce="XXX", oauth_signature="XXX", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1642421266", oauth_token="XXX", oauth_version="1.0"',
'content-type': 'application/json',
accept: 'application/json',
'accept-encoding': 'gzip, deflate'
},
hooks: {
beforeRequest: [],
beforeRedirect: [],
beforeRetry: [],
afterResponse: [],
beforeError: [],
init: []
},
decompress: true,
throwHttpErrors: true,
followRedirect: true,
stream: false,
form: false,
json: { text: 'Hello world!' },
cache: false,
useElectronNet: false,
responseType: 'json',
method: 'POST'
},
statusCode: 400,
statusMessage: 'Bad Request',
headers: {
date: 'Mon, 17 Jan 2022 12:07:47 UTC',
server: 'tsa_f',
'set-cookie': [
'guest_id_marketing=XXX; Max-Age=63072000; Expires=Wed, 17 Jan 2024 12:07:47 GMT; Path=/; Domain=.twitter.com; Secure; SameSite=None',
'guest_id_ads=XXX; Max-Age=63072000; Expires=Wed, 17 Jan 2024 12:07:47 GMT; Path=/; Domain=.twitter.com; Secure; SameSite=None',
'personalization_id="XXX"; Max-Age=63072000; Expires=Wed, 17 Jan 2024 12:07:47 GMT; Path=/; Domain=.twitter.com; Secure; SameSite=None',
'guest_id=XXX; Max-Age=63072000; Expires=Wed, 17 Jan 2024 12:07:47 GMT; Path=/; Domain=.twitter.com; Secure; SameSite=None'
],
'api-version': '2.34',
'content-type': 'application/json; charset=utf-8',
'cache-control': 'no-cache, no-store, max-age=0',
'content-length': '187',
'x-access-level': 'read-write',
'x-frame-options': 'SAMEORIGIN',
'content-encoding': 'gzip',
'x-xss-protection': '0',
'x-rate-limit-limit': '200',
'x-rate-limit-reset': '1642421945',
'content-disposition': 'attachment; filename=json.json',
'x-content-type-options': 'nosniff',
'x-rate-limit-remaining': '197',
'strict-transport-security': 'max-age=631138519',
'x-response-time': '147',
'x-connection-hash': '2863900f313c672dd21c6ea0b1ba9b1f80b4ef8de9bc20aa2d5bfaa350f10016',
connection: 'close'
},
body: {
errors: [ [Object] ],
title: 'Invalid Request',
detail: 'One or more parameters to your request was invalid.',
type: 'https://api.twitter.com/2/problems/invalid-request'
}
}

[Bug Report] Error 403 Forbidden when using GET /2/users/:id/following with Twitter API v2 endpoint

Describe the bug
Hello,
I am currently subscribed to the $100 Basic Plan. I encountered a bug while using the Twitter API v2 endpoint with the GET /2/users/:id/following method.

When making the request, I received the following error message:
"403 Forbidden
When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal."

I want to highlight that my app is already attached to a project, and I am not the only user experiencing this bug. Several other users are also encountering the same issue.

Please investigate this bug and take the necessary actions to resolve it as soon as possible. If you require any additional information, such as screenshots or logs, please let me know.

Thank you for your attention to this matter.

GET /2/users/by/username/:username/following endpoint returns 404 error

Describe the bug
In the dashboard, there are two endpoints given to getting the followings of an account,
one is by using the user's ID <GET /2/users/:id/following>
and the other is by using the user's name <GET /2/users/by/username/:username/following>
the one with ID works, however, the one with username return 404 in response

To Reproduce
Run this code:

import requests
import json

bearer_token = "{YOUR TOKEN}"

def bearer_oauth(r):
    r.headers["Authorization"] = f"Bearer {bearer_token}"
    r.headers["User-Agent"] = "v2FullArchiveSearchPython"
    return r

def connect_to_endpoint(url, params, method: str = 'GET'):
    response = requests.request(method, 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 get_acc_followings(user_name: str):
    search_url = "https://api.twitter.com/2/users/by/username/%s/following" % user_name
    print(search_url)
    query_params = {"user.fields": "id,name,public_metrics,username"}
    json_response = connect_to_endpoint(search_url, query_params)
    print(json.dumps(json_response, indent=4, sort_keys=True))

if __name__ == "__main__":
    get_acc_followings('{PUT USERNAME HERE}')

Expected behavior
The response should include details of "following" users

Additional context
Running the same code by using the user's ID works just fine.

def get_acc_followings_by_id(user_id: str):
    search_url = "https://api.twitter.com/2/users/%s/following" % user_id
    print(search_url)
    query_params = {"user.fields": "id,name,public_metrics,username"}
    json_response = connect_to_endpoint(search_url, query_params)
    print(json.dumps(json_response, indent=4, sort_keys=True))

Add golang examples

Add examples showing how to connect using golang/golang libraries to the new V2 API

User timeline API is not returning the right results

Describe the bug
I'm trying to pull the timeline for @forbes from 2022-04-19 to 2022-05-19. The url I'm sending the requests to is as follows:

"https://api.twitter.com/2/users/Forbes/tweets?max_results=100&start_time=2022-04-19T00:00:00Z&end_time=2022-05-19T00:00:00Z"

The returned response is as follows:

{ "meta": { "result_count": 0 } }

However, there are some tweets in that period, including this one: https://twitter.com/Forbes/status/1518671125563199492

When I change the user ID (For example to "CNN"), it works just fine.

To Reproduce
Go to Twitters Public Workspace on Postman, set your bearer token, and send the following request:

image

Additional context
I tried different methods (python code on my laptop, postman, python code on google colab). I tried two different bearer auth tokens. Still getting the same empty response.

Java Code samples are broken

Describe the bug
Java code samples don't work

To Reproduce
Try running any of the Java code samples locally, they are full of errors - syntax error, logical error. Don't anyone at Twitter know how to write a good Java Program, can't believe it. Twitter is supposed to be a huge Java shop.

Expected behavior
try to compile java program - any of them for example inside of "Tweet-Lookup" folder, run javac get_users.java and see what happens. Can't believe you guys don't even know how to name java classes and programs?

Additional context
I've forked the repo and started to fix your bugs, will submit a PR soon 😑🔫

Python sample -> create_headers

I would say that in the python samples the function create_headers should be:

'def create_headers(bearer_token):
headers = {"Authorization: Bearer {}".format(bearer_token)}
return headers'

instead of

'def create_headers(bearer_token):
headers = {"Authorization": "Bearer {}".format(bearer_token)}
return headers'

At least that is what worked for me. Cheers guys

Unauthorized Error 401. Tried to regenerate tokens but still issue persists

I am using python sample code provided in the repository. But I am getting "builtins.Exception: (401, '{\n "title": "Unauthorized",\n "type": "about:blank",\n "status": 401,\n "detail": "Unauthorized"\n}')" error whenever I try to fetch data using any Endpoint. I tried to regenerate tokens with Read, Write Permissions but still the issue persists.

Typhoeus run returning empty

Describe the bug
I am running the ruby get timeline tweet script but it is returning empty

To Reproduce

Expected behavior
TheTyphoeus request object should return with data

Additional context
Add any other context about the problem here.

image

Incorrect usage of template literal in JavaScript code

Describe the bug
There is an error in the usage of template literal in the following code:

const endpointURL = `https://api.twitter.com/2/users/me?{params}`;

It should be corrected to:

const endpointURL = `https://api.twitter.com/2/users/me?${params}`;

This bug is causing unexpected behavior in the program.

To Reproduce
Steps to reproduce the behavior:

  1. Go to the section where the code is used
  2. Execute the code

Expected behavior
The code should execute without any error or unexpected behavior.

Additional context
Nothing

HTTPError: Response code 403 (Forbidden) using delete_tweets.js

Describe the bug
I'm new to javascript and I'm trying to use the delete_tweets.js code provided in the Twitter-API-v2-sample-code. After copying over most of the code, and making a few small changes, I am encountering a HTTP 403 error. Furthermore, I'm seeing lots of type errors when using the "got" package. I've downgraded the package to install a pre-pure-ESM version (i.e., npm install got@"<12.0.0"). The full output of the error is:

HTTPError: Response code 403 (Forbidden)
    at Request.<anonymous> (/path/to/my/code/directory/node_modules/got/dist/source/as-promise/index.js:118:42)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_NON_2XX_3XX_RESPONSE',
  timings: {
    start: 1655492679063,
    socket: 1655492679064,
    lookup: 1655492679066,
    connect: 1655492679117,
    secureConnect: 1655492679168,
    upload: 1655492679168,
    response: 1655492679234,
    end: 1655492679235,
    error: undefined,
    abort: undefined,
    phases: {
      wait: 1,
      dns: 2,
      tcp: 51,
      tls: 51,
      request: 0,
      firstByte: 66,
      download: 1,
      total: 172
    }
  }
}

The header I am submitting is:

{
  Authorization: 'OAuth oauth_consumer_key="XXX", oauth_nonce="XXX", oauth_signature="XXX", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1655493042", oauth_token="XXX", oauth_version="1.0"',
  'user-agent': 'v2DeleteTweetJS',
  'content-type': 'application/json',
  accept: 'application/json'
}

To Reproduce
I've installed all the dependencies listed in the README for javascript. I've made a couple of minor changes. The first change I made is to use a .txt file to store my credentials, so at the beginning of the script I read them in using PapaParse:

function get_creds(credentialsFile) {

    let credentialFile = fs.readFileSync(
        credentialsFile,
        "utf-8"
    );

    let credentials = papa.parse(
        credentialFile,
        {
            delimiter: ",",
            header: true,
        }
    );

    return credentials.data[0]
};

const credentialFile = "/path/to/my/twitter/credentials.txt";

const credentials = get_creds(credentialFile);

I also used this credentials variable when passing in my access_token, so I've replaced some code:

(async () => {
    try {
        // ########################################################
        // THIS CODE IS COMMENTED OUT BUT IS PART OF THE ORIGINAL SCRIPT

        // // 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());

       // ########################################################

        const oAuthAccessToken = {
            "oauth_token": credentials.access_token,
            "oauth_token_secret": credentials.access_token_secret,
            "screen_name": "my-screen-name--this-is-fake",
            "user_id": credentials.access_token.split("-")[0],
        };

        // Make the request
        const response = await getRequest(oAuthAccessToken);
        console.dir(response, {
            depth: null,
        });

    } catch (e) {
        console.log(e);
        process.exit(-1);
    }

    process.exit();
}) ();

I doubt that using this credentials file is changing much, but as a dummy check, I used the commented out method (i.e., getting a PIN from my app) and got the following error:

HTTPError: Response code 403 (Forbidden)
    at Request.<anonymous> (/path/to/my/code/directory/node_modules/got/dist/source/as-promise/index.js:118:42)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_NON_2XX_3XX_RESPONSE',
  timings: {
    start: 1655492679063,
    socket: 1655492679064,
    lookup: 1655492679066,
    connect: 1655492679117,
    secureConnect: 1655492679168,
    upload: 1655492679168,
    response: 1655492679234,
    end: 1655492679235,
    error: undefined,
    abort: undefined,
    phases: {
      wait: 1,
      dns: 2,
      tcp: 51,
      tls: 51,
      request: 0,
      firstByte: 66,
      download: 1,
      total: 172
    }
  }
}

Expected behavior
I expect that I can pass in a tweet ID and it would get deleted.

Adding location parameter to filtered-stream query

Example code is super helpful as I migrate my app to the v2 api, but I can't find any documentation on how to add location tags to a query (specifically for countries, though geo-bounding-boxes, as in v1, would also work)

Spaces lookup

Describe the bug
Are you sure that the sample code for Spaces lookup (JS) is actually doing what it should? :)

To Reproduce
Have a quick look at the code.

Expected behavior
It should use the spaces lookup endpoint.

Additional context
It seems to be counting tweets instead.

Extending character limit beyond 280 for Twitter Blue users with API v2

Describe the bug
When using the Twitter API v2 to post tweets for Twitter Blue users, the API does not allow posting extended tweets beyond the standard 280-character limit.

To Reproduce
Steps to reproduce the behavior:

Authenticate with the Twitter API v2 as a Twitter Blue user.
Compose a tweet with more than 280 characters.
Attempt to post the tweet using the API v2.
Observe the error or unexpected behavior.

Expected behavior
As a Twitter Blue user, the API should allow posting tweets with an extended character limit (beyond 280 characters). The API should recognize the user's Twitter Blue status and accommodate the increased character limit accordingly.

Additional context
This issue affects developers who are trying to provide an enhanced experience for Twitter Blue users by supporting extended tweets in their applications. It would be helpful to have clear documentation or guidance on how to implement this functionality using the API v2.

delete_tweet.py provides an authorization link that doesn't return the authorization PIN

Problem:
"delete_tweet.py" provides an authorization link that doesn't return the authorization PIN.

I do refer to the following block in the log after running the script:

...
Please go here and authorize: https://api.twitter.com/oauth/authorize?oauth_token=<token>
Paste the PIN here: <pin>
...

Solution:
As for "create_tweet.py", replacing the following line:

request_token_url = "https://api.twitter.com/oauth/request_token"

with the following:

request_token_url = "https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write"

to fix the issue.

Please update the file in the repository accordingly.

When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project.

Describe the bug
Context - We would like to use Full Archive v2 search/all endpoint. We have a premium subscription. We do not have a standalone app. We have a project and an app is added to it. I have tested using the bearer and also with the API keys. v2/search/recent works fine though. Only the v2/search/all is throwing below error.

When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.
"title": "Client Forbidden",
"required_enrollment": "Standard Basic",
"reason": "client-not-enrolled",

To Reproduce

Expected behavior
A clear and concise description of what you expected to happen.

Additional context
Add any other context about the problem here.

400 Bad Request upon using next token

I am using the code in the github example page to check followers with node.js. The command works well, except when the number of followers exceeds the max.results (1000). When this happens, the code resends the request using the nextToken parameter. But the response is a 400 error (Bad Request).

After prodding through the documentation I discovered the proper parameter is pagination_token, instead of next_token. So, in the code, line 53 should change to:
params.pagination_token = nextToken;

(Info from: quickstart followers documentation )

When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project

Describe the bug
Cannot get rules (HTTP 403): {"client_id":"xxxxx","detail":"When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.","registration_url":"https://developer.twitter.com/en/docs/projects/overview","title":"Client Forbidden","required_enrollment":"Standard Basic","reason":"client-not-enrolled","type":"https://api.twitter.com/2/problems/client-forbidden"}

To Reproduce

  1. Create environment variable with Bearer token.
  2. Run the py script.

Truncated tweet texts returned, even tho explicitly filtering out retweets

Describe the bug
I'm seeing truncated tweet texts, even though I've explicitly filtered out retweets in my query.

To Reproduce

import requests
import os
import json

# To set your environment variables in your terminal run the following line:
# export 'BEARER_TOKEN'='<your_bearer_token>'
bearer_token = os.environ.get("BEARER_TOKEN")

search_url = "https://api.twitter.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:lightningai -is:retweet)',
                'tweet.fields': 'author_id,created_at,public_metrics', 
                'max_results':10}

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()

Expected behavior
I would expect all the tweet texts returned to be the full text.

Additional context
An example of what I'm seeing, where it's clear that the tweet is truncated at StableLM, Pythia,...:

{'author_id': '1157283331509235713', 'created_at': '2023-05-09T15:13:09.000Z', 'edit_history_tweet_ids': ['1655954064474279938'], 'id': '1655954064474279938', 'public_metrics': {'impression_count': 14351, 'like_count': 113, 'quote_count': 3, 'reply_count': 3, 'retweet_count': 29}, 'text': '⚡Lit-Parrot 🦜 - the simplest implementation of the best open-source language models out there is now available!\n\nFresh out of the cage👉 https://t.co/TWSVqU6izY\n\n💡“nanoGPT” minimal\n🛠️hackable\n📜comes with pre-training + finetuning scripts\n\nShips with StableLM, Pythia,… https://t.co/RypG8NLUgy https://t.co/nW2W80Cwup'}

Any guidance would be greatly appreciated. Thank you!

[BUG] `GET /2/tweets/:id` not returning tweet url for some/many tweets

Describe the bug
This is an issue with the Twitter API V2, which I have noticed that for many tweets it does not return the url mentioned in the tweet or as part of the attached media.

To Reproduce
Try finding tweet details for the following tweet:
1537477582194626560 (accessible via https://twitter.com/961227801365008385/status/1537477582194626560). This will give you correct results (url included)

Now do the same for the following tweet:
id: 1559108202666397696 accessible via https://twitter.com/961227801365008385/status/1559108202666397696. Although the tweet has a url, the API will NOT return it.

Expected behavior
API response matches what we see in the tweet via the link and tweet URLs are returned properly.

Additional context
I could confirm this issue via the Live Request of Twitter API dashboard as well as with Python client.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.