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:org.opencrx.application.twitter.SendDirectMessageWorkflow.java

License:BSD License

@Override
public void execute(WorkflowTarget wfTarget, ContextCapable targetObject, WfProcessInstance wfProcessInstance)
        throws ServiceException {
    PersistenceManager pm = JDOHelper.getPersistenceManager(wfProcessInstance);
    PersistenceManager rootPm = pm.getPersistenceManagerFactory()
            .getPersistenceManager(SecurityKeys.ROOT_PRINCIPAL, null);
    try {/*  w w w.  j  a v a 2 s .c  o m*/
        UserHome userHome = (UserHome) pm.getObjectById(wfProcessInstance.refGetPath().getParent().getParent());
        String providerName = userHome.refGetPath().get(2);
        String segmentName = userHome.refGetPath().get(4);
        ComponentConfiguration configuration = TwitterUtils.getComponentConfiguration(providerName, segmentName,
                rootPm);
        Map<String, Object> params = WorkflowHelper.getWorkflowParameters(wfProcessInstance);
        // Find default twitter account
        TwitterAccountQuery twitterAccountQuery = (TwitterAccountQuery) pm.newQuery(TwitterAccount.class);
        twitterAccountQuery.thereExistsIsDefault().isTrue();
        twitterAccountQuery.thereExistsIsActive().isTrue();
        List<TwitterAccount> twitterAccounts = userHome.getEMailAccount(twitterAccountQuery);
        TwitterAccount twitterAccount = twitterAccounts.isEmpty() ? null : twitterAccounts.iterator().next();
        String subject = null;
        String text = null;
        if (twitterAccount == null) {
            subject = "ERROR: " + Notifications.getInstance().getNotificationSubject(pm, targetObject,
                    wfProcessInstance.refGetPath(), userHome, params, true // useSendMailSubjectPrefix
            );
            text = "ERROR: direct message not sent. No default twitter account\n";
        } else {
            // Send direct message
            subject = Notifications.getInstance().getNotificationSubject(pm, targetObject,
                    wfProcessInstance.refGetPath(), userHome, params, true //this.useSendMailSubjectPrefix
            );
            String tinyUrl = TinyUrlUtils
                    .getTinyUrl(Notifications.getInstance().getAccessUrl(targetObject.refGetPath(), userHome));
            if (tinyUrl != null) {
                if (subject.length() > TwitterUtils.MESSAGE_SIZE - 30 - 4) {
                    subject = subject.substring(0, TwitterUtils.MESSAGE_SIZE - 30 - 4) + "...";
                }
                subject += " " + tinyUrl;
            } else {
                if (subject.length() > TwitterUtils.MESSAGE_SIZE - 3) {
                    subject = subject.substring(0, TwitterUtils.MESSAGE_SIZE - 3) + "...";
                }
            }
            TwitterFactory twitterFactory = new TwitterFactory(

            );
            AccessToken accessToken = new AccessToken(twitterAccount.getAccessToken(),
                    twitterAccount.getAccessTokenSecret());
            Twitter twitter = twitterFactory.getInstance();
            twitter.setOAuthConsumer(TwitterUtils.getConsumerKey(twitterAccount, configuration),
                    TwitterUtils.getConsumerSecret(twitterAccount, configuration));
            twitter.setOAuthAccessToken(accessToken);
            SysLog.detail("Send direct message message");
            DirectMessage message = twitter.sendDirectMessage(twitterAccount.getName(), subject);
            SysLog.detail("Done", message);
        }
        WorkflowHelper.createLogEntry(wfProcessInstance, subject, text);
    } catch (Exception e) {
        SysLog.warning("Can not send direct message");
        ServiceException e0 = new ServiceException(e);
        SysLog.detail(e0.getMessage(), e0.getCause());
        WorkflowHelper.createLogEntry(wfProcessInstance, "Can not send direct message: Exception",
                e.getMessage());
        throw e0;
    } finally {
        if (rootPm != null) {
            rootPm.close();
        }
    }
}

From source file:org.opencrx.kernel.portal.wizard.TwitterSendMessageWizardController.java

License:BSD License

/**
 * OK action./*w  w w  .ja  v  a 2 s  . c  o  m*/
 * 
 * @param formFields
 * @throws ServiceException
 */
