Example #1
0
  /**
   * Sends a Tweet via Twitter
   *
   * @param tweetTxt the Tweet to send
   * @return <code>true</code>, if sending the tweet has been successful and <code>false</code> in
   *     all other cases.
   */
  @ActionDoc(
      text = "Sends a Tweet via Twitter",
      returns =
          "<code>true</code>, if sending the tweet has been successful and <code>false</code> in all other cases.")
  public static boolean sendTweet(
      @ParamDoc(name = "tweetTxt", text = "the Tweet to send") String tweetTxt) {
    if (!TwitterActionService.isProperlyConfigured) {
      logger.debug("Twitter client is not yet configured > execution aborted!");
      return false;
    }
    if (!isEnabled) {
      logger.debug("Twitter client is disabled > execution aborted!");
      return false;
    }

    try {
      // abbreviate the Tweet to meet the 140 character limit ...
      tweetTxt = StringUtils.abbreviate(tweetTxt, CHARACTER_LIMIT);
      // send the Tweet
      Status status = client.updateStatus(tweetTxt);
      logger.debug("Successfully sent Tweet '{}'", status.getText());
      return true;
    } catch (TwitterException e) {
      logger.error(
          "Failed to send Tweet '" + tweetTxt + "' because of: " + e.getLocalizedMessage());
      return false;
    }
  }
    protected Void doInBackground(String... args) {

      String status = args[0];
      try {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(consumerKey);
        builder.setOAuthConsumerSecret(consumerSecret);

        // Access Token
        String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
        // Access Token Secret
        String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");

        AccessToken accessToken = new AccessToken(access_token, access_token_secret);
        Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

        // Update status
        StatusUpdate statusUpdate = new StatusUpdate(status);
        twitter4j.Status response = twitter.updateStatus(statusUpdate);

        Log.d("Status", response.getText());

      } catch (TwitterException e) {
        Log.d("Failed to post!", e.getMessage());
      }
      return null;
    }
Example #3
0
    /** getting Places JSON */
    protected String doInBackground(String... args) {
      Log.d("Tweet Text", "> " + args[0]);
      String status = args[0];
      try {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

        // Access Token
        String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
        // Access Token Secret
        String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");

        AccessToken accessToken = new AccessToken(access_token, access_token_secret);
        Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

        // Update status
        twitter4j.Status response = twitter.updateStatus(status);

        Log.d("Status", "> " + response.getText());
      } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
      }
      return null;
    }
  private void tweet(String tweetText) {
    // SharedPreferencesからtokenとtoken secretの取得
    SharedPreferences spObj = getSharedPreferences("token", MODE_PRIVATE);
    String tokenStr = spObj.getString("token", "");
    String tokenSecretStr = spObj.getString("token_seacret", "");

    // twitterオブジェクトの作成
    Twitter tw = new TwitterFactory().getInstance();

    // AccessTokenオブジェクトの作成
    AccessToken at = new AccessToken(tokenStr, tokenSecretStr);

    // Consumer keyとConsumer key seacretの設定
    tw.setOAuthConsumer("iy2FEHXmSXNReJ6nYQ8FRg", "KYro4jM8BHlLSMsSdTylnTcm3pYaTCiG2UZrYK1yI4");

    // AccessTokenオブジェクトを設定
    tw.setOAuthAccessToken(at);

    // ツイート送信
    try {
      tw.updateStatus(tweetText);
    } catch (TwitterException e) {
      e.printStackTrace();
      Toast.makeText(this, "ネットーワークの問題です", Toast.LENGTH_LONG);
    }
  }
