Beispiel #1
0
  /**
   * Sends a direct message via Twitter
   *
   * @param recipientId the receiver of this direct message
   * @param messageTxt the direct message to send
   * @return <code>true</code>, if sending the direct message has been successful and <code>false
   *     </code> in all other cases.
   */
  @ActionDoc(
      text = "Sends a direct message via Twitter",
      returns =
          "<code>true</code>, if sending the direct message has been successful and <code>false</code> in all other cases.")
  public static boolean sendDirectMessage(
      @ParamDoc(name = "recipientId", text = "the receiver of this direct message")
          String recipientId,
      @ParamDoc(name = "messageTxt", text = "the direct message to send") String messageTxt) {
    if (!isEnabled) {
      logger.debug("Twitter client is disabled > execution aborted!");
      return false;
    }

    try {
      // abbreviate the Tweet to meet the 140 character limit ...
      messageTxt = StringUtils.abbreviate(messageTxt, CHARACTER_LIMIT);
      // send the direct message
      DirectMessage message = client.sendDirectMessage(recipientId, messageTxt);
      logger.debug(
          "Successfully sent direct message '{}' to @",
          message.getText(),
          message.getRecipientScreenName());
      return true;
    } catch (TwitterException e) {
      logger.error(
          "Failed to send Tweet '" + messageTxt + "' because of: " + e.getLocalizedMessage());
      return false;
    }
  }
  @SuppressWarnings("unchecked")
  public void onScroll(
      AbsListView absListView, int firstVisible, int visibleCount, int totalCount) {

    boolean loadMore = /* maybe add a padding */ firstVisible + visibleCount >= totalCount - 1;

    //        Log.d("onScroll:","loadMore f=" + firstVisible + ", vc=" + visibleCount + ", tc="
    // +totalCount);
    if (loadMore) {
      // Debug.startMethodTracing("list" + firstVisible);
      ListAdapter adapter = absListView.getAdapter();
      if (adapter instanceof StatusAdapter) {
        StatusAdapter sta = (StatusAdapter) adapter;
        if (totalCount > 0) {
          Object item = sta.getItem(totalCount - 1);
          int i = 0;
          if (item instanceof DirectMessage) {
            DirectMessage message = (DirectMessage) item;

            List<DirectMessage> messages = th.getDirectsFromDb(message.getId(), 7);
            for (DirectMessage direct : messages) {
              sta.insert(direct, totalCount + i);
              directs.add(direct);
              i++;
            }
          } else if (item instanceof Status) {
            Status last = (Status) item;
            if (statuses == null) statuses = new ArrayList<Status>();

            List<Status> newStatuses = th.getStatuesFromDb(last.getId(), 7, list_id);
            // TODO add checking for old
            List<Long> readIds = obtainReadIds(newStatuses);
            sta.readIds.addAll(readIds);
            for (Status status : newStatuses) {
              if (!matchesFilter(status)) {
                sta.insert(status, totalCount + i);
                statuses.add(status);
                i++;
              }
            }
          }
          sta.notifyDataSetChanged();
        }
      }
      // Debug.stopMethodTracing();
    }
  }
 /**
  * Usage: java twitter4j.examples.DirectMessage senderID senderPassword message recipientId
  *
  * @param args String[]
  */
 public static void main(String[] args) {
   if (args.length < 4) {
     System.out.println("No TwitterID/Password specified.");
     System.out.println(
         "Usage: java twitter4j.examples.DirectMessage senderID senderPassword message recipientId");
     System.exit(-1);
   }
   Twitter twitter = new TwitterFactory().getInstance(args[0], args[1]);
   try {
     DirectMessage message = twitter.sendDirectMessage(args[2], args[3]);
     System.out.println("Direct message successfully sent to " + message.getRecipientScreenName());
     System.exit(0);
   } catch (TwitterException te) {
     System.out.println("Failed to send message: " + te.getMessage());
     System.exit(-1);
   }
 }
 public void testDirectMessagesAsJSON() throws Exception {
   HttpClientImpl http = new HttpClientImpl();
   List<DirectMessage> directMessages =
       DirectMessageJSONImpl.createDirectMessageList(
           http.get("http://twitter4j.org/en/testcases/direct_messages.json"), conf);
   DirectMessage dm = directMessages.get(0);
   Assert.assertEquals(new java.util.Date(1248177356000l), dm.getCreatedAt());
   Assert.assertEquals(6358482, dm.getRecipient().getId());
   Assert.assertEquals(246928323, dm.getId());
   Assert.assertEquals(6358482, dm.getRecipientId());
   Assert.assertEquals("twit4j", dm.getRecipientScreenName());
   Assert.assertEquals(6377362, dm.getSender().getId());
   Assert.assertEquals(6377362, dm.getSenderId());
   Assert.assertEquals("twit4j2", dm.getSenderScreenName());
   Assert.assertEquals("Tue Jul 21 20:55:39 KST 2009:directmessage test", dm.getText());
   assertDeserializedFormIsEqual(directMessages);
 }
    @Override
    protected ResponseList<DirectMessage> doInBackground(Void... params) {
      try {
        Twitter twitter = TwitterManager.getTwitter();

        // 受信したDM
        Paging directMessagesPaging = new Paging();
        if (mDirectMessagesMaxId > 0 && !mReloading) {
          directMessagesPaging.setMaxId(mDirectMessagesMaxId - 1);
          directMessagesPaging.setCount(BasicSettings.getPageCount() / 2);
        } else {
          directMessagesPaging.setCount(10);
        }
        ResponseList<DirectMessage> directMessages =
            twitter.getDirectMessages(directMessagesPaging);
        for (DirectMessage directMessage : directMessages) {
          if (mDirectMessagesMaxId <= 0L || mDirectMessagesMaxId > directMessage.getId()) {
            mDirectMessagesMaxId = directMessage.getId();
          }
        }

        // 送信したDM
        Paging sentDirectMessagesPaging = new Paging();
        if (mSentDirectMessagesMaxId > 0 && !mReloading) {
          sentDirectMessagesPaging.setMaxId(mSentDirectMessagesMaxId - 1);
          sentDirectMessagesPaging.setCount(BasicSettings.getPageCount() / 2);
        } else {
          sentDirectMessagesPaging.setCount(10);
        }
        ResponseList<DirectMessage> sentDirectMessages =
            twitter.getSentDirectMessages(sentDirectMessagesPaging);
        for (DirectMessage directMessage : sentDirectMessages) {
          if (mSentDirectMessagesMaxId <= 0L || mSentDirectMessagesMaxId > directMessage.getId()) {
            mSentDirectMessagesMaxId = directMessage.getId();
          }
        }

        directMessages.addAll(sentDirectMessages);

        // 日付でソート
        Collections.sort(
            directMessages,
            new Comparator<DirectMessage>() {

              @Override
              public int compare(DirectMessage arg0, DirectMessage arg1) {
                return arg1.getCreatedAt().compareTo(arg0.getCreatedAt());
              }
            });
        return directMessages;
      } catch (OutOfMemoryError e) {
        return null;
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }
    }
  @Override
  public void onDirectMessage(DirectMessage directMessage) {
    Debug.logln(
        "TwitterServer.onDirectMessage sender: "
            + directMessage.getSenderScreenName()
            + " recipient: "
            + directMessage.getRecipientScreenName()
            + " text: "
            + directMessage.getText());

    if (directMessage.getSenderId() == this.ownerID) {
      return; // outgoing message
    }

    // incoming message
    String text = directMessage.getText();
    String sender = directMessage.getSenderScreenName();
    String recipient = directMessage.getRecipientScreenName();

    // Detect trackback
    Trackback trackback = null;
    try {
      trackback = TrackbackStore.getInstance().loadByIncomingText(Channel.TWITTER, sender, text);
    } catch (Exception e) {
      LogEntryStore.log(e);
    }
    if (trackback == null) {
      // !$! Send back error message?
      return;
    }

    // Dispatch event
    TwitterMessage msg = new TwitterMessage();
    msg.setDestination(recipient);
    msg.setSender(sender);
    msg.write(TrackbackStore.getInstance().cleanIncomingText(text));

    this.listener.onTwitterReceived(msg, trackback.getExternalID());
  }
  /**
   * remove any direct messages (dm in twitter slang) that were sent and received by the user prior
   * to a certain date)
   */
  public void deleteDirectMessages() {
    try {
      boolean found = true;
      int start = 1;
      int increment = twitterConfig.getIncrementCount();
      // Removing messages sent to user
      while (found) {
        found = false;
        ResponseList<DirectMessage> responses =
            twitter.getDirectMessages(new Paging(start, start + increment));
        for (DirectMessage dm : responses) {
          if (earlier.getTime() > dm.getCreatedAt().getTime()) {
            twitter.destroyDirectMessage(dm.getId());
            logger.debug("delete dm: " + dm.getId());
            found = true;
          }
        }
      }
      found = true;
      start = 1;
      increment = twitterConfig.getIncrementCount();
      // Removing messages sent by user.
      while (found) {
        found = false;
        ResponseList<DirectMessage> responses =
            twitter.getSentDirectMessages(new Paging(start, start + increment));
        for (DirectMessage dm : responses) {
          if (earlier.getTime() > dm.getCreatedAt().getTime()) {
            twitter.destroyDirectMessage(dm.getId());
            logger.debug("delete dm: " + dm.getId());
            found = true;
          }
        }
      }

    } catch (TwitterException e) {
      logger.error("Twitter exception occurred", e);
    }
  }
Beispiel #8
0
 /**
  * 스크린명이 변경 되었는지 체크..
  *
  * @param twitter
  * @param cacheDb
  * @return
  */
 public boolean screenNameChanged(DirectMessage twitter, DirectMessage cacheDb) {
   if (cacheDb == null) {
     return false;
   }
   return twitter.getSenderScreenName().equals(cacheDb.getSenderScreenName());
 }