Removed unnecessary threading (ThreadedModule, etc.)

This commit is contained in:
Erik C. Thauvin 2022-12-07 12:08:15 -08:00
parent e510a77af1
commit 0fba4445f8
24 changed files with 73 additions and 181 deletions

View file

@ -54,7 +54,7 @@
<ID>NestedBlockDepth:EntryLink.kt$EntryLink$private fun setTags(tags: List&lt;String?&gt;)</ID> <ID>NestedBlockDepth:EntryLink.kt$EntryLink$private fun setTags(tags: List&lt;String?&gt;)</ID>
<ID>NestedBlockDepth:FeedsManager.kt$FeedsManager.Companion$@JvmStatic @Throws(IOException::class, FeedException::class) fun loadFeed(entries: Entries, currentFile: String = currentXml): String</ID> <ID>NestedBlockDepth:FeedsManager.kt$FeedsManager.Companion$@JvmStatic @Throws(IOException::class, FeedException::class) fun loadFeed(entries: Entries, currentFile: String = currentXml): String</ID>
<ID>NestedBlockDepth:FeedsManager.kt$FeedsManager.Companion$@JvmStatic fun saveFeed(entries: Entries, currentFile: String = currentXml)</ID> <ID>NestedBlockDepth:FeedsManager.kt$FeedsManager.Companion$@JvmStatic fun saveFeed(entries: Entries, currentFile: String = currentXml)</ID>
<ID>NestedBlockDepth:GoogleSearch.kt$GoogleSearch$override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent)</ID> <ID>NestedBlockDepth:GoogleSearch.kt$GoogleSearch$override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent)</ID>
<ID>NestedBlockDepth:GoogleSearch.kt$GoogleSearch.Companion$@JvmStatic @Throws(ModuleException::class) fun searchGoogle( query: String, apiKey: String?, cseKey: String?, quotaUser: String = ReleaseInfo.PROJECT ): List&lt;Message&gt;</ID> <ID>NestedBlockDepth:GoogleSearch.kt$GoogleSearch.Companion$@JvmStatic @Throws(ModuleException::class) fun searchGoogle( query: String, apiKey: String?, cseKey: String?, quotaUser: String = ReleaseInfo.PROJECT ): List&lt;Message&gt;</ID>
<ID>NestedBlockDepth:LinksManager.kt$LinksManager$override fun commandResponse(channel: String, args: String, event: GenericMessageEvent)</ID> <ID>NestedBlockDepth:LinksManager.kt$LinksManager$override fun commandResponse(channel: String, args: String, event: GenericMessageEvent)</ID>
<ID>NestedBlockDepth:Lookup.kt$Lookup$override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent)</ID> <ID>NestedBlockDepth:Lookup.kt$Lookup$override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent)</ID>
@ -66,7 +66,7 @@
<ID>NestedBlockDepth:TwitterOAuth.kt$TwitterOAuth$@JvmStatic fun main(args: Array&lt;String&gt;)</ID> <ID>NestedBlockDepth:TwitterOAuth.kt$TwitterOAuth$@JvmStatic fun main(args: Array&lt;String&gt;)</ID>
<ID>NestedBlockDepth:Utils.kt$Utils$@JvmStatic fun loadData(file: String, default: Any, logger: Logger, description: String): Any</ID> <ID>NestedBlockDepth:Utils.kt$Utils$@JvmStatic fun loadData(file: String, default: Any, logger: Logger, description: String): Any</ID>
<ID>NestedBlockDepth:Utils.kt$Utils$@JvmStatic fun saveData(file: String, data: Any, logger: Logger, description: String)</ID> <ID>NestedBlockDepth:Utils.kt$Utils$@JvmStatic fun saveData(file: String, data: Any, logger: Logger, description: String)</ID>
<ID>NestedBlockDepth:Weather2.kt$Weather2$override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent)</ID> <ID>NestedBlockDepth:Weather2.kt$Weather2$override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent)</ID>
<ID>NestedBlockDepth:Weather2.kt$Weather2.Companion$@JvmStatic @Throws(ModuleException::class) fun getWeather(query: String, apiKey: String?): List&lt;Message&gt;</ID> <ID>NestedBlockDepth:Weather2.kt$Weather2.Companion$@JvmStatic @Throws(ModuleException::class) fun getWeather(query: String, apiKey: String?): List&lt;Message&gt;</ID>
<ID>PrintStackTrace:TwitterOAuth.kt$TwitterOAuth$ioe</ID> <ID>PrintStackTrace:TwitterOAuth.kt$TwitterOAuth$ioe</ID>
<ID>PrintStackTrace:TwitterOAuth.kt$TwitterOAuth$te</ID> <ID>PrintStackTrace:TwitterOAuth.kt$TwitterOAuth$te</ID>