Example #5
0
  @Override
  public void onClick(View v) {
    vnosnoPolje = (EditText) findViewById(R.id.vnosP);
    switch (v.getId()) {
      case R.id.buttonTweet:
        try {
          String text = vnosnoPolje.getText().toString();
          twitter.updateStatus(text);
        } catch (TwitterException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        break;

      case R.id.buttonClear:
        String vp = vnosnoPolje.getText().toString();

        if (vp.length() > 0) {
          vnosnoPolje.setText(vp.substring(0, 0));
        }
        break;

      case R.id.buttonCancel:
        finish();
        break;

      default:
        break;
    }
  }
Example #6
0
 private static void primeiraTwittada() throws TwitterException, IOException {
   Twitter twitter = TwitterFactory.getSingleton();
   twitter.setOAuthConsumer("HSPokkXFfwsjWwTGy8kfw", "zMNRv0G9kORPiSXcJuPrnWFOBESewPirr8Lf6fRLpA");
   RequestToken requestToken = twitter.getOAuthRequestToken();
   AccessToken accessToken = null;
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   while (null == accessToken) {
     System.out.println("Open the following URL and grant access to your account:");
     System.out.println(requestToken.getAuthorizationURL());
     System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
     String pin = br.readLine();
     try {
       if (pin.length() > 0) {
         accessToken = twitter.getOAuthAccessToken(requestToken, pin);
       } else {
         accessToken = twitter.getOAuthAccessToken();
       }
     } catch (TwitterException te) {
       if (401 == te.getStatusCode()) {
         System.out.println("Unable to get the access token.");
       } else {
         te.printStackTrace();
       }
     }
   }
   // persist to the accessToken for future reference.
   storeAccessToken(twitter.verifyCredentials().getId(), accessToken);
   Status status = twitter.updateStatus("GO GO GO");
   System.out.println("Successfully updated the status to [" + status.getText() + "].");
   System.exit(0);
 }
  /**
   * Usage: java twitter4j.examples.tweets.UpdateStatus [text]
   *
   * @param args message
   */
  public static void main(String[] args) {
    if (args.length < 1) {
      System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]");
      System.exit(-1);
    }
    try {
      Twitter twitter = new TwitterFactory().getInstance();
      try {
        // get request token.
        // this will throw IllegalStateException if access token is already available
        RequestToken requestToken = twitter.getOAuthRequestToken();
        System.out.println("Got request token.");
        System.out.println("Request token: " + requestToken.getToken());
        System.out.println("Request token secret: " + requestToken.getTokenSecret());
        AccessToken accessToken = null;

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (null == accessToken) {
          System.out.println("Open the following URL and grant access to your account:");
          System.out.println(requestToken.getAuthorizationURL());
          System.out.print(
              "Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
          String pin = br.readLine();
          try {
            if (pin.length() > 0) {
              accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
              accessToken = twitter.getOAuthAccessToken(requestToken);
            }
          } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
              System.out.println("Unable to get the access token.");
            } else {
              te.printStackTrace();
            }
          }
        }
        System.out.println("Got access token.");
        System.out.println("Access token: " + accessToken.getToken());
        System.out.println("Access token secret: " + accessToken.getTokenSecret());
      } catch (IllegalStateException ie) {
        // access token is already available, or consumer key/secret is not set.
        if (!twitter.getAuthorization().isEnabled()) {
          System.out.println("OAuth consumer key/secret is not set.");
          System.exit(-1);
        }
      }
      Status status = twitter.updateStatus(args[0]);
      System.out.println("Successfully updated the status to [" + status.getText() + "].");
      System.exit(0);
    } catch (TwitterException te) {
      te.printStackTrace();
      System.out.println("Failed to get timeline: " + te.getMessage());
      System.exit(-1);
    } catch (IOException ioe) {
      ioe.printStackTrace();
      System.out.println("Failed to read the system input.");
      System.exit(-1);
    }
  }
