Giter Club home page Giter Club logo

simple-slack-api's Introduction

Build Status GitHub release Coverage Status Join the chat at https://gitter.im/Ullink/simple-slack-api

Simple Slack API

This library allows an application to connect to Slack to receive and send messages from any channel as if it were a slack client.

The main purpose of this library is to build Slack bots able to react to channel events without having to configure any web hook.

With this library you should be able to connect to Slack and to send some messages in less than 20 lines (no one-liners).

Maven/Gradle

You can add this library as a dependency to your Maven or Gradle project through JitPack.

Released versions are also availables on the maven central repository :

  • group id: com.ullink.slack
  • artifact id: simpleslackapi

How to use it ?

You can find some samples of the most common use cases in the samples folder.

Sample code

SlackSession session = SlackSessionFactory.createWebSocketSlackSession("slack-bot-auth-token");
session.connect();
SlackChannel channel = session.findChannelByName("general"); //make sure bot is a member of the channel.
session.sendMessage(channel, "hi im a bot" );

Features

Supported Slack commands

All these commands can be sent through the library provided your bot has the rights to (IE : the bot has to be a member of the group or the channel to post some messages on it)

  • Post a message on a channel / private group / user
  • Post a typing indicator on a channel
  • Update a message
  • Delete a message
  • Join a channel
  • Leave a channel / a private group
  • Invite to a channel / a private group
  • Archive a channel
  • Open a direct message channel (since v0.5.0)
  • Open a multiparty direct message channel (since v0.5.0)
  • Get the presence status of a user
  • Add a reaction emoji to a message
  • Fetch the channel history (since v0.5.0) (needs full user credentials)
  • Invite a user to Slack (since v0.5.0)

On top of these built-in features, it is now possible to send not yet implemented API calls by using the postGenericSlackCommand method :

postGenericSlackCommand(Map<String, String> params, String command);

Supported Slack events

All these events can be listen provided your bot has the rights to (IE : the bot has to be a member of the group or a channel to gets the message events related to it)

  • message posted event
  • message deleted event
  • message updated event
  • channel created event
  • channel / private group deleted event
  • channel / private group archived event
  • channel / private group unarchived event
  • channel / private group renamed event
  • channel / private group joined event
  • reaction added to message event (since v0.5.0)
  • reaction removed from message event (since v0.5.0)
  • team joined event

Attention

From version 1.4.0 upward, channel members are not loaded in memory anymore in order for the api to start up faster. This should have no impact on the current behavior.

Thanks

Many thanks to everyone who has contributed to this library :

  • Christian Sprecher
  • Jan Vidar Krey
  • David Seebacher
  • Wouter Vernaillen
  • Claudio Comandini
  • Maxim Gurkin
  • Ole Kozaczenko
  • Georges Gomes
  • François Valdy
  • Harry Fox
  • Logan Clément
  • Rhys Kenwell
  • Aman Gupta
  • Miklos Sagi
  • Nathalie Mahe
  • Sebastien Lelouvier
  • Nicolas Haquet

(Let me know if I forgot someone, I'll fix that ASAP ;) )

License

This library is licensed under the Creative Commons CC0 1.0 Universal license with no warranty (expressed or implied) for any purpose.

simple-slack-api's People

Contributors

bcorne avatar bobbyjohansen avatar ccomandini avatar dkowis avatar dmitriid avatar drxaos avatar dseebacher avatar freesoft avatar gingergeek avatar gluck avatar hfoxy avatar ja-ko avatar janvidar avatar jevanlingen avatar johighley-ssnc avatar kindofwhat avatar kushal avatar logscl avatar massigerardi avatar matush-v avatar morfeusys avatar morria avatar moults31 avatar msagi avatar nishtahir avatar offirt avatar redcraft avatar vbeskrovnov avatar vernaillen avatar woshinisenbaba avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

simple-slack-api's Issues

Error session.connect()

[main] INFO com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl - connecting to slack
Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:52)
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:56)
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:46)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:72)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:84)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:59)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager$InternalConnectionFactory.(PoolingHttpClientConnectionManager.java:493)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:149)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:138)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:114)
at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:726)
at com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl.getHttpClient(SlackWebSocketSessionImpl.java:671)
at com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl.connectImpl(SlackWebSocketSessionImpl.java:254)
at com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl.connect(SlackWebSocketSessionImpl.java:230)

I couldn't fix this

Attachment not working

I'm unable to send attachment.
Is this a known bug?


This is how I'm connecting to the slack:

