Search in sources :

Example 26 with TwitterFactory

use of twitter4j.TwitterFactory in project twitter4j by yusuke.

the class ShowFriendship method main.

/**
     * Usage: java twitter4j.examples.friendship.ShowFriendship  [source screen name] [target screen name]
     *
     * @param args message
     */
public static void main(String[] args) {
    if (args.length < 2) {
        System.out.println("Usage: java twitter4j.examples.friendship.ShowFriendship [source screen name] [target screen name]");
        System.exit(-1);
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        Relationship relationship = twitter.showFriendship(args[0], args[1]);
        System.out.println("isSourceBlockingTarget: " + relationship.isSourceBlockingTarget());
        System.out.println("isSourceFollowedByTarget: " + relationship.isSourceFollowedByTarget());
        System.out.println("isSourceFollowingByTarget: " + relationship.isSourceFollowingTarget());
        System.out.println("isSourceNotificationsEnabled: " + relationship.isSourceNotificationsEnabled());
        System.out.println("canSourceDm: " + relationship.canSourceDm());
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to show friendship: " + te.getMessage());
        System.exit(-1);
    }
}
Also used : Relationship(twitter4j.Relationship) Twitter(twitter4j.Twitter) TwitterFactory(twitter4j.TwitterFactory) TwitterException(twitter4j.TwitterException)

Example 27 with TwitterFactory

use of twitter4j.TwitterFactory in project Ardent by adamint.

the class Ardent method main.

