Coder Social home page Coder Social logo

twitter4j-v2's Introduction

v2 CI

twitter4j-v2

twitter4j-v2 is a simple wrapper for Twitter API v2 that is designed to be used with Twitter4J.

More information is here.

How do I use it?

Setup

Dependencies
repositories {
    mavenCentral()
}

dependencies {
    implementation "io.github.takke:jp.takke.twitter4j-v2:$twitter4jV2Version"
}

see search.maven.org

Example

val twitter: Twitter = yourTwitterInstanceProvider.get()
val tweetId = 656974073491156992L

val tweetsResponse = twitter.v2.getTweets(tweetId,
                            mediaFields = null,
                            placeFields = null,
                            pollFields = "duration_minutes,end_datetime,id,options,voting_status",
                            tweetFields = "id,public_metrics",
                            userFields = null,
                            expansions = "attachments.poll_ids")

println(tweetsResponse.tweets[0].poll(tweetsResponse.pollsMap))
// or
println(tweetsResponse.pollsMap[tweetsResponse.tweets[0].pollId])

// => Poll(id=656974073113636864, options=[PollOption(position=1, label=Roboto, votes=391), 
//    PollOption(position=2, label=San Francisco, votes=691)], 
//    votingStatus=CLOSED, endDatetime=Fri Oct 23 08:23:19 GMT+09:00 2015, durationMinutes=1440)

See more examples in kotlin and java.

Requirements

  • Kotlin 1.7.10
  • Twitter4J 4.0.7

Supported APIs

End-point twitter4j-v2 method
Tweets Tweet Lookup GET /2/tweets Twitter.v2.getTweets()
Manage Tweets POST /2/tweets Twitter.v2.createTweet()
DELETE /2/tweets/:id Twitter.v2.deleteTweet()
Timelines GET /2/users/:id/tweets Twitter.v2.getUserTweets()
GET /2/users/:id/mentions Twitter.v2.getUserMentions()
GET /2/users/:id/timelines/reverse_chronological Twitter.v2.getReverseChronologicalTimeline()
Search Tweets GET /2/tweets/search/recent Twitter.v2.searchRecent()
GET /2/tweets/search/all Twitter.v2.searchAll()
Tweet counts GET /2/tweets/counts/recent Twitter.v2.countRecent()
GET /2/tweets/counts/all Twitter.v2.countAll()
Filtered stream GET /2/tweets/search/stream N/A #1
Volume stream GET /2/tweets/sample/stream N/A #1
Retweets lookup GET /2/tweets/:id/retweeted_by Twitter.v2.getRetweetUsers()
Quote Tweets lookup GET /2/tweets/:id/quote_tweets Twitter.v2.getQuoteTweets()
Manage Retweets POST /2/users/:id/retweets Twitter.v2.retweet()
DELETE /2/users/:id/retweets/:source_tweet_id Twitter.v2.unretweet()
Likes lookup GET /2/tweets/:id/liking_users Twitter.v2.getLikingUsers()
GET /2/users/:id/liked_tweets Twitter.v2.getLikedTweets()
Manage Likes POST /2/users/:id/likes Twitter.v2.likeTweet()
DELETE /2/users/:id/likes/:tweet_id Twitter.v2.unlikeTweet()
Bookmarks GET /2/users/:id/bookmarks Twitter.v2.getBookmarks()
POST /2/users/:id/bookmarks Twitter.v2.addBookmark()
DELETE /2/users/:id/bookmarks/:tweet_id Twitter.v2.deleteBookmark()
Hide replies PUT /2/tweets/:id/hidden N/A (Twitter4J v4.0.7 does not support PUT methods that contain json parameters.)
Users Users lookup GET /2/users Twitter.v2.getUsers()
GET /2/users/by Twitter.v2.getUsersBy()
GET /2/users/me Twitter.v2.getMe()
Follows lookup GET /2/users/:id/following Twitter.v2.getFollowingUsers()
GET /2/users/:id/followers Twitter.v2.getFollowerUsers()
Manage follows POST /2/users/:id/following Twitter.v2.followUser()
DELETE /2/users/:source_user_id/following/:target_user_id Twitter.v2.unfollowUser()
Blocks lookup GET /2/users/:id/blocking Twitter.v2.getBlockingUsers()
Manage blocks POST /2/users/:id/blocking Twitter.v2.blockUser()
DELETE /2/users/:source_user_id/blocking/:target_user_id Twitter.v2.unblockUser()
Mutes lookup GET /2/users/:id/muting Twitter.v2.getMutingUsers()
Manage mutes POST /2/users/:id/muting Twitter.v2.muteUser()
DELETE /2/users/:source_user_id/muting/:target_user_id Twitter.v2.unmuteUser()
Spaces Spaces lookup GET /2/spaces Twitter.v2.getSpaces()
GET /2/spaces/by/creator_ids Twitter.v2.getSpacesByCreatorIds()
Spaces search GET /2/spaces/search Twitter.v2.searchSpaces()
Lists Lists lookup GET /2/lists/:id Twitter.v2.getList()
GET /2/users/:id/owned_lists Twitter.v2.getOwnedLists()
Manage Lists POST /2/lists Twitter.v2.createList()
DELETE /2/lists/:id Twitter.v2.deleteList()
PUT /2/lists/:id N/A (Twitter4J v4.0.7 does not support PUT methods that contain json parameters.)
Lists Tweets lookup GET /2/lists/:id/tweets Twitter.v2.getListTweets()
List members GET /2/lists/:id/members Twitter.v2.getListMembers()
GET /2/users/:id/list_memberships Twitter.v2.getListMemberships()
POST /2/lists/members Twitter.v2.addListMember()
DELETE /2/lists/members/:user_id Twitter.v2.deleteListMember()
Lists follows GET /2/lists/:id/followers Twitter.v2.getListFollowers()
GET /2/users/:id/followed_lists Twitter.v2.getFollowedLists()
POST /2/users/:id/followed_lists Twitter.v2.followList()
DELETE /2/users/followed_lists/:list_id Twitter.v2.unfollowList()
Pinned Lists GET /2/users/:id/pinned_lists Twitter.v2.getPinnedLists()
POST /2/users/:id/pinned_lists Twitter.v2.pinList()
DELETE /2/users/pinned_lists/:list_id Twitter.v2.unpinList()

