use std, math, http, json, functional, files, jdbc conn = getConnection("jdbc:sqlite:redditimages.db") include "own-modules/telegram-bot/TelegramBot.own" include "Reddit.own" include "database.own" bot = new TelegramBot(config.token) reddit = new Reddit(config.cookie) subreddits = reddit.fetchSubreddits(config.subreddits, config["items-in-top"]) media = stream(subreddits) .filter(def(p) = reduce([".jpg", ".jpeg", ".png"], false, def(acc, ext) = acc || indexOf(p.url, ext) > 0)) .filter(::isPostUnique) //.peek(def(p) = bot.sendPhoto(config.peer, p.url)) .limit(10) .peek(::addPost) .map(def(p) = { "type": "photo", "media": p.url, "caption": getCaption(p), "parse_mode": "html" }) .toArray() debug(media) while (length(media) > 0) { r = bot.sendMediaGroupSync(config.peer, media) if (r.ok) break println r retryAfter = try(def() = parseInt(r.description.replaceAll(".*retry after (\d+).*", "$1")), 0) if (retryAfter > 0) { sleep(retryAfter * 1000 + 2800) continue } mediaIndex = try(def() = parseInt(r.description.replaceAll(".*failed.*?#(\d+).*", "$1")), -1) if (mediaIndex == -1) break media = arraySplice(media, mediaIndex - 1, 1) sleep(3000) } thread(def() { sleep(15000) exit(0) }) stIsPostExists.close() stAddPost.close() conn.close() // Helpers def debug(r) { echo(jsonencode(r)) } def strToHashtag(str) = str.toLowerCase() .replaceAll("[^a-z_0-9\s]", "") .replaceAll("\s+", "_") def safe(str) = str.replace("&", "&") .replace("<", "<").replace(">", ">") def getCaption(post) { tag = "" if (length(post.flair_text ?? "") > 0) { tag = " #" + strToHashtag(post.sub + "_" + post.flair_text) } else if (length(post.link_flair_text ?? "") > 0) { tag = " #" + strToHashtag(post.sub + "_" + post.link_flair_text) } return sprintf( "%s\n" + "🗨 Comments%s\n" + "🔎 SauceNAO, " + "Alamy", safe(post.url), safe(post.title), safe(post.permalink), tag, urlencode(post.url), urlencode(post.url) ) }