public static void main(String[] args) throws Exception {
    new DefaultAudioPlayerManager();
    Logger root1 = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    root1.setLevel(Level.OFF);
    for (String s : args) {
        if (s.contains("premium"))
            premiumBot = true;
    }
    if (!testingBot) {
        spotifyApi = Api.builder().clientId("471f277107704e3b89d489284b65c6c6").clientSecret(IOUtils.toString(new FileInputStream(new File("/root/Ardent/spotifysecret.key")))).redirectURI("https://ardentbot.tk").build();
        SpotifyTokenRefresh spotifyTokenRefresh = new SpotifyTokenRefresh();
        spotifyTokenRefresh.run();
        globalExecutorService.scheduleAtFixedRate(spotifyTokenRefresh, 10, 10, TimeUnit.MINUTES);
    } else
        spotifyApi = Api.DEFAULT_API;
    if (!testingBot) {
        dbPassword = IOUtils.toString(new FileReader(new File("/root/Ardent/v2password.key")));
        botsDiscordPwToken = IOUtils.toString(new FileReader(new File("/root/Ardent/botsdiscordpw.key")));
        discordBotsOrgToken = IOUtils.toString(new FileReader(new File("/root/Ardent/discordbotsorg.key")));
    } else {
        try {
            dbPassword = IOUtils.toString(new FileReader(new File("C:\\Users\\AMR\\Desktop\\Ardent\\v2password.key")));
            discordBotsOrgToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjE2OTkwNDMyNDk4MDI0NDQ4MCIsImlhdCI6MTQ5MzMyNDM1OX0.LQ97UtslzaM5Qo__gkihOX5afaZA5z3TjMjSovMzDTI";
        } catch (Exception ex) {
            dbPassword = IOUtils.toString(new FileReader(new File("/root/Ardent/.key")));
        }
    }
    Database.setup();
    Cursor<HashMap> apiKeys = r.db("data").table("api_keys").run(connection);
    apiKeys.forEach((outside) -> {
        outside.forEach((uId, uValue) -> {
            String id = (String) uId;
            String value = (String) uValue;
            if (id.equalsIgnoreCase("mashape"))
                mashapeKey = value;
            else if (id.equalsIgnoreCase("google"))
                GOOGLE_API_KEY = value;
            else if (id.equalsIgnoreCase("node0"))
                node0Url = value;
            else if (id.equalsIgnoreCase("node1"))
                node1Url = value;
            else if (id.equalsIgnoreCase("cleverbotuser"))
                cleverbotUser = value;
            else if (id.equalsIgnoreCase("cleverbotkey"))
                cleverbotKey = value;
            else if (id.equalsIgnoreCase("premiumbottoken"))
                premiumBotToken = value;
            else if (id.equalsIgnoreCase("testbottoken"))
                testBotToken = value;
            else if (id.equalsIgnoreCase("googlesecret"))
                clientSecret = value;
            else if (id.equalsIgnoreCase("twitch"))
                twitch = value;
        });
    });
    ShardManager.register(shardCount);
    BotlistUpdater updater = new BotlistUpdater();
    globalExecutorService.scheduleAtFixedRate(updater, 0, 1, TimeUnit.HOURS);
    StuckVoiceConnection playerStuckDaemon = new StuckVoiceConnection();
    globalExecutorService.scheduleAtFixedRate(playerStuckDaemon, 10, 10, TimeUnit.SECONDS);
    UpdatePremiumMembers updatePremiumMembers = new UpdatePremiumMembers();
    globalExecutorService.scheduleAtFixedRate(updatePremiumMembers, 0, 1, TimeUnit.MINUTES);
    ProfileUpdater profileUpdater = new ProfileUpdater();
    globalExecutorService.scheduleWithFixedDelay(profileUpdater, 1, 5, TimeUnit.MINUTES);
    if (!premiumBot) {
        SparkServer.setup();
    /*Class currentClass = new Object() {
            }.getClass().getEnclosingClass();
            premiumProcess = Runtime.getRuntime().exec("java -jar " + currentClass.getProtectionDomain().getCodeSource().getLocation()
                    .getPath() + " -premium");*/
    } else {
        CheckIfPremiumGuild checkIfPremiumGuild = new CheckIfPremiumGuild();
        globalExecutorService.scheduleAtFixedRate(checkIfPremiumGuild, 1, 5, TimeUnit.MINUTES);
    }
    GoogleSearch.setup(GOOGLE_API_KEY);
    int status = Unirest.post("https://cleverbot.io/1.0/create").field("user", cleverbotUser).field("key", cleverbotKey).field("nick", "ardent").asString().getStatus();
    if (status != 200)
        new BotException("Unable to connect to cleverbot!");
    WebsiteDaemon websiteDaemon = new WebsiteDaemon();
    globalExecutorService.scheduleAtFixedRate(websiteDaemon, 5, 15, TimeUnit.SECONDS);
    PermissionsDaemon permissionsDaemon = new PermissionsDaemon();
    globalExecutorService.scheduleAtFixedRate(permissionsDaemon, 0, 60, TimeUnit.SECONDS);
    GuildDaemon guildDaemon = new GuildDaemon();
    globalExecutorService.scheduleAtFixedRate(guildDaemon, 0, 10, TimeUnit.SECONDS);
    MuteDaemon muteDaemon = new MuteDaemon();
    globalExecutorService.scheduleAtFixedRate(muteDaemon, 1, 5, TimeUnit.SECONDS);
    RankableDaemon rankableDaemon = new RankableDaemon();
    globalExecutorService.scheduleAtFixedRate(rankableDaemon, 0, 1, TimeUnit.MINUTES);
    Music.checkMusicConnections();
    globalExecutorService.scheduleAtFixedRate(() -> {
        Shard[] shards = ShardManager.getShards();
        for (int i = 0; i < shards.length; i++) {
            Shard shard = shards[i];
            if ((System.currentTimeMillis() - shard.getLAST_EVENT()) > 20000) {
                shard.jda.getRegisteredListeners().forEach(shard.jda::removeEventListener);
                int finalI = i;
                globalExecutorService.schedule(() -> {
                    shard.jda.shutdown(false);
                    try {
                        shards[finalI] = new Shard(testingBot, finalI, shardCount);
                    } catch (Exception e) {
                        new BotException(e);
                    }
                }, 3, TimeUnit.SECONDS);
            }
        }
    }, 60, 15, TimeUnit.SECONDS);
    if (!testingBot) {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("Fi9IjqqsGmOXqjR5uYK8YM2Pr").setOAuthConsumerSecret(IOUtils.toString(new FileReader(new File("/root/Ardent/twitterconsumersecret.key")))).setOAuthAccessToken("818984879018954752-aCzxyML6Xp0QcRpq5sjoe8wfp0sjVDt").setOAuthAccessTokenSecret(IOUtils.toString(new FileReader(new File("/root/Ardent/twitteroauthsecret.key"))));
        TwitterFactory tf = new TwitterFactory(cb.build());
        twitter = tf.getInstance();
    }
    java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
    java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(java.util.logging.Level.OFF);
    java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(java.util.logging.Level.OFF);
    ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
    root.setLevel(Level.OFF);
    try {
        transport = GoogleNetHttpTransport.newTrustedTransport();
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
        jsonFactory = JacksonFactory.getDefaultInstance();
        sheetsApi = getSheetsService();
        globalExecutorService.schedule(() -> {
            try {
                triviaSheet = sheetsApi.spreadsheets().values().get("1qm27kGVQ4BdYjvPSlF0zM64j7nkW4HXzALFNcan4fbs", "A2:C").execute();
            } catch (IOException e) {
                new BotException(e);
            }
            List<List<Object>> values = triviaSheet.getValues();
            values.forEach(row -> {
                String category = (String) row.get(0);
                String q = (String) row.get(1);
                String answerUnparsed = (String) row.get(2);
                TriviaQuestion triviaQuestion = new TriviaQuestion();
                triviaQuestion.setQuestion(q);
                triviaQuestion.setCategory(category);
                for (String answer : answerUnparsed.split("~")) {
                    triviaQuestion.withAnswer(answer);
                }
                Trivia.triviaQuestions.add(triviaQuestion);
            });
        }, 30, TimeUnit.SECONDS);
    } catch (Exception e) {
        e.printStackTrace();
    }
    started = true;
}
Also used : ConfigurationBuilder(twitter4j.conf.ConfigurationBuilder) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) DefaultAudioPlayerManager(com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager) Logger(ch.qos.logback.classic.Logger) FileDataStoreFactory(com.google.api.client.util.store.FileDataStoreFactory) BotException(tk.ardentbot.core.misc.logging.BotException) ArrayList(java.util.ArrayList) List(java.util.List) GoogleSearch(tk.ardentbot.utils.searching.GoogleSearch) TwitterFactory(twitter4j.TwitterFactory) BotException(tk.ardentbot.core.misc.logging.BotException) Logger(ch.qos.logback.classic.Logger) StuckVoiceConnection(tk.ardentbot.commands.music.StuckVoiceConnection) TriviaQuestion(tk.ardentbot.utils.models.TriviaQuestion) CheckIfPremiumGuild(tk.ardentbot.utils.premium.CheckIfPremiumGuild) UpdatePremiumMembers(tk.ardentbot.utils.premium.UpdatePremiumMembers)