v2 APIs table from Twitter API endpoint map

See also Response Field Mapping

Developed By

TAKEUCHI Hiroaki (@takke) - takke30 at gmail.com

License

Copyright 2020 takke

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

twitter4j-v2's People

Contributors

livexenon avatar potpot59 avatar takke avatar zackmon 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

twitter4j-v2's Issues

"getUserTweets" Method Return Exception

Hi,

First of all thank you very much to share these repository with us. I am using your repository to get,post delete etc for twitter. Bu I am getting an excepiton when I want to get tweets timeline with user Id. When I want to get a timeline of tweets containing videos, Code throw this exception "preview_image_url_not_found". You can fing my java from picture below.

image

How can I solve this exception ?

This the exception:

image

Java 17 required?

I want to use this library in a project which is still using Java 11.

I get the following error while trying to resolve the dependency with Gradle:

> No matching variant of io.github.takke:jp.takke.twitter4j-v2:1.4.1 was found. The consumer was configured to find an API of a library compatible with Java 11, packaged as a jar, and its dependencies declared externally but:
    - Variant 'apiElements' capability io.github.takke:jp.takke.twitter4j-v2:1.4.1 declares an API of a library, packaged as a jar, and its dependencies declared externally:
        - Incompatible because this component declares a component compatible with Java 17 and the consumer needed a component compatible with Java 11
    - Variant 'runtimeElements' capability io.github.takke:jp.takke.twitter4j-v2:1.4.1 declares a runtime of a library, packaged as a jar, and its dependencies declared externally:
        - Incompatible because this component declares a component compatible with Java 17 and the consumer needed a component compatible with Java 11

