danboo/danboo.own
2024-08-11 18:57:47 +03:00

106 lines
2.6 KiB
Scala

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)
.filter(def(p) = p.isImage())
.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
blacklisted = post.containsTags(blacklistTags)
if (blacklisted) continue
score = post.getScore()
for target : config.targets {
minScore = target.minScore ?? 0
if (score < minScore) continue
matched = post.containsTags(target.tags)
if (!matched) continue
url = "https://danbooru.donmai.us/posts/" + post.id
println "%s: %s -> %s".sprintf(newDate(), url, target.name)
caption = getCaption(post)
buttonText = sprintf("%s 📈%d", post.getResolution(), score)
markup = jsonencode({"inline_keyboard": [
[{"text":buttonText, "url":url}]
]})
bot.invoke("sendPhoto", {
"chat_id": target.chat,
"message_thread_id": target.topic,
"photo": post.getImageUrl(),
"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,
"photo": post.getSampleImageUrl(),
"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 getCharacterHashtags(post) {
characters = post.getCharacters()
if characters.isEmpty() {
return "#original"
}
copyrights = post.getCopyrights()
hashtags = []
for character : characters {
hashtag = strToHashtag(character)
// Clean-up copyright suffix
for copyright : copyrights {
replaceFrom = "_" + copyright
hashtag = hashtag.replace(replaceFrom, "")
}
hashtags += hashtag
}
return hashtags.joinToString(" ")
}
def getCaption(post) = sprintf(
"%s | <a href=\"%s\">source</a>",
getCharacterHashtags(post),
post.getSource()
)