async def info_post(tags=None): client = Moebooru('yandere') posts = client.post_list(tags=tags) tags = {} for post in posts: tags = post return tags
def grab(*grab_tags:str, grab_count:int, source:str): client = Moebooru(site_url="https://"+source) posts = client.post_list(tags=grab_tags, limit=grab_count) count = 0 printAwesomeASCII() if(len(grab_count) == 0): print("No grab count specified!") print("returning...") gui() else: if((float(checkDiskSpace())-(float(grab_count)*5/1024)) >= 0): if(not posts): print("There wasn't any post to grab!") print("returning...") gui() else: print("=============================================================") printProgressBar(0, int(grab_count), prefix = 'Progress:', suffix = 'Complete', length = 50) for post in posts: image_url = post["file_url"] image_name = image_url.split("/")[-1] image_path = os.getcwd()+"/pictures/" img_data = requests.get(image_url).content with open(image_path+image_name, "wb") as handler: handler.write(img_data) count+=1 printProgressBar(count, int(grab_count), prefix="Progress:", suffix="Complete", length=50) print("=============================================================") print("Finished grabbing") gui() else: print("Not enough disk space!") print("returning...") gui()
async def idd(message, tags=None): randomint = randint(1000, 10000000) try: client = Moebooru('yandere') posts = client.post_list(tags=tags) for post in posts: urllib.request.urlretrieve( post['file_url'], "tmp/NekobinRobot_" + str(randomint) + ".jpg") try: c_id = parse_data['commands'].index(lastcmd.get(message.chat.id)) except: c_id = 1 # For when downloading a file from channel without using a bot prior to this, default set to rating:s ckeyboard = types.InlineKeyboardMarkup(row_width=1) text_and_data = (('→ Next', c_id), ) row_btns = (types.InlineKeyboardButton(text, callback_data=callback_cb.new( function=text, data=data)) for text, data in text_and_data) ckeyboard.row(*row_btns) reply_markup = ckeyboard photo = open('tmp/NekobinRobot_' + str(randomint) + ".jpg", 'rb') await message.answer_document(photo, reply_markup=reply_markup) photo.close() os.remove('tmp/anime_bot_' + str(randomint) + ".jpg") except Exception: traceback.print_exc()
def get_anime(update, query, filename): update.message.chat.send_action(ChatAction.UPLOAD_PHOTO) client = Moebooru("yandere") max_posts_to_load = 200 posts = client.post_list(tags=query, limit=max_posts_to_load) post_count = len(posts) random = randint(0, post_count - 1) image_post = "https://yande.re/post/show/" + str(posts[random]["id"]) image_url = posts[random]["sample_url"] dl = requests.get(image_url) with open(path + filename + ".jpg", "wb") as f: f.write(dl.content) return image_post
def __init__(self, client): self.client = client self.dan_client = Danbooru('danbooru', username='******', api_key='PubbhbW6nutC3yiFrBCrZs7S') self.yan_client = Moebooru(site_url='https://yande.re', username='******', password='******') self.default_tags = ['yuri']
async def inline_function(inline_query: InlineQuery): query = inline_query.query offset = inline_query.offset if offset != '': query = offset.split(' ', 1)[0] offset = int(offset.split('page=', 1)[1]) offset += 1 offset = ' page=' + str(offset) else: offset = ' page=1' if query is None: query = 'rating:s' client = Moebooru('yandere') posts = client.post_list(tags=query, limit=50, page=int(offset.split('page=', 1)[1])) lposts = len(posts) inlinequery = list() for post in posts: inlinequery.append( InlineQueryResultPhoto( id=str(uuid4()), photo_url=post['sample_url'], photo_width=post['width'], photo_height=post['height'], thumb_url=post['preview_url'], caption= '<a href="https://t.me/NekobinRobot?start=%s">Download</a>' % (post['id']), parse_mode=ParseMode.HTML), ) if lposts >= 50: await bot.answer_inline_query(inline_query.id, results=inlinequery, next_offset=query + offset) else: await bot.answer_inline_query(inline_query.id, results=inlinequery) inlinequery.clear()
def idd(bot, update, tags=None, chat_id=None): randomint = randint(1000, 10000000) try: bot.sendChatAction(chat_id, "upload_document") try: client = Moebooru('yandere') posts = client.post_list(tags=tags) for post in posts: urllib.request.urlretrieve( post['file_url'], "tmp/uncensored_bot_" + str(randomint) + ".jpg") ckeyboard = InlineKeyboardMarkup([[ InlineKeyboardButton("Donate", url='https://paypal.me/ev3rest') ], [InlineKeyboardButton("More", callback_data="{'data':'More'}")]]) reply_markup = ckeyboard photo = open('tmp/uncensored_bot_' + str(randomint) + ".jpg", 'rb') bot.sendDocument(chat_id, photo, reply_markup=reply_markup) photo.close() os.remove('tmp/uncensored_bot_' + str(randomint) + ".jpg") except Exception: traceback.print_exc() except Exception: traceback.print_exc()
def inline(bot, update): #Inline Handler & Parser query = update.inline_query.query offset = update.inline_query.offset if offset != '': query = offset.split(' ', 1)[0] offset = int(offset.split('page=', 1)[1]) offset += 1 offset = ' page=' + str(offset) else: offset = ' page=1' if query is None: query = 'rating:s' client = Moebooru('yandere') posts = client.post_list(tags=query, limit=50, page=int(offset.split('page=', 1)[1])) lposts = len(posts) inlinequery = list() for post in posts: inlinequery.append( InlineQueryResultPhoto(type='photo', id=uuid4(), photo_url=post['sample_url'], photo_width=post['width'] * 6, photo_height=post['height'] * 6, thumb_url=post['preview_url']), ) if lposts >= 50: bot.answerInlineQuery(update.inline_query.id, results=inlinequery, next_offset=query + offset) else: bot.answerInlineQuery(update.inline_query.id, results=inlinequery) inlinequery.clear() else: client = Moebooru('yandere') posts = client.post_list(tags=query, limit=50, page=int(offset.split('page=', 1)[1])) lposts = len(posts) inlinequery = list() for post in posts: inlinequery.append( InlineQueryResultPhoto(type='photo', id=uuid4(), photo_url=post['sample_url'], photo_width=post['width'] * 6, photo_height=post['height'] * 6, thumb_url=post['preview_url']), ) if lposts >= 50: bot.answerInlineQuery(update.inline_query.id, results=inlinequery, next_offset=query + offset) else: bot.answerInlineQuery(update.inline_query.id, results=inlinequery) inlinequery.clear()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pybooru import Moebooru client = Moebooru(site_name='Konachan') # notes = client.note_list() # print(notes) # wiki = client.wiki_list(query='nice', order='date') # for msg in wiki: # print("Message: {0}".format(msg['body'])) # posts = client.post_list(tags='blue_eyes', limit=2) # for post in posts: # print("Image URL: {0}".format(post['file_url'])) # tags = client.tag_list() # for tag in tags: # print("Tag: {0} ----- {1}".format(tag['name'], tag['type']))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pybooru import Moebooru client = Moebooru('Konachan') posts = client.post_list(tags='blue_eyes', limit=10) for post in posts: print("URL image: {0}".format(post['file_url']))
def parser(bot, update, tags, pages, chat_id, info=None, ch_id=None): #Usual parser for usual commands global x global p_id randomint = randint(1000, 10000000) if ch_id == '9': bot.sendChatAction(chat_id, "upload_document") client = Danbooru('danbooru', username='******', api_key=danbooru_key) else: bot.sendChatAction(chat_id, "upload_photo") client = Moebooru('yandere') try: randompage = randint(1, int(pages)) if len(x[str(ch_id)]['url']) == 0: posts = client.post_list(tags=str(tags), page=randompage, limit=40) for post in posts: if ch_id == '9': fileurl = post['file_url'] else: fileurl = post['sample_url'] x[str(ch_id)]['url'].append(fileurl) x[str(ch_id)]['id'].append(post['id']) if ch_id == '9': ikeyboard = InlineKeyboardMarkup( [[ InlineKeyboardButton("Donate", url='https://paypal.me/ev3rest') ], [InlineKeyboardButton("Music", url='https://t.me/musicave')], [ InlineKeyboardButton( "More", callback_data="{'data':'More', 'c_id':%s}" % ch_id) ]]) else: ikeyboard = InlineKeyboardMarkup( [[ InlineKeyboardButton("Donate", url='https://paypal.me/ev3rest') ], [InlineKeyboardButton("Music", url='https://t.me/musicave')], [ InlineKeyboardButton( "Download", callback_data="{'data':'Download', 'id':%s}" % x[str(ch_id)]['id'][0]) ], [ InlineKeyboardButton( "More", callback_data="{'data':'More', 'c_id':%s}" % ch_id) ]]) reply_markup = ikeyboard if ch_id != '9': bot.sendPhoto(chat_id, photo=x[str(ch_id)]['url'][0], reply_markup=reply_markup, caption=info) else: bot.sendDocument(chat_id, document=x[str(ch_id)]['url'][0], reply_markup=reply_markup, caption=info) try: x[str(ch_id)]['url'].pop(0) except: traceback.print_exc() try: x[str(ch_id)]['id'].pop(0) except: traceback.print_exc() except Exception: traceback.print_exc() bot.sendMessage( chat_id, 'Oops... Something went wrong, please call the command again!') try: os.remove('tmp/uncensored_bot_' + str(randomint) + ".jpg") except: pass try: x[str(ch_id)]['url'].pop(0) except: traceback.print_exc() try: x[str(ch_id)]['id'].pop(0) except: traceback.print_exc()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pybooru import Moebooru # replace login information client = Moebooru("Konachan", username="******", password="******") client.comment_create(post_id=id, comment_body="Comment content") print(client.last_call)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pybooru import Moebooru client = Moebooru('Konachan') tags = client.tag_list(order='name') for tag in tags: print("Tag: {0} ----- {1}".format(tag['name'], tag['type']))
class SakugabooruService(object): BASE_URL = SAKUGABOORU_BASE_URL MAX_DEPTH = 11 def __init__(self): self.client = Moebooru(site_url=self.BASE_URL) self.local_cache = dict() self.max_page = 1e9 self.created_tags = list() def _save_post(self, post_dict): post, created = Post.objects.update_or_create( id=post_dict['id'], defaults={ 'source': post_dict['source'], 'file_size': post_dict['file_size'], 'is_shown': post_dict['is_shown_in_index'], 'is_pending': post_dict['status'] == "pending", 'md5': post_dict['md5'], 'ext': post_dict['file_ext'], 'created_at': datetime.fromtimestamp(int(post_dict['created_at']), tz=utc), 'score': post_dict['score'], 'rating': post_dict['rating'], 'sample_url': post_dict['sample_url'], 'sample_file_size': post_dict['sample_file_size'] }) tags = self.update_tags(post_dict['tags'].split(' ')) with transaction.atomic(): post.tags.clear() for tag in tags: post.tags.add(tag) post.uploader = self.update_uploader(post_dict['author'], post.is_pending, post.is_shown) post.save() return post @staticmethod def update_uploader(author, is_pending, is_shown): uploader, created = Uploader.objects.get_or_create(name=author) if is_shown and not (is_pending or uploader.in_whitelist): uploader.in_whitelist = True uploader.save() return uploader def update_tag(self, tag): res = self.client.tag_list(name=tag.name) for tag_dict in res: if tag_dict['name'] == tag.name: if tag.type != tag_dict['type']: tag.type = tag_dict['type'] tag.save() logger.info("Tag[{}] type has been updated.".format( tag.name)) break return tag def update_tags(self, tag_str_list, force_update=False): tags = list() for tag_str in tag_str_list: tag, created = Tag.objects.get_or_create(name=tag_str) if created or force_update: self.created_tags.append(tag) try: self.update_tag(tag) except: logger.exception( "Update tag [] from sakugabooru failed.".format( tag.name)) tags.append(tag) return tags def _get_post_dict_by_api(self, post_id): """ get post_dict by post_id using api and save every accessed page to cache. :param post_id: Integer :return: success: post_dict; failed: None """ limit = 100 post_dict = self.local_cache.get(post_id, None) if post_dict: return post_dict page_stack = list() min_page = 1 page_stack.append(min_page) max_page = self.max_page while page_stack and len(page_stack) <= self.MAX_DEPTH: res = self._get_posts_page(page=page_stack[-1], limit=limit) if not res: last_page = page_stack.pop() if last_page < self.max_page: self.max_page = last_page if last_page < max_page: max_page = last_page if len(page_stack) > 0: page_stack.append((max_page + page_stack[-1]) // 2) continue return None first_id = res[0]["id"] last_id = res[-1]["id"] logger.info("Posts Page[{}]: first[{}], last [{}]".format( page_stack[-1], first_id, last_id)) if post_id > first_id: if page_stack[-1] <= 1: return None next_page = max( page_stack[-1] + (-(post_id - first_id) // limit), (min_page + page_stack[-1]) // 2) max_page = page_stack[-1] if next_page < 1: next_page = 1 page_stack.append(next_page) elif post_id < last_id: next_page = min( page_stack[-1] - (-(last_id - post_id) // limit), (max_page + page_stack[-1]) // 2) min_page = page_stack[-1] if next_page in page_stack: break if next_page > self.max_page: next_page = (self.max_page + page_stack[-1]) // 2 page_stack.append(next_page) else: return self.local_cache.get(post_id) return self.local_cache.get(post_id, None) def update_post(self, post_id): posts = self.update_posts(post_id) if posts: return posts[0] return None def update_posts(self, *post_ids): try: for post_id in post_ids: if post_id not in self.local_cache: if not self._get_post_dict_by_api(post_id): try: post = Post.objects.get(id=post_id) post.is_shown = False post.is_pending = False post.save() except Post.DoesNotExist: pass finally: updated = [] for v in self.local_cache.values(): self._save_post(v) updated.append(str(v['id'])) logger.info(f"Posts[{','.join(updated)}] Updated.") return Post.objects.filter(id__in=post_ids) def _save_cache(self, res): for post_dict in res: self.local_cache[post_dict["id"]] = post_dict @staticmethod def _refresh_is_shown(page_res): if page_res: for post in Post.objects.filter( id__gte=page_res[-1]['id'], id__lte=page_res[0]['id']).exclude( id__in=[x['id'] for x in page_res]): post.is_pending = False post.is_shown = False post.save() def _get_posts_page(self, page=1, limit=100): try: res = self.client.post_list(page=page, limit=limit) self._save_cache(res) self._refresh_is_shown(res) return res except: logger.exception( "Failed to get posts page [{}] from sakugabooru with limit[{}]." .format(page, limit)) return dict() def update_posts_by_page(self, page=1, limit=100, escape_id=None): posts = list() logger.info( "Getting posts page [{}] from sakugabooru with limit[{}].".format( page, limit)) for post_dict in self._get_posts_page(page=page, limit=limit): if escape_id and post_dict["id"] <= escape_id: break post = self._save_post(post_dict) if post: posts.append(post) logger.info(f"Posts[{','.join([str(x.id) for x in posts])}] Updated.") return posts
class yandere: """Yandere image search""" def __init__(self, bot): self.bot = bot self.yandere = Moebooru('yandere') @commands.command(name='yandere', aliases=['nsfw', 'sfw'], pass_context=True) async def yandere_search(self, ctx, *, tags: str = ""): """Aliases !nsfw and !sfw for specific rated images, accepts tags""" nsfw = [x for x in ctx.message.server.channels if x.name == "nsfw"][0] images = [x for x in ctx.message.server.channels if x.name == "image"][0] cmd = ctx.invoked_with tags = tags.split() tags.append("order:random -partial_scan") check = None if cmd == 'yandere': if ctx.message.channel in [nsfw, images]: if ctx.message.channel == images: check = "some string" else: await self.bot.say( "Please try again in an image channel such as <#%s> or <#%s>" % (images.id, nsfw.id)) return elif cmd == 'sfw': if ctx.message.channel in [nsfw, images]: tags.append("rating:s") else: await self.bot.say( "Please try again in an image channel such as <#%s> or <#%s>" % (images.id, nsfw.id)) return elif cmd == 'nsfw': if ctx.message.channel == nsfw: tags.append("-rating:s") else: await self.bot.say( "Please try again in an nsfw channel such as <#%s>" % nsfw.id) return tags = ' '.join(tags) try: try: image_list = self.yandere.post_list(limit=20, tags=tags) except pybooru_errors.PybooruHTTPError: await self.bot.say( "You have entered too many tags. Please learn to restrain yourself" ) image = choice(image_list) image_url = image['sample_url'] except IndexError: await self.bot.say( "Nothing found. Please check the spelling or try again with different tags" ) return if image['rating'] != 's': title = "NSFW Image" else: title = "SFW Image" if image['rating'] != 's' and check is not None: await self.bot.say( "This image is too lewd for this channel, please try again with `!sfw` or append a `rating:s` to the tags" ) return tags = tags.split(' ') tags = '+'.join(tags) embed = discord.Embed(title=title, url='https://yande.re/post/show/%s' % image['id']) embed.set_author(name="Search Results", url='https://yande.re/post?tags=%s' % tags) embed.set_image(url=image_url) embed.set_footer( text= "Image might take a while to appear | Disclaimer: The user is responsible for his searches. The bartender cares not." ) await self.bot.say(embed=embed)
def __init__(self, _tags, _pages, _booru): r = random.randint(1, 40 * _pages) client = Moebooru(_booru) print(_tags, _pages) self.posts = client.post_list(limit=1, tags=_tags, page=r)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pybooru import Moebooru client = Moebooru("yandere") wiki = client.wiki_list(query="nice", order="date", limit=2, page=1) for msg in wiki: print("Message: {0}".format(msg["body"]))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pybooru import Moebooru client = Moebooru("yandere") wiki = client.wiki_list(body_matches="great", order="date") for page in wiki: print("Message: {0}".format(page["body"]))
# encoding: utf-8 from __future__ import print_function from pybooru import Danbooru from pybooru import Moebooru konachan = Moebooru("konachan") kona_tags = konachan.tag_list(order='date') print(konachan.last_call) kona_post = konachan.post_list() print(konachan.last_call) lolibooru = Moebooru("lolibooru") kona_tags = lolibooru.tag_list(order='date') print(lolibooru.last_call) kona_post = lolibooru.post_list() print(lolibooru.last_call) danbooru = Danbooru('danbooru') dan_tags = danbooru.tag_list(order='name') print(danbooru.last_call) dan_post = danbooru.post_list(tags="computer") print(danbooru.last_call)
def __init__(self): self.client = Moebooru(site_url=self.BASE_URL) self.local_cache = dict() self.max_page = 1e9 self.created_tags = list()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pybooru import Moebooru client = Moebooru('yandere') wiki = client.wiki_list(body_matches='great', order='date') for page in wiki: print("Message: {0}".format(page['body']))
async def parser(message, tags, pages, chat_id, info=None, ch_id=None): #Usual parser for usual commands global x randomint = randint(1000, 10000000) await message.bot.send_chat_action(message.chat.id, ChatActions.UPLOAD_PHOTO) client = Moebooru('yandere') try: randompage = randint(1, int(pages)) if len(x[str(ch_id)]['url']) == 0: posts = client.post_list(tags=str(tags), page=randompage, limit=40) for post in posts: if ch_id == '9': fileurl = post['file_url'] else: fileurl = post['sample_url'] x[str(ch_id)]['url'].append(fileurl) x[str(ch_id)]['id'].append(post['id']) x[str(ch_id)]['tags'].append(post['tags']) else: ikeyboard = types.InlineKeyboardMarkup(row_width=1) text_and_data = ( ('ⓘ Info', x[str(ch_id)]['id'][0]), ('→ Next', ch_id), ) row_btns = (types.InlineKeyboardButton( text, callback_data=callback_cb.new(function=text, data=data)) for text, data in text_and_data) ikeyboard.row(*row_btns) text_and_data = (('↧ Download', x[str(ch_id)]['id'][0]), ) row_btns = (types.InlineKeyboardButton( text, callback_data=callback_cb.new(function=text, data=data)) for text, data in text_and_data) ikeyboard.row(*row_btns) reply_markup = ikeyboard # if info == None: # info = '' # info = info + "\n" + '<a href="%s">Source</a>' % (x[str(ch_id)]['tags'][0]) await message.answer_photo(photo=x[str(ch_id)]['url'][0], reply_markup=reply_markup, caption=info, parse_mode=ParseMode.HTML) try: x[str(ch_id)]['url'].pop(0) except: traceback.print_exc() try: x[str(ch_id)]['id'].pop(0) except: traceback.print_exc() except Exception: traceback.print_exc() await message.reply( 'Oops... Something went wrong, please call the command again!') try: os.remove('tmp/NekobinRobot_' + str(randomint) + ".jpg") except: pass try: x[str(ch_id)]['url'].pop(0) except: traceback.print_exc() try: x[str(ch_id)]['id'].pop(0) except: traceback.print_exc()
# encoding: utf-8 from __future__ import print_function from pybooru import Danbooru from pybooru import Moebooru konachan = Moebooru("konachan") kona_tags = konachan.tag_list(order='date') print(konachan.last_call) kona_post = konachan.post_list() print(konachan.last_call) danbooru = Danbooru('danbooru') dan_tags = danbooru.tag_list(order='name') print(danbooru.last_call) dan_post = danbooru.post_list(tags="computer") print(danbooru.last_call)
def __init__(self, bot): self.bot = bot self.yandere = Moebooru('yandere')
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pybooru import Moebooru # replace login information client = Moebooru('Konachan', username='******', password='******') client.comment_create(post_id=id, comment_body='Comment content') print(client.last_call)
from flask import request, render_template, send_from_directory, url_for from pybooru import Danbooru, Moebooru, PybooruHTTPError from booru_extension import Safebooru, Gelbooru from app.posts import bp # Commas on the left for easy commenting clients = [ (Moebooru('konachan'), False), (Moebooru('yandere'), False), (Safebooru(), True) #,(Gelbooru(), True) # Currently, Gelbooru commonly 404s on its own images ] def download_posts(tags, page): posts = [] errors = [] tag_count = {} for client, altbooru in clients: postList = [] try: postList = client.post_list( tags=tags, limit=50, page=page) # change the limit to be user defined from config except PybooruHTTPError as err: errors.append("{0} error: {1}".format(client.site_url, err)) continue list_of_tags = [] for post in postList:
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pybooru import Moebooru client = Moebooru('yandere') wiki = client.wiki_list(query='nice', order='date', limit=2, page=1) for msg in wiki: print("Message: {0}".format(msg['body']))