public void doOK(@FormParameter(forms = "TwitterSendMessageForm") Map<String, Object> formFields)
        throws ServiceException {
    PersistenceManager pm = this.getPm();
    RefObject_1_0 obj = this.getObject();
    this.doRefresh(formFields);
    String toUsers = (String) formFields.get("org:opencrx:kernel:base:SendAlertParams:toUsers");
    String text = (String) formFields.get("org:opencrx:kernel:base:Note:text");
    if ((toUsers != null) && !toUsers.isEmpty() && (text != null) && !text.isEmpty()) {
        javax.jdo.PersistenceManager rootPm = pm.getPersistenceManagerFactory()
                .getPersistenceManager(org.opencrx.kernel.generic.SecurityKeys.ROOT_PRINCIPAL, null);
        org.opencrx.kernel.admin1.jmi1.ComponentConfiguration configuration = org.opencrx.application.twitter.TwitterUtils
                .getComponentConfiguration(this.getProviderName(), this.getSegmentName(), rootPm);
        // Find default twitter account
        org.opencrx.kernel.home1.jmi1.UserHome userHome = UserHomes.getInstance().getUserHome(obj.refGetPath(),
                pm);
        TwitterAccountQuery twitterAccountQuery = (TwitterAccountQuery) pm.newQuery(TwitterAccount.class);
        twitterAccountQuery.thereExistsIsDefault().isTrue();
        twitterAccountQuery.thereExistsIsActive().isTrue();
        List<TwitterAccount> twitterAccounts = userHome.getEMailAccount(twitterAccountQuery);
        TwitterAccount twitterAccount = twitterAccounts.isEmpty() ? null : twitterAccounts.iterator().next();
        if (twitterAccount != null) {
            TwitterFactory twitterFactory = new TwitterFactory();
            AccessToken accessToken = new AccessToken(twitterAccount.getAccessToken(),
                    twitterAccount.getAccessTokenSecret());
            Twitter twitter = twitterFactory.getInstance();
            twitter.setOAuthConsumer(TwitterUtils.getConsumerKey(twitterAccount, configuration),
                    TwitterUtils.getConsumerSecret(twitterAccount, configuration));
            twitter.setOAuthAccessToken(accessToken);
            StringTokenizer users = new StringTokenizer(toUsers, " ,", false);
            while (users.hasMoreTokens()) {
                String user = users.nextToken();
                try {
                    @SuppressWarnings("unused")
                    DirectMessage message = twitter.sendDirectMessage(user, text);
                } catch (Exception e) {
                    new ServiceException(e).log();
                }
            }
            // Send alert if invoked on user's home
            String title = NOTE_TITLE_PREFIX + " [" + twitterAccount.getName() + "] @ " + new Date();
            if (obj instanceof org.opencrx.kernel.home1.jmi1.UserHome) {
                org.opencrx.kernel.home1.jmi1.UserHome user = (org.opencrx.kernel.home1.jmi1.UserHome) obj;
                Base.getInstance().sendAlert(user, // target
                        user.refGetPath().getBase(), title, text, (short) 2, // importance
                        0, // resendDelayInSeconds
                        null // reference
                );
            }
            // Attach message as Note                
            else if (obj instanceof org.opencrx.kernel.generic.jmi1.CrxObject) {
                try {
                    pm.currentTransaction().begin();
                    org.opencrx.kernel.generic.jmi1.CrxObject crxObject = (org.opencrx.kernel.generic.jmi1.CrxObject) obj;
                    org.opencrx.kernel.generic.jmi1.Note note = pm
                            .newInstance(org.opencrx.kernel.generic.jmi1.Note.class);
                    note.setTitle(title);
                    note.setText(text);
                    crxObject.addNote(Base.getInstance().getUidAsString(), note);
                    pm.currentTransaction().commit();
                    // FollowUp if obj is an activity
                    if (obj instanceof Activity) {
                        try {
                            Activity activity = (Activity) obj;
                            ActivityProcess activityProcess = activity.getActivityType().getControlledBy();
                            ActivityProcessTransitionQuery processTransitionQuery = (ActivityProcessTransitionQuery) pm
                                    .newQuery(
                                            org.opencrx.kernel.activity1.cci2.ActivityProcessTransition.class);
                            processTransitionQuery.thereExistsPrevState().equalTo(activity.getProcessState());
                            processTransitionQuery.orderByNewPercentComplete().ascending();
                            List<ActivityProcessTransition> processTransitions = activityProcess
                                    .getTransition(processTransitionQuery);
                            if (!processTransitions.isEmpty()) {
                                ActivityProcessTransition processTransition = processTransitions.iterator()
                                        .next();
                                pm.currentTransaction().begin();
                                @SuppressWarnings("unused")
                                ActivityFollowUp followUp = Activities.getInstance().doFollowUp(activity, title,
                                        text, processTransition, null, // reportingContact
                                        null // parentProcessInstance
                                );
                                pm.currentTransaction().commit();
                            }
                        } catch (Exception e) {
                            try {
                                pm.currentTransaction().rollback();
                            } catch (Exception e0) {
                            }
                        }
                    }
                } catch (Exception e) {
                    try {
                        pm.currentTransaction().rollback();
                    } catch (Exception e0) {
                    }
                }
            }
            this.forward("Cancel", this.getRequest().getParameterMap());
        }
    }
}

