Last active
December 18, 2015 09:59
-
-
Save AyeGill/5765532 to your computer and use it in GitHub Desktop.
Simple clojure IRC interaction.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (require '(org.schwering.irc)) ;available on clojars | |
| ;;There's really no sane default for these values, but for testing purposes it's nice to not need to type them in. Laziness. | |
| ;;These are out here instead of in the function definition so you can rebind them if you want to connect several times with the same credentials | |
| (def default-name "IRC Bot") | |
| (def default-nick "Bot") | |
| (def default-realname "John Robot") | |
| (defn make-connection | |
| "Establish a connection, returns an instance of org.schwering.irc.lib.IRCConnection. Hosts should be an int vector, not an array" | |
| [{:keys [host pass name nick realname ports] :or {name default-name nick default-nick realname default-realname ports [6667] pass ""}}] | |
| (new org.schwering.irc.lib.IRCConnection host (int-array ports) pass nick name realname)) | |
| (defmacro make-listener | |
| "Make a IRCEventListener. Each argument should be a function." | |
| [{:keys [disconnect error invite join kick mode nick notice part ping privmsg quit registered reply topic unknown]}] | |
| (defn mkapp [fn args] | |
| (if fn | |
| `(apply ~fn ~args) | |
| nil)) | |
| `(proxy [org.schwering.irc.lib.IRCEventListener] [] | |
| ~@(map (fn [sym fn] `(~sym [& ~'args] ~(mkapp fn 'args))) | |
| '(onDisconnected onError onInvite onJoin onKick onMode onNick onNotice onPart onPing onPrivmsg onQuit onRegistered onReply onTopic unknown) | |
| [disconnect error invite join kick mode nick notice part ping privmsg quit registered reply topic unknown]))) | |
| ;add listeners to connections with (. connection addIRCEventListener listener) | |
| (defmacro with-connection | |
| "Name is an identifier to use in the events&body as the name of the connection. | |
| connection-info is a map passed to make-connection | |
| events is a vector of vectors of the form [event argslist body], the given event triggers the body with the args | |
| body is the code to be executed once the connection has been set up. The connection is closed at the end" | |
| [name connection-info events & body] | |
| `(let [~name (make-connection ~connection-info) | |
| listen# (make-listener ~(apply hash-map (apply concat (map (fn [[event argslist & body]] `(~(keyword event) (fn ~argslist ~@body))) events))))] | |
| (. ~name addIRCEventListener listen#) | |
| (. ~name connect) | |
| ~@body | |
| (. ~name close))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment