From 274a09390a5e9b2f9c090af2dc51ef522bcb37f1 Mon Sep 17 00:00:00 2001 From: aNNiMON Date: Thu, 15 Aug 2024 00:20:16 +0300 Subject: [PATCH] Add Telegram bot --- bot.own | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 bot.own diff --git a/bot.own b/bot.own new file mode 100644 index 0000000..b07770a --- /dev/null +++ b/bot.own @@ -0,0 +1,72 @@ +use std, functional, types, regex + +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(6200) + updates = bot.getUpdatesSync(lastUpdateId + 1, 50, 58) + if (updates.isEmpty()) continue + + lastUpdateId = stream(updates) + .map(::processUpdate) + .reduce(0, def(a, b) = a + b) +} +// Confirm updates +bot.getUpdatesSync(lastUpdateId + 1, 1, 10) +thread(def() { + sleep(2000) + exit(0) +}) + + +def processUpdate(update) { + if !arrayKeyExists("message", update) { + return update.update_id + } + msg = update.message + text = msg.text ?? "" + if text.isEmpty() { + return update.update_id + } + m = DANBOORU_REGEX.matcher(text) + while m.find() { + processPost(m.group(1), msg.chat.id, msg.message_id) + } + return update.update_id +} + +def processPost(id, chatId, msgId) { + post = api.getPost(id) + println "Got post: " + post + if !post.isImage() return 0 + blacklistTags = config.danbooru.blacklistTags + if post.containsTags(blacklistTags) return 0 + + caption = getCaption(post) + reply = jsonencode({"message_id": msgId, "chat_id": chatId}) + bot.invoke("sendPhoto", { + "chat_id": chatId, + "reply_parameters": reply, + "photo": post.getImageUrl(), + "parse_mode": "html", + "caption": caption, + }, def(r) { + if !r.contains("wrong file identifier") return 1 + bot.invoke("sendPhoto", { + "chat_id": chatId, + "reply_parameters": reply, + "photo": post.getSampleImageUrl(), + "parse_mode": "html", + "caption": "small " + caption, + }, def(r) = 1) + }) +} + +