danboo/danboo.own

97 lines
2.4 KiB
Scala
Raw Normal View History

2024-08-10 19:12:42 +03:00
use std, functional, types, date
include "own-modules/telegram-bot/TelegramBot.own"
include "config.own"
include "database.own"
include "DanbooruApi.own"
bot = new TelegramBot(config.telegram.token)
api = new DanbooruApi(config.danbooru.auth)
// Get posts from API
posts = api.getPosts(config.danbooru.params)
// Skip previously processed
lastPostId = getLastPostId()
skipToPostId = lastPostId
filteredPosts = stream(posts)
2024-08-11 18:30:44 +03:00
.filter(def(p) = p.isImage())
2024-08-10 19:12:42 +03:00
.sortBy(def(p) = p.id)
.dropWhile(def(p) = p.id <= skipToPostId)
.peek(def(p) = lastPostId = p.id)
.toArray()
setLastPostId(lastPostId)
// Process
blacklistTags = config.danbooru.blacklistTags
for post : filteredPosts {
// Check global blacklist
2024-08-11 18:30:44 +03:00
blacklisted = post.containsTags(blacklistTags)
2024-08-10 19:12:42 +03:00
if (blacklisted) {
continue
}
2024-08-11 18:30:44 +03:00
score = post.getScore()
2024-08-10 19:12:42 +03:00
for target : config.targets {
minScore = target.minScore ?? 0
if (score < minScore) continue
2024-08-11 18:30:44 +03:00
matched = post.containsTags(target.tags)
2024-08-10 19:12:42 +03:00
if (!matched) continue
2024-08-11 18:30:44 +03:00
url = "https://danbooru.donmai.us/posts/" + post.id
2024-08-10 19:12:42 +03:00
println "%s: %s -> %s".sprintf(newDate(), url, target.name)
caption = getCaption(post)
2024-08-11 18:30:44 +03:00
buttonText = sprintf("%s 📈%d", post.getResolution(), score)
2024-08-10 19:12:42 +03:00
markup = jsonencode({"inline_keyboard": [
[{"text":buttonText, "url":url}]
]})
bot.invoke("sendPhoto", {
"chat_id": target.chat,
"message_thread_id": target.topic,
2024-08-11 18:30:44 +03:00
"photo": post.getImageUrl(),
2024-08-10 19:12:42 +03:00
"parse_mode": "html",
"caption": caption,
"reply_markup": markup
}, def(r) {
if !r.contains("wrong file identifier") return 1
bot.invoke("sendPhoto", {
"chat_id": target.chat,
"message_thread_id": target.topic,
2024-08-11 18:30:44 +03:00
"photo": post.getSampleImageUrl(),
2024-08-10 19:12:42 +03:00
"parse_mode": "html",
"caption": "small " + caption,
"reply_markup": markup
}, def(r) = 1)
})
sleep(2000)
}
}
closeDB()
thread(def() {
sleep(2000)
exit(0)
})
// Helpers
def strToHashtag(str) =
"#" + str.toLowerCase()
.replaceAll("[^a-z_0-9\s]", "")
.replaceAll("\s+", "_")
def getCaption(post) {
2024-08-11 18:30:44 +03:00
characters = post.getCharacters()
2024-08-10 19:12:42 +03:00
if characters.length > 0 {
charactersHashTag = map(characters, ::strToHashtag).joinToString(" ")
} else {
charactersHashTag = "#original"
}
2024-08-11 18:30:44 +03:00
sourceUrl = post.getSource()
2024-08-10 19:12:42 +03:00
return "%s | <a href=\"%s\">source</a>".sprintf(
charactersHashTag,
sourceUrl
)
}