Example 28 with TwitterFactory

use of twitter4j.TwitterFactory in project asterixdb by apache.

the class TwitterUtil method getTwitterService.

public static Twitter getTwitterService(Map<String, String> configuration) {
    ConfigurationBuilder cb = getAuthConfiguration(configuration);
    TwitterFactory tf = null;
    try {
        tf = new TwitterFactory(cb.build());
    } catch (Exception e) {
        if (LOGGER.isLoggable(Level.WARNING)) {
            StringBuilder builder = new StringBuilder();
            builder.append("Twitter Adapter requires the following config parameters\n");
            builder.append(AuthenticationConstants.OAUTH_CONSUMER_KEY + "\n");
            builder.append(AuthenticationConstants.OAUTH_CONSUMER_SECRET + "\n");
            builder.append(AuthenticationConstants.OAUTH_ACCESS_TOKEN + "\n");
            builder.append(AuthenticationConstants.OAUTH_ACCESS_TOKEN_SECRET + "\n");
            LOGGER.warning(builder.toString());
            LOGGER.warning("Unable to configure Twitter adapter due to incomplete/incorrect authentication credentials");
            LOGGER.warning("For details on how to obtain OAuth authentication token, visit https://dev.twitter.com/oauth" + "/overview/application-owner-access-tokens");
        }
    }
    Twitter twitter = tf.getInstance();
    return twitter;
}
Also used : ConfigurationBuilder(twitter4j.conf.ConfigurationBuilder) Twitter(twitter4j.Twitter) TwitterFactory(twitter4j.TwitterFactory) AsterixException(org.apache.asterix.common.exceptions.AsterixException)

Example 29 with TwitterFactory

use of twitter4j.TwitterFactory in project twitter-2-weibo by rjyo.

the class UserServlet method handleRequest.