Example #8
0
 public void updateStatus(String status) throws Exception {
   try {
     twitter.updateStatus(status);
   } catch (TwitterException e) {
     throw e;
   }
 }
 @Override
 public void updateStatus(Twitter api, String message) {
   try {
     api.updateStatus(message);
   } catch (TwitterException e) {
   }
 }
  /** Posta in Twitt */
  public boolean postTwitt(String sMessage) {
    try {

      if (twitter != null) {
        try {
          AccessToken a =
              new AccessToken(
                  mSharedPreferences.getString(Const.PREF_KEY_TOKEN, ""),
                  mSharedPreferences.getString(Const.PREF_KEY_SECRET, ""));
          twitter.setOAuthAccessToken(a);
          Status oStatus = twitter.updateStatus(sMessage);
          Log.i(this.getClass().getCanonicalName(), "Post Twitter OK");
          return oStatus.isRetweet();
        } catch (IllegalArgumentException e) {
          Log.e(
              this.getClass().getCanonicalName(),
              "Post Twitter error: "
                  + mSharedPreferences.getString(Const.PREF_KEY_TOKEN, "")
                  + " "
                  + mSharedPreferences.getString(Const.PREF_KEY_SECRET, ""));
          return false;
        }
      } else {
        String oauthAccessToken = mSharedPreferences.getString(Const.PREF_KEY_TOKEN, "");
        String oAuthAccessTokenSecret = mSharedPreferences.getString(Const.PREF_KEY_SECRET, "");

        ConfigurationBuilder confbuilder = new ConfigurationBuilder();
        Configuration configuration =
            confbuilder
                .setOAuthConsumerKey(Const.CONSUMER_KEY)
                .setOAuthConsumerSecret(Const.CONSUMER_SECRET)
                .setOAuthAccessToken(oauthAccessToken)
                .setOAuthAccessTokenSecret(oAuthAccessTokenSecret)
                .build();
        twitter = new TwitterFactory(configuration).getInstance();

        Status oStatus = twitter.updateStatus(sMessage);
        Log.i(this.getClass().getCanonicalName(), "Post Twitter OK");
        return oStatus.isRetweet();
      }
    } catch (TwitterException e) {
      Log.e(this.getClass().getCanonicalName(), e.getMessage());
    } catch (NullPointerException e) {
      Log.e(this.getClass().getCanonicalName(), e.getMessage());
    }
    return false;
  }
Example #11
0
 public Status updateStatus(StatusUpdate update) {
   Status status = null;
   try {
     status = twitter.updateStatus(update);
   } catch (TwitterException e) {
     e.printStackTrace();
   }
   return status;
 }
 @Override
 public void sendTweet(String message) {
   initTwitter();
   try {
     twitter.updateStatus(message);
   } catch (TwitterException e) {
     e.printStackTrace();
   }
 }
  @Override
  public void publishUuid(TwitterStatusMessage message) throws Exception {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKeyStr, consumerSecretStr);

    AccessToken accessToken = new AccessToken(accessTokenStr, accessTokenSecretStr);
    twitter.setOAuthAccessToken(accessToken);

    twitter.updateStatus(message.getTwitterPublicationString());
  }
 public void postTweet(String message) throws TwitterException {
   Twitter twitter = TwitterFactory.getSingleton();
   Status status = null;
   try {
     status = twitter.updateStatus(message);
   } catch (TwitterException te) {
     System.out.println("Unsuccessfull updated the status");
   }
   System.out.println("Successfully updated the status to [estado].");
 }
Example #15
0
 private static void twittarAlgo() throws TwitterException {
   TwitterFactory factory = new TwitterFactory();
   AccessToken accessToken = loadAccessToken();
   Twitter twitter = factory.getInstance();
   twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
   twitter.setOAuthAccessToken(accessToken);
   Status status = twitter.updateStatus("go go go go");
   System.out.println("Successfully updated the status to [" + status.getText() + "].");
   System.exit(0);
 }