SlackSessionFactory.createWebSocketSlackSession("token");

When a new message is posted I reply with:

session.sendMessageOverWebSocket(event.getChannel(), null, new SlackAttachment("test", "test", "test", "test"));

The generated JSON looks good:

{
    "attachments": [
        {
            "pretext": "test",
            "text": "test",
            "title": "test",
            "fallback": "test"
        }
    ],
    "channel": "D0J38QR3L",
    "text": null,
    "type": "message"
}

But in Slack nothing shows up.

isOk() in ParsedSlackReply is difficult to use

Hi
I just updated to version 0.5
You decided to move the isOk() method from SlackReply to ParsedSlackReply. However no handle or Reply returned by SlackSession is related to ParsedSlackReply.
That means that whenever I want to check isOk() I need to cast my SlackReply to ParsedSlackReply and check isOk() then.
Did I miss something or is this the preferred approach?
If not, can you make isOk() easier to use?

NoClassDefFoundError in Android Build

Stacktrace
----------------
java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/impl/client/HttpClientBuilder;
    at com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl.getHttpClient(SlackWebSocketSessionImpl.java:373)
    at com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl.connect(SlackWebSocketSessionImpl.java:148)
    at com.loqooapps.Views.Activities.Startup.onCreate(Startup.java:322)
    at android.app.Activity.performCreate(Activity.java:6056)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
    at android.app.ActivityThread.access$800(ActivityThread.java:162)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5431)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.impl.client.HttpClientBuilder" on path: DexPathList[[zip file "/data/app/com.teamxna.fmc.inhouse-2/base.apk"],nativeLibraryDirectories=[/data/app/com.teamxna.fmc.inhouse-2/lib/arm, /vendor/lib, /system/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    ... 16 more
    Suppressed: java.lang.ClassNotFoundException: org.apache.http.impl.client.HttpClientBuilder
        at java.lang.Class.classForName(Native Method)
        at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
        at java.lang.BootClassLoader.loadClass(ClassLoade

Publish new version to Maven

Can you please publish a new version to maven so recent changes (specifically #25, #26, and #27) can be accessed?

Also, are you publishing snapshots anywhere?

Thanks again!

Unable to send msg to a specific channel

When I connect to slack via this API

SlackSession ss = SlackSessionFactory.createWebSocketSlackSession("xxx");
ss.connect();

I get the following output:

asoiaf
data-quality-planning
design
development
fabrica_builds
general
hn
implementation
jira-notifications
meeting-notes
project-admin-todo
qa-webtool
random

Listing all the channels for our account.

If the following is executed:
ss = sendMessageOverWebSocket(slackSession.findChannelByName("general"), "Hello world", null);

"Hello world" appears on the "general" channel in Slack

BUT, if ANY other channel is selected, (for example: replace "general" with "hn")

I get the following error:
[Grizzly(2)] DEBUG com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl - receiving from websocket {"type":"error","error":{"code":0,"msg":"invalid channel id"}}

The following code was executed:

Collection channels = slackSession.getChannels();
logger.info("Number of slack channels found is " + channels.size());
for(SlackChannel sc : channels)
{
system.out.println(sc.name());
}

The number of channels and the list of names for each channel is properly shown.

Suggestions?
James
([email protected])

Unclear how to use event handlers?

So what I did which I thought would work, was make a class that implemented the listener I wanted to use, in this case, SlackMessagePostedListener. I implemented the onEvent, but when I passed the class to session.addSlackMessagePostedListener, it threw an error "Expression expected" So what do I do here?

SlackPreparedMessage in 0.5.1 via maven?

The samples include the following example of assembling a more complex message:

SlackPreparedMessage preparedMessage = new SlackPreparedMessage.Builder()
.withMessage("Hey, this is a message")
.withUnfurl(false)
.addAttachment(new SlackAttachment())
.addAttachment(new SlackAttachment())
.build();

0.5.1 doesn't seem to include the SlackPreparedMessage type: can you provide an example of using attachments in that release (latest seemingly available via maven, whcih is how i need it)? ta

support for reactions

hi,

i like your simpleslackapi a lot.
would it be possible to add support for listening to reactions to messages in a channel?
or can you tell me if slack provides this feature via it's api?
it would be very helpful.

best regards,
jan

ch.qos.logback runtime dependencies cause unwanted and excessive logging from other libraries

SimpleSlackAPI is packaged with 2 logging jars from package ch.qos.logback as maven runtime dependencies.
For some reason, that causes the couchbase java connector to print tons of logging messages in DEBUG level. I would only assume that it would be the same for other libraries that use SLF4J.
I'm not an expert on maven packaging, but other libraries (including couch) know how to "hide" the fact that they use a logger without exposing it to the outside world.

As a quick and dirty workaround, I had to manually exclude the 2 jars from my pom.xml file, but that doesn't feel right at all.

10x

Tagging users

Is there a way for a slack bot to tag a user in a message? I.e. an @user_name tag that alerts a user that the message is directed towards them in the group? Same thing for listening for a tag as well? Any help would be appreciated.

Two listeners are being registered

I'm configuring a Spring Boot project to use this library, but it appears I've somehow configured it to start two listeners, instead of one. Debugging, I can only see one call made to SlackSession.addMessagePostedListener, but I'm having difficulty understanding what is happening after that. Any help is appreciated!

I have an example project here, that should be pretty easy to replicate: https://github.com/AndrewBell/johnny5/tree/bf7aa772072271cda1b0965a8d0cee85c2b0855c

I use Spring Boot's CommandLineRunner to fetch a session, and add a listener on startup:

@Component
public class Startup implements CommandLineRunner{

    private final Logger log = LoggerFactory.getLogger(Startup.class);

    @Value("${slack.api.key}")
    public String apiKey;

    @Autowired
    SlackSession slackSession;

    @Override
    public void run(String... args) throws Exception {
        log.info("Service started with key: " + apiKey);
        slackSession.connect();
        slackSession.addMessagePostedListener(new HelloListener());
    }
}

I have a Configuration file used to configure a bean for the slack session:

@Configuration
public class SlackConfig {

    private final Logger log = LoggerFactory.getLogger(SlackConfig.class);

    @Value("${slack.channel}")
    String channel;

    @Value("${slack.api.key}")
    String key;

    SlackSession slackSession;

    @Bean
    SlackSession slackSession() throws IOException {
        if (null == slackSession) {
            slackSession = SlackSessionFactory.createWebSocketSlackSession(key);
            slackSession.connect();
            log.debug("New session created: {}", slackSession);
        }
        return slackSession;
    }

    @Bean
    SlackChannel slackChannel() throws IOException {
        return slackSession.findChannelByName(channel);
    }

}

And a basic listener:

public class HelloListener implements SlackMessagePostedListener {

    private final Logger log = LoggerFactory.getLogger(HelloListener.class);

    @Override
    public void onEvent(SlackMessagePosted event, SlackSession session) {
        log.debug("Message Posted: {}", event.getMessageContent());

        if (event.getMessageContent().trim().toUpperCase().contains("HELLO <@U0CSFUZHB>")){
            session.sendMessage(event.getChannel(),"Hello " + event.getSender().getUserName(), null);
        }
    }

}

Startup logging:

2015-12-06 22:50:38.004  INFO 8092 --- [           main] c.r.johnny5.Johnny5Application           : Starting Johnny5Application on GINA with PID 8092 (C:\workspace\johnny5-spring\target\classes started by andrew in C:\workspace\johnny5-spring)
2015-12-06 22:50:38.006 DEBUG 8092 --- [           main] c.r.johnny5.Johnny5Application           : Running with Spring Boot v1.3.0.M5, Spring v4.2.1.RELEASE
2015-12-06 22:50:38.037  INFO 8092 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@3c87521: startup date [Sun Dec 06 22:50:38 CST 2015]; root of context hierarchy
2015-12-06 22:50:38.690  INFO 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : connecting to slack
2015-12-06 22:50:39.391 DEBUG 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : HTTP/1.1 200 OK
2015-12-06 22:50:39.397 DEBUG 8092 --- [           main] c.u.s.s.i.SlackJSONSessionStatusParser   : parsing session status : ...
2015-12-06 22:50:39.419 DEBUG 8092 --- [           main] c.u.s.s.i.SlackJSONSessionStatusParser   : slack bot found : B0CKUQW1E
...
2015-12-06 22:50:39.419 DEBUG 8092 --- [           main] c.u.s.s.i.SlackJSONSessionStatusParser   : slack bot found : B0CKR0ACU
2015-12-06 22:50:39.419 DEBUG 8092 --- [           main] c.u.s.s.i.SlackJSONSessionStatusParser   : slack public channel found : C0CHM9QUW
...
2015-12-06 22:50:39.420 DEBUG 8092 --- [           main] c.u.s.s.i.SlackJSONSessionStatusParser   : slack public channel found : C0DGK1CJY
2015-12-06 22:50:39.420 DEBUG 8092 --- [           main] c.u.s.s.i.SlackJSONSessionStatusParser   : slack im channel found : D0CSFUZHT
2015-12-06 22:50:39.420  INFO 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : 28 users found on this session
2015-12-06 22:50:39.420  INFO 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : 11 channels found on this session
2015-12-06 22:50:39.420 DEBUG 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : retrieved websocket URL : wss://ms370.slack-msgs.com/websocket/OoPaRslZtCXXkzyC26_6m_Q0Au6D-O0O53pX3PZ0e9ChYYWbGCeKfh1c6juxvCxk1B-LWj_Xvwjjuna7y-pgCCSnWbf1GAm0OCAcuXB_ZzmBonhkFKHRnwe0J_cbZPkBobiqdlKYSh9eu73UaYwvgw==
2015-12-06 22:50:39.426 DEBUG 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : initiating connection to websocket
2015-12-06 22:50:39.971 DEBUG 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : websocket connection established
2015-12-06 22:50:39.971  INFO 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : slack session ready
2015-12-06 22:50:39.971 DEBUG 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : starting connection monitoring
2015-12-06 22:50:39.972 DEBUG 8092 --- [       Thread-2] c.u.s.s.impl.SlackWebSocketSessionImpl   : monitoring thread started
2015-12-06 22:50:39.972 DEBUG 8092 --- [           main] c.r.johnny5.config.SlackConfig           : New session created: com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl@3a71c100
2015-12-06 22:50:40.022 DEBUG 8092 --- [     Grizzly(1)] c.u.s.s.impl.SlackWebSocketSessionImpl   : receiving from websocket {"type":"hello"}
2015-12-06 22:50:40.025 DEBUG 8092 --- [     Grizzly(1)] c.u.s.s.impl.SlackWebSocketSessionImpl   : receiving from websocket {"type":"presence_change","user":"U0CSFUZHB","presence":"active"}
2015-12-06 22:50:40.025 DEBUG 8092 --- [     Grizzly(1)] c.u.s.s.impl.SlackWebSocketSessionImpl   : receiving from websocket {"type":"presence_change","user":"U0CSFUZHB","presence":"active"}
2015-12-06 22:50:40.258  INFO 8092 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2015-12-06 22:50:40.263  INFO 8092 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2015-12-06 22:50:40.305  INFO 8092 --- [           main] c.recursivechaos.johnny5.config.Startup  : Service started with key: xoxb-
2015-12-06 22:50:40.305  INFO 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : connecting to slack
2015-12-06 22:50:40.705 DEBUG 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : HTTP/1.1 200 OK
2015-12-06 22:50:40.707 DEBUG 8092 --- [           main] c.u.s.s.i.SlackJSONSessionStatusParser   : parsing session status : ...
2015-12-06 22:50:40.714 DEBUG 8092 --- [           main] c.u.s.s.i.SlackJSONSessionStatusParser   : slack user found : U0CFU8BDJ
...
2015-12-06 22:50:40.717 DEBUG 8092 --- [           main] c.u.s.s.i.SlackJSONSessionStatusParser   : slack user found : USLACKBOT
...
2015-12-06 22:50:40.718 DEBUG 8092 --- [           main] c.u.s.s.i.SlackJSONSessionStatusParser   : slack bot found : B0CKR0ACU
2015-12-06 22:50:40.718 DEBUG 8092 --- [           main] c.u.s.s.i.SlackJSONSessionStatusParser   : slack public channel found : C0CHM9QUW
...
2015-12-06 22:50:40.719 DEBUG 8092 --- [           main] c.u.s.s.i.SlackJSONSessionStatusParser   : slack public channel found : C0DGK1CJY
2015-12-06 22:50:40.719 DEBUG 8092 --- [           main] c.u.s.s.i.SlackJSONSessionStatusParser   : slack im channel found : D0CSFUZHT
2015-12-06 22:50:40.719  INFO 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : 28 users found on this session
2015-12-06 22:50:40.719  INFO 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : 11 channels found on this session
2015-12-06 22:50:40.720 DEBUG 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : retrieved websocket URL : wss://ms370.slack-msgs.com/websocket/KQDQxCuie4e9dZ0clPY43HdLKOcknSDAUBI9YDpFGqYyR5H9IeF7WtjgP72nvSnWAi-iDzv30UfTpwSpUTcrHx5QBiC8dhicMuk0kLrjREagifqr7vh7Sezd18AAoPnP_UqM0-yhaWqr7GJWB2-G1Q==
2015-12-06 22:50:40.720 DEBUG 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : initiating connection to websocket
2015-12-06 22:50:41.091 DEBUG 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : websocket connection established
2015-12-06 22:50:41.091  INFO 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : slack session ready
2015-12-06 22:50:41.091 DEBUG 8092 --- [           main] c.u.s.s.impl.SlackWebSocketSessionImpl   : starting connection monitoring
2015-12-06 22:50:41.091 DEBUG 8092 --- [       Thread-3] c.u.s.s.impl.SlackWebSocketSessionImpl   : monitoring thread started
2015-12-06 22:50:41.093  INFO 8092 --- [           main] c.r.johnny5.Johnny5Application           : Started Johnny5Application in 3.296 seconds (JVM running for 3.508)
2015-12-06 22:50:41.174 DEBUG 8092 --- [     Grizzly(1)] c.u.s.s.impl.SlackWebSocketSessionImpl   : receiving from websocket {"type":"hello"}
2015-12-06 22:50:45.579 DEBUG 8092 --- [     Grizzly(2)] c.u.s.s.impl.SlackWebSocketSessionImpl   : receiving from websocket {"type":"user_typing","channel":"C0CSLGT0A","user":"U0CAJG99V"}
2015-12-06 22:50:45.579 DEBUG 8092 --- [     Grizzly(2)] c.u.s.s.impl.SlackWebSocketSessionImpl   : receiving from websocket {"type":"user_typing","channel":"C0CSLGT0A","user":"U0CAJG99V"}
2015-12-06 22:50:49.232 DEBUG 8092 --- [     Grizzly(1)] c.u.s.s.impl.SlackWebSocketSessionImpl   : receiving from websocket {"type":"message","channel":"C0CSLGT0A","user":"U0CAJG99V","text":"hello <@U0CSFUZHB>","ts":"1449463848.000125","team":"T09C5HCG1"}
2015-12-06 22:50:49.232 DEBUG 8092 --- [     Grizzly(1)] c.u.s.s.impl.SlackWebSocketSessionImpl   : receiving from websocket {"type":"message","channel":"C0CSLGT0A","user":"U0CAJG99V","text":"hello <@U0CSFUZHB>","ts":"1449463848.000125","team":"T09C5HCG1"}
2015-12-06 22:50:49.233 DEBUG 8092 --- [     Grizzly(1)] c.r.johnny5.listener.HelloListener       : Message Posted: hello <@U0CSFUZHB>
2015-12-06 22:50:49.233 DEBUG 8092 --- [     Grizzly(1)] c.r.johnny5.listener.HelloListener       : Message Posted: hello <@U0CSFUZHB>
2015-12-06 22:50:49.585 DEBUG 8092 --- [     Grizzly(1)] c.u.s.s.impl.SlackWebSocketSessionImpl   : PostMessage return: {"ok":true,"channel":"C0CSLGT0A","ts":"1449463849.000127","message":{"type":"message","user":"U0CSFUZHB","text":"Hello doctorsound","ts":"1449463849.000127"}}
2015-12-06 22:50:49.586 DEBUG 8092 --- [     Grizzly(2)] c.u.s.s.impl.SlackWebSocketSessionImpl   : receiving from websocket {"type":"message","user":"U0CSFUZHB","text":"Hello doctorsound","channel":"C0CSLGT0A","ts":"1449463849.000126"}
2015-12-06 22:50:49.586 DEBUG 8092 --- [     Grizzly(2)] c.r.johnny5.listener.HelloListener       : Message Posted: Hello doctorsound
2015-12-06 22:50:49.590 DEBUG 8092 --- [     Grizzly(1)] c.u.s.s.impl.SlackWebSocketSessionImpl   : receiving from websocket {"type":"message","user":"U0CSFUZHB","text":"Hello doctorsound","channel":"C0CSLGT0A","ts":"1449463849.000127"}
2015-12-06 22:50:49.590 DEBUG 8092 --- [     Grizzly(1)] c.r.johnny5.listener.HelloListener       : Message Posted: Hello doctorsound
2015-12-06 22:50:49.595 DEBUG 8092 --- [     Grizzly(1)] c.u.s.s.impl.SlackWebSocketSessionImpl   : PostMessage return: {"ok":true,"channel":"C0CSLGT0A","ts":"1449463849.000126","message":{"type":"message","user":"U0CSFUZHB","text":"Hello doctorsound","ts":"1449463849.000126"}}
2015-12-06 22:50:49.595 DEBUG 8092 --- [     Grizzly(2)] c.u.s.s.impl.SlackWebSocketSessionImpl   : receiving from websocket {"type":"message","user":"U0CSFUZHB","text":"Hello doctorsound","channel":"C0CSLGT0A","ts":"1449463849.000126"}
2015-12-06 22:50:49.595 DEBUG 8092 --- [     Grizzly(2)] c.r.johnny5.listener.HelloListener       : Message Posted: Hello doctorsound
2015-12-06 22:50:49.595 DEBUG 8092 --- [     Grizzly(2)] c.u.s.s.impl.SlackWebSocketSessionImpl   : receiving from websocket {"type":"message","user":"U0CSFUZHB","text":"Hello doctorsound","channel":"C0CSLGT0A","ts":"1449463849.000127"}
2015-12-06 22:50:49.595 DEBUG 8092 --- [     Grizzly(2)] c.r.johnny5.listener.HelloListener       : Message Posted: Hello doctorsound

SlackMessagePosted do not contain subtypes

It'd be great to have access to message subtypes in SlackMessagePosted. Right now I can't filter messages like user left a channel for example. Unless I'm missing something.

Thanks for your library. Great work.

Newest Release

Hi I just wanted to see when the newest version with sendFile will be up on Jitpack. Thanks!

README example code is outdated

Title speaks all, really. Regarding the updating and deletion of the message sent, I had to rummage around the source to find a solution, which was actually casting the getReply() from the event to the correct class. Seems a little sketchy if you ask me, but oh well.

why are member fields public?

hi - i was wondering if there was a reason the member fields in the various classes are public instead of private and final.

thanks!!

New Maven Central Version

Greetings,

Do you mind pushing a new build to Maven Central? Some recent changes I'd like to have without having the whole project pulled.

Thanks,
Holt Herndon

Full dependency list

I'm trying to use this in a vanilla Eclipse Java project. Since I might want to use this in the company I work for, I want to keep a strict understanding of what other dependencies this uses. (They are allergic to certain Open Source licenses, but fine with others.) So rather than let gradle spider out and download the world, I'm trying to assemble the jar files by hand. So far I have:
javax.websocket-api-1.1.jar
json-simple-1.1.1.jar
slf4j-api-1.7.10.jar
slf4j-simple-1.7.10.jar
tyrus-client-1.9.jar
tyrus-core-1.9.jar
It compiles file. When I call session.connect() it connects, lists the channels, notifies of found users, bots and channels, then exceptions:

java.lang.RuntimeException: javax.websocket.DeploymentException: org.glassfish.tyrus.container.grizzly.client.GrizzlyClientContainer

at org.glassfish.tyrus.client.ClientManager.<init>(ClientManager.java:269)
at org.glassfish.tyrus.client.ClientManager.createClient(ClientManager.java:237)
at org.glassfish.tyrus.client.ClientManager.createClient(ClientManager.java:216)
at com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl.connect(SlackWebSocketSessionImpl.java:125)
at com.ibm.ba.cloud.slack.test.ConnectTest.main(ConnectTest.java:13)

Caused by: javax.websocket.DeploymentException: org.glassfish.tyrus.container.grizzly.client.GrizzlyClientContainer

at org.glassfish.tyrus.core.ErrorCollector.composeComprehensiveException(ErrorCollector.java:83)
... 5 more

I'm guessing this is a problem in my environment rather than in the code. Did I miss a tyrus jar?
Thanks,
Jo

Session.connect failure

If the Slack session fails to connect, for instance due to a bad auth token, there is no way to know if you have a valid session or not. It appears the connect() method silently swallows all exceptions. It would be better to throw them so that we can fail early.

Publishing Artifacts

Hello - is there a plan to publish the artifacts on some maven repo somwhere ?

ChannelHistoryModule always get blank

Are there any examples with the Channel History? I tried to use both the channel name and channel id, but get nothing back.

I'm trying to do the following, but get an empty list every time:

SlackSession session = SlackSessionFactory.createWebSocketSlackSession("token");
ChannelHistoryModule history = ChannelHistoryModuleFactory.createChannelHistoryModule(session);

session.addMessagePostedListener(new SlackMessagePostedListener()
{
    @Override
    public void onEvent(SlackMessagePosted event, SlackSession session)
    {
      System.out.println(event.getMessageContent()+" timestamp:"+event.getTimestamp());
      ChannelHistoryModule history = ChannelHistoryModuleFactory.createChannelHistoryModule(session);
      System.out.println(history);
      System.out.println("history:");
      System.out.println(history.fetchHistoryOfChannel(event.getChannel().getId()));
      List <SlackMessagePosted> messages = history.fetchHistoryOfChannel(event.getChannel().getId());
      for (int i = 0; i < messages.size(); i++) {
        SlackMessagePosted message=messages.get(i);
                    System.out.println(message.getChannel()+": "+message.getMessageContent()+" sender:"+message.getSender().getUserName());
    }

Jackson or Gson than JSON.simple

Jackson parser is way faster for the processing big size of JSON messages, and Gson is the best for handling small size of JSON message. And JSON.simple library this project has been using is somewhere between those two previous libraries that I mentioned.
Introducing Jackson library can be something this project committers are considering?

Multiple attachments

Hey -- is there a way to add multiple attachments for 1 message? I know the API supports it, and I've noticed SlackJSONAttachmentFormatter.encodeAttachments does accept varargs SlackAttachment, but I couldn't find any support for it in any sendMessage method...

Am I missing something?

Upload newest version to Maven Central

We'd like to use some of the newest features, like coloring for attachments. Unfortunately, the newest version available on Maven Central is only from May, not including some of the latest changes.

It would be awesome if you could upload a new version to Maven Central, so we can easily benefit from the latest changes.

Reply as a Slack bot

I managed to build a bot that receives messages, but couldn't find a way to make it reply to the user who sent it the message (and only that user).

The method:
session.sendMessageOverWebSocket()
only accepts a SlackChannel, while you'd think that it should also accept a "SlackChat" or something like that.

The Slack API supports this functionality.

I'm pretty sure that I'm missing something, because it has to be a very basic functionality, but for some reason I can't find a way to do it.

Help would be very appreciated,
10x

Build is failing.during setup.

Hi,

I tried to import this as existing Gradle project in eclipse but it is failing with below error:-

FAILURE: Build failed with an exception.

  • Where:
    Build file 'LocalPath\simple-slack-api\build.gradle' line: 81

  • What went wrong:
    A problem occurred evaluating root project 'simpleslackapi'.

    Could not find property 'bintray_user' on com.jfrog.bintray.gradle.BintrayExtension_Decorated@4e726a39.

Please help in doing this setup.
Have I missed something?

Thanks,
Pradeep

retrieve attachment

Hello there,
how do I retrieve an attachment?
I have a messagePostedListener, which works fine, but sometimes other bots post attachments and I couldn't figure out yet how to retrieve the attachment and process it.
I tried getJsonSource, but this only returned me a null Object.
getMessageContent returned nothing.

no SlackUser information in SlackChannel?

I was trying to do something like

      // blabla
        SlackSession session = SlackSessionFactory.createWebSocketSlackSession(SLACK_BOT_TOKEN);
        try {
            session.connect();
        } catch (IOException e) {
            // blabla
        }
        SlackChannel slackChannel = session.findChannelById(existingChannelId);
        if (slackChannel == null){
            // throw exception
        }
        Collection<SlackUser> users = slackChannel.getMembers();
        if (users == null || users.isEmpty()){
            // throw exception
        }

        // do something with retrieved user list in the channel

which is basically retrieve channel information from the session, and then get the members info who are in the channel by calling slackChannel.getMembers(). However, it looks like Channel doesn't include any of member information who are joined in the channel.

When I tried with Slack bot API (https://api.slack.com/bot-users), especially rim.start API, JSON response has members field in the each channel's response message, so I thought this library is going to populate the members as well but apparently not? Or am I missing something?

Looking at SlackWebSocketSessionImpl, SlackJSONParsingUtils, and SlackJSONSessionStatusParser, and it seems populating members field in the channel though...

I'm using Spring Boot 1.3.5, and my Maven dependency is getting Jackson 2.6.6. Any help will be appreciated.

ERROR com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl - javax.websocket.DeploymentException: Handshake response not received

Hi,
I am getting the below error while executing the "SlackDirectConnection.java"

ERROR com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl - javax.websocket.DeploymentException: Handshake response not received.
Exception in thread "main" java.lang.NullPointerException
at com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl.openDirectMessageChannel(SlackWebSocketSessionImpl.java:569)
at com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl.getIMChannelForUser(SlackWebSocketSessionImpl.java:123)
at com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl.sendMessageToUser(SlackWebSocketSessionImpl.java:96)
at actions.SendingMessages.sendDirectMessageToAUser(SendingMessages.java:37)
at com.ullink.slack.simpleslackapi.samples.connection.SlackDirectConnection.main(SlackDirectConnection.java:22)

Please let us know how to resolve this.
Thanks in Advance.

SlackChannel.getMembers() is not updated after establishing a connection

Looks like the list of the members of a channel/group is not updated after establishing a connection to Slack. SlackChannel.getMembers() returns only the list of the members that was up-to-date at the time of connection establishment.

Since I need the current information about the participating users of a channel/group I had to implement it by myself using postGenericSlackCommand().

Multiple bots on one server

Hi,
What happens if you create multiple web socket slack sessions (with different auth tokens)? Will that work? Do they have to be created on different ports?
Oliver

Question: Markdown on SlackAttachments

Hi, I am trying to figure it out from the code how the Markdowns work, but I don't see where they are used.

Any example or idea of how to use them?

Thanks
Fer

java.lang.IllegalArgumentException using SlackSessionFactory.createWebSocketSlackSession(String oauth)

Link to change here:

https://github.com/Ullink/simple-slack-api/blob/2019b7810f3aa07cf05464b473ce0e2e40f5cbfa/sources/src/main/java/com/ullink/slack/simpleslackapi/impl/SlackWebSocketSessionImpl.java

The above change eliminates the constructor in the SlackWebSocketSessionImpl class where the user does not need to specify a proxy which resulted in the following error:

Exception in thread "main" java.lang.IllegalArgumentException: Host name may not be null
    at org.apache.http.util.Args.containsNoBlanks(Args.java:81)
    at org.apache.http.HttpHost.<init>(HttpHost.java:80)
    at org.apache.http.HttpHost.<init>(HttpHost.java:99)
    at com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl.<init>(SlackWebSocketSessionImpl.java:192)
    at com.ullink.slack.simpleslackapi.impl.SlackSessionFactory.createWebSocketSlackSession(SlackSessionFactory.java:12)
    at main.MyBot.<init>(MyBot.java:52)
    at main.MyBot.main(MyBot.java:665)

The current version contains only one constructor in the SlackWebSocketSessionImpl class. This constructor, where if null is passed, will cause the application will fail on this line:
this.proxyHost = new HttpHost(proxyAddress, proxyPort);

Meaning if one uses the examples, or only specifies their OAuth token using the SlackSessionFactory.createWebSocketSlackSession(String oauth), this will result in the above error.

Keep-alive mechanism fails when connection is closed (probably due to network error)

In some cases, I get this error. After this occurs, the session no longer responds to messages sent.

[WARNING]
java.lang.IllegalStateException: The connection has been closed.
        at org.glassfish.tyrus.core.TyrusSession.checkConnectionState(TyrusSession.java:518)
        at org.glassfish.tyrus.core.TyrusSession.getBasicRemote(TyrusSession.java:206)
        at com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl$2.run(SlackWebSocketSessionImpl.java:189)

It seems that this case is not handled by the connectionMonitoringThread, and the error causes the session to become invalid.

Caused by: java.lang.NoClassDefFoundError: com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl

I added simpleslackapi-0.5.1.jar in Android Studio libs/ of my project, and tried to use bot to send message to a specific channel:

SlackSession session = SlackSessionFactory.createWebSocketSlackSession(bot_token);
session.connect();

SlackChannel channel = session.findChannelByName(channel_name);
session.sendMessage(message);

My gradle settings is:

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.1'
    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 22
    ....
}

But it failed and the error message below:

                                                                               Process: com.xxxxx.debug, PID: 20156
                                                                               java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                                                   at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                                                   at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                                                   at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                                                   at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                                   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                   at java.lang.Thread.run(Thread.java:818)
                                                                                Caused by: java.lang.NoClassDefFoundError: com.ullink.slack.simpleslackapi.impl.SlackWebSocketSessionImpl
                                                                                   at com.ullink.slack.simpleslackapi.impl.SlackSessionFactory.createWebSocketSlackSession(SlackSessionFactory.java:10)
                                                                                   at com.xxxxx.views.FeedbackActivity$SendMessageTask.doInBackground(XXXXActivity.java:187)
                                                                                   at com.xxxxx.views.FeedbackActivity$SendMessageTask.doInBackground(XXXXActivity.java:175)
                                                                                   at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                                   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
                                                                                   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
                                                                                   at java.lang.Thread.run(Thread.java:818) 

Anything I did wrong? Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.