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 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 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 __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
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 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 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)
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)
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 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)
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 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 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
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)
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 __init__(self, _tags): client = Danbooru('danbooru') self.posts = client.post_list(limit=1, tags=_tags)
'language': language, } r = requests.post( 'https://api.ocr.space/parse/image', data=payload, ) return r.content.decode() #Load Danbooru API key with open('api.json') as api_file: api_key = json.load(api_file) #Load the API Key and the Danbooru module danbooru_api = api_key["API"][1]["danbooru"] dpic = Danbooru('danbooru', username='******', api_key=danbooru_api) #Create embed objetc def embedpic(title, pic_url, description=None, url=None, author=None, footer=None, color=0x8c4e68): em_color = discord.Colour(color) em = discord.Embed(title=title, description=description, url=url, colour=em_color)
#!/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.
def __init__(self, bot): self.client = Danbooru('danbooru', api_key=dbexec('danbooruKey', log=True)) self.bot = bot
def __init__(self, bot): self.bot = bot self.danbooru_client = Danbooru('danbooru') self.safe_channels = ["general", "robot-shop"] self.blacklisted_tags = set()
import random from uuid import uuid4 from telegram import InlineQueryResultArticle, InputTextMessageContent,\ InlineQueryResultPhoto, InlineQueryResultGif, Bot from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, InlineQueryHandler from pybooru import Danbooru PORT = int(os.environ.get('PORT', 5000)) TOKEN = os.environ["TOKEN"] DUSERNAME = os.environ["DUSERNAME"] DAPIKEY = os.environ["DAPIKEY"] updater = Updater(TOKEN, use_context=True) client = Danbooru('danbooru', username=DUSERNAME, api_key=DAPIKEY) bot = Bot(TOKEN) logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) def main(): dp = updater.dispatcher dp.add_handler(CommandHandler("help", help_command)) dp.add_handler(CommandHandler("random", random_command))
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()
def __init__(self, bot): self.bot = bot self.danbooru_client = Danbooru(site_name='danbooru')