@Override
protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) {
    HttpServletRouter r = new HttpServletRouter(request);
    r.setPattern("/:id");
    HttpSession session = request.getSession(false);
    DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);
    // Service limit
    String uId = r.get(":id");
    if (!helper.isUser(uId) && helper.getUserCount() > 50) {
        return getTemplate("full.vm");
    }
    T2WUser user = helper.findOneByUser(uId);
    if (r.has(":id")) {
        log.info("Displaying user info for @" + uId);
        ctx.put("user_id", uId);
        ctx.put("user", helper.findOneByUser(uId));
        try {
            User weiboUser = (User) session.getAttribute(Keys.SESSION_WEIBO_USER);
            if (weiboUser == null) {
                Users um = new Users();
                weiboUser = um.showUserById(user.getWeiboUserId());
                session.setAttribute(Keys.SESSION_WEIBO_USER, weiboUser);
            }
            ctx.put("weibo_user", weiboUser.getScreenName());
            ctx.put("weibo_user_image", weiboUser.getProfileImageURL().toString());
            ctx.put("weibo_login", 1);
            // save weiboUser ID mapping
            helper.setWeiboId(user.getUserId(), weiboUser.getScreenName());
        } catch (Exception e) {
            // 401 = not logged in
            if (e instanceof WeiboException && ((WeiboException) e).getStatusCode() != 401) {
                e.printStackTrace();
            }
        }
        try {
            twitter4j.User twitterUser = (twitter4j.User) session.getAttribute(Keys.SESSION_TWITTER_USER);
            if (twitterUser == null) {
                TwitterFactory factory = new TwitterFactory();
                Twitter t = factory.getInstance();
                t.setOAuthAccessToken(new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret()));
                twitterUser = t.verifyCredentials();
                session.setAttribute(Keys.SESSION_TWITTER_USER, twitterUser);
            }
            ctx.put("twitter_user", twitterUser.getScreenName());
            ctx.put("twitter_user_image", twitterUser.getProfileImageURL().toString());
            ctx.put("twitter_login", 1);
        } catch (Exception e) {
            // 401 = not logged in
            if (e instanceof TwitterException && ((TwitterException) e).getStatusCode() != 401) {
                e.printStackTrace();
            }
        }
    }
    Object message = session.getAttribute(Keys.SESSION_MESSAGE);
    if (message != null) {
        ctx.put("message", message);
        session.removeAttribute(Keys.SESSION_MESSAGE);
    }
    Object prompt = session.getAttribute(Keys.SESSION_PROMPT_TWEET);
    if (prompt != null) {
        ctx.put("prompt", prompt);
        session.removeAttribute(Keys.SESSION_PROMPT_TWEET);
    }
    return getTemplate("user.vm");
}
Also used : T2WUser(h2weibo.model.T2WUser) User(weibo4j.model.User) HttpSession(javax.servlet.http.HttpSession) DBHelper(h2weibo.model.DBHelper) Twitter(twitter4j.Twitter) Users(weibo4j.Users) TwitterFactory(twitter4j.TwitterFactory) WeiboException(weibo4j.model.WeiboException) TwitterException(twitter4j.TwitterException) WeiboException(weibo4j.model.WeiboException) T2WUser(h2weibo.model.T2WUser) AccessToken(twitter4j.auth.AccessToken) HttpServletRouter(h2weibo.HttpServletRouter) TwitterException(twitter4j.TwitterException)

Example 30 with TwitterFactory

use of twitter4j.TwitterFactory in project ddf by codice.

the class TwitterSource method init.

public void init() {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    Configuration configuration = configurationBuilder.setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret).setApplicationOnlyAuthEnabled(true).build();
    twitterFactory = new TwitterFactory(configuration);
}
Also used : ConfigurationBuilder(twitter4j.conf.ConfigurationBuilder) Configuration(twitter4j.conf.Configuration) TwitterFactory(twitter4j.TwitterFactory)

Aggregations

TwitterFactory (twitter4j.TwitterFactory)68 Twitter (twitter4j.Twitter)60 TwitterException (twitter4j.TwitterException)55 ConfigurationBuilder (twitter4j.conf.ConfigurationBuilder)10 Status (twitter4j.Status)7 IDs (twitter4j.IDs)6 AccessToken (twitter4j.auth.AccessToken)5 SavedSearch (twitter4j.SavedSearch)4 RequestToken (twitter4j.auth.RequestToken)4 Configuration (twitter4j.conf.Configuration)4 File (java.io.File)3 User (twitter4j.User)3 UserList (twitter4j.UserList)3 Intent (android.content.Intent)2 AppSettings (com.klinker.android.twitter.settings.AppSettings)2 HttpServletRouter (h2weibo.HttpServletRouter)2 HashMap (java.util.HashMap)2 HttpSession (javax.servlet.http.HttpSession)2 AccessToken (twitter4j.http.AccessToken)2 AlarmManager (android.app.AlarmManager)1