Example usage for twitter4j Twitter sendDirectMessage

List of usage examples for twitter4j Twitter sendDirectMessage

Introduction

In this page you can find the example usage for twitter4j Twitter sendDirectMessage.

Prototype

DirectMessage sendDirectMessage(long userId, String text) throws TwitterException;

Source Link

Document

Sends a new direct message to the specified user from the authenticating user.

Usage

From source file:SendDirectMessage.java

License:Apache License

/**
 * Usage: java twitter4j.examples.directMessage.DirectMessage [recipient screen name] [message]
 *
 * @param args String[]// ww w .  j  av  a 2  s. c  om
 */
public static void main(String[] args) {
    if (args.length < 2) {
        System.out.println(
                "Usage: java twitter4j.examples.directmessage.SendDirectMessage [recipient screen name] [message]");
        System.exit(-1);
    }
    Twitter twitter = new TwitterFactory().getInstance();
    try {
        DirectMessage message = twitter.sendDirectMessage(args[0], args[1]);
        System.out.println("Direct message successfully sent to " + message.getRecipientScreenName());
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to send a direct message: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:com.appspot.bitlyminous.service.impl.TwitterServiceImpl.java

License:Apache License

public void sendUrlStatistics() {
    try {//from w  w  w. j  a  v  a  2s.  c o m
        Twitter twitter = getTwitterClient();
        UserService userService = ServiceFactory.newInstance().createUserService();
        for (User user : twitter.getFriendsStatuses()) {
            com.appspot.bitlyminous.entity.User entity = userService.getUserByScreenName(user.getScreenName());
            List<Url> urls = entity.getUrls();
            twitter.sendDirectMessage(user.getId(), buildUrlStatisticsStatus(urls));
        }
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:com.appspot.bitlyminous.service.impl.TwitterServiceImpl.java

License:Apache License

public void importFriends() {
    try {//w  ww.j  a  va  2s. c  om
        Twitter twitter = getTwitterClient();
        UserService userService = ServiceFactory.newInstance().createUserService();
        boolean exists = true;
        long cursor = -1;

        while (exists) {
            //return 100 follower with status per request
            PagableResponseList<User> twitterFollowers = twitter.getFollowersStatuses(cursor);

            for (User user : twitterFollowers) {
                com.appspot.bitlyminous.entity.User entity = userService
                        .getUserByScreenName(user.getScreenName());
                if (entity == null) {
                    entity = new com.appspot.bitlyminous.entity.User();
                    entity.setScreenName(user.getScreenName());
                    entity.setLevel(com.appspot.bitlyminous.entity.User.Level.DIRECT_USER);
                    userService.updateUser(entity);
                    twitter.createFriendship(user.getScreenName());
                    twitter.sendDirectMessage(user.getScreenName(),
                            ApplicationResources.getLocalizedString("com.appspot.bitlyminous.message.welcome"));
                    // following fofs will hit the limit soon.
                    //                   IDs friendsIDs = twitter.getFriendsIDs(user.getId());
                    //                   for (int id : friendsIDs.getIDs()) {
                    //                      twitter.createFriendship(id);
                    //                   }
                } else if (entity.getLevel() != com.appspot.bitlyminous.entity.User.Level.DIRECT_USER) {
                    entity.setLevel(com.appspot.bitlyminous.entity.User.Level.DIRECT_USER);
                    userService.updateUser(entity);
                    twitter.createFriendship(user.getScreenName());
                    twitter.sendDirectMessage(user.getScreenName(),
                            ApplicationResources.getLocalizedString("com.appspot.bitlyminous.message.welcome"));
                    // following fofs will hit the limit soon.
                    //                   IDs friendsIDs = twitter.getFriendsIDs(user.getId());
                    //                   for (int id : friendsIDs.getIDs()) {
                    //                      twitter.createFriendship(id);
                    //                   }
                }
            }

            exists = twitterFollowers.hasNext();
            cursor = twitterFollowers.getNextCursor();
        }
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:com.ikon.module.common.CommonNotificationModule.java

License:Open Source License

/**
 * Send twitter subscription message/*from w  w  w  .ja va 2s .  co m*/
 */
public static void sendTwitterSubscription(String user, String nodePath, String eventType, String comment,
        Set<String> users)
        throws TemplateException, TwitterException, DatabaseException, HttpException, IOException {
    log.debug("sendTwitterSubscription({}, {}, {}, {}, {})",
            new Object[] { user, nodePath, eventType, comment, users });
    Twitter twitter = new Twitter(Config.SUBSCRIPTION_TWITTER_USER, Config.SUBSCRIPTION_TWITTER_PASSWORD);
    StringWriter swStatus = new StringWriter();
    Configuration cfg = TemplateUtils.getConfig();

    Map<String, String> model = new HashMap<String, String>();
    model.put("documentUrl", MailUtils.getTinyUrl(Config.APPLICATION_URL + "?docPath=" + nodePath));
    model.put("documentPath", nodePath);
    model.put("documentName", PathUtils.getName(nodePath));
    model.put("userId", user);
    model.put("eventType", eventType);
    model.put("subscriptionComment", comment);

    if (TemplateUtils.templateExists(Config.SUBSCRIPTION_TWITTER_STATUS)) {
        Template tpl = cfg.getTemplate(Config.SUBSCRIPTION_TWITTER_STATUS);
        tpl.process(model, swStatus);
    } else {
        StringReader sr = new StringReader(Config.SUBSCRIPTION_TWITTER_STATUS);
        Template tpl = new Template("SubscriptionTwitterStatus", sr, cfg);
        tpl.process(model, swStatus);
        sr.close();
    }

    for (Iterator<String> itUsers = users.iterator(); itUsers.hasNext();) {
        String itUser = itUsers.next();
        Collection<TwitterAccount> twitterAccounts = TwitterAccountDAO.findByUser(itUser, true);

        for (Iterator<TwitterAccount> itTwitter = twitterAccounts.iterator(); itTwitter.hasNext();) {
            TwitterAccount ta = itTwitter.next();
            log.info("Twitter Notify from {} to {} ({}) - {}",
                    new Object[] { twitter.getUserId(), ta.getTwitterUser(), itUser, swStatus.toString() });
            twitter.sendDirectMessage(ta.getTwitterUser(), swStatus.toString());
        }
    }
}

From source file:com.jetbrains.twitter.MessageSender.java

public static void sendDirectMessage(final Twitter twitter, final String recipient, final String text) {
    try {//from  www  .j av  a 2  s.c o  m
        final DirectMessage message = twitter.sendDirectMessage(recipient, text);
        System.out.println("Direct message successfully sent to " + message.getRecipientScreenName());
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to send a direct message: " + te.getMessage());
        System.exit(-1);
    }

}

From source file:fr.istic.taa.jaxrs.StatusEndpoint.java

License:Apache License

@GET
@Path("/sendTweet")
@Produces(MediaType.APPLICATION_JSON)//from   w ww.j a v a2 s  .  c om
public String sendTweet() throws IOException, TwitterException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("jUTzyyI3zjBqiKQqhfQyFeqpm")
            .setOAuthConsumerSecret("gMkOSO9EYqlzrnq35kdoZIqvX12sJwP1wHKMqo6uYbvq2q0LGl")
            .setOAuthAccessToken("89767958-C2cLIz69SpdR6wmQGdzE8rQSXAMzIVBpYOuaZGmHQ")
            .setOAuthAccessTokenSecret("oG7FQJMQsX2OHKxcaHjUxgZI94ZqUShGi0qCAsI50xfpZ");
    TwitterFactory tf = new TwitterFactory(cb.build());

    Twitter twitter = tf.getInstance();

    String recipientId;
    recipientId = "@nassssssiim";

    String message;
    message = "test";

    DirectMessage message1 = twitter.sendDirectMessage(recipientId, message);
    System.out.println(" to @" + message1.getRecipientScreenName());
    return " to @" + message1.getRecipientScreenName();

}

From source file:ikemen.Main.java

License:Apache License

public static void main(String[] args) {
    final Twitter twitter = TwitterFactory.getSingleton();
    final TwitterStream stream = TwitterStreamFactory.getSingleton();
    stream.addListener(new UserStreamAdapter() {
        public void onStatus(Status status) {
            if (yonda(status.getText())) {
                try {
                    twitter.createFavorite(status.getId());
                } catch (TwitterException ignore) {
                }//w ww  . ja  v  a  2s . c  o m
                try {
                    twitter.sendDirectMessage("yusuke", "http://twitter.com/yusuke/status/" + status.getId());
                } catch (TwitterException ignore) {
                }
            }
        }
    });
    stream.user();
}

From source file:io.warp10.script.functions.TWITTERDM.java

License:Apache License

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
    ////from www  .  java 2  s. c o  m
    // Extract parameters
    //

    String text = stack.pop().toString();
    String recipient = stack.pop().toString();
    String accessSecret = stack.pop().toString();
    String accessToken = stack.pop().toString();
    String consumerSecret = stack.pop().toString();
    String consumerKey = stack.pop().toString();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessSecret);
    TwitterFactory tf = new TwitterFactory(cb.build());

    Twitter twitter = tf.getInstance();

    try {
        twitter.sendDirectMessage(recipient, text);
    } catch (TwitterException te) {
        throw new WarpScriptException("Error while sending Twitter Direct Message", te);
    }

    return stack;
}

From source file:it.greenvulcano.gvesb.social.twitter.directcall.TwitterOperationSendDirectMessage.java

License:Open Source License

@Override
public void execute(SocialAdapterAccount account) throws SocialAdapterException {
    try {/*from  w w  w . jav  a  2  s. c  o  m*/
        Twitter twitter = (Twitter) account.getProxyObject();
        if (message.length() > 140) {
            message = message.substring(0, 139);
            logger.warn("TwitterOperationSendDirectMessage - Message shortened to 140 characters.");
        }
        try {
            long id = Long.parseLong(toAccountId);
            status = twitter.sendDirectMessage(id, message);
        } catch (NumberFormatException exc) {
            status = twitter.sendDirectMessage(toAccountId, message);
        }
    } catch (NumberFormatException exc) {
        logger.error("Call to TwitterOperationSendDirectMessage failed. Check toAccountId[" + toAccountId
                + "] format.", exc);
        throw new SocialAdapterException("Call to TwitterOperationSendDirectMessage failed. Check toAccountId["
                + toAccountId + "] format.", exc);
    } catch (TwitterException exc) {
        logger.error("Call to TwitterOperationSendDirectMessage toAccountId[" + toAccountId + "] failed.", exc);
        throw new SocialAdapterException(
                "Call to TwitterOperationSendDirectMessage toAccountId[" + toAccountId + "] failed.", exc);
    }
}

From source file:org.bonitasoft.connectors.twitter.TwitterDirectMessageConnector.java

License:Open Source License

@Override
protected void executeTask(Twitter twitter) throws Exception {
    twitter.sendDirectMessage(recipientId, message);
}