-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* feat: send telegram messages task: #12 * fix code format * add test cases and correct service * remove default chat_id * Minor refact in Telegram integration * Update docs for Telegram integration Co-authored-by: akobor <[email protected]>
- Loading branch information
Showing
11 changed files
with
501 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
This file contains 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
18 changes: 18 additions & 0 deletions
18
src/main/kotlin/com/kuvaszuptime/kuvasz/config/handlers/TelegramEventHandlerConfig.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
package com.kuvaszuptime.kuvasz.config.handlers | ||
|
||
import io.micronaut.context.annotation.ConfigurationProperties | ||
import io.micronaut.core.annotation.Introspected | ||
import javax.inject.Singleton | ||
import javax.validation.constraints.NotBlank | ||
|
||
@ConfigurationProperties("handler-config.telegram-event-handler") | ||
@Singleton | ||
@Introspected | ||
class TelegramEventHandlerConfig { | ||
|
||
@NotBlank | ||
var token: String = "" | ||
|
||
@NotBlank | ||
var chatId: String = "" | ||
} |
84 changes: 84 additions & 0 deletions
84
src/main/kotlin/com/kuvaszuptime/kuvasz/handlers/TelegramEventHandler.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
package com.kuvaszuptime.kuvasz.handlers | ||
|
||
import com.kuvaszuptime.kuvasz.config.handlers.TelegramEventHandlerConfig | ||
import com.kuvaszuptime.kuvasz.models.MonitorDownEvent | ||
import com.kuvaszuptime.kuvasz.models.MonitorUpEvent | ||
import com.kuvaszuptime.kuvasz.models.TelegramAPIMessage | ||
import com.kuvaszuptime.kuvasz.models.UptimeMonitorEvent | ||
import com.kuvaszuptime.kuvasz.models.runWhenStateChanges | ||
import com.kuvaszuptime.kuvasz.models.toEmoji | ||
import com.kuvaszuptime.kuvasz.models.toStructuredMessage | ||
import com.kuvaszuptime.kuvasz.services.EventDispatcher | ||
import com.kuvaszuptime.kuvasz.services.TelegramAPIService | ||
import io.micronaut.context.annotation.Context | ||
import io.micronaut.context.annotation.Requires | ||
import io.micronaut.http.HttpResponse | ||
import io.micronaut.http.client.exceptions.HttpClientResponseException | ||
import io.micronaut.scheduling.TaskExecutors | ||
import io.micronaut.scheduling.annotation.ExecuteOn | ||
import io.reactivex.Flowable | ||
import org.slf4j.LoggerFactory | ||
|
||
@Context | ||
@Requires(property = "handler-config.telegram-event-handler.enabled", value = "true") | ||
class TelegramEventHandler( | ||
private val telegramAPIService: TelegramAPIService, | ||
private val telegramEventHandlerConfig: TelegramEventHandlerConfig, | ||
private val eventDispatcher: EventDispatcher | ||
) { | ||
companion object { | ||
private val logger = LoggerFactory.getLogger(TelegramEventHandler::class.java) | ||
} | ||
|
||
init { | ||
subscribeToEvents() | ||
} | ||
|
||
@ExecuteOn(TaskExecutors.IO) | ||
private fun subscribeToEvents() { | ||
eventDispatcher.subscribeToMonitorUpEvents { event -> | ||
logger.debug("A MonitorUpEvent has been received for monitor with ID: ${event.monitor.id}") | ||
event.runWhenStateChanges { telegramAPIService.sendMessage(it.toTelegramMessage()).handleResponse() } | ||
} | ||
eventDispatcher.subscribeToMonitorDownEvents { event -> | ||
logger.debug("A MonitorDownEvent has been received for monitor with ID: ${event.monitor.id}") | ||
event.runWhenStateChanges { telegramAPIService.sendMessage(it.toTelegramMessage()).handleResponse() } | ||
} | ||
} | ||
|
||
private fun UptimeMonitorEvent.toTelegramMessage(): TelegramAPIMessage = | ||
TelegramAPIMessage( | ||
text = "${toEmoji()} ${toHTMLMessage()}", | ||
chat_id = telegramEventHandlerConfig.chatId | ||
) | ||
|
||
private fun Flowable<HttpResponse<String>>.handleResponse() = | ||
subscribe( | ||
{ | ||
logger.debug("A Telegram message to your configured webhook has been successfully sent") | ||
}, | ||
{ ex -> | ||
if (ex is HttpClientResponseException) { | ||
val responseBody = ex.response.getBody(String::class.java) | ||
logger.error("Telegram message cannot be delivered due to an error: $responseBody") | ||
} | ||
} | ||
) | ||
|
||
private fun UptimeMonitorEvent.toHTMLMessage() = | ||
when (this) { | ||
is MonitorUpEvent -> toStructuredMessage().let { details -> | ||
listOfNotNull( | ||
"<b>${details.summary}</b>", | ||
"<i>${details.latency}</i>", | ||
details.previousDownTime.orNull() | ||
) | ||
} | ||
is MonitorDownEvent -> toStructuredMessage().let { details -> | ||
listOfNotNull( | ||
"<b>${details.summary}</b>", | ||
details.previousUpTime.orNull() | ||
) | ||
} | ||
}.joinToString("\n") | ||
} |
12 changes: 12 additions & 0 deletions
12
src/main/kotlin/com/kuvaszuptime/kuvasz/models/TelegramAPIMessage.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
package com.kuvaszuptime.kuvasz.models | ||
|
||
import io.micronaut.core.annotation.Introspected | ||
|
||
@Suppress("ConstructorParameterNaming") | ||
@Introspected | ||
data class TelegramAPIMessage( | ||
val chat_id: String, | ||
val text: String, | ||
val disable_web_page_preview: Boolean = true, | ||
val parse_mode: String = "HTML" | ||
) |
41 changes: 41 additions & 0 deletions
41
src/main/kotlin/com/kuvaszuptime/kuvasz/services/TelegramAPIService.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
package com.kuvaszuptime.kuvasz.services | ||
|
||
import com.kuvaszuptime.kuvasz.config.handlers.TelegramEventHandlerConfig | ||
import com.kuvaszuptime.kuvasz.models.TelegramAPIMessage | ||
import io.micronaut.context.annotation.Requires | ||
import io.micronaut.context.event.ShutdownEvent | ||
import io.micronaut.core.type.Argument | ||
import io.micronaut.http.HttpRequest | ||
import io.micronaut.http.HttpResponse | ||
import io.micronaut.http.client.RxHttpClient | ||
import io.micronaut.runtime.event.annotation.EventListener | ||
import io.reactivex.Flowable | ||
import javax.inject.Inject | ||
import javax.inject.Singleton | ||
|
||
@Singleton | ||
@Requires(property = "handler-config.telegram-event-handler.enabled", value = "true") | ||
class TelegramAPIService @Inject constructor( | ||
telegramEventHandlerConfig: TelegramEventHandlerConfig, | ||
private val httpClient: RxHttpClient | ||
) { | ||
private val url = "https://api.telegram.org/bot" + telegramEventHandlerConfig.token + "/sendMessage" | ||
|
||
companion object { | ||
private const val RETRY_COUNT = 3L | ||
} | ||
|
||
fun sendMessage(message: TelegramAPIMessage): Flowable<HttpResponse<String>> { | ||
val request: HttpRequest<TelegramAPIMessage> = HttpRequest.POST(url, message) | ||
|
||
return httpClient | ||
.exchange(request, Argument.STRING, Argument.STRING) | ||
.retry(RETRY_COUNT) | ||
} | ||
|
||
@EventListener | ||
@Suppress("UNUSED_PARAMETER") | ||
internal fun onShutdownEvent(event: ShutdownEvent) { | ||
httpClient.close() | ||
} | ||
} |
This file contains 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
65 changes: 65 additions & 0 deletions
65
src/test/kotlin/com/kuvaszuptime/kuvasz/config/TelegramEventHandlerConfigTest.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
package com.kuvaszuptime.kuvasz.config | ||
|
||
import io.kotest.assertions.exceptionToMessage | ||
import io.kotest.assertions.throwables.shouldThrow | ||
import io.kotest.core.spec.style.BehaviorSpec | ||
import io.kotest.matchers.string.shouldContain | ||
import io.micronaut.context.ApplicationContext | ||
import io.micronaut.context.env.PropertySource | ||
import io.micronaut.context.exceptions.BeanInstantiationException | ||
|
||
class TelegramEventHandlerConfigTest : BehaviorSpec({ | ||
given("a TelegramEventHandlerConfig bean") { | ||
`when`("there is no API token in the configuration") { | ||
val properties = PropertySource.of( | ||
"test", | ||
mapOf( | ||
"handler-config.telegram-event-handler.enabled" to "true", | ||
"handler-config.telegram-event-handler.chat-id" to "chat-id" | ||
) | ||
) | ||
then("ApplicationContext should throw a BeanInstantiationException") { | ||
val exception = shouldThrow<BeanInstantiationException> { | ||
ApplicationContext.run(properties) | ||
} | ||
exceptionToMessage(exception) shouldContain | ||
"Bean definition [com.kuvaszuptime.kuvasz.handlers.TelegramEventHandler] could not be loaded" | ||
} | ||
} | ||
|
||
`when`("there is no chat ID in the configuration") { | ||
val properties = PropertySource.of( | ||
"test", | ||
mapOf( | ||
"handler-config.telegram-event-handler.enabled" to "true", | ||
"handler-config.telegram-event-handler.token" to "your-token" | ||
) | ||
) | ||
then("ApplicationContext should throw a BeanInstantiationException") { | ||
val exception = shouldThrow<BeanInstantiationException> { | ||
ApplicationContext.run(properties) | ||
} | ||
exceptionToMessage(exception) shouldContain | ||
"Bean definition [com.kuvaszuptime.kuvasz.handlers.TelegramEventHandler] could not be loaded" | ||
} | ||
} | ||
|
||
`when`("chat ID and API token are empty strings") { | ||
val properties = PropertySource.of( | ||
"test", | ||
mapOf( | ||
"handler-config.telegram-event-handler.enabled" to "true", | ||
"handler-config.telegram-event-handler.token" to "", | ||
"handler-config.telegram-event-handler.chat-id" to "" | ||
) | ||
) | ||
then("ApplicationContext should throw a BeanInstantiationException") { | ||
val exception = shouldThrow<BeanInstantiationException> { | ||
ApplicationContext.run(properties) | ||
} | ||
exceptionToMessage(exception) shouldContain | ||
"Bean definition [com.kuvaszuptime.kuvasz.handlers.TelegramEventHandler] could not be loaded" | ||
} | ||
} | ||
} | ||
}) |
Oops, something went wrong.