如何通过Twitter4J进行身份验证?

问题描述 投票:0回答:1

我在环境变量中存储了一些参数-当然,这些环境变量可以与powershell一起使用。

也许我需要稍微不同的参数才能通过Twitter4J进行身份验证吗?

powershell脚本输出:

thufir@dur:~$ 
thufir@dur:~$ pwsh /home/thufir/powershell/helloPSTwitterAPI/twitter.ps1 
RT @adamdriscoll: Today is the last day to sign up for the #Powershell #UniversalDashboard @udemy course at a discount rate. Check it out h…
RT @DirectoryRanger: Invoke-CommandAs

htt...
RT @adamdriscoll: Just added some #UniversalAutomation documentation about pre-defined variables in UA jobs. htt....
RT @adamdriscoll: #PowerShell #UniversalDashboard 2.8.2 is now available on the PowerShell Gallery. Lots of fixes, some improvements to Adm…
@psdevuk @adamdriscoll @psdbatools 👀
@adamdriscoll 🔥
@BillKindle @McDonalds @Wendys Sad, but that’s what I’m going to do next time. It should be ‘BigMac with Bacon Bits… htt...
I was excited to try out the new BigMac with Bacon... but horrible portion.. looks like cesar salad bacon bits...… htt...
@WindosNZ PSTwitterAPI? ;)
@Marioperator Thanks for the shoutout ❤️
RT @adamdriscoll: Nice! Financial charts for UD! htt.... #powershell htt...
@TomatoApp1 Constantly having to bind/unbind MiaoMiao device. And now the app won’t even open after trying reinstal… htt....
@adamdriscoll It shall get indexed and searchable in 15 minutes! I can just imagine your amazon shopping suggestions...
@adamdriscoll @LeeAlanBerg Pics or it didn’t happen
@SwiftOnSecurity @adbertram Did you end up finding a more elegant solution?
RT @racheldianeb: Had cake and wine tonight. 2 things I said I wouldn’t consume in Jan and would generally limit in 2020. It’s Jan 1st. So…
@adilio @sstranger Someone would probably be wrong.. 😝
@AndrewPlaTech @sstranger You have nothing to lose.. I mean, clearly I lost.. ;)
Someone’s mother has four sons. North, South and East. What is the name of the fourth son. Private message me the n… htt....
RT @EssentialSign_: For whoever needs this this evening. htt....
done
thufir@dur:~$ 

powershell脚本源:

thufir@dur:~$ 
thufir@dur:~$ cat /home/thufir/powershell/helloPSTwitterAPI/twitter.ps1 
Import-Module PSTwitterAPI


#Set-TwitterOAuthSettings -ApiKey $env:ApiKey -ApiSecret $env:ApiSecret -AccessToken $env:AccessToken -AccessTokenSecret $env:AccessTokenSecret


Set-TwitterOAuthSettings -ApiKey $env:oAuthConsumerKey -ApiSecret $env:oAuthConsumerSecret -AccessToken $env:oAuthAccessToken -AccessTokenSecret $env:oAuthAccessTokenSecret


$TwitterStatuses = Get-TwitterStatuses_UserTimeline -screen_name 'mkellerman'

Foreach ($status in $TwitterStatuses) {
  Write-Host $status.text
}

Write-Host "done"



thufir@dur:~$ 

java崩溃:

thufir@dur:~/java/helloTwitter4J$ 
thufir@dur:~/java/helloTwitter4J$ gradle clean run

> Task :run FAILED
Jan. 29, 2020 4:16:31 P.M. helloTwitter4J.App runQuery
INFO: {oAuthAccessToken=abc, oAuthConsumerKey=def, oAuthConsumerSecret=ghi, oAuthAccessTokenSecret=jkl}
Exception in thread "main" java.lang.IllegalStateException: Authentication credentials are missing. See http://twitter4j.org/en/configuration.html for details
        at twitter4j.TwitterBaseImpl.ensureAuthorizationEnabled(TwitterBaseImpl.java:201)
        at twitter4j.TwitterImpl.get(TwitterImpl.java:1966)
        at twitter4j.TwitterImpl.search(TwitterImpl.java:293)
        at helloTwitter4J.App.runQuery(App.java:52)
        at helloTwitter4J.App.main(App.java:60)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':run'.
