def download(tags, pages): try: randomint = randint(1000, 10000000) randompage = randint(1, int(pages)) client = Danbooru('danbooru', username='******', api_key='your_api_key') if len(x) == 0: #Checks if the array is empty of links posts = client.post_list(tags=str(tags), page=str(randompage), limit=200) for post in posts: fileurl = 'http://danbooru.donmai.us' + post['file_url'] x.append(fileurl) else: pass try: urllib.request.urlretrieve(x[1], "tmp/danbooru_" + str(randomint) + ".jpg") x.pop(0) except Exception as e: print(e) except: download(tags, pages)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pybooru import Danbooru client = Danbooru('danbooru') tags = client.tag_list(order='date') for tag in tags: print("Tag: {0} ----- {1}".format(tag['name'], tag['category']))
def download(tags, pages): try: client = Danbooru('danbooru', username='******', api_key='your_api_key') # Collect links while len(x) is not 200: # Checks if the list is full randompage = randint(1, pages) posts = client.post_list(tags=tags, page=randompage, limit=200) for post in posts: try: fileurl = 'https://danbooru.donmai.us' + post['file_url'] except: fileurl = 'https://danbooru.donmai.us' + post['source'] x.append(fileurl) # Download images for url in x: try: randomint = randint(1000, 10000000) urllib.request.urlretrieve( url, "tmp/danbooru_/{0}.jpg".format(randomint)) except: continue except Exception as e: raise e
def collect(tags, pages): try: #authentication client = Danbooru('danbooru', username="******", api_key="12d62QBEC2XbxnEoEV6iRu1G") #Global variables to make the download function happy global fileurl global posts #getting max page, tags, and creating output.txt randompage = int(input("What are the maximum amount of pages? ")) chosenpage = random.choice(range(0, randompage)) #chooses a random page between 1 and the specified max page, prevents empty files posts = client.post_list(tags=tags, page=chosenpage, limit=200) #seems to be a hardcoded limit of 200, documentation says 100? output = open("output.txt", "a+") #creates output.txt if it doesn't exist, appends to output.txt if it does exist output.write("From page " + str(chosenpage) + " with tag(s) " + tags + ": \n") #writes page number and tag(s) before links #getting links... i think? for post in posts: try: fileurl = post['file_url'] except: fileurl = post['source'] #writing links output.write(fileurl + "\n") #outputs URLs to output.txt print("Done! Written links to output.txt... hopefully") except Exception as err: print(err) raise err #doesn't really do shit honestly unless something goes catastrophically wrong
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']
def __init__(self, line, reddit, dvart, tw, youtube): self.client = Danbooru(site_url='https://safebooru.donmai.us/') self.limit = 3 self.bpm = 660 self.line_bot_api = line self.reddit = reddit self.da = dvart self.tw = tw self.yt = youtube
async def dhentai(self, ctx, tags): dClient = Danbooru('danbooru') s = dClient.post_list(limit=1, tags=tags, random=True) embed = discord.Embed(title="Danbooru hentai!", color=0xff00f6) try: embed.set_image(url=s[0]['file_url']) embed.set_footer(text=s[0]['tag_string']) await ctx.send(embed=embed) except: await ctx.send('попробуй ещё раз')
def __init__(self, bot): self.bot = bot configParser = configparser.RawConfigParser() configfilepath = 'config.txt' configParser.read(configfilepath) self.danbooruUsername = configParser.get('danbooru', 'username') self.danbooruPassword = configParser.get('danbooru', 'password') self.imgurToken = configParser.get('imgur', 'token') self.fuccboiname = 'bonkery' self.fuccboidate = date(2018, 12, 6) self.dbclient = Danbooru('danbooru', username=self.danbooruUsername, api_key=self.danbooruPassword)
def danbooru(danbooru_id): '''returns danbooru post using id''' if danbooru_id != 0: print('checking details on danbooru.donmai.us') try: client = Danbooru('danbooru') post = client.post_show(danbooru_id) logger.dump(post, 'last_danbooru_response.txt') #debug return post except Exception as e: print(e) return ''
def get_from_danbooru_by_tag(tag): client = Danbooru('danbooru') tags = client.tag_list(name_matches=tag, hide_empty="yes", order="count") tag = "" for x in tags: if len(x) != 0: #making sure that the particular tag isn't empty. If it is, then a random image is displayed. tag = x["name"] break #got the tags. Now what? Images! posts = client.post_list(tags=tag, random=True, raw=True) return posts
def init_client(self): if self.api: if not self.username: raise ValueError('Danbooru API Services need a Username when API key is given.') self.client = PyDanbooru(site_name=self.name, site_url=self.url, api_key=self.api, username=self.username) else: self.client = PyDanbooru(site_name=self.name, site_url=self.url) self.user_level = self.get_user_level() self.tag_limit = self.LEVEL_RESTRICTIONS['tag_limit'][self.user_level] self.censored_tags = self.LEVEL_RESTRICTIONS['censored_tags'][self.user_level] if not self.url: self.url = self.client.site_url.lstrip('/')
def danbooru(tags): for i in range(0,5): dan = Danbooru('danbooru', username=config.get('danbooru_username'), api_key=config.get('danbooru_key')) while True: try: posts = dan.post_list(tags=tags, limit=1, random="True") return posts[0]['file_url'], posts[0]['id'], posts[0]['created_at'], posts[0]['source'] except KeyError: continue except IndexError: break except: continue break
async def get_anime(ctx, *, tag: str = None): if tag is None: return await ctx.send('Enter a tag') client = Danbooru('danbooru') get_image = client.post_list(**{ 'limit': 1, 'page': 1, 'tags': tag, 'random': True }) for image in get_image: response = image['large_file_url'] await ctx.send(response)
def __init__(self, bot: Konoha): self.bot: Konoha = bot self.client = Danbooru("danbooru", username=config.danbooru_name, api_key=config.danbooru_key) # pylint: disable=no-member self.postloop.start()
def __init__(self, config): self.config = config self.api = get_api(self.config) self.danbooru = Danbooru(site_url=DANBOORU_URL) self.image_list = [] self.last_notification = -1 if os.path.exists(self.config.state_file): with open(self.config.state_file) as f: try: self.last_notification = int(f.read()) logging.debug( 'Recovering state, last notification id is %d', self.last_notification) except ValueError: logging.debug('No previous state found')
async def lewd(message, attempts=0): if attempts == 5: return try: query = message.content[message.content.index(' ') + 1:] bclient = Danbooru('danbooru') pic = bclient.post_list(tags=query, random=True) try: fileurl = pic[0]['file_url'] except: fileurl = pic[0]['source'] except: await lewd(message, attempts + 1) await core.reply(message.channel, fileurl)
async def safebooru(self, ctx): """Same as danbooru, but looks for safe images.""" client = Danbooru('danbooru', username='******', api_key=self.bot.settings.danboorutoken) image_found = False while not image_found: temp = self.fixDanbooruJSON(str(client.post_list(random=True, limit=1, tags="rating:s -status:deleted"))) data = json.loads(temp) if 'file_url' in data: image_found = True url = data['file_url'] if ctx.message.guild is not None: color = ctx.message.guild.me.color else: color = discord.Colour.blue() embed = discord.Embed(color=color, title="Image from Project Danbooru!", description="Here's your image, {}~".format(ctx.message.author.name)) embed.set_image(url=url) embed.set_footer(text="Powered by Project Danbooru.") await ctx.send(embed=embed)
class Photos(commands.Cog): def __init__(self, bot): self.bot = bot self.danbooru_client = Danbooru(site_name='danbooru') def _get_url_list_danbooru(self, tag, request_number): posts = self.danbooru_client.post_list(limit=request_number, tags=tag, random=True) pictures = [] for post in posts: pictures += [post['file_url']] return pictures @commands.command() async def unleash_load_danbooru(self, ctx, arg1): urls = self._get_url_list_danbooru(arg1, 5) # Check if at least 1 image is found if urls == []: await ctx.send('no images found') return fmt = "" for url in urls: fmt += url + "\n" await ctx.send(fmt) @commands.command() async def danbooru(self, ctx, arg1): urls = self._get_url_list_danbooru(arg1, 1) # construct embedded image discord_embed = discord.Embed(colour=0x4286f4) discord_embed.set_author(name=arg1) discord_embed.set_footer(text=ctx.message.author) # check if danbooru tag returns url if urls == []: discord_embed.title = 'No image found' else: discord_embed.set_image(url=urls[0]) try: await ctx.send(embed=discord_embed) except discord.HTTPException: print('sending the message failed') finally: print(discord_embed.to_dict())
async def danbooru(ctx, *, search: str): from pybooru import Danbooru, exceptions client = Danbooru('danbooru') try: posts = client.post_list(tags=search, random=True, limit=1) except exceptions.PybooruHTTPError: await ctx.send('Danbooru only allows you to search with 2 tags. Consider donating $20 if you want to search with more tags') url = 'https://danbooru.donmai.us/posts/' for post in posts: id = str(post['id']) dblink = url + id if str(post['file_url']).startswith('/data/'): file = 'https://donmai.us{}'.format(post['file_url']) else: file = post['file_url'] if post['rating'] == "s": rating = 'Safe' elif post['rating'] == 'q': rating = 'Questionable' elif post['rating'] == 'e': rating = 'Explicit' score = post['score'] source = post['source'] emb = discord.Embed( title='Click here to view in your browser', url=dblink, colour=0xEC40DF, description='__Post ID: {}__'.format(id) ) emb.set_image(url=file) emb.set_author(name='Danbooru', url='http://danbooru.donmai.us', icon_url='https://qt-anime-grils.is-serious.business/555270.png') emb.add_field(name='Rating: ', value=rating, inline=True) emb.add_field(name='Score: ', value=score, inline=True) emb.add_field(name='Source: ', value='[Click Here]({})'.format(source), inline=False) await ctx.send(embed=emb)
async def danbooru(self, ctx): """Posts an image directly from Project Danbooru.""" client = Danbooru('danbooru', username='******', api_key=self.bot.settings.danboorutoken) if ctx.message.channel.is_nsfw(): image_found = False while not image_found: temp = self.fixDanbooruJSON(str(client.post_list(random=True, limit=1, tags="rating:e -status:deleted"))) data = json.loads(temp) if 'file_url' in data: image_found = True url = data['file_url'] else: await ctx.send("Sorry, but I can't load anything from Project Danbooru unless you're in a NSFW channel.") return if ctx.message.guild is not None: color = ctx.message.guild.me.color else: color = discord.Colour.blue() embed = discord.Embed(color=color, title="Image from Project Danbooru!", description="Here's your image, {}~".format(ctx.message.author.name)) embed.set_image(url=url) embed.set_footer(text="Powered by Project Danbooru.") await ctx.send(embed=embed)
class anime(commands.Cog): def __init__(self, bot): self.client=Danbooru('danbooru', api_key=dbexec('danbooruKey', log=True)) self.bot = bot @commands.command(aliases=['dnb']) async def danbooru(self, ctx, *, tags1: str): """Gets an image from Danbooru, tags must be valid tags on the website""" #replacement_table = { # r' ': '_', # r',': ' ' #} #for regex, replace_with in replacement_table.items(): # tags1 = re.sub(regex, replace_with, tags1) try: #Create post object class post: def __init__(self, data): self.id = data[0]['id'] self.score = data[0]['score'] self.rating = data[0]['rating'] self.img = data[0]['file_url'] self.uploadername = data[0]['uploader_name'] try: while True: counter=1 print("Attempt {}".format(counter)) data = self.client.post_list(limit=1,tags=tags1, random=True) if (not data): await ctx.send("Invalid tag*(s)*") return bnd = post(data) if(bnd.rating =='s'): break except(Exception) as e: print(e) await ctx.send('An error occured') return em = discord.Embed(title="Search result", url=bnd.img) em.add_field(name='Uploaded by', value=bnd.uploadername, inline=True) em.add_field(name="Score", value=bnd.score, inline=True) em.set_image(url=bnd.img) print("img={}".format(bnd.img)) await ctx.send(embed=em) except(Exception) as e: print(e)
def pic(update: Update, context: CallbackContext, ind: int, uind: int, is_group: bool, lang: str): message = update.effective_message ab = message.text.split(' ') if (len(ab) == 1): sendtext = other.proc(other.getl(lang).error_pic_noTag) context.bot.send_message(message.chat.id, sendtext, parse_mode='HTML') return client = Danbooru('danbooru') temp = None if (ab[1] == 'hentai'): temp = client.post_list(tags='rating:e', page=random.randint(1, 200), limit=1)[0] elif (ab[1] == 'anime'): temp = client.post_list(tags='rating:s', page=random.randint(1, 200), limit=1)[0] elif (ab[1] == 'ecchi'): temp = client.post_list(tags='rating:q', page=random.randint(1, 200), limit=1)[0] elif (ab[1] == 'yuri'): temp = client.post_list(tags='yuri', page=random.randint(1, 200), limit=1)[0] elif (ab[1] == 'uncensored'): temp = client.post_list(tags='uncensored', page=random.randint(1, 200), limit=1)[0] elif (ab[1] == 'neko'): temp = client.post_list(tags='cat_ears', page=random.randint(1, 200), limit=1)[0] elif (ab[1] == 'wallpaper'): temp = client.post_list(tags='wallpaper', page=random.randint(1, 200), limit=1)[0] context.bot.send_photo(message.chat.id, temp['file_url'], caption='Tags: ' + temp['tag_string']) print('done')
def send_found_photos(message): msg_args = message.text.split(' ') POST_PER_REQUEST = 200 bot.send_message(message.chat.id, 'Начинаю...') tag_names = msg_args[1] client = Danbooru('danbooru') total_posts = client.tag_list(name=tag_names)[0]['post_count'] pages_found = (total_posts // POST_PER_REQUEST) + 1 params = {'limit': total_posts, 'tags': tag_names, 'page': None} for page in range(1, pages_found + 1): params['page'] = page founded_posts = client.post_list(**params) for post in founded_posts: if not 'file_url' in post.keys(): continue file_url = post['file_url'] response = requests.get(file_url) file_content = response.content bot.send_photo(message.chat.id, file_content)
def login(self): logger.info("login into mastodon bot...") self.mastodon_api = Mastodon(client_id=self.settings.client_id, client_secret=self.settings.client_secret, access_token=self.settings.access_token, api_base_url=self.settings.domain) try: logger.info("login into twitter account...") auth = tweepy.OAuthHandler( self.settings.accounts.twitter.consumer_key, self.settings.accounts.twitter.consumer_secret) auth.set_access_token( self.settings.accounts.twitter.access_token, self.settings.accounts.twitter.access_token_secret) self.tweet_api = tweepy.API(auth) except AttributeError: logger.debug("twitter credentials not definied") self.tweet_api = False try: logger.info("login into danbooru account...") self.danbooru_api = Danbooru( 'danbooru', username=self.settings.accounts.danbooru.username, api_key=self.settings.accounts.danbooru.token) except AttributeError: logger.debug("danbooru credentials not definied") self.danbooru_api = False try: logger.info("login into pixiv account...") self.pixiv_api = AppPixivAPI() self.pixiv_api.login(self.settings.accounts.pixiv.username, self.settings.accounts.pixiv.password) except AttributeError: logger.debug("pixiv credentials not definied") # self.pixiv_api = AppPixivAPI() self.pixiv_api = False
def getEroPic() -> str: reqTags = 'rating:s -male_focus' pages = 100 client = Danbooru('danbooru') randompage = randint(1, pages) posts = client.post_list(tags=reqTags, page=randompage, limit=1) post = posts[0] try: picUrl = post['file_url'] except: picUrl = post['source'] picUrl = re.sub('^https', 'http', picUrl, count=1) #改为返回图片的url # picDat = requests.get(picUrl).content # picFormat = re.findall('.[a-zA-Z]+$', picUrl) # picName = randint(1000, 10000000) # picAddr = './plugins/eroPic/{0}'.format(picName)+picFormat[0] # with open(picAddr, 'wb') as handle: # handle.write(picDat) return picUrl
def download(tags, pages): try: client = Danbooru('danbooru', username='******', api_key='your_api_key') # Collect links while len(x) is not 200: # Checks if the list is full randompage = randint(1, pages) posts = client.post_list(tags=tags, page=randompage, limit=200) for post in posts: try: fileurl = post['file_url'] except: fileurl = 'https://danbooru.donmai.us' + post['source'] x.append(fileurl) # Download images for url in x: try: randomint = randint(1000, 10000000) urllib.request.urlretrieve(url, "tmp/danbooru_/{0}.jpg".format(randomint)) except: continue except Exception as e: raise e
def __init__(self, duname: str, dapi: str, rid: str, rsec: str, rname: str, runame: str, rpass: str, nsfw_allowed=False): if (duname and dapi and rid and rsec and rname and runame and rpass): self.danbooru = Danbooru(site_url="https://danbooru.donmai.us/", username=duname, api_key=dapi) self.reddit = praw.Reddit(client_id=rid, client_secret=rsec, user_agent=rname, username=runame, password=rpass) self.nsfw_allowed = nsfw_allowed
def get_from_danbooru(char_name, anime_name): full_tag = char_name + " (" + anime_name + ")" #print(full_tag) client = Danbooru('danbooru') #getting full tag AKA Character_Nme(Anime Name) format tags = client.tag_list(name_matches=full_tag, hide_empty="yes", order="count") print(tags) tag = "" #Checking if there were no search results, and then getting tags with merely the character name if (len(tags) == 0): tags = client.tag_list(name_matches=char_name, hide_empty="yes", order="count") if (len(tags) == 0): #searching for last name, first name format, if the other doesn't work reverse_name = "" name = char_name.split(' ') n = len(name) - 1 while (n >= 0): reverse_name = reverse_name + " " + name[n] n -= 1 print(reverse_name) tags = client.tag_list(name_matches=reverse_name, hide_empty="yes", order="count") for x in tags: if len(x) != 0: tag = x["name"] break print(tag) #get posts for tag. posts = client.post_list(tags=tag, random=True, raw=True) #print(posts[0]['large_file_url']) return posts
class DanbooruService(BaseService): FREE_LEVEL = 20 GOLD_LEVEL = 30 PLATINUM_LEVEL = 31 BUILDER = 32 JANITOR = 35 MODERATOR = 40 ADMIN = 50 LEVEL_RESTRICTIONS = { 'tag_limit': { FREE_LEVEL: 2, GOLD_LEVEL: 6, PLATINUM_LEVEL: 12, BUILDER: 32, JANITOR: 35, MODERATOR: 40, ADMIN: 50, }, 'censored_tags': { FREE_LEVEL: True, GOLD_LEVEL: False, PLATINUM_LEVEL: False, BUILDER: False, JANITOR: False, MODERATOR: False, ADMIN: False, } } type = 'danbooru' def __init__(self, name: str, url: str, api: str = None, username: str = None, password: str = None) -> None: super(DanbooruService, self).__init__(name=name, url=url, api=api, username=username, password=password) self.user_level = None self.init_client() # self.init_session() def init_client(self): if self.api: if not self.username: raise ValueError('Danbooru API Services need a Username when API key is given.') self.client = PyDanbooru(site_name=self.name, site_url=self.url, api_key=self.api, username=self.username) else: self.client = PyDanbooru(site_name=self.name, site_url=self.url) self.user_level = self.get_user_level() self.tag_limit = self.LEVEL_RESTRICTIONS['tag_limit'][self.user_level] self.censored_tags = self.LEVEL_RESTRICTIONS['censored_tags'][self.user_level] if not self.url: self.url = self.client.site_url.lstrip('/') def init_session(self): if self.username and self.password and self.url: self.session = HTMLSession() login_page = self.session.get(f'{self.url.lstrip("/")}/session/new') try: form = login_page.html.find('.simple_form')[0] except Exception as err: __import__('pdb').set_trace() raise err login_data = { 'name': self.username, 'password': self.password, 'remember': '1', } for input in form.find('input'): value = input.attrs.get('value', None) name = input.attrs.get('name', None) if name: login_data.setdefault(name, value) self.session.post(f'{self.url.lstrip("/")}/session', login_data) def get_user_level(self): user_level = 20 if self.username: user = self.client.user_list(name_matches=self.client.username) user_level = user[0]['level'] return user_level
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pybooru import Danbooru client = Danbooru('danbooru', username='******', api_key='yout-api_key') response = client.comment_create(post_id=id, body='your comment') print(client.last_call)
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from telegram.ext import Updater, CommandHandler, MessageHandler, Filters import logging from pybooru import Danbooru client = Danbooru('danbooru') # Enable logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) configFile = open("config.txt", "r") #Replace that line with YOUR config.txt token = str(configFile.readline()) def start(bot, update): update.message.reply_text('Hi {}!'.format( update.message.from_user.first_name)) def help(bot, update): update.message.reply_text(""" Jill at your service.
# 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.danbooru_client = Danbooru(site_name='danbooru')
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 Danbooru client = Danbooru('danbooru') posts = client.post_list(tags='blue_eyes', limit=5) for post in posts: print("Image path: {0}".format(post['file_url']))