From source file:org.opennms.netmgt.notifd.MicroblogDMNotificationStrategy.java

License:Open Source License

/** {@inheritDoc} */
@Override//w  w  w  . j  av a  2s  .  co  m
public int send(List<Argument> arguments) {
    Twitter svc = buildUblogService(arguments);
    String destUser = findDestName(arguments);
    DirectMessage response;

    if (destUser == null || "".equals(destUser)) {
        LOG.error(
                "Cannot send a microblog DM notice to a user with no microblog username set. Either set a microblog username for this OpenNMS user or use the MicroblogUpdateNotificationStrategy instead.");
        return 1;
    }

    // In case the user tried to be helpful, avoid a double @@
    if (destUser.startsWith("@"))
        destUser = destUser.substring(1);

    String fullMessage = buildMessageBody(arguments);

    LOG.debug(
            "Dispatching microblog DM notification at base URL '{}' with destination user '{}' and message '{}'",
            svc.getConfiguration().getClientURL(), destUser, fullMessage);
    try {
        response = svc.sendDirectMessage(destUser, fullMessage);
    } catch (TwitterException e) {
        LOG.error("Microblog notification failed at service URL '{}' to destination user '{}'",
                svc.getConfiguration().getClientURL(), destUser, e);
        return 1;
    }

    LOG.info("Microblog DM notification succeeded: DM sent with ID {}", response.getId());
    return 0;
}

From source file:org.osframework.maven.plugins.twitter.DirectMessageMojo.java

License:Apache License

protected void executeInTwitter(Twitter twitter) throws MojoExecutionException, MojoFailureException {
    try {/*from w w w .j a v  a  2s  .c  om*/
        DirectMessage dm = twitter.sendDirectMessage(recipientScreenName, getMessage());
        getLog().info("Sent direct message to @" + dm.getRecipientScreenName() + ": " + dm.getText());
        logDirectMessage(dm);
    } catch (TwitterException te) {
        throw new MojoFailureException("Could not send direct message", te);
    }
}

From source file:org.wso2.carbon.connector.twitter.TwitterSendDirectMesage.java

License:Open Source License

@Override
public void connect(MessageContext messageContext) throws ConnectException {
    try {//ww  w .j av a 2s. c  om
        String userID = TwitterUtils.lookupTemplateParamater(messageContext, USER_ID);
        String screenName = TwitterUtils.lookupTemplateParamater(messageContext, SCREEN_NAME);
        String message = TwitterUtils.lookupTemplateParamater(messageContext, MESSAGE);
        Twitter twitter = new TwitterClientLoader(messageContext).loadApiClient();
        if (userID != null && !userID.isEmpty()) {
            twitter.sendDirectMessage(Long.parseLong(userID), message);
        }

        if (screenName != null && !screenName.isEmpty()) {
            twitter.sendDirectMessage(screenName, message);
        }

        if (log.isDebugEnabled()) {
            log.info("sending direct message to user completed!");
        }
    } catch (Exception e) {
        log.error("Failed to login user: " + e.getMessage(), e);
        TwitterUtils.storeErrorResponseStatus(messageContext, e);
    }
}

From source file:tweete.Tweete.java

License:Open Source License

public void sendMessage(String id, String msg) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("######################")
            .setOAuthConsumerSecret("######################")
            .setOAuthAccessToken("############################################")
            .setOAuthAccessTokenSecret("############################################");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    try {//w w  w  .j  a  v  a  2  s . c  om
        DirectMessage message = null;
        message = twitter.sendDirectMessage(id, msg);
        System.out.println("Sent: " + message.getText() + " to @" + message.getRecipientScreenName());

    } catch (TwitterException te) {
        //te.printStackTrace();

        if (401 == te.getStatusCode()) {
            System.out.println("Unable to get the access token.");
        }

        else if (92 == te.getStatusCode()) {
            System.out.println("SSL is required");
        }

        else {
            System.out.println("Failed to get timeline: " + te.getMessage());
            System.exit(-1);
        }
    } catch (Exception e) {
        System.out.println("Something went wrong");
    }

}

From source file:twitter.botframework.connector.TwitterBotframeworkConnector.java

public static void SendDirectMessageAsResponse(Twitter twitter) {
    //Twitter twitter = new TwitterFactory().getInstance();
    try {/*  w w  w .  j a  v  a2 s.  c o m*/
        DirectMessage message = twitter.sendDirectMessage(user_name, user_message);
        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:twitter4j.examples.directmessage.SendDirectMessage.java

License:Apache License

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