> Process 'command '/home/thufir/.sdkman/candidates/java/12.0.1-zulu/bin/java'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
4 actionable tasks: 4 executed
thufir@dur:~/java/helloTwitter4J$ 

java来源:

package helloTwitter4J;

import java.io.IOException;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Logger;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

public class App {

    private static final Logger log = Logger.getLogger(App.class.getName());
    private final Properties properties = new Properties();

    private void loadProperties() throws InvalidPropertiesFormatException, IOException {

        properties.loadFromXML(App.class.getResourceAsStream("/twitter.xml"));
        log.fine(properties.toString());

        Set<Object> keySet = properties.keySet();
        String key = null;
        String value = null;

        for (Object obj : keySet) {
            key = obj.toString();
            value = System.getenv(key);
            log.fine(key + value);
            properties.setProperty(key, value);
        }
    }



    private void runQuery() throws TwitterException, InvalidPropertiesFormatException, IOException {
        loadProperties();
        log.info(properties.toString());  //this matches what powershell uses
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.setDebugEnabled(true)
            .setOAuthConsumerKey(properties.getProperty("oAuthConsumerKey"))
            .setOAuthConsumerSecret(properties.getProperty("oAuthConsumerSecret"))
            .setOAuthAccessToken(properties.getProperty("oAuthAccessToken"))
            .setOAuthAccessTokenSecret(properties.getProperty("oAuthAccessTokenSecret"));
    Twitter twitter = TwitterFactory.getSingleton();
         Query query = new Query("source:twitter4j yusukey");
         QueryResult result = twitter.search(query);
     //   for (Status status : result.getTweets()) {
      //       log.info("@" + status.getUser().getScreenName() + ":" + status.getText());
    //    }

    }

    public static void main(String[] args) throws InvalidPropertiesFormatException, IOException, TwitterException {
        new App().runQuery();
    }


}

我还将属性文件打印到控制台,并且它looks正确。当然,这些变量正在被使用,我只是不完全是sure他们才是Twitter4J所需要的。特定的twitter.properties文件可能是help

哦,需要正确地实际建立工厂:

https://www.dummies.com/web-design-development/mobile-apps/how-to-make-a-configurationbuilder-to-talk-to-the-twitter-server-with-your-android-app/

java powershell twitter oauth twitter4j
1个回答
0
投票

您好,世界类型代码:

package helloTwitter4J;

import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Logger;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

public class App {

    private static final Logger log = Logger.getLogger(App.class.getName());
    private Properties loadProperties() throws IOException {
        Properties properties = new Properties();
        properties.loadFromXML(App.class.getResourceAsStream("/twitter.xml"));
        log.fine(properties.toString());

        Set<Object> keySet = properties.keySet();
        String key = null;
        String value = null;

        for (Object obj : keySet) {
            key = obj.toString();
            value = System.getenv(key);
            log.fine(key + value);
            properties.setProperty(key, value);
        }
        return properties;
    }

    private TwitterFactory configTwitterFactory() throws IOException {
        Properties properties = loadProperties();
        log.info(properties.toString());  //this matches what powershell uses
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.setDebugEnabled(true)
                .setOAuthConsumerKey(properties.getProperty("oAuthConsumerKey"))
                .setOAuthConsumerSecret(properties.getProperty("oAuthConsumerSecret"))
                .setOAuthAccessToken(properties.getProperty("oAuthAccessToken"))
                .setOAuthAccessTokenSecret(properties.getProperty("oAuthAccessTokenSecret"));

        TwitterFactory twitterFactory = null;
        twitterFactory = new TwitterFactory(configurationBuilder.build());
        return twitterFactory;
    }

    private void getHomeTimeLine() throws TwitterException, IOException {
        Twitter twitter = configTwitterFactory().getInstance();
        List<Status> statuses = null;
        statuses = twitter.getHomeTimeline();

        System.out.println("Showing home timeline.");
        if (statuses != null) {
            for (Status status : statuses) {
                System.out.println(status.getUser().getName() + ":"
                        + status.getText());
            }
        }
    }

    public static void main(String[] args) throws TwitterException, IOException {
        new App().getHomeTimeLine();
    }

}

另请参阅https://github.com/nisrulz/twitterbot-java/blob/master/src/github/nisrulz/bot/TwitterBot.java

© www.soinside.com 2019 - 2024. All rights reserved.