View file

@ -65,7 +65,7 @@ class FeedReader(private val url: String, val event: GenericMessageEvent) : Runn
event.sendMessage("An error has occurred while parsing the feed: ${e.message}") event.sendMessage("An error has occurred while parsing the feed: ${e.message}")
} catch (e: IOException) { } catch (e: IOException) {
if (logger.isWarnEnabled) logger.warn("Unable to fetch the feed at $url", e) if (logger.isWarnEnabled) logger.warn("Unable to fetch the feed at $url", e)
event.sendMessage("An error has occurred while fetching the feed: ${e.message}") event.sendMessage("An IO error has occurred while fetching the feed: ${e.message}")
} }
} }

View file

@ -176,7 +176,7 @@ class Mobibot(nickname: String, val channel: String, logsDirPath: String, p: Pro
override fun onDisconnect(event: DisconnectEvent?) { override fun onDisconnect(event: DisconnectEvent?) {
event?.let { event?.let {
with(event.getBot<PircBotX>()) { with(event.getBot<PircBotX>()) {
LinksManager.socialManager.notification("$nick disconnected from irc://$serverHostname") LinksManager.socialManager.notification("$nick disconnected from $serverHostname")
seen.add(userChannelDao.getChannel(channel).users) seen.add(userChannelDao.getChannel(channel).users)
} }
} }
@ -202,7 +202,7 @@ class Mobibot(nickname: String, val channel: String, logsDirPath: String, p: Pro
with(event.getBot<PircBotX>()) { with(event.getBot<PircBotX>()) {
if (user.nick == nick) { if (user.nick == nick) {
LinksManager.socialManager.notification( LinksManager.socialManager.notification(
"$nick has joined ${event.channel.name} on irc://$serverHostname" "$nick has joined ${event.channel.name} on $serverHostname"
) )
seen.add(userChannelDao.getChannel(channel).users) seen.add(userChannelDao.getChannel(channel).users)
} else { } else {
@ -215,12 +215,10 @@ class Mobibot(nickname: String, val channel: String, logsDirPath: String, p: Pro
override fun onMessage(event: MessageEvent?) { override fun onMessage(event: MessageEvent?) {
event?.user?.let { user -> event?.user?.let { user ->
val sender = user.nick
val message = event.message
tell.send(event) tell.send(event)
if (message.matches("(?i)${Pattern.quote(event.bot().nick)}:.*".toRegex())) { // mobibot: <command> if (event.message.matches("(?i)${Pattern.quote(event.bot().nick)}:.*".toRegex())) { // mobibot: <command>
if (logger.isTraceEnabled) logger.trace(">>> $sender: $message") if (logger.isTraceEnabled) logger.trace(">>> ${user.nick}: ${event.message}")
val cmds = message.substring(message.indexOf(':') + 1).trim().split(" ".toRegex(), 2) val cmds = event.message.substring(event.bot().nick.length + 1).trim().split(" ".toRegex(), 2)
val cmd = cmds[0].lowercase() val cmd = cmds[0].lowercase()
val args = cmds.lastOrEmpty().trim() val args = cmds.lastOrEmpty().trim()
if (cmd.startsWith(Constants.HELP_CMD)) { // mobibot: help if (cmd.startsWith(Constants.HELP_CMD)) { // mobibot: help
@ -230,10 +228,10 @@ class Mobibot(nickname: String, val channel: String, logsDirPath: String, p: Pro
addons.exec(channel, cmd, args, event) addons.exec(channel, cmd, args, event)
} }
} else if (addons.match(channel, event)) { // Links, e.g.: https://www.example.com/ or L1: , etc. } else if (addons.match(channel, event)) { // Links, e.g.: https://www.example.com/ or L1: , etc.
if (logger.isTraceEnabled) logger.trace(">>> $sender: $message") if (logger.isTraceEnabled) logger.trace(">>> ${user.nick}: ${event.message}")
} }
storeRecap(sender, message, false) storeRecap(user.nick, event.message, false)
seen.add(sender) seen.add(user.nick)
} }
} }
@ -252,7 +250,7 @@ class Mobibot(nickname: String, val channel: String, logsDirPath: String, p: Pro
with(event.getBot<PircBotX>()) { with(event.getBot<PircBotX>()) {
if (user.nick == nick) { if (user.nick == nick) {
LinksManager.socialManager.notification( LinksManager.socialManager.notification(
"$nick has left ${event.channel.name} on irc://$serverHostname" "$nick has left ${event.channel.name} on $serverHostname"
) )
seen.add(userChannelDao.getChannel(channel).users) seen.add(userChannelDao.getChannel(channel).users)
} else { } else {

View file

@ -32,8 +32,6 @@
package net.thauvin.erik.mobibot package net.thauvin.erik.mobibot
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.thauvin.erik.mobibot.entries.EntryLink import net.thauvin.erik.mobibot.entries.EntryLink
import net.thauvin.erik.pinboard.PinboardPoster import net.thauvin.erik.pinboard.PinboardPoster
import java.time.ZoneId import java.time.ZoneId
@ -53,12 +51,8 @@ class Pinboard {
*/ */
fun addPin(ircServer: String, entry: EntryLink) { fun addPin(ircServer: String, entry: EntryLink) {
if (poster.apiToken.isNotBlank()) { if (poster.apiToken.isNotBlank()) {
runBlocking { with(entry) {
launch { poster.addPin(link, title, postedBy(ircServer), formatTags(), date.toTimestamp())
with(entry) {
poster.addPin(link, title, postedBy(ircServer), formatTags(), date.toTimestamp())
}
}
} }
} }
} }
@ -75,12 +69,9 @@ class Pinboard {
*/ */
fun deletePin(entry: EntryLink) { fun deletePin(entry: EntryLink) {
if (poster.apiToken.isNotBlank()) { if (poster.apiToken.isNotBlank()) {
runBlocking { poster.deletePin(entry.link)
launch {
poster.deletePin(entry.link)
}
}
} }
} }
/** /**
@ -88,15 +79,11 @@ class Pinboard {
*/ */
fun updatePin(ircServer: String, oldUrl: String, entry: EntryLink) { fun updatePin(ircServer: String, oldUrl: String, entry: EntryLink) {
if (poster.apiToken.isNotBlank()) { if (poster.apiToken.isNotBlank()) {
runBlocking { with(entry) {
launch { if (oldUrl != link) {
with(entry) { poster.deletePin(oldUrl)
if (oldUrl != link) {
poster.deletePin(oldUrl)
}
poster.addPin(link, title, postedBy(ircServer), formatTags(), date.toTimestamp())
}
} }
poster.addPin(link, title, postedBy(ircServer), formatTags(), date.toTimestamp())
} }
} }
} }
@ -106,8 +93,7 @@ class Pinboard {
*/ */
private fun Date.toTimestamp(): String { private fun Date.toTimestamp(): String {
return ZonedDateTime.ofInstant( return ZonedDateTime.ofInstant(
toInstant().truncatedTo(ChronoUnit.SECONDS), toInstant().truncatedTo(ChronoUnit.SECONDS), ZoneId.systemDefault()
ZoneId.systemDefault()
).format(DateTimeFormatter.ISO_INSTANT) ).format(DateTimeFormatter.ISO_INSTANT)
} }

View file

@ -32,8 +32,6 @@
package net.thauvin.erik.mobibot.commands package net.thauvin.erik.mobibot.commands
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.thauvin.erik.mobibot.FeedReader import net.thauvin.erik.mobibot.FeedReader
import net.thauvin.erik.mobibot.Utils.helpFormat import net.thauvin.erik.mobibot.Utils.helpFormat
import org.pircbotx.hooks.types.GenericMessageEvent import org.pircbotx.hooks.types.GenericMessageEvent
@ -55,11 +53,7 @@ class ChannelFeed(channel: String) : AbstractCommand() {
override fun commandResponse(channel: String, args: String, event: GenericMessageEvent) { override fun commandResponse(channel: String, args: String, event: GenericMessageEvent) {
if (isEnabled()) { if (isEnabled()) {
runBlocking { properties[FEED_PROP]?.let { FeedReader(it, event).run() }
launch {
properties[FEED_PROP]?.let { FeedReader(it, event).run() }
}
}
} }
} }

View file

@ -33,6 +33,7 @@
package net.thauvin.erik.mobibot.commands package net.thauvin.erik.mobibot.commands
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import net.thauvin.erik.mobibot.Utils.bot import net.thauvin.erik.mobibot.Utils.bot
import net.thauvin.erik.mobibot.Utils.helpFormat import net.thauvin.erik.mobibot.Utils.helpFormat
@ -51,10 +52,12 @@ class Cycle : AbstractCommand() {
with(event.bot()) { with(event.bot()) {
if (event.isChannelOp(channel)) { if (event.isChannelOp(channel)) {
runBlocking { runBlocking {
sendIRC().message(channel, "${event.user.nick} asked me to leave. I'll be back!") launch {
userChannelDao.getChannel(channel).send().part() sendIRC().message(channel, "${event.user.nick} asked me to leave. I'll be back!")
delay(wait * 1000L) userChannelDao.getChannel(channel).send().part()
sendIRC().joinChannel(channel) delay(wait * 1000L)
sendIRC().joinChannel(channel)
}
} }
} else { } else {
helpResponse(channel, args, event) helpResponse(channel, args, event)

View file

@ -141,7 +141,7 @@ class Ignore : AbstractCommand() {
override fun setProperty(key: String, value: String) { override fun setProperty(key: String, value: String) {
super.setProperty(key, value) super.setProperty(key, value)
if (IGNORE_PROP == key) { if (IGNORE_PROP == key) {
ignored.addAll(value.split(LinksManager.TAG_MATCH) ignored.addAll(value.split(LinksManager.TAG_MATCH))
} }
} }

View file

@ -45,15 +45,7 @@ class Users : AbstractCommand() {
override val isVisible = true override val isVisible = true
override fun commandResponse(channel: String, args: String, event: GenericMessageEvent) { override fun commandResponse(channel: String, args: String, event: GenericMessageEvent) {
val nicks = mutableListOf<String>()
val ch = event.bot().userChannelDao.getChannel(channel) val ch = event.bot().userChannelDao.getChannel(channel)
ch.users.forEach { event.sendList(ch.users.map { if (it.channelsOpIn.contains(ch)) "@${it.nick}" else it.nick }, 8)
if (it.channelsOpIn.contains(ch)) {
nicks.add("@${it.nick}")
} else {
nicks.add(it.nick)
}
}
event.sendList(nicks, 8)
} }
} }

View file

@ -37,7 +37,7 @@ import java.time.LocalDateTime
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
/** /**
* The `TellMessage` class. * Tell Message.
*/ */
class TellMessage( class TellMessage(
/** /**

View file

@ -46,12 +46,12 @@ import java.net.http.HttpClient
import java.net.http.HttpRequest import java.net.http.HttpRequest
import java.net.http.HttpResponse import java.net.http.HttpResponse
class ChatGpt : ThreadedModule() { class ChatGpt : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(ChatGpt::class.java) private val logger: Logger = LoggerFactory.getLogger(ChatGpt::class.java)
override val name = "ChatGPT" override val name = "ChatGPT"
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) { override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (args.isNotBlank()) { if (args.isNotBlank()) {
try { try {
event.sendMessage( event.sendMessage(

View file

@ -46,7 +46,7 @@ import java.io.IOException
/** /**
* The Cryptocurrency Prices module. * The Cryptocurrency Prices module.
*/ */
class CryptoPrices : ThreadedModule() { class CryptoPrices : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(CryptoPrices::class.java) private val logger: Logger = LoggerFactory.getLogger(CryptoPrices::class.java)
override val name = "CryptoPrices" override val name = "CryptoPrices"
@ -55,7 +55,7 @@ class CryptoPrices : ThreadedModule() {
* Returns the cryptocurrency market price from * Returns the cryptocurrency market price from
* [Coinbase](https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-prices#get-spot-price). * [Coinbase](https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-prices#get-spot-price).
*/ */
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) { override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (CURRENCIES.isEmpty()) { if (CURRENCIES.isEmpty()) {
try { try {
loadCurrencies() loadCurrencies()

View file

@ -52,7 +52,7 @@ import java.util.TreeMap
/** /**
* The CurrencyConverter module. * The CurrencyConverter module.
*/ */
class CurrencyConverter : ThreadedModule() { class CurrencyConverter : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(CurrencyConverter::class.java) private val logger: Logger = LoggerFactory.getLogger(CurrencyConverter::class.java)
override val name = "CurrencyConverter" override val name = "CurrencyConverter"
@ -71,7 +71,7 @@ class CurrencyConverter : ThreadedModule() {
/** /**
* Converts the specified currencies. * Converts the specified currencies.
*/ */
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) { override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
reload() reload()
if (SYMBOLS.isEmpty()) { if (SYMBOLS.isEmpty()) {

View file

@ -54,7 +54,7 @@ import java.net.URL
/** /**
* The GoogleSearch module. * The GoogleSearch module.
*/ */
class GoogleSearch : ThreadedModule() { class GoogleSearch : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(GoogleSearch::class.java) private val logger: Logger = LoggerFactory.getLogger(GoogleSearch::class.java)
override val name = "GoogleSearch" override val name = "GoogleSearch"
@ -62,7 +62,7 @@ class GoogleSearch : ThreadedModule() {
/** /**
* Searches Google. * Searches Google.
*/ */
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) { override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (args.isNotBlank()) { if (args.isNotBlank()) {
try { try {
val results = searchGoogle( val results = searchGoogle(

View file

@ -31,8 +31,6 @@
*/ */
package net.thauvin.erik.mobibot.modules package net.thauvin.erik.mobibot.modules
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.thauvin.erik.jokeapi.exceptions.HttpErrorException import net.thauvin.erik.jokeapi.exceptions.HttpErrorException
import net.thauvin.erik.jokeapi.exceptions.JokeException import net.thauvin.erik.jokeapi.exceptions.JokeException
import net.thauvin.erik.jokeapi.getJoke import net.thauvin.erik.jokeapi.getJoke
@ -52,21 +50,15 @@ import java.io.IOException
/** /**
* The Joke module. * The Joke module.
*/ */
class Joke : ThreadedModule() { class Joke : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(Joke::class.java) private val logger: Logger = LoggerFactory.getLogger(Joke::class.java)
override val name = "Joke" override val name = "Joke"
override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
runBlocking {
launch { run(channel, cmd, args, event) }
}
}
/** /**
* Returns a random joke from [JokeAPI](https://v2.jokeapi.dev/). * Returns a random joke from [JokeAPI](https://v2.jokeapi.dev/).
*/ */
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) { override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
with(event.bot()) { with(event.bot()) {
try { try {
randomJoke().forEach { randomJoke().forEach {
@ -92,12 +84,8 @@ class Joke : ThreadedModule() {
@Throws(ModuleException::class) @Throws(ModuleException::class)
fun randomJoke(): List<Message> { fun randomJoke(): List<Message> {
return try { return try {
val messages = mutableListOf<Message>()
val joke = getJoke(safe = true, type = Type.SINGLE, splitNewLine = true) val joke = getJoke(safe = true, type = Type.SINGLE, splitNewLine = true)
joke.joke.forEach { joke.joke.map { PublicMessage(it, Colors.CYAN) }
messages.add(PublicMessage(it, Colors.CYAN))
}
messages
} catch (e: JokeException) { } catch (e: JokeException) {
throw ModuleException("randomJoke(): ${e.additionalInfo}", e.message, e) throw ModuleException("randomJoke(): ${e.additionalInfo}", e.message, e)
} catch (e: HttpErrorException) { } catch (e: HttpErrorException) {

View file

@ -93,7 +93,7 @@ class Mastodon : SocialModule() {
private const val MASTODON_CMD = "mastodon" private const val MASTODON_CMD = "mastodon"
/** /**
* Toots on Mastodon. * Post on Mastodon.
*/ */
@JvmStatic @JvmStatic
@Throws(ModuleException::class) @Throws(ModuleException::class)

View file

@ -52,7 +52,7 @@ import java.net.URL
/** /**
* The StockQuote module. * The StockQuote module.
*/ */
class StockQuote : ThreadedModule() { class StockQuote : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(StockQuote::class.java) private val logger: Logger = LoggerFactory.getLogger(StockQuote::class.java)
override val name = "StockQuote" override val name = "StockQuote"
@ -60,7 +60,7 @@ class StockQuote : ThreadedModule() {
/** /**
* Returns the specified stock quote from Alpha Vantage. * Returns the specified stock quote from Alpha Vantage.
*/ */
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) { override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (args.isNotBlank()) { if (args.isNotBlank()) {
try { try {
val messages = getQuote(args, properties[ALPHAVANTAGE_API_KEY_PROP]) val messages = getQuote(args, properties[ALPHAVANTAGE_API_KEY_PROP])

View file

@ -1,58 +0,0 @@
/*
* ThreadedModule.kt
*
* Copyright (c) 2004-2022, Erik C. Thauvin (erik@thauvin.net)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of this project nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.thauvin.erik.mobibot.modules
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.pircbotx.hooks.types.GenericMessageEvent
/**
* The `ThreadedModule` class.
*/
abstract class ThreadedModule : AbstractModule() {
override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (isEnabled && event.message.isNotEmpty()) {
runBlocking {
launch {
run(channel, cmd, args, event)
}
}
} else {
helpResponse(event)
}
}
/**
* Runs the thread.
*/
abstract fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent)
}

View file

@ -88,7 +88,7 @@ class Twitter : SocialModule() {
private const val TWITTER_CMD = "twitter" private const val TWITTER_CMD = "twitter"
/** /**
* Tweets on Twitter. * Post on Twitter.
*/ */
@JvmStatic @JvmStatic
@Throws(ModuleException::class) @Throws(ModuleException::class)

View file

@ -54,7 +54,7 @@ import kotlin.math.roundToInt
/** /**
* The `Weather2` module. * The `Weather2` module.
*/ */
class Weather2 : ThreadedModule() { class Weather2 : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(Weather2::class.java) private val logger: Logger = LoggerFactory.getLogger(Weather2::class.java)
override val name = "Weather" override val name = "Weather"
@ -62,7 +62,7 @@ class Weather2 : ThreadedModule() {
/** /**
* Fetches the weather data from a specific city. * Fetches the weather data from a specific city.
*/ */
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) { override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (args.isNotBlank()) { if (args.isNotBlank()) {
try { try {
val messages = getWeather(args, properties[OWM_API_KEY_PROP]) val messages = getWeather(args, properties[OWM_API_KEY_PROP])

View file

@ -43,7 +43,7 @@ import org.slf4j.LoggerFactory
import java.io.IOException import java.io.IOException
import java.net.URL import java.net.URL
class WolframAlpha : ThreadedModule() { class WolframAlpha : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(WolframAlpha::class.java) private val logger: Logger = LoggerFactory.getLogger(WolframAlpha::class.java)
override val name = "WolframAlpha" override val name = "WolframAlpha"
@ -56,7 +56,7 @@ class WolframAlpha : ThreadedModule() {
} }
} }
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) { override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (args.isNotBlank()) { if (args.isNotBlank()) {
try { try {
val query = args.trim().split("units=", limit = 2, ignoreCase = true) val query = args.trim().split("units=", limit = 2, ignoreCase = true)

View file

@ -110,8 +110,8 @@ class SocialManager {
*/ */
fun shutdown() { fun shutdown() {
timer.cancel() timer.cancel()
for (index in entries) { entries.forEach {
postEntry(index) postEntry(it)
} }
} }
} }

View file

@ -32,18 +32,16 @@
package net.thauvin.erik.mobibot.social package net.thauvin.erik.mobibot.social
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.thauvin.erik.mobibot.commands.links.LinksManager import net.thauvin.erik.mobibot.commands.links.LinksManager
import net.thauvin.erik.mobibot.entries.EntriesUtils.toLinkLabel import net.thauvin.erik.mobibot.entries.EntriesUtils.toLinkLabel
import net.thauvin.erik.mobibot.entries.EntryLink import net.thauvin.erik.mobibot.entries.EntryLink
import net.thauvin.erik.mobibot.modules.AbstractModule
import net.thauvin.erik.mobibot.modules.ModuleException import net.thauvin.erik.mobibot.modules.ModuleException
import net.thauvin.erik.mobibot.modules.ThreadedModule
import org.pircbotx.hooks.types.GenericMessageEvent import org.pircbotx.hooks.types.GenericMessageEvent
import org.slf4j.Logger import org.slf4j.Logger
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
abstract class SocialModule : ThreadedModule() { abstract class SocialModule : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(SocialManager::class.java) private val logger: Logger = LoggerFactory.getLogger(SocialManager::class.java)
abstract val handle: String? abstract val handle: String?
@ -56,15 +54,11 @@ abstract class SocialModule : ThreadedModule() {
*/ */
fun notification(msg: String) { fun notification(msg: String) {
if (isEnabled && !handle.isNullOrBlank()) { if (isEnabled && !handle.isNullOrBlank()) {
runBlocking { try {
launch { post(message = msg, isDm = true)
try { if (logger.isDebugEnabled) logger.debug("Notified $handle on $name: $msg")
post(message = msg, isDm = true) } catch (e: ModuleException) {
if (logger.isDebugEnabled) logger.debug("Notified $handle on $name: $msg") if (logger.isWarnEnabled) logger.warn("Failed to notify $handle on $name: $msg", e)
} catch (e: ModuleException) {
if (logger.isWarnEnabled) logger.warn("Failed to notify $handle on $name: $msg", e)
}
}
} }
} }
} }
@ -76,25 +70,21 @@ abstract class SocialModule : ThreadedModule() {
*/ */
fun postEntry(index: Int) { fun postEntry(index: Int) {
if (isAutoPost && LinksManager.entries.links.size >= index) { if (isAutoPost && LinksManager.entries.links.size >= index) {
runBlocking { try {
launch { if (logger.isDebugEnabled) {
try { logger.debug("Posting {} to $name.", index.toLinkLabel())
if (logger.isDebugEnabled) {
logger.debug("Posting {} to $name.", index.toLinkLabel())
}
post(message = formatEntry(LinksManager.entries.links[index]), isDm = false)
} catch (e: ModuleException) {
if (logger.isWarnEnabled) logger.warn(
"Failed to post entry ${index.toLinkLabel()} on $name.",
e
)
}
} }
post(message = formatEntry(LinksManager.entries.links[index]), isDm = false)
} catch (e: ModuleException) {
if (logger.isWarnEnabled) logger.warn(
"Failed to post entry ${index.toLinkLabel()} on $name.",
e
)
} }
} }
} }
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) { override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
try { try {
event.respond(post("$args (by ${event.user.nick} on $channel)", false)) event.respond(post("$args (by ${event.user.nick} on $channel)", false))
} catch (e: ModuleException) { } catch (e: ModuleException) {

View file

@ -40,7 +40,6 @@ import assertk.assertions.isFalse
import assertk.assertions.isTrue import assertk.assertions.isTrue
import assertk.assertions.prop import assertk.assertions.prop
import assertk.assertions.size import assertk.assertions.size
import assertk.assertions.startsWith
import com.rometools.rome.feed.synd.SyndCategory import com.rometools.rome.feed.synd.SyndCategory
import com.rometools.rome.feed.synd.SyndCategoryImpl import com.rometools.rome.feed.synd.SyndCategoryImpl
import org.testng.annotations.Test import org.testng.annotations.Test

View file

@ -1,9 +1,9 @@
#Generated by the Semver Plugin for Gradle #Generated by the Semver Plugin for Gradle
#Wed Dec 07 02:53:01 PST 2022 #Sat Dec 10 10:16:56 PST 2022
version.buildmeta=857 version.buildmeta=874
version.major=0 version.major=0
version.minor=8 version.minor=8
version.patch=0 version.patch=0
version.prerelease=rc version.prerelease=rc
version.project=mobibot version.project=mobibot
version.semver=0.8.0-rc+857 version.semver=0.8.0-rc+874