danboo/bot.own

80 lines
2.0 KiB
Scala

use std, functional, types, regex, date
include "own-modules/telegram-bot/TelegramBot.own"
include "config.own"
include "DanbooruApi.own"
DANBOORU_REGEX = regex("https://danbooru[^0-9 ]+([0-9]{5,9})")
bot = new TelegramBot(config.telegram.token)
api = new DanbooruApi(config.danbooru.auth)
lastUpdateId = -1
while true {
sleep(1200)
updates = bot.getUpdatesSync(lastUpdateId + 1, 50, 58)
if (updates.isEmpty()) continue
for update : updates {
lastUpdateId = update.update_id
processUpdate(update)
}
}
// Confirm updates
bot.getUpdatesSync(lastUpdateId + 1, 1, 10)
thread(def() {
sleep(2000)
exit(0)
})
def processUpdate(update) {
if !arrayKeyExists("message", update) return 0
msg = update.message
text = msg.text ?? ""
if text.isEmpty() return 0
m = DANBOORU_REGEX.matcher(text)
while m.find() {
processPost(m.group(1), msg.chat.id, msg.message_id, msg.from)
sleep(2000)
}
}
def processPost(id, chatId, msgId, from) {
post = api.getPost(id)
url = "https://danbooru.donmai.us/posts/" + id
println "%s: %s (%d %d)".sprintf(newDate(), url, chatId, msgId)
if !post.isImage() return 0
blacklistTags = config.danbooru.blacklistTags
if post.containsTags(blacklistTags) return 0
caption = getCaption(post)
sender = ""
if (from.id != chatId) sender = from.first_name + " "
buttonText = sprintf("%s%s 📈%d", sender, post.getResolution(), post.getScore())
markup = jsonencode({"inline_keyboard": [
[{"text":buttonText, "url":url}]
]})
bot.invoke("sendPhoto", {
"chat_id": chatId,
"photo": post.getImageUrl()
"parse_mode": "html",
"caption": caption,
"reply_markup": markup
}, def(r) {
bot.invoke("deleteMessage", {
"chat_id": chatId,
"message_id": msgId,
}, def(r) = 1)
if !r.contains("wrong file identifier") return 1
bot.invoke("sendPhoto", {
"chat_id": chatId,
"photo": post.getSampleImageUrl()
"parse_mode": "html",
"caption": "small " + caption,
"reply_markup": markup
}, def(r) = 1)
})
}