@@ -15,10 +15,12 @@ import scala.collection.mutable.ListBuffer
1515 */
1616class TwitchChatConnector (override val sourceIdentifier : String ) extends Connector (sourceIdentifier) with WithLogger {
1717 private val twitchChatListener = new TwitchChatListener
18+ private val connectionListener = new TwitchChatConnectListener (onConnect)
1819 private val oauthKey = " oauth"
1920 override protected var requiredCredentialKeys : List [String ] = List (oauthKey)
2021 override protected var optionalCredentialKeys : List [String ] = List ()
2122 private var bot : PircBotX = _
23+ private var status : Option [(Boolean , String )] = None
2224 private val channels = ListBuffer [String ]()
2325
2426 def addMessageEventListener (listener : MessageEvent => Unit ): Unit = {
@@ -63,6 +65,7 @@ class TwitchChatConnector(override val sourceIdentifier: String) extends Connect
6365 .setName(credentials.get.credentialsIdentifier)
6466 .setServerPassword(password.getOrElse(" " ))
6567 .addListener(twitchChatListener)
68+ .addListener(connectionListener)
6669 .buildConfiguration()
6770 } else {
6871 logger error " No credentials set!"
@@ -71,33 +74,47 @@ class TwitchChatConnector(override val sourceIdentifier: String) extends Connect
7174
7275 }
7376
77+ /**
78+ * Gets called by the TwitchChatConnectListener when the bot has connected.
79+ * Saves the passed information into the status variable.
80+ */
81+ private def onConnect (success : Boolean , msg : String ): Unit = {
82+ status.synchronized {
83+ // tell the thread which starts the connector that the status has been reported
84+ status.notify()
85+ status = Some ((success, msg))
86+ }
87+ }
88+
7489 /**
7590 * Starts the connector, e.g. creates a connection with its platform.
7691 */
7792 override def start (): Boolean = {
7893 bot = new PircBotX (getConfig)
7994 startBot()
80- true
8195 }
8296
83- private def startBot (): Unit = {
84-
85- var errorCount = 0
86-
97+ private def startBot (): Boolean = {
8798 new Thread (() => {
8899 bot.startBot()
89100 }).start()
90101
91- while (bot.getState != PircBotX .State .CONNECTED && errorCount < 30 ) {
92- logger info " Waiting while the bot is connecting..."
93- Thread .sleep(100 )
94- errorCount += 1
102+ logger info " Waiting while the bot is connecting and logging in..."
103+ status.synchronized {
104+ status.wait(10000 )
105+ }
106+
107+ if (status.isEmpty) {
108+ logger error " Bot couldn't connect within timeout of 10 seconds."
109+ return false
95110 }
96111
97- if (errorCount >= 30 ) {
98- logger error " Fatal. Unable to start bot."
112+ val (success, msg) = status.get
113+ if (! success) {
114+ logger error s " Bot couldn't connect. Reason: $msg. "
99115 }
100116
117+ success
101118 }
102119
103120 /**
@@ -106,6 +123,7 @@ class TwitchChatConnector(override val sourceIdentifier: String) extends Connect
106123 override def stop (): Boolean = {
107124 bot.sendIRC().quitServer()
108125 bot.close()
126+ status = None
109127 true
110128 }
111129}
0 commit comments