Skip to content

Instantly share code, notes, and snippets.

@DrRibosome
Created August 1, 2015 23:21
Show Gist options
  • Save DrRibosome/14105e14af3aa26a1455 to your computer and use it in GitHub Desktop.
Save DrRibosome/14105e14af3aa26a1455 to your computer and use it in GitHub Desktop.
scala netty irc
package irc
import java.net.URI
import java.util.concurrent.TimeUnit
import io.netty.bootstrap.Bootstrap
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.channel.{ChannelHandlerContext, ChannelHandlerAdapter, ChannelInitializer, EventLoopGroup}
import io.netty.handler.codec.string.{StringDecoder, StringEncoder}
import io.netty.util.CharsetUtil
import scala.util.Random
/**
* super simple irc client
*/
class IRCClient(uri: URI, port: Int, group: EventLoopGroup) {
private val b = new Bootstrap()
.group(group)
.channel(classOf[NioSocketChannel])
.handler(new ChannelInitializer[NioSocketChannel] {
override def initChannel(ch: NioSocketChannel): Unit = {
ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8))
/*ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8))
ch.pipeline().addLast(new ChannelHandlerAdapter {
override def channelRead(ctx: ChannelHandlerContext, msg: scala.Any): Unit = {
msg match {
case s: String => println(s)
}
}
})*/
}
})
private val ch = b.connect(uri.toString, port).sync().channel()
val eventLoop = ch.eventLoop()
sendMsg("NICK mirrorbot")
sendMsg("USER miscuser 0 * :the botman")
private val ping = new Runnable {
val pingMsg = "PING "+uri.toString
override def run(): Unit = {
sendMsg(pingMsg)
}
}
eventLoop.scheduleAtFixedRate(ping, 0, 45, TimeUnit.SECONDS)
/** send arbitrary message*/
def sendMsg(msg: String): Unit = {
ch.eventLoop().execute(new Runnable {
override def run(): Unit = {
Thread.sleep(500)
ch.write(msg)
ch.write("\r\n")
ch.flush()
}
})
}
def joinChannel(ircChannel: String): Unit = {
ch.eventLoop().execute(new Runnable {
override def run(): Unit = {
Thread.sleep(500)
ch.write("JOIN :#")
ch.write(ircChannel)
ch.write("\r\n")
ch.flush()
}
})
}
def sendChannelMsg(msg: String, ircChannel: String): Unit = {
ch.eventLoop().execute(new Runnable {
override def run(): Unit = {
Thread.sleep(500)
ch.write("PRIVMSG #")
ch.write(ircChannel)
ch.write(" :")
ch.write(msg)
ch.write("\r\n")
ch.flush()
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment