Beispiel #1
1
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)
Beispiel #2
0
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
Beispiel #3
0
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
Beispiel #4
0
 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('попробуй ещё раз')
Beispiel #5
0
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())
Beispiel #6
0
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)
Beispiel #7
0
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
Beispiel #8
0
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
Beispiel #9
0
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)
Beispiel #10
0
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)
Beispiel #11
0
 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)
Beispiel #12
0
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
Beispiel #13
0
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')
Beispiel #14
0
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)
Beispiel #15
0
 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)
Beispiel #16
0
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)
Beispiel #17
0
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
Beispiel #18
0
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
Beispiel #19
0
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)
            await ctx.send(embed=em)

        except (Exception) as e:
            print(e)

    @commands.command()
    async def charinfo(self, ctx, *, name: str):
        """Gets info about anime/manga character"""
        content = doALrequest(q="""query ($s: String, $page: Int) {
			Page(page: $page, perPage: 1) {
				pageInfo {
				total
				currentPage
				lastPage
				hasNextPage
				perPage
				}
				characters(search: $s) {
				name{
					first
					last
					native
					alternative
				}
				image{
					large
				}
				description(asHtml: false)
				}
			}
			}""",
                              v={"s": name})
        if content['data']['Page']['characters']:
            c = content['data']['Page']['characters'][0]
            em = discord.Embed(
                title=
                f"{c['name']['first']} {c['name']['last']if c['name']['last'] is not None else ''} ({c['name']['native']})"
            )
            em.add_field(name='Description',
                         value=c['description'] if len(c['description']) < 1024
                         else c['description'][0:1023],
                         inline=True)
            em.set_image(url=c['image']['large'])
            await ctx.send(embed=em)
        else:
            await ctx.send("This character doesn't exist")

    @commands.command(aliases=['ainfo', 'anime'])
    async def animeinfo(self, ctx, *, name: str):
        """Gets info about an anime"""
        content = doALrequest(q="""query ($s: String, $page: Int) {
        Page(page: $page, perPage: 1) {
            pageInfo {
            total
            currentPage
            lastPage
            hasNextPage
            perPage
            }
            media(search: $s) {
            title {
                romaji
                english
                native
            }
            status
            startDate {
                year
                month
                day
            }
            endDate {
                year
                month
                day
            }
            episodes
            duration
            source
            genres
            averageScore
            popularity
            coverImage {
                large
            }
            description(asHtml: false)
            }
        }
        }""",
                              v={"s": name})
        if content['data']['Page']['media']:
            c = content['data']['Page']['media'][0]
            em = discord.Embed(
                title=
                f"{c['title']['english'] if c['title']['english'] else ''} |  {c['title']['romaji']} ({c['title']['native']})"
            )
            em.add_field(name=c['status'], value='lol')
            em.add_field(name="Episodes",
                         value=f"{c['episodes']}",
                         inline=True)
            em.add_field(name="Duration",
                         value=f"{c['duration']}min per ep",
                         inline=True)
            em.add_field(name='Description',
                         value=c['description'] if len(c['description']) < 1024
                         else c['description'][0:1023],
                         inline=True)
            em.set_image(url=c['coverImage']['large'])
            await ctx.send(embed=em)
        else:
            await ctx.send("This character doesn't exist")
Beispiel #20
0
# 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)
Beispiel #21
0
from pybooru import Danbooru
from pathlib import Path
import urllib.request
import os

client = Danbooru('danbooru')

min_pages = 0
max_pages = min_pages + 2
count = 0

for page in range(min_pages, max_pages):
    posts = client.post_list(limit=100, page=page, random=False, raw=False)
    for post in posts:
        if 'file_url' in post:
            image_url = post['file_url']
            FILE = image_url.split("/")[-1]
            if not os.path.exists("images"):
                os.makedirs("images")
            imagepath = Path("./images")
            if not imagepath.joinpath(FILE).exists():
                try:
                    urllib.request.urlretrieve(image_url, "./images/%s" % FILE)
                    count = count + 1
                    print("*%i: %s" % (count, FILE))
                except:
                    print("%s cannot be retrieved from %s ." %
                          (FILE, image_url))
            else:
                count = count + 1
                print("%i: %s" % (count, image_url))
    import subprocess
    subprocess.check_call(["python", '-m', 'pip', 'install',
                           'requests'])  # install requests
    import requests

client = Danbooru('danbooru',
                  username=DanbooruUsername,
                  api_key=DanbooruAPIKey)
links = []  #create link list
fileNumber = int(000000000)  #i doubt you'll need more space than this

showMoreInfo = False  #change to true if you need to find errors

bannedExtensions = ["zip", "swf", "ebm"]  #put problematic extensions here

posts = client.post_list(tags=tagList,
                         limit=amountOfImages)  #get list of posts
ending = saveLocation[-1]
if ending == "\\" or ending == "/":
    pass  #good file path
else:
    print("Please add two slashes to the end of your save location!")
    os._exit(0)

for post in posts:
    try:
        links.append(post["file_url"])  #get tally of links
        if showMoreInfo == True:  #debug info
            print("Image path: {0}".format(post['file_url']))
    except:
        continue
Beispiel #23
0
# 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)
Beispiel #24
0
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()
Beispiel #25
0
# -*- 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']))
Beispiel #26
0
class ImageBot:
    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')

    def handle_notifications(self):
        try:
            notifications = self.api.notifications()
        except Exception as e:
            logging.error('Exception while fetching notifications: %s', e)
            return
        ln_changed = False

        if isinstance(notifications, dict) and ('error' in notifications):
            raise Exception('API error: {}'.format(notifications['error']))

        if self.last_notification == -1:
            # if this is the first time the bot is running, don't autorespond
            # retroactively
            if len(notifications) > 0:
                self.last_notification = int(notifications[0]['id'])
                logging.debug('Ignoring previous notifications up to %d',
                              self.last_notification)
            else:
                self.last_notification = 0
            ln_changed = True
        else:
            # reversed order to process notification in chronological order
            for notification in notifications[::-1]:
                if int(notification['id']) <= self.last_notification:
                    continue
                if notification['type'] != 'mention':
                    continue

                logging.debug('Handling notification %s', notification['id'])
                self.last_notification = int(notification['id'])
                ln_changed = True

                text = html_to_text(notification['status']['content'])
                text = sanitize_forwarded_toot(text)

                sender = notification['status']['account']['acct']
                sent_by_maintainer = (sender == self.config.maintainer)

                if DELETE_CMD in text:
                    if not sent_by_maintainer:
                        continue
                    try:
                        self.api.status_delete(
                            notification['status']['in_reply_to_id'])
                    except Exception as e:
                        logging.error('exception while deleting status %d: %s',
                                      notification['status']['in_reply_to_id'],
                                      e)

                if sent_by_maintainer:
                    continue

                if not self.config.forward_messages:
                    continue

                if self.config.maintainer in {
                        account['acct']
                        for account in notification['status']['mentions']
                }:
                    # maintainer is already mentioned, no need to forward this message
                    continue

                response = '@{} {}'.format(self.config.maintainer,
                                           self.config.message)

                response_sent = self.api.status_post(
                    response,
                    in_reply_to_id=notification['status']['id'],
                    visibility='direct')

                if notification['status']['visibility'] != 'public':
                    # the bot was sent a DM, we should forward that too
                    recipient_prefix = ' '.join(
                        '@' + x for x in [self.config.maintainer])
                    prev_part_id = response_sent['id']
                    for part in split_into_toots(recipient_prefix, text):
                        part_sent = self.api.status_post(
                            part,
                            in_reply_to_id=prev_part_id,
                            visibility='direct')
                        prev_part_id = part_sent['id']

                logging.info('Responded to status %d from %s',
                             notification['status']['id'],
                             notification['status']['account']['acct'])

        if ln_changed:
            with open(self.config.state_file, 'a') as f:
                f.seek(0)
                f.truncate(0)
                f.write(str(self.last_notification))
                f.flush()

    def post_image(self):
        while not self.image_list:
            try:
                unfiltered_images = self.danbooru.post_list(tags=' '.join(
                    self.config.required_tags),
                                                            limit=100,
                                                            random=True)
                self.image_list = [
                    image for image in unfiltered_images
                    if 'file_url' in image and image['source']
                    and 'bad_id' not in image['tag_string_meta'] and not any(
                        tag in image['tag_string']
                        for tag in self.config.forbidden_tags)
                ]
            except Exception as e:
                logging.error('exception while fetching candidate images: %s',
                              e)
                self.image_list = None

        image = self.image_list.pop()
        source = (PIXIV_SOURCE_PATTERN %
                  image['pixiv_id']) if image['pixiv_id'] else image['source']
        try:
            req = urllib.request.Request(
                image['file_url'],
                headers={
                    "Referer":
                    DANBOORU_URL + "/posts/" + str(image['id']),
                    "User-Agent":
                    "Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0"
                })
            with urllib.request.urlopen(req) as u:
                image_data = u.read()
            image_type = mime.from_buffer(image_data)
            if image_type not in ALLOWED_MIME_TYPES:
                logging.error('unknown mime type %s for file %s', image_type,
                              image['file_url'])
                return
            media = self.api.media_post(image_data, image_type)
            self.api.status_post('{0}/posts/{1}\nsource: {2}'.format(
                DANBOORU_URL, image['id'], source),
                                 media_ids=[media['id']],
                                 visibility='unlisted',
                                 sensitive=True)
            logging.info('posted image: %d', image['id'])
        except Exception as e:
            logging.error('exception while posting image %d: %s', image['id'],
                          e)

    def run(self):
        countdown = 0
        while True:
            if countdown <= 0:
                self.post_image()
                countdown = self.config.post_interval
            countdown -= 1
            self.handle_notifications()
            time.sleep(60)
