Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
madhead committed Jan 14, 2023
1 parent fff9701 commit e12048c
Show file tree
Hide file tree
Showing 9 changed files with 33 additions and 25 deletions.
5 changes: 4 additions & 1 deletion .deploy/lambda/lib/JProfByBotStack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export class JProfByBotStack extends cdk.Stack {
code: lambda.Code.fromAsset('../../pins/unpin/build/libs/jprof_by_bot-pins-unpin-all.jar'),
handler: 'by.jprof.telegram.bot.pins.unpin.Handler',
environment: {
'JAVA_TOOL_OPTIONS': '-Dsoftware.amazon.awssdk.http.async.service.impl=software.amazon.awssdk.http.nio.netty.NettySdkAsyncHttpService',
'LOG_THRESHOLD': 'INFO',
'TABLE_PINS': pinsTable.tableName,
'TOKEN_TELEGRAM_BOT': props.telegramToken,
Expand Down Expand Up @@ -160,10 +161,11 @@ export class JProfByBotStack extends cdk.Stack {
timeout: lambdaWebhookTimeout,
maxEventAge: cdk.Duration.minutes(5),
retryAttempts: 0,
memorySize: 512,
memorySize: 768,
code: lambda.Code.fromAsset('../../launchers/lambda/build/libs/jprof_by_bot-launchers-lambda-all.jar'),
handler: 'by.jprof.telegram.bot.launchers.lambda.JProf',
environment: {
'JAVA_TOOL_OPTIONS': '-Dsoftware.amazon.awssdk.http.async.service.impl=software.amazon.awssdk.http.nio.netty.NettySdkAsyncHttpService',
'LOG_THRESHOLD': 'INFO',
'TABLE_VOTES': votesTable.tableName,
'TABLE_YOUTUBE_CHANNELS_WHITELIST': youtubeChannelsWhitelistTable.tableName,
Expand Down Expand Up @@ -195,6 +197,7 @@ export class JProfByBotStack extends cdk.Stack {
code: lambda.Code.fromAsset('../../english/urban-dictionary-daily/build/libs/jprof_by_bot-english-urban-dictionary-daily-all.jar'),
handler: 'by.jprof.telegram.bot.english.urban_dictionary_daily.Handler',
environment: {
'JAVA_TOOL_OPTIONS': '-Dsoftware.amazon.awssdk.http.async.service.impl=software.amazon.awssdk.http.nio.netty.NettySdkAsyncHttpService',
'LOG_THRESHOLD': 'INFO',
'TABLE_URBAN_WORDS_OF_THE_DAY': urbanWordsOfTheDayTable.tableName,
'TABLE_LANGUAGE_ROOMS': languageRoomsTable.tableName,
Expand Down
6 changes: 6 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ subprojects {
withType<Jar> {
// Workaround for https://stackoverflow.com/q/42174572/750510
archiveBaseName.set(rootProject.name + "-" + this.project.path.removePrefix(":").replace(":", "-"))
manifest {
attributes["Multi-Release"] = true
}
}
withType<Test> {
useJUnitPlatform {
Expand All @@ -40,6 +43,9 @@ subprojects {
}
withType<ShadowJar> {
transform(Log4j2PluginsCacheFileTransformer::class.java)
manifest {
attributes["Multi-Release"] = true
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@ import dev.inmo.tgbotapi.requests.abstracts.MultipartFile
import dev.inmo.tgbotapi.types.chat.member.AdministratorChatMember
import dev.inmo.tgbotapi.types.message.MarkdownV2ParseMode
import dev.inmo.tgbotapi.types.update.abstracts.Update
import dev.inmo.tgbotapi.utils.PreviewFeature
import dev.inmo.tgbotapi.utils.RiskFeature
import io.ktor.utils.io.streams.asInput
import org.apache.logging.log4j.LogManager

@OptIn(PreviewFeature::class, RiskFeature::class)
class EnglishCommandUpdateProcessor(
private val languageRoomDAO: LanguageRoomDAO,
private val bot: RequestsExecutor,
Expand All @@ -30,7 +33,7 @@ class EnglishCommandUpdateProcessor(
}

override suspend fun process(update: Update) {
val update = update.asBaseMessageUpdate() ?: return
@Suppress("NAME_SHADOWING") val update = update.asBaseMessageUpdate() ?: return
val message = update.data.asContentMessage() ?: return
val content = message.content.asTextContent() ?: return
val (_, argument) = (content.textSources + null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import dev.inmo.tgbotapi.types.message.textsources.link
import dev.inmo.tgbotapi.types.message.textsources.regular
import dev.inmo.tgbotapi.types.message.textsources.underline
import dev.inmo.tgbotapi.types.update.abstracts.Update
import dev.inmo.tgbotapi.utils.PreviewFeature
import java.time.Duration
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
Expand All @@ -34,6 +35,7 @@ import kotlinx.coroutines.supervisorScope
import kotlinx.coroutines.time.withTimeoutOrNull
import org.apache.logging.log4j.LogManager

@OptIn(PreviewFeature::class)
class ExplainerUpdateProcessor(
private val languageRoomDAO: LanguageRoomDAO,
private val urbanDictionaryClient: UrbanDictionaryClient,
Expand All @@ -45,7 +47,7 @@ class ExplainerUpdateProcessor(
}

override suspend fun process(update: Update) {
val update = update.asBaseMessageUpdate() ?: return
@Suppress("NAME_SHADOWING") val update = update.asBaseMessageUpdate() ?: return
val roomId = update.data.chat.id
val message = update.data.asContentMessage() ?: return
val content = message.content.asTextContent() ?: return
Expand All @@ -58,7 +60,7 @@ class ExplainerUpdateProcessor(

val emphasizedWords = extractEmphasizedWords(content)

logger.debug("Emphasized words: $emphasizedWords")
logger.info("Emphasized words: $emphasizedWords")

val explanations = fetchExplanations(emphasizedWords)

Expand Down Expand Up @@ -134,7 +136,7 @@ class ExplainerUpdateProcessor(

private fun StringBuilder.dictionaryDotDevExplanations(dictionaryDotDevExplanations: Collection<Word>?) {
dictionaryDotDevExplanations?.let { definitions ->
definitions.take(3).forEachIndexed { index, definition ->
definitions.take(3).forEachIndexed { _, definition ->
val link = definition.sourceUrls?.firstOrNull()

if (link != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ import dev.inmo.tgbotapi.extensions.utils.asContentMessage
import dev.inmo.tgbotapi.extensions.utils.asTextContent
import dev.inmo.tgbotapi.requests.abstracts.MultipartFile
import dev.inmo.tgbotapi.types.update.abstracts.Update
import dev.inmo.tgbotapi.utils.PreviewFeature
import io.ktor.utils.io.streams.asInput
import kotlin.random.Random
import org.apache.logging.log4j.LogManager

@OptIn(PreviewFeature::class)
class MotherfuckingUpdateProcessor(
private val languageRoomDAO: LanguageRoomDAO,
private val bot: RequestsExecutor,
Expand All @@ -26,7 +28,7 @@ class MotherfuckingUpdateProcessor(
}

override suspend fun process(update: Update) {
val update = update.asBaseMessageUpdate() ?: return
@Suppress("NAME_SHADOWING") val update = update.asBaseMessageUpdate() ?: return
val roomId = update.data.chat.id
val message = update.data.asContentMessage() ?: return
val content = message.content.asTextContent() ?: return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ import dev.inmo.tgbotapi.extensions.utils.asContentMessage
import dev.inmo.tgbotapi.extensions.utils.asTextContent
import dev.inmo.tgbotapi.types.message.MarkdownV2
import dev.inmo.tgbotapi.types.update.abstracts.Update
import dev.inmo.tgbotapi.utils.PreviewFeature
import java.time.LocalDate
import org.apache.logging.log4j.LogManager

@OptIn(PreviewFeature::class)
class UrbanWordOfTheDayUpdateProcessor(
private val languageRoomDAO: LanguageRoomDAO,
private val urbanWordOfTheDayDAO: UrbanWordOfTheDayDAO,
Expand All @@ -27,7 +29,7 @@ class UrbanWordOfTheDayUpdateProcessor(
}

override suspend fun process(update: Update) {
val update = update.asBaseMessageUpdate() ?: return
@Suppress("NAME_SHADOWING") val update = update.asBaseMessageUpdate() ?: return
val roomId = update.data.chat.id
val message = update.data.asContentMessage() ?: return
val content = message.content.asTextContent() ?: return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ import dev.inmo.tgbotapi.extensions.utils.asContentMessage
import dev.inmo.tgbotapi.extensions.utils.asTextContent
import dev.inmo.tgbotapi.requests.abstracts.MultipartFile
import dev.inmo.tgbotapi.types.update.abstracts.Update
import dev.inmo.tgbotapi.utils.PreviewFeature
import io.ktor.utils.io.streams.asInput
import org.apache.logging.log4j.LogManager

@OptIn(PreviewFeature::class)
class WhatWordUpdateProcessor(
private val languageRoomDAO: LanguageRoomDAO,
private val bot: RequestsExecutor,
Expand All @@ -23,7 +25,7 @@ class WhatWordUpdateProcessor(
}

override suspend fun process(update: Update) {
val update = update.asBaseMessageUpdate() ?: return
@Suppress("NAME_SHADOWING") val update = update.asBaseMessageUpdate() ?: return
val roomId = update.data.chat.id
val message = update.data.asContentMessage() ?: return
val content = message.content.asTextContent() ?: return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,22 +25,15 @@ class SupportSuccessfulPaymentUpdateProcessor(
}

override suspend fun process(update: Update) {
logger.info("1")
val message = update.asMessageUpdate()?.data?.asPossiblyPaymentMessage() ?: return
logger.info("2")
val user = (message as? FromUser)?.user ?: return
logger.info("3")
val payment = (message.paymentInfo as? SuccessfulPaymentEvent)?.payment ?: return
logger.info("4")
val payload = try {
logger.info("5")
json.decodeFromString<Payload>(payment.invoicePayload) as SupportPayload
} catch (_: Exception) {
logger.info("6")
return
}

logger.info("7")
bot.reply(message, "Thank you for the donation!")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class YouTubeUpdateProcessor(
companion object {
private val logger = LogManager.getLogger(YouTubeUpdateProcessor::class.java)!!
private val linkRegex =
"^.*((youtu.be/)|(v/)|(/u/\\w/)|(embed/)|(watch\\?))\\??v?=?([^#&?]*).*".toRegex()
"https?://(?:m.)?(?:www\\.)?youtu(?:\\.be/|(?:be-nocookie|be)\\.com/(?:watch|\\w+\\?(?:feature=\\w+.\\w+&)?v=|v/|e/|embed/|user/(?:[\\w#]+/)+))(?<id>[^&#?\\n]+)".toRegex()
private const val ACCEPTED_DISPLAY_LEN = 500
}

Expand All @@ -55,11 +55,9 @@ class YouTubeUpdateProcessor(
}

private suspend fun processMessage(message: Message) {
logger.debug("Processing message: {}", message)

val youTubeVideos = extractYoutubeVideos(message) ?: return

logger.debug("YouTube videos: {}", youTubeVideos)
logger.info("Detected {} YouTube videos: {}", youTubeVideos.size, youTubeVideos)

supervisorScope {
youTubeVideos
Expand All @@ -76,20 +74,17 @@ class YouTubeUpdateProcessor(
.mapNotNull {
(it as? URLTextSource)?.source ?: (it as? TextLinkTextSource)?.url
}
.mapNotNull {
linkRegex.matchEntire(it)?.destructured
.mapNotNull { url ->
linkRegex.matchEntire(url)?.groups?.get("id")?.value?.takeUnless { it.isBlank() }
}
.map { (_, _, _, _, _, _, id) -> id }
}
}

private suspend fun replyToYouTubeVideo(video: String, message: Message) {
logger.debug("YouTube video ID: {}", video)

val response = withContext(Dispatchers.IO) {
youTube.videos().list(listOf("snippet", "statistics")).setId(listOf(video)).execute()
}
val videoDetails = response.items.first()
val videoDetails = response.items.firstOrNull() ?: return
val snippet = videoDetails.snippet
val channelId = snippet.channelId

Expand Down

0 comments on commit e12048c

Please sign in to comment.