Search in sources :

Example 11 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class Telegram method sendTelegram.

@ActionDoc(text = "Sends a Telegram via Telegram REST API - direct message")
public static boolean sendTelegram(@ParamDoc(name = "group") String group, @ParamDoc(name = "message") String message) {
    if (groupTokens.get(group) == null) {
        logger.error("Bot '{}' not defined, action skipped", group);
        return false;
    }
    String url = String.format(TELEGRAM_URL, groupTokens.get(group).getToken());
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setContentCharset("UTF-8");
    postMethod.getParams().setSoTimeout(HTTP_TIMEOUT);
    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] data = { new NameValuePair("chat_id", groupTokens.get(group).getChatId()), new NameValuePair("text", message) };
    postMethod.setRequestBody(data);
    try {
        int statusCode = client.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            return true;
        }
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: {}", postMethod.getStatusLine());
            return false;
        }
        InputStream tmpResponseStream = postMethod.getResponseBodyAsStream();
        Header encodingHeader = postMethod.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.debug("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.debug("Deflated InputStream from {}", url);
                }
            }
        }
        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
        return false;
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
        return false;
    } finally {
        postMethod.releaseConnection();
    }
    return true;
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) PostMethod(org.apache.commons.httpclient.methods.PostMethod) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ImageInputStream(javax.imageio.stream.ImageInputStream) InputStream(java.io.InputStream) HeaderElement(org.apache.commons.httpclient.HeaderElement) InflaterInputStream(java.util.zip.InflaterInputStream) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) Header(org.apache.commons.httpclient.Header) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 12 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class Twitter method sendTweet.

/**
     * 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;
    }
}
Also used : Status(twitter4j.Status) TwitterException(twitter4j.TwitterException) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 13 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class Twitter method sendDirectMessage.

/**
     * 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;
    }
}
Also used : DirectMessage(twitter4j.DirectMessage) TwitterException(twitter4j.TwitterException) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 14 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class XMPP method chatXMPP.

/**
     * Sends a message to an XMPP multi user chat.
     * 
     * @param message the message to send
     * 
     * @return <code>true</code>, if sending the message has been successful and
     *         <code>false</code> in all other cases.
     */
@ActionDoc(text = "Sends a message to an XMPP multi user chat.")
public static boolean chatXMPP(@ParamDoc(name = "message") String message) {
    boolean success = false;
    try {
        MultiUserChat chat = XMPPConnect.getChat();
        try {
            while (message.length() >= 2000) {
                chat.sendMessage(message.substring(0, 2000));
                message = message.substring(2000);
            }
            chat.sendMessage(message);
            logger.debug("Sent message '{}' to multi user chat.", message);
            success = true;
        } catch (XMPPException e) {
            logger.warn("Error Delivering block", e);
        } catch (NotConnectedException e) {
            logger.warn("Error Delivering block", e);
        }
    } catch (NotInitializedException e) {
        logger.warn("Could not send XMPP message as connection is not correctly initialized!");
    }
    return success;
}
Also used : MultiUserChat(org.jivesoftware.smackx.muc.MultiUserChat) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) XMPPException(org.jivesoftware.smack.XMPPException) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Aggregations

ActionDoc (org.openhab.core.scriptengine.action.ActionDoc)14 Message (com.ciscospark.Message)2 SparkException (com.ciscospark.SparkException)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ImageInputStream (javax.imageio.stream.ImageInputStream)2 AddressException (javax.mail.internet.AddressException)2 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)2 HttpClient (org.apache.commons.httpclient.HttpClient)2 HttpException (org.apache.commons.httpclient.HttpException)2 PostMethod (org.apache.commons.httpclient.methods.PostMethod)2 NotConnectedException (org.jivesoftware.smack.SmackException.NotConnectedException)2 XMPPException (org.jivesoftware.smack.XMPPException)2 MultiUserChat (org.jivesoftware.smackx.muc.MultiUserChat)2 TwitterException (twitter4j.TwitterException)2 InputStream (java.io.InputStream)1 BigDecimal (java.math.BigDecimal)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1