Does this library really require Java 17? The .module file states this library requires Java 17, but I didn't see this info anywhere else.

Add Mention and Hashtag Entities please.

Tweet Id: 1545438020412837888
TweetFields: "entities"

Postman Response:

{
    "data": {
        "entities": {
            "hashtags": [
                {
                    "start": 45,
                    "end": 50,
                    "tag": "mufc"
                }
            ],
            "urls": [
                {
                    "start": 51,
                    "end": 74,
                    "url": "https://t.co/qQ6rbC5XtB",
                    "expanded_url": "https://twitter.com/HarryMaguire93/status/1545438020412837888/photo/1",
                    "display_url": "pic.twitter.com/qQ6rbC5XtB",
                    "media_key": "3_1545438014343725056"
                }
            ],
            "mentions": [
                {
                    "start": 33,
                    "end": 40,
                    "username": "ManUtd",
                    "id": "558797310"
                }
            ]
        },
        "id": "1545438020412837888",
        "text": "A shirt to be proud of. Let’s go @ManUtd 🙌🏼🔴 #mufc https://t.co/qQ6rbC5XtB"
    }
}

missing features (filtered stream, etc)

Thanks a lot for making this library that works with Twitter API v2. It seems to be missing some features that I want to such as filtered stream data etc, any plans to add that anytime soon?

Authentification doc

Can your documentation make documentation for authentification in oAuth2

Thank you

Some methods are not visible if you are using Java

For example getFollowingUsers:

Screenshot 2023-03-31 alle 13 29 55

The strange thing is that these are present in the TwitterV2 interface.
This happens when you import the library into a new maven/gradle project.

Is anyone having the same problem?

Library version: 1.4.0
Java version: 1.8

Oauth2 PKCE example?

Hi, I'm struggling with using the getBookmarks(). It's saying the authentication credentials are missing but I have the AccessToken.

val cb = ConfigurationBuilder().apply {
            setDebugEnabled(true)
            setOAuthConsumerKey(BuildConfig.TWITTER_API_KEY)
            setOAuthConsumerSecret(BuildConfig.TWITTER_API_KEY_SECRET)
            setTweetModeExtended(true)
        }
val tokenProvider = OAuth2TokenProvider(cb.build())

val url = tokenProvider.createAuthorizeUrl(
                    BuildConfig.CLIENT_ID,
                    BuildConfig.REDIRECT_URL,
                    TwitterUtils.v2Scopes,
                    "challenge"
                )

val result = tokenProvider.getAccessToken(BuildConfig.CLIENT_ID, BuildConfig.REDIRECT_URL, oauth2Code, "challenge")

val accessToken = result.accessToken

val builder = ConfigurationBuilder().apply {
                    setDebugEnabled(true)
                    setOAuthConsumerKey(BuildConfig.TWITTER_API_KEY)
                    setOAuthConsumerSecret(BuildConfig.TWITTER_API_KEY_SECRET)
                    setOAuth2AccessToken(accessToken)
                    setOAuth2TokenType("bearer")
                    setTweetModeExtended(true)
                }

val twitter = TwitterFactory(builder.build()).instance
val bookmarks = twitter.getBookmarks(MyID)                

Error: Authentication credentials are missing.

I'm not sure if I'm doing this right or not. I believe I've got all the required details needed to call v2 methods.

I would love to see an example of using the Oauth2 PKCE accessToken to create a Twitter instance and to call v2 methods.
Thanks

Add media support

Please add support for media fields.

Image Response:

{
    "data": {
        "attachments": {
            "media_keys": [
                "3_1541785060919185408"
            ]
        },
        "id": "1541785063028842498",
        "text": "This player just won't let go of his old boots... 😆 \n\nWho is it? 🤷‍♂️\n\n#UCL https://t.co/4dETe8vjyL"
    },
    "includes": {
        "media": [
            {
                "type": "photo",
                "height": 712,
                "media_key": "3_1541785060919185408",
                "url": "https://pbs.twimg.com/media/FWWFWBwXkAApnXt.jpg",
                "width": 632
            }
        ]
    }
}

