Giter Site home page Giter Site logo

simple-slack-api's Introduction

Etat du build

Simple Slack API

This library allows an aplication 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.

Short example

Slack connection :

The connection is made through the SlackSessionFactory class :

Direct connection :

SlackSession session = SlackSessionFactory.
  createWebSocketSlackSession("authenticationtoken");
session.connect();

Through a proxy :

SlackSession session = SlackSessionFactory.
  createWebSocketSlackSession("authenticationtoken", Proxy.Type.HTTP, "myproxy", 1234);
session.connect();

Listening to messages :

Slack messages can be retrieved by attaching a SlackMessageListener to the session provided by the factory :

  session.addMessagePostedListener(new SlackMessagePostedListener()
  {
      @Override
      public void onEvent(SlackMessagePosted event, SlackSession session)
      {
          session.sendMessageOverWebSocket(session.findChannelByName("general"), "Message sent : " + event.getMessageContent(), null);
      }
  });

(Since v0.4.0, lambda friendly version)

session.addMessagePostedListener((e, s) 
  -> s.sendMessageOverWebSocket(s.findChannelByName("general"), "Message sent : " + e.getMessageContent(), null));

Message operation :

The SlackSession interface provides various methods to send/modify and delete messages on a given channel :

SlackMessageHandle sendMessage(SlackChannel channel, String message, SlackAttachment attachment);
SlackMessageHandle sendMessage(SlackChannel channel, String message, SlackAttachment attachment, SlackChatConfiguration chatConfiguration);
SlackMessageHandle updateMessage(String timeStamp, SlackChannel channel, String message);
SlackMessageHandle deleteMessage(String timeStamp, SlackChannel channel)

(Since v0.4.3, emoji reactions on channel messages)

The SlackSession interface provides a method to add an emoji reaction to a message on a given channel :

SlackMessageHandle addReactionToMessage(SlackChannel channel, String messageTimeStamp, String emojiCode);

Full example :

Here's a full example with an echoing bot using this library :

	public static void main(String[] args) {
		final SlackSession session = SlackSessionFactory.createWebSocketSlackSession(BOTONE_TOKEN);

		session.addMessagePostedListener(createMessagePostedListener());
		session.connect();

		while (true) {
			Thread.sleep(1000);
		}
	}
	
	private SlackMessagePostedListener createMessagePostedListener() {
		return (event, session1) -> {
			if (event.getSender().getId().equals(session1.sessionPersona().getId())) { return; }

			//let's send a message
			final SlackChannel responseChannel = event.getChannel();
			session1.joinChannel(responseChannel.getName());
			final SlackMessageHandle response = session1.sendMessage( 
					responseChannel, 
					event.getMessageContent(), 
					null);
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				LOGGER.error("error when sleeping", e);
			}

			//2 secs later, let's update the message (I can only update my own messages)
			final SlackMessageHandle updated = session1.updateMessage( 
					timestamp(response.getReply()), 
					responseChannel, 
					event.getMessageContent() + " UPDATED" 
			);

			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				LOGGER.error("error when sleeping", e);
			}
			//2 secs later, let's now delete the message (I can only delete my own messages)
			session1.deleteMessage( 
					timestamp(response.getReply()), 
					responseChannel);

		};
	}

	private String timestamp(final SlackReply reply) {
		if (reply instanceof GenericSlackReply) {
			return timestamp((GenericSlackReply) reply);
		}
		throw new IllegalArgumentException(reply + " is not a " + GenericSlackReply.class);
	}

	private String timestamp(final GenericSlackReply reply) {
		return (String) reply.getPlainAnswer().get("ts");
	}
}	

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
  • 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)

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

(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 rsquelbut avatar kindofwhat avatar vernaillen avatar ccomandini avatar hfoxy avatar dseebacher avatar gluck avatar janvidar avatar ja-ko avatar jamesbarnes88 avatar jstanier avatar kushal avatar redcraft avatar georges-gomes avatar hcherndon avatar

Watchers

 avatar James Cloos avatar

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.