Beispiel #27
0
class BotClass:
    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

    # Check input and reply according
    def check(self, event):
        check = re.match(r"(!\w+)(\s)?(\D+)?", event.message.text)

        # Command list
        if check.group(1) == "!help":
            message = TextSendMessage(
                text=
                "Commands:\n!tag [query]\n!random\n!dvart [query]\n!rs\n!reddit [subreddit]\n!rsearch [subreddit] [query]\n!tw [name] {#}\n!yt [keywords]\n!bpm set [###]\n!bpm [###]"
            )
            self.line_bot_api.reply_message(event.reply_token, message)

        # !random !tag - Image functions
        elif check.group(1) == "!random":
            self.reply(event)
        elif check.group(1) == "!tag":
            self.reply(event, check.group(3))

        # !site - Check current site
        elif check.group(1) == "!site":
            message = TextSendMessage(text=self.client.site_url)
            self.line_bot_api.reply_message(event.reply_token, message)

        # !hiyuki - Safe mode toggle
        elif check.group(1) == "!hiyuki" and check.group(3) == "lewd":
            self.client = Danbooru('danbooru')
            message = TextSendMessage(text="Safe Mode Off.")
            self.line_bot_api.reply_message(event.reply_token, message)

        elif check.group(1) == "!hiyuki":
            self.client = Danbooru(site_url='https://safebooru.donmai.us/')
            message = TextSendMessage(text="Hiyuki Online!")
            self.line_bot_api.reply_message(event.reply_token, message)

        # !reddit - Reddit Hot
        elif check.group(1) == "!reddit":
            check = re.match(r"!reddit\s(\w+)?", event.message.text)
            subreddit = self.reddit.subreddit(check.group(1))
            search = "r/{0}\n\n".format(check.group(1))
            for submission in subreddit.hot(limit=self.limit):
                search += "{0}\n{1}\n\n".format(submission.title,
                                                submission.url)
            message = TextSendMessage(text=search)
            self.line_bot_api.reply_message(event.reply_token, message)

        # !rsearch - Reddit Search
        elif check.group(1) == "!rsearch":
            check = re.match(r"!rsearch\s(\w+)?(\s)?(\w+)?",
                             event.message.text)
            search = "Searching for \"{0}\" in r/{1}:\n\n".format(
                check.group(3), check.group(1))
            for submission in self.reddit.subreddit(check.group(1)).search(
                    check.group(3), limit=self.limit):
                search += "{0}\n{1}\n\n".format(submission.title,
                                                submission.url)
            message = TextSendMessage(text=search)
            self.line_bot_api.reply_message(event.reply_token, message)

        # !limit - Reddit Limit
        elif check.group(1) == "!limit":
            check = re.match(r"!limit\s(\d)?", event.message.text)
            if check.group(1) is not None:
                self.limit = int(check.group(1))
            message = TextSendMessage(
                text="Limit set to {0}.".format(self.limit))
            self.line_bot_api.reply_message(event.reply_token, message)

        # !rs - Display information about a random Runescape item
        elif check.group(1) == "!rs":
            random = randint(0, 23100)
            url = ("https://www.osrsbox.com/osrsbox-db/items-json/{0}.json".
                   format(random))
            response = urlopen(url)
            data = response.read().decode("utf-8")
            json_obj = json.loads(data)
            message = TextSendMessage(text="{0}\n\n{1}".format(
                json_obj["name"], json_obj["examine"]))
            image = ImageSendMessage(
                original_content_url=
                'https://www.osrsbox.com/osrsbox-db/items-icons/{0}.png'.
                format(random),
                preview_image_url=
                'https://www.osrsbox.com/osrsbox-db/items-icons/{0}.png'.
                format(random))
            self.line_bot_api.reply_message(event.reply_token,
                                            [image, message])

        # !dvart - DeviantArt
        elif check.group(1) == "!dvart":
            loop = 0
            max = 30000
            self.dvart(event, loop, max, check.group(3))

        # !bpm - BPM calculator
        elif check.group(1) == "!bpm":
            check = re.match(r"(!bpm+?)(\s)*(set)*(\s)*(\d+)*",
                             event.message.text)

            # Set the target BPM
            if check.group(3) == "set":
                self.bpm = int(check.group(5))
                message = TextSendMessage(
                    text="BPM set to {0}.".format(self.bpm))
                self.line_bot_api.reply_message(event.reply_token, message)

            # Do BPM multiplication calculations
            else:
                if check.group(5) is not None:
                    input = int(check.group(5))
                    calc = self.bpm / input
                    multi = [
                        0.25, 0.50, 0.75, 1.00, 1.25, 1.50, 1.75, 2.00, 2.25,
                        2.50, 2.75, 3.00, 3.25, 3.50, 3.75, 4.0, 4.5, 5.0, 5.5,
                        6.0, 6.5, 7.0, 7.5, 8.0
                    ]
                    lower = min(multi, key=lambda x: abs(x - calc))
                    if lower * input > self.bpm:
                        upper = multi[multi.index(lower) - 1]
                    elif multi.index(lower) < 23:
                        upper = multi[multi.index(lower) + 1]
                    else:
                        upper = lower
                    low = lower * input
                    up = upper * input
                    if upper == lower or calc == lower:
                        message = TextSendMessage(
                            text="Target: {0}\nInput: {1}\n\n{2}x = {3}".
                            format(self.bpm, input, lower, low))
                    else:
                        message = TextSendMessage(
                            text=
                            "Target: {0}\nInput: {1}\n\n{2}x = {3}\n{4}x = {5}"
                            .format(self.bpm, input, lower, low, upper, up))
                    self.line_bot_api.reply_message(event.reply_token, message)

                # Show the current target BPM if nothing is specified
                else:
                    message = TextSendMessage(
                        text="BPM is currently set to {0}.".format(self.bpm))
                    self.line_bot_api.reply_message(event.reply_token, message)

        # !tw - Retrieve latest Tweet from specified username
        elif check.group(1) == "!tw":
            check = re.match(r"!tw\s(\w+)?\s?(\d+)?", event.message.text)

            # Check for count
            if check.group(2) is None or int(check.group(2)) < 0:
                i = 0
            else:
                i = int(check.group(2))

            # Check for user's existence
            try:
                obj = self.tw.statuses.user_timeline(
                    screen_name=check.group(1), count=i + 1)

                text = TextSendMessage(text="@{0} ({1})\n\n{2}".format(
                    obj[i]['user']['screen_name'], obj[i]['created_at'], obj[i]
                    ['text']))

                # Check for video
                try:
                    video = VideoSendMessage(
                        original_content_url='{0}'.format(
                            obj[i]['extended_entities']['media'][0]
                            ['video_info']['variants'][0]['url']),
                        preview_image_url='{0}'.format(
                            obj[i]['entities']['media'][0]['media_url_https']))
                    self.line_bot_api.reply_message(event.reply_token,
                                                    [text, video])

                # If no video is posted, check for image.
                except KeyError:
                    try:
                        image = ImageSendMessage(
                            original_content_url=obj[i]['entities']['media'][0]
                            ['media_url_https'],
                            preview_image_url=obj[i]['entities']['media'][0]
                            ['media_url_https'])
                        self.line_bot_api.reply_message(
                            event.reply_token, [text, image])

                    # If no image is posted, send text only.
                    except KeyError:
                        self.line_bot_api.reply_message(
                            event.reply_token, text)

            # If user is not found.
            except:
                message = TextSendMessage(text="User not found.")
                self.line_bot_api.reply_message(event.reply_token, message)

        # !yt - Retrieve search results of videos in YouTube using keywords
        elif check.group(1) == "!yt":
            check = re.match(r"!yt\s(.+)?", event.message.text)
            search_response = self.yt.search().list(
                part="snippet", maxResults=5, q=check.group(1)).execute()

            videos = []
            for search_result in search_response.get('items', []):
                if search_result['id']['kind'] == 'youtube#video':
                    videos.append('%s %s' % (search_result['snippet']['title'],
                                             "\nhttps://youtu.be/" +
                                             search_result['id']['videoId']))
            message = TextSendMessage(
                text="YouTube results for \"{0}\":\n\n{1}".format(
                    check.group(1), '\n\n'.join(videos)))
            self.line_bot_api.reply_message(event.reply_token, message)

    # DeviantArt search, multiple tries or else not found
    def dvart(self, event, loop, max, search):
        while loop < 10:
            send = ""
            deviations = []
            fetched_deviations = self.da.browse(endpoint='newest',
                                                q=search,
                                                limit=1,
                                                offset=randint(0, max))
            deviations += fetched_deviations['results']
            for deviation in deviations:
                send += "{0}".format(deviation.content)

            message = re.match(r"{'src': '(\w.+)',", send)
            if message is not None:
                image = ImageSendMessage(original_content_url=message.group(1),
                                         preview_image_url=message.group(1))
                self.line_bot_api.reply_message(event.reply_token, image)
                loop = 10
            else:
                if loop == 9:
                    message = TextSendMessage(text="Not Found.")
                    self.line_bot_api.reply_message(event.reply_token, message)
                    loop += 1
                else:
                    self.dvart(event, loop + 1, max // 3, search)

    # Image reply function
    def reply(self, event, *tag):
        for post in self.client.post_list(tags=tag, limit=1, random=True):
            try:
                image = ImageSendMessage(original_content_url=post['file_url'],
                                         preview_image_url=post['file_url'])
                self.line_bot_api.reply_message(event.reply_token, image)
            except KeyError:
                message = TextSendMessage(text="Too Lewd!")
                self.line_bot_api.reply_message(event.reply_token, message)
        else:
            if contact.print_name == recipient:
                contactFound = True
                break
    if not contactFound:
        print('No matching contact found!')
print('Contact found!')
client = Danbooru('danbooru')
tags = args.tags if args.tags != '' else input(
    'Enter a tag or a collection of tags seperated by ` `: ')
limit = args.amount if args.amount != 0 else input(
    'Enter the amount of photos to send (default is 10): ')
page = args.number if args.number != 0 else input(
    'Enter the page number to send images from (default is 1st page): ')
#posts = client.post_list(limit=2, page=randint(1, 50), tags=tags)
posts = client.post_list(limit=limit, page=page, tags=tags)
print('Found {0} photos'.format(len(posts)))
if isdir('tmp'):
    rmtree('tmp')
mkdir('tmp')
for post in posts:
    if not 'file_url' in post:
        break
    url = 'https://danbooru.donmai.us' + post['file_url']
    path = 'tmp/' + url.split('/')[::-1][0]
    print(url, end='', flush=True)
    request = get(url)
    if request.ok:
        with open(path, 'wb') as file:
            file.write(request.content)
    try:
Beispiel #29
0
class DanbooruSearcher():
    def __init__(self, bot):
        self.bot = bot
        self.danbooru_client = Danbooru('danbooru')
        self.safe_channels = ["general", "robot-shop"]
        self.blacklisted_tags = set()

    @commands.group(pass_context=True)
    async def react(self, ctx, *tags: str):
        if len(tags) == 0:
            tags = ('trap', )
        safe_search_enabled = str(
            ctx.message.channel.name) in self.safe_channels
        if len(tags) > 2:
            await self.bot.say(
                'Sorry. Danbooru only lets me search for two tags at a time. You searched for \'{}\'. If this channel is SFW, you can only search for one tag at a time.'
                .format(', '.join(tags)))
            return
        print('Seeking image for ' + ' '.join(tags))
        try:
            posts = await self.safe_search(
                ctx, tags) if safe_search_enabled else await self.search(tags)
            if posts:
                url = 'https://danbooru.donmai.us' + posts[0]['file_url']
                await self.bot.say(url)
            else:
                return
        except Exception as e:
            print('{} : {}'.format(type(e).__name__, e))
            await self.bot.say(
                'Sorry. I couldn\'t find any images using these tags: ' +
                ' '.join(tags))

    async def search(self, tags: str):
        return self.danbooru_client.post_list(tags=' '.join(tags),
                                              random=True,
                                              limit=1)

    async def safe_search(self, ctx, tags: str):
        print('This is a SFW channel! Adding non-explicit rating tag!')
        tags = tags + ('rating:safe', )
        posts = await self.search(tags)
        attempts = 0
        while self.blacklisted_tags & set(
                posts[0]['tag_string_general'].split(' ')) and attempts < 5:
            posts = await self.search(tags)
            attempts = attempts + 1
        if attempts >= 5:
            await self.bot.say('Couldn\'t find any clean images.')
            await self.bot.send_file(ctx.message.channel,
                                     'images/guess_ill_die.jpg')
            return None
        return posts

    @commands.group(pass_context=True)
    async def blacklist(self, ctx):
        if ctx.invoked_subcommand is None:
            await self.bot.say('Blacklisted tags are: {}'.format(', '.join(
                self.blacklisted_tags)))

    @blacklist.command()
    async def add(self, *tags: str):
        await self.bot.say('Adding tag(s) \'{}\' to blacklist')
        for tag in tags:
            self.blacklisted_tags.add(tag)
Beispiel #30
0
class Bean:
    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)
        
    @commands.command(pass_context=True)
    async def mymmr(self, ctx):
        """Check your true MMR"""
        mmr = randint(0,9999)
        reply_message = 'Hey ' + str(ctx.message.author).split('#', 1)[0] if ctx.message.author.nick == None else 'Hey ' + str(ctx.message.author.nick)
        reply_message += ', your MMR is ' + str(mmr)
        reply_message += ' PogChamp' if  mmr > 5999 else ' LUL'
        await self.bot.say(reply_message)
    
    
    @commands.command(pass_context=True)
    async def gei(self, ctx, *member: discord.User):
        """big gei"""
        gei_percent = randint(0,100)
        if(member):
            reply_message = member[0].mention + ' is '
        else:
            reply_message = 'Hey ' + ctx.message.author.mention + ', you are ' 
        reply_message += str(gei_percent) + '% gei'
        categorylist = [(100, 'Tidp#9927'), (99, 'nitro members'), (97, '4Head'), (96, 'twin turbine c**k'), (86, 'maybe touches your dick'), (76, 'nice butt'), (61, 'arguably gay'), (46, 'wears boating shoes'), (30, 'average european'), (26, '**DO NOT DISTURB THE STATUES**'), (11, '*How did we match clothes again*'), (1, "basic understanding of fashion"), (0, 'HYPERION CHAD PogChamp')]
        for i in range(len(categorylist)):
            if gei_percent >= categorylist[i][0]:
                category = categorylist[i][1]
                break
        await self.bot.say(reply_message + ' - ' + category)

    @commands.command(pass_context=True)
    async def weeb(self, ctx, *member: discord.User):
        """VoHiYo"""
        weeb_percent = 100 if(ctx.message.author.id == "106822120276832256") else randint(0,100)
        if(member):
            if(member[0].id == "106822120276832256"):
                weeb_percent = 100
            reply_message = member[0].mention + ' is '
        else:
            reply_message = 'Hey ' + ctx.message.author.mention + ', you are ' 
        reply_message += str(weeb_percent) + '% weeb'
        reply_message += ' VoHiYo' if  weeb_percent > 50 else ' FeelsGoodMan'
        await self.bot.say(reply_message)


    @commands.command(pass_context=True)
    async def mydong(self, ctx):
        """ur mum knows about it anyway haHAA"""
        dicc = randint(0,25)
        reply_message = 'Hey ' + str(ctx.message.author).split('#', 1)[0] if ctx.message.author.nick == None else 'Hey ' + str(ctx.message.author.nick)
        reply_message = reply_message + ', your dong hangs ' + str(dicc)
        reply_message = reply_message + ' cms low KappaPride' if  dicc > 17 else reply_message + ' cms low Jebaited'
        await self.bot.say(reply_message)


    @commands.command(pass_context=True)
    async def mylove(self, ctx):
        """gachiGASM"""
        if ctx.message.author.nick == None:
            reply_message = 'Hey ' + str(ctx.message.author).split('#', 1)[0]
        else:
            reply_message = 'Hey ' + str(ctx.message.author.nick)
        reply_message = reply_message + ' your true love is '
        server = ctx.message.author.server
        member_list = [x for x in server.members]
        online_member_list = [i for i in member_list if str(i.status) == 'online']
        loveboy = random.choice(online_member_list)
        await self.bot.say(reply_message + loveboy.display_name)

    @commands.command(pass_context=True)
    async def love(self, ctx, *member: discord.User):
        """KappaPride"""
        if member == None:
            reply_message = "You need to mention a name."
        else:
            mmr = randint(0,100)
            reply_message = 'Hey ' + str(ctx.message.author).split('#', 1)[0] if ctx.message.author.nick == None else 'Hey ' + str(ctx.message.author.nick)
            reply_message += ' '.join[', your love for ', member[0].display_name, ' is around ', str(mmr), '%']
            reply_message = reply_message + ' KappaPride' if(mmr > 50) else reply_message + ' FeelsBadMan'
        await self.bot.say(reply_message)
    

    @commands.group(pass_context=True, invoke_without_command=True)
    async def kumiko(self, ctx):
        """ehhhhhh"""
        with open("cogs/res/kumiko.txt", "r+") as f:
            kumiko_img_list = f.read().splitlines()
            reply_message = random.choice(kumiko_img_list)
        await self.bot.say(reply_message)

    @kumiko.command(pass_context=True, name='add')
    async def add_kumiko(self, ctx, *args):
        kumiko_link = list(args)
        link = ' '.join(kumiko_link)
        with open("cogs/res/kumiko.txt", "a+") as f:
            if(ctx.message.author.id in ['106822120276832256', '77462706893881344']):
                f.write(link)
                f.write("\n")
                reply_message = 'Image added'
            else:
                reply_message = "You are not authorized to add rarekumikos"
        await self.bot.say(reply_message)

    @commands.command()
    async def koi(self):
        """bad taste"""
        reply_message = 'https://www.youtube.com/watch?v=DBYDvnAkiao'
        await self.bot.say(reply_message)
    @commands.command()
    async def msking(self):
	    await self.bot.say("https://media.discordapp.net/attachments/292869746293211146/563413592888705024/unknown.png")
    @commands.command()
    async def gorgcblame(self):
        await self.bot.say("Rolling the Gorgc Wheel of Blame")
        time.sleep(2)
        with open("cogs/res/gorgcblame.txt", "r") as f:
            blame = f.readlines()
        await self.bot.say(random.choice(blame))
    @commands.command()
    async def vlecc(self):
        """Retard"""
        await self.bot.say("https://cdn.discordapp.com/attachments/292869746293211146/565075918939357184/unknown.png")

    @commands.group(pass_context=True, invoke_without_command=True)
    async def grill(self, ctx):
        """not gay"""
        with open("cogs/res/grill_list.txt", "r+") as f:
            trap_list = f.read().splitlines()
            reply_message = random.choice(trap_list)
        await self.bot.say(reply_message)

    @grill.command(pass_context=True, name='add')
    async def add_grill(self, ctx, *, query:str):
        with open("cogs/res/grill_list.txt", "a+") as f:
            if(ctx.message.author.id in ['120473568382418945', '77462706893881344']):
                print(query)
                f.write(query)
                f.write("\n")
                reply_message = 'Image added'
            else:
                reply_message = "You are not authorized to add traps"
        await self.bot.say(reply_message)



    @commands.command()   
    async def explosion(self):
        """EKSUPUROOOOOSHUN"""
        expfile = os.path.join("cogs", "res", "explosion.txt")
        with open(expfile, "r") as f:
            explist = f.readlines()
        await self.bot.say(random.choice(explist))


    @commands.group(pass_context=True, invoke_without_command=True)
    async def smug(self, ctx):
        """no explanation needed"""
        with open("cogs/res/smug.txt", "r+") as f:
            smug_list = f.readlines()
        reply_message = random.choice(smug_list)
        await self.bot.say(reply_message)

    @smug.command(pass_context=True, name='add')
    async def add_smug(self, ctx, *args):
        smug_link = list(args)
        link = ' '.join(smug_link)
        with open("cogs/res/smug.txt", "a+") as f:
            if(ctx.message.author.id in ['106822120276832256', '77462706893881344']):
                f.write(link)
                f.write("\n")
                reply_message = 'Image added'
            else:
                reply_message = "You are not authorized to add rarekumikos"
        await self.bot.say(reply_message)


    @commands.command()
    async def mycolor(self):
        """cmonBruh"""
        colors = ['TriHard', 'C-Word', 'KKona', 'jew', 'pajeet', 'ANELE', 'Ruski']
        reply_message = "You're a " + random.choice(colors)
        await self.bot.say(reply_message)


    @commands.command(pass_context=True)
    async def gender(self, ctx, *args):
        """HotPokket"""
        dir = os.path.join("cogs", "res", "gender.txt")
        with open(dir) as f:
            lines = f.read().splitlines()
        auth = str(ctx.message.author).split('#', 1)[0] if ctx.message.author.nick == None else ctx.message.author.nick
        if(len(args) == 0):
            reply_message = auth + " identifies themselves as " + random.choice(lines)
        else:
            genderlist = list(args)
            gender = ' '.join(genderlist)
            print(gender)
            reply_message = gender + " identifies themselves as " + random.choice(lines) if gender.startswith('<@') or gender.startswith('@') else "Enter a valid username or role"
        await self.bot.say(reply_message)    

    @commands.command(pass_context=True)
    async def avatar(self, ctx, *member: discord.User):
        """the fucc do you need a description for"""
        reply_message = member[0].avatar_url if member else ctx.message.author.avatar_url
        await self.bot.say(reply_message)

    @commands.group(pass_context=True, invoke_without_command=True, aliases=['f'])
    async def frenzlin(self, ctx):
        """love u m8"""
        dir = os.path.join("cogs", "res", "frenzlin.txt")
        with open(dir) as f:
            lines = f.readlines()
            await self.bot.say(random.choice(lines))


    @frenzlin.command(pass_context=True, name='add')
    async def add_ritsu(self, ctx, *args):
        ritsu_link = list(args)
        link = ' '.join(ritsu_link)
        with open("cogs/res/frenzlin.txt", "a+") as f:
            if(ctx.message.author.id in ['110840185155010560', '77462706893881344']):
                f.write(link)
                f.write("\n")
                reply_message = 'Image added'
            else:
                reply_message = "You are not authorized to add ritsus"
        await self.bot.say(reply_message)



    @commands.command()
    async def haidomo(self):
        """bacchuaru youtuba"""
        dir = os.path.join("cogs", "res", "kizuna.txt")
        with open(dir) as f:
            lines = f.read().splitlines()
            await self.bot.say(random.choice(lines))

    @commands.command()
    async def havocc(self):
        """gei"""
        dir = os.path.join("cogs", "res", "havok.txt")
        with open(dir) as f:
            lines = f.readlines()
            await self.bot.say(random.choice(lines))


    @commands.command()
    async def bean(self):
        """BEANED"""
        await self.bot.say("http://i0.kym-cdn.com/photos/images/facebook/001/166/993/284.png")
    
    @commands.group(pass_context=True, invoke_without_command=True)
    async def danbooru(self, ctx, *query : str):
        search_string = ' '.join(query)
        print(search_string)
        response = self.dbclient.post_list(tags=search_string, limit=1, random=True)   
        print(response)
        try:
            response_url = response[0]["file_url"]
            if response_url.startswith("https") == False:
                response_url = response_url.replace("/data/", "/data/__")
                response_url = "https://danbooru.donmai.us" + response_url
            await self.bot.say(response_url)
        except:
            await self.bot.say("There's something wrong with your query, because I can't find anything with that tag.")
    
    @commands.command(pass_context=True)
    async def nyx(self, ctx):
        img = os.path.join("cogs", "res", "nyx.png")
        await self.bot.send_file(ctx.message.channel, fp=img)
    
    @commands.command(pass_context=True)
    async def nyxkoi(self, ctx):
        await self.bot.say("https://i.imgur.com/xabuEyd.jpg")

    @commands.command()
    async def christmas(self):
        dir = os.path.join("cogs", "res", "padoruids.txt")
        with open(dir) as f:
            lines = f.readlines()
            await self.bot.say("https://imgur.com/" + random.choice(lines))

    @commands.command()
    async def givemetheipofeveryoneinthischat(self):
        reply_message = '.'.join([str(randint(0, 255)) for x in range(4)])
        await self.bot.say(reply_message)
    
    @commands.command(pass_context=True)
    async def tidp(self,ctx):
        if(random.randint(0, 1) == 0):
            await self.bot.send_typing(ctx.message.channel)
            await self.bot.say('The tiddest of')
            await self.bot.send_typing(ctx.message.channel)
            await self.bot.say('P\'s')
        else:
            for i in range(5):
                await self.bot.send_typing(ctx.message.channel)
                await self.bot.say(":crab: TIDP IS ALIVE :crab: :crab: TIDP IS ALIVE :crab: :crab: TIDP IS ALIVE :crab: :crab: TIDP IS ALIVE :crab: :crab: TIDP IS ALIVE :crab: :crab: TIDP IS ALIVE :crab: :crab: TIDP IS ALIVE :crab: ")
        
    @commands.command(pass_context=True)
    async def fuccboi(self, ctx):
        server = ctx.message.author.server
        member_list = [x for x in server.members]
        self.fuccboiname = random.choice(member_list).display_name if self.fuccboidate != date.today() else self.fuccboiname
        self.fuccboidate = date.today() if self.fuccboidate != date.today() else self.fuccboidate
        reply_message = "Today's fuccboi is " + self.fuccboiname
        await self.bot.say(reply_message)

    @commands.command(pass_context=True)
    async def imgur(self, ctx, *query : str):
        search_string = ' '.join(query)
        url = 'https://api.imgur.com/3/gallery/search/viral/{{window}}/{{page}}?q=' + search_string
        payload = {}
        headers = {
            'Authorization': 'Client-ID ' + self.imgurToken
        }
        response = requests.request('GET', url, headers = headers, data = payload, allow_redirects=False)
        responsejson = json.loads(response.text)
        imgurls = []
        for data in responsejson["data"]:
            try:
                for image in data["images"]:
                    imgurls.append(image["link"])
            except Exception as e:
                pass
        await self.bot.say(random.choice(imgurls))
    
    @commands.command(pass_context=True)
    async def block(self, ctx, *member: discord.User):
        message = await self.bot.get_message(self.bot.get_channel("292869746293211146"), 423951424217677824)
        await self.bot.say("*"+ message.content + "* - Vlecxius, March 15, 2018.")
    
    @commands.command(pass_context=True)
    async def chetp(self, ctx):
        message = '''
            I open up chetp. Koi has already posted lolis. Tidp is frogposting and there's three different conversations about anime studios.

"Ugh, this shit again," I groan. I unzip my pants.

I try my hardest to jerk my soft penis but to no avail. Then Donk astolfo-posts. Instant d-d-d-diamonds. The thought of the little penis is enough to get me going. Then Koi posts a doujin screencap of astolfo falling onto railing. I'm soft again. 

No, I sob internally. This can't be happening. Tidp posts another frog emote. Sheep joins the chat and he's typing single word posts. They're all song lyrics. Donk is thinking now; he's posting the thinking face so he has to be thinking.

But my saving grace finally arrives. Vlecxius posts something revolutionary. 

"COLLEGE BOY <:gachigasm:293953451023663116> PEPEPLS" he proudly proclaims. 

D... d...

D-d-d-d....

DIAMONDS

My prostate almost explodes from the ground shattering nut. Thoughts begin rushing through my head: the Golden Age. Calbee, the eastern slavic white supremacist invasion, the First Bean, Daniel, arcana giveaways, the drawing games, and so much more.

I enter a seizure and let the darkness consume me. My last thought: "die tidp."'''
        await self.bot.say(message)