Example #16
0
 @FXML
 void onTweetButton(ActionEvent event) {
   String tweet = tweetTextArea.getText();
   try {
     @SuppressWarnings("unused")
     Status status = twitter.updateStatus(tweet);
     reloadHomeTL(lastStatusId);
   } catch (TwitterException e) {
     e.printStackTrace();
   }
   tweetTextArea.clear();
 }
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   request.setCharacterEncoding("UTF-8");
   String text = request.getParameter("text");
   Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
   try {
     twitter.updateStatus(text);
   } catch (TwitterException e) {
     throw new ServletException(e);
   }
   response.sendRedirect(request.getContextPath() + "/");
 }
 public void tweetNote(String symbol) {
   HttpSession session = super.getThreadLocalRequest().getSession();
   Twitter twitter = new TwitterFactory().getInstance();
   twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
   AccessToken accessToken = (AccessToken) session.getAttribute("accessToken");
   twitter.setOAuthAccessToken(accessToken);
   try {
     Status status = twitter.updateStatus(symbol);
   } catch (TwitterException e) {
     e.printStackTrace();
   }
 }
  /**
   * Twitter Post
   *
   * @param userModel
   * @param msg
   * @return
   */
  private void postMessage(UserModel userModel, String msg) throws Exception {

    System.out.println(msg);

    // 承認情報の生成
    ConfigurationBuilder cb = getConfigurationBuilder(userModel);

    // Titterオブジェクトの生成
    TwitterFactory twitterFactory = new TwitterFactory(cb.build());
    Twitter twitter = twitterFactory.getInstance();

    twitter.updateStatus(msg);
  }
  @Override
  public void tweet() {
    // アカウントとテキストはnullにできない
    Objects.requireNonNull(twitter, "User is null.");
    Objects.requireNonNull(text, "TweetText is null.");

    StatusUpdate status = new StatusUpdate(text);
    reply.map(Tweet::getStatusId).ifPresent(status::setInReplyToStatusId);
    try {
      twitter.updateStatus(status);
    } catch (TwitterException e) {
      e.printStackTrace();
    }
  }
  // 6355366
  private static void testTwitterAPI() throws Exception {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
        .setOAuthConsumerKey("qHzxaFrfzktB7DonlQXLzQ")
        .setOAuthConsumerSecret("WTcdE2vN9U3nl3t6mQkUbfF4PNNey2t2dp78AEajp8")
        .setOAuthAccessToken("351435596-KpFoMU2mdiu5OhdBi0BRPpdd7bQgkJFakkTV6Zh6")
        .setOAuthAccessTokenSecret("80OjYaYPmmKYG6DAUCSfstJEMPl2UnnLJunF8r0GGXQ");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    // DirectMessage msg = twitter.sendDirectMessage("prakash_sandeep", "test direct message1.");
    Status status = twitter.updateStatus("This is a test message13.");
    // System.out.println(msg + " published a message.");
  }
  /**
   * Posts a status to Twitter.
   *
   * @param statusText Text of the messsage.
   * @param at AccessToken to validate with
   * @throws Exception
   */
  public void updateStatus(String statusText, AccessToken at) throws Exception {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey(ourConsumerKey);
    cb.setOAuthConsumerSecret(ourConsumerSecret);
    cb.setOAuthAccessToken(at.getToken());
    cb.setOAuthAccessTokenSecret(at.getTokenSecret());

    myTwitter.setOAuthAccessToken(at);

    Status status = myTwitter.updateStatus(statusText);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
  }
Example #23
0
  @Override
  public long tweet(String txt) {

    if (txt.length() > 140) {
      throw new ScriptusRuntimeException("tweet > 140 characters: " + txt);
    }

    Status s;
    try {
      s = twitter.updateStatus(new StatusUpdate(txt));
    } catch (TwitterException e) {
      throw new ScriptusRuntimeException(e);
    }
    return s.getId();
  }
Example #24
0
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/plain");

    TwitterFactory factory = new TwitterFactory();
    Twitter twitter = factory.getInstance();
    try {
      twitter.updateStatus("テスト");
      response.getWriter().println("OK");
    } catch (TwitterException e) {
      e.printStackTrace();
      response.getWriter().println(e.getMessage());
    }
  }
Example #25
0
  public void tweet(String tweet) {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
    AccessToken oathAccessToken = new AccessToken(ACCESS_TOKEN, ACCESS_TOKEN_SECRET);

    twitter.setOAuthAccessToken(oathAccessToken);

    try {
      LoggerUtils.info("Tweeting: " + tweet);
      twitter.updateStatus(tweet);
    } catch (TwitterException ex) {
      LoggerUtils.warning(plugin, "Failed to Submit Tweet.");
    }

    LoggerUtils.info(plugin, "Tweet Successfully Sent");
  }
Example #26
0
 /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   request.setCharacterEncoding("UTF-8");
   Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
   try {
     FileTemp fileTemp = getFileInfo(request, response);
     StatusUpdate su = new StatusUpdate(fileTemp.getStatus());
     if (fileTemp.getStream() != null
         && fileTemp.getFileName() != null
         && fileTemp.getFileName().length() > 0) {
       su.setMedia(fileTemp.getFileName(), fileTemp.getStream());
     }
     twitter.updateStatus(su);
   } catch (TwitterException e) {
     throw new ServletException(e);
   }
   response.sendRedirect(request.getContextPath() + "/");
 }