GIF Response:

{
    "data": {
        "id": "1323351722119495681",
        "text": "https://t.co/aLA9mVBAfB",
        "attachments": {
            "media_keys": [
                "16_1323351712476717057"
            ]
        }
    },
    "includes": {
        "media": [
            {
                "preview_image_url": "https://pbs.twimg.com/tweet_video_thumb/El19Xv8UYAEWxVd.jpg",
                "width": 498,
                "height": 278,
                "type": "animated_gif",
                "media_key": "16_1323351712476717057"
            }
        ]
    }
}

Video Response:

{
    "data": {
        "attachments": {
            "media_keys": [
                "13_1335947635014905857"
            ]
        },
        "text": "All types of goals from all situations 🔥\n\nCristiano Ronaldo's best Champions League goals are something else! 🍿\n\nhttps://t.co/lSzee8d61m",
        "id": "1543286684846104576"
    },
    "includes": {
        "media": [
            {
                "media_key": "13_1335947635014905857",
                "duration_ms": 256240,
                "type": "video",
                "width": 1920,
                "preview_image_url": "https://pbs.twimg.com/media/Eoo9YilXcAI6tNm.jpg",
                "public_metrics": {
                    "view_count": 231570
                },
                "height": 1080
            }
        ]
    }
}

merge with Twitter4j 4.1.2

Twitter4j introduced twitter4j.v1, it would be nice to use same lib with twitter4j.v2. Also, the lib is not compatible with last version of twitter4j.

Blocked Users throws a JSON parse error if there's no blocked users

The API doesn't return a data field in the JSON response if there's no users blocked, which breaks the parser. You can work around it by catching the exception and looking for the specific error message, but probably it shouldn't break the parser in a normal use case.

Let me know if you need me to provide any specific info to repro this.

[Java] メソッド名が不正

JavaでTwitter4j-v2 v1.4.0を使用しています
Javaで使用する際にしか起きないのかもしれませんが、searchAllsearchRecent の後に -F9r_5Hs といった文字列が付いてしまっており、不正なメソッド名になってしまっています。
他にも意図しない文字列が付いてしまっているメソッドがあるようです。
スクリーンショット 2023-02-15 16 32 19
スクリーンショット 2023-02-15 16 40 45
スクリーンショット 2023-02-15 16 41 31

twitter4j.JSONException: No value for expanded_url

There are an uncontrolled exception at:

TwitterException{exceptionCode=[e3c9a651-0001217b 6afa67f8-1b4dc763], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=4.0.7}
	at twitter4j.V2ResponseFactory.createTweetsResponse(V2ResponseFactory.kt:17)
	at twitter4j.SearchExKt.searchTweetsIn(SearchEx.kt:127)
	at twitter4j.SearchExKt.searchAll(SearchEx.kt:73)
Caused by: twitter4j.JSONException: No value for expanded_url
	at twitter4j.JSONObject.get(JSONObject.java:437)
	at twitter4j.JSONObject.getString(JSONObject.java:641)
	at twitter4j.UrlEntity2.<init>(UrlEntity2.kt:19)
	at twitter4j.User2$Companion.parse(User2.kt:54)
	at twitter4j.V2Util.collectUsers(V2Util.kt:29)
	at twitter4j.TweetsResponse.parse(TweetsResponse.kt:54)
	at twitter4j.TweetsResponse.<init>(TweetsResponse.kt:36)
	at twitter4j.V2ResponseFactory.createTweetsResponse(V2ResponseFactory.kt:15)

which does not allow to continue obtain Tweets at SearchExKt.searchAll method when the twitter API does not return the "expanded_url" value for one of the tweets.

Support for Direct Message lookup

Hey, I was wondering if you're planning to add support for Direct Message lookup?
I have to switch from API v1.1 to v2 and your library supports all the other requests I need, but Direct Messages seem to be missing, probably because that was added at a later point in time?

Thank you for this library. :)

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.