Beispiel #31
0
class Danbooru(commands.Cog):
    """Commands for Danbooru integration"""
    def __init__(self, bot):
        self.bot = bot
        self.client = Client('danbooru')

    @commands.group(aliases=['db'],
                    pass_context=True,
                    invoke_without_command=True)
    @commands.cooldown(1, 5, commands.BucketType.member)
    async def danbooru(self, ctx, *, query: str):
        """Return a random image from danbooru"""
        exceptions = (custom_exceptions.NSFWException,
                      custom_exceptions.ResourceNotFound,
                      custom_exceptions.Error, Exception)
        try:
            adapted_query = check_query(query)
            post = self.client.post_list(tags='rating:safe ' + adapted_query,
                                         limit=1,
                                         random=True)
            embed = discord.Embed(color=discord.Colour.red()).set_image(
                url=return_valid_image(post))
            await ctx.message.add_reaction('\U00002705')
            await ctx.send(embed=embed)
        except exceptions as e:
            await ctx.message.add_reaction('\U0000274c')
            await ctx.send(e, delete_after=10)

    @danbooru.command(aliases=['n'])
    @commands.cooldown(1, 5, commands.BucketType.member)
    async def nsfw(self, ctx, *, query: str):
        """Return a random NSFW image from danbooru"""
        exceptions = (custom_exceptions.NSFWException,
                      custom_exceptions.ResourceNotFound,
                      custom_exceptions.Error, Exception)
        try:
            check_nsfw(ctx)
            adapted_query = check_nsfw_query(query)
            post = self.client.post_list(tags=adapted_query,
                                         limit=1,
                                         random=True)
            embed = discord.Embed(color=discord.Colour.red()).set_image(
                url=return_valid_image(post))
            await ctx.message.add_reaction('\U00002705')
            await ctx.send(embed=embed)
        except exceptions as e:
            await ctx.message.add_reaction('\U0000274c')
            await ctx.send(e, delete_after=10)

    @danbooru.command(aliases=['t'])
    @commands.cooldown(1, 5, commands.BucketType.member)
    async def tags(self, ctx, *, query: str):
        """Return name matches from your query"""
        exceptions = (custom_exceptions.ResourceNotFound, Exception)
        try:
            list_tags = self.client.tag_list(name_matches=query)
            tags = return_tags(list_tags)
            pages = Pages(ctx, lines=tags)
            await ctx.message.add_reaction('\U00002705')
            await pages.paginate()
        except exceptions as e:
            await ctx.message.add_reaction('\U0000274c')
            await ctx.send(e, delete_after=10)
Beispiel #32
0
 def __init__(self, _tags):
     client = Danbooru('danbooru')
     self.posts = client.post_list(limit=1, tags=_tags)