Example #27
0
  public static void doNotAutomatedVersion() {
    String search =
        "site:brainyquote.com \""
            + JOptionPane.showInputDialog("Enter a keyword to find quotes for here.")
            + "\"";
    String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
    String charset = "UTF-8";

    URL url = null;
    try {
      url = new URL(google + URLEncoder.encode(search, charset));
    } catch (Exception e) {
      e.printStackTrace();
    }
    Reader reader = null;
    try {
      reader = new InputStreamReader(url.openStream(), charset);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);

    String urlOfTheKeyWord = results.getResponseData().getResults().get(0).getUrl();

    BrainyQuote brainyQuote = new BrainyQuote(urlOfTheKeyWord);
    if (brainyQuote.isBrainyQuote()) {
      Twitter twitter = TwitterFactory.getSingleton();
      try {
        String quote = brainyQuote.getRandomQuote();
        Status newStatus = null;
        List<Status> statuses = twitter.getHomeTimeline();
        for (Status status : statuses) {
          if (!quote.equalsIgnoreCase(status.getText()) && quote.length() < 134) {

            newStatus = twitter.updateStatus(quote + " #Quote");
          }
        }

      } catch (TwitterException ex) {
        JOptionPane.showMessageDialog(null, "There was an error tyring to post a tweet!");
      }
    }
  }
  public void tweetMode() throws TwitterException {

    System.out.println("<< Tweet mode >>");

    String tweet = "";

    while (true) {

      System.out.print("TWEET: ");
      tweet = scan.nextLine();

      if (tweet.isEmpty()) {
        continue;
      }

      if (tweet.equals("exit")) {
        return;
      }

      if (tweet.length() > 140) {
        System.out.println("ツイートは140文字までです。");
        tweet = "";
        continue;
      }

      System.out.print("この内容でTweetしますか?(y/n) : ");

      if (scan.nextLine().equals("y")) {
        break;
      }

      return;
    }

    Twitter twitter = new TwitterFactory().getInstance();
    Status status = twitter.updateStatus(tweet);
    System.out.println(status.getUser().getName() + " として投稿しました。");

    // scan.close();
  }
  @Override
  public void run(ActionParam param) {

    if (param instanceof TweetActionParam == false) {
      return;
    }

    // Setting up twitter client
    initTwitter();

    TweetActionParam tweetParams = (TweetActionParam) param;

    Pattern titlePattern = Pattern.compile("STS-ALERT \\(([0-9]+) new strings?\\)");
    Pattern itemPattern = Pattern.compile("([0-9]+) new strings? for: ([a-z0-9/_]+\\.txt)");

    for (FeedMessage feedMessage : tweetParams.feedMessages) {
      Matcher titleMatcher = titlePattern.matcher(feedMessage.getTitle());

      if (titleMatcher.matches()) {
        // Feed message is a STS Update

        int nbStringsUpdated = Integer.parseInt(titleMatcher.group(1));

        Matcher itemMatcher = itemPattern.matcher(feedMessage.getDescription());

        String tokenText = nbStringsUpdated == 1 ? "token" : "tokens";
        String tweetIntro =
            String.format("STS Update: %1$d new %2$s: ", nbStringsUpdated, tokenText);

        int nbOthers = 0;

        List<String> tweetParts = new ArrayList<>();
        List<String> tweetMessages = new ArrayList<>();

        while (itemMatcher.find()) {
          int nbStringsInFile = Integer.parseInt(itemMatcher.group(1));
          String fileName = itemMatcher.group(2);

          if (Localization.INSTANCE.aliases.containsKey(fileName)) {
            String subUpdate =
                String.format(
                    "%1$s (%2$d), ", Localization.INSTANCE.aliases.get(fileName), nbStringsInFile);
            tweetParts.add(subUpdate);
          } else {
            nbOthers += nbStringsInFile;
          }
        }

        if (nbOthers > 0) {
          tweetParts.add(String.format("Others (%1$d)", nbOthers));
        }

        final int TWEET_MAX_LENGTH_CORRECTED =
            Constants.TWITTER_TWEET_MAX_LENGTH - Constants.TWITTER_SHORT_URL_LENGTH_HTTPS - 1;

        int partIdx = 0;
        while (partIdx < tweetParts.size()) {
          StringBuilder tweetMessage = new StringBuilder(tweetIntro);

          while (partIdx < tweetParts.size()
              && ((tweetMessage.length() + tweetParts.get(partIdx).length())
                  < TWEET_MAX_LENGTH_CORRECTED)) {
            // There's enough room for the next part
            tweetMessage.append(tweetParts.get(partIdx));
            partIdx++;
          }

          // No more room in the current tweet
          if (tweetMessage.toString().endsWith(", ")) {
            tweetMessage.delete(tweetMessage.length() - 2, tweetMessage.length());
          }
          tweetMessage.append(" ");
          tweetMessage.append(feedMessage.getLink());

          // Tweet is ready to be sent
          tweetMessages.add(tweetMessage.toString());
        }

        for (String tweet : tweetMessages) {
          logger.info("Tweet: {}", tweet);
          logger.info("NbChars: {}", tweet.length());

          if (Configuration.INSTANCE.dryRun == true) {
            // This is a 'dry' run, so we shouldn't send any tweet
            continue;
          }

          // Sending tweet
          StatusUpdate statusUpdate = new StatusUpdate(tweet);
          statusUpdate.setLocation(Constants.VALVE_LOCATION);
          try {
            mTwitter.updateStatus(statusUpdate);
          } catch (TwitterException e) {
            logger.error("Failed to send tweet: {}", e);
            throw new RuntimeException("Failed to send tweet", e);
          }

          // Throttling tweet sending a tiny bit
          try {
            Thread.sleep(50);
          } catch (InterruptedException e) {
            logger.error("Failed to sleep: ", e);
            throw new RuntimeException("Failed to sleep", e);
          }
        }
      }
    }
  }
 private void sendTweet() {
   t = new TwitterFactory().getInstance();
   t.setOAuthConsumer(OAUTH.CONSUMER_KEY, OAUTH.CONSUMER_SECRET);
   if (getToken() == null) {
     sendError = true;
   } else {
     aToken = getToken();
   }
   t.setOAuthAccessToken(aToken);
   if (day.split(",")[getcDay() - 1].equals("true") || date) {
     if (prefs.getBoolean("direct", false)) {
       try {
         t.updateStatus(mentions + " " + message + " " + mentions + " " + getRandom());
         if (mentions.length() < 2 || mentions == null) {
           logSend("Twitter", getFormattedTime(), message, "--", true);
         } else {
           logSend("Twitter", getFormattedTime(), message, mentions, true);
         }
       } catch (Exception e) {
         sendError = true;
         e.printStackTrace();
       }
     } else {
       try {
         t.updateStatus(getRandom() + " " + message + " " + mentions);
         if (mentions.length() < 2 || mentions == null) {
           logSend("Twitter", getFormattedTime(), message, "--", true);
         } else {
           logSend("Twitter", getFormattedTime(), message, mentions, true);
         }
       } catch (Exception e) {
         sendError = true;
         e.printStackTrace();
       }
     }
     if (!sendError) {
       if (prefs.getBoolean("notify", true)) {
         if (!prefs.getBoolean("notifyIntrusive", true)) {
           mHandler.post(
               new Runnable() {
                 @Override
                 public void run() {
                   Toast.makeText(ctx, message, Toast.LENGTH_LONG).show();
                 }
               });
         } else {
           alertT(message, ctx);
         }
       }
     } else {
       if (mentions.length() < 2 || mentions == null) {
         logSend("Twitter", getFormattedTime(), message, "--", false);
       } else {
         logSend("Twitter", getFormattedTime(), message, mentions, false);
       }
       mHandler.post(
           new Runnable() {
             @Override
             public void run() {
               Toast.makeText(ctx, "Error while sending, " + message, Toast.LENGTH_LONG).show();
             }
           });
     }
   }
 }