Exemplo n.º 1
0
def send_message():
	image = Images.query.filter_by(is_sent=0).first()

	if image == None:
		imgur_client = ImgurClient(os.environ.get('IMGUR_CLIENT_ID'), os.environ.get('IMGUR_CLIENT_SECRET'))
		clarifai_api = ClarifaiApi()

		images = imgur_client.subreddit_gallery(subreddit='aww', page=0)

		for image in images:
			if image.is_album == False and ('jpeg' in image.type):
				try:
					result = clarifai_api.tag_image_urls(image.link)
					total_result = result['results'][0]['result']['tag']['classes']
					if len(set(total_result).intersection(['dog', 'puppy', 'cat', 'kitten', 'bird'])) > 0:
						db.session.add(Images(image.link))
						db.session.commit()
				except:
					pass

		image = Images.query.filter_by(is_sent=0).first()

	users = Users.query.filter_by(active=1).all()

	for user in users:
		try:
			client = TwilioRestClient(os.environ.get('TWILIO_ACCOUNT_SID'), os.environ.get('TWILIO_AUTH_TOKEN'))
			message  = client.messages.create(to=user.number, from_="+19733214779", media_url=[image.link])
		except:
			pass
		
	image.is_sent = 1
	db.session.commit()
Exemplo n.º 2
0
    async def imgur(self, *text):
        """Retrieves a picture from imgur

        imgur search [keyword] - Retrieves first hit of search query.
        imgur [subreddit section] [top or new] - Retrieves top 3 hottest or latest pictures of today for given a subreddit section, e.g. 'funny'."""
        imgurclient = ImgurClient("1fd3ef04daf8cab", "f963e574e8e3c17993c933af4f0522e1dc01e230")
        if text == ():
            rand = randint(0, 59) #60 results per generated page
            items = imgurclient.gallery_random(page=0)
            await self.bot.say(items[rand].link)
        elif text[0] == "search":
            items = imgurclient.gallery_search(" ".join(text[1:len(text)]), advanced=None, sort='time', window='all', page=0)
            if len(items) < 1:
                await self.bot.say("NI PRSLO DO REZULTATU DJOPORKO!")
            else:
                await self.bot.say(items[0].link)
        elif text[0] != ():
            try:
                if text[1] == "top":
                    imgSort = "top"
                elif text[1] == "new":
                    imgSort = "time"
                else:
                    await self.bot.say("Only top or new is a valid subcommand.")
                    return
                items = imgurclient.subreddit_gallery(text[0], sort=imgSort, window='day', page=0)
                if (len(items) < 3):
                    await self.bot.say("This subreddit section does not exist, try 'funny'")
                else:
                    await self.bot.say("{} {} {}".format(items[0].link, items[1].link, items[2].link))
            except:
                await self.bot.say("Type help imgur for details.")
Exemplo n.º 3
0
def imgur_hon():
    client = ImgurClient(ckey, csecret)
    window_list = ['month','year','all']
    item_select = random.randint(0,10)
    items = client.subreddit_gallery('models', sort='top', window=random.choice(window_list), page=random.randint(0,5))
    image = items[item_select].link
    return image
Exemplo n.º 4
0
def get_images():
    client_id = 'a07481456742e43'
    client_secret = '2046f8fb4c75f5bba6d0312a1519957571ffd88e'

    client = ImgurClient(client_id, client_secret)

    items = client.subreddit_gallery(subreddit="GifRecipes",
                                     sort="top",
                                     window="all")
    recipes = {}
    for item in items:
        curRecipe = {}
        if "removed" not in item.link:
            curRecipe["title"] = item.title
            curRecipe["views"] = item.views

            pictureLink = item.link[:-4]
            if (pictureLink.endswith("h") and len(pictureLink) == 27):
                pictureLink = pictureLink[:-1]
            pictureLink = pictureLink + ".gif"

            curRecipe["picture_link"] = pictureLink
            curRecipe["submit_date"] = time.strftime(
                '%Y-%m-%d', time.localtime(item.datetime))
            recipes[item.title] = curRecipe

    for r, recipe_data in recipes.items():
        add_recipe(recipe_data["title"], recipe_data["views"], None,
                   recipe_data["picture_link"], recipe_data["submit_date"])
Exemplo n.º 5
0
    async def imgur(self, *text):
        """Retrieves a picture from imgur

        imgur search [keyword] - Retrieves first hit of search query.
        imgur [subreddit section] [top or new] - Retrieves top 3 hottest or latest pictures of today for given a subreddit section, e.g. 'funny'."""
        imgurclient = ImgurClient("1fd3ef04daf8cab", "f963e574e8e3c17993c933af4f0522e1dc01e230")
        if text == ():
            rand = randint(0, 59) #60 results per generated page
            items = imgurclient.gallery_random(page=0)
            await self.bot.say(items[rand].link)
        elif text[0] == "search":
            items = imgurclient.gallery_search(" ".join(text[1:len(text)]), advanced=None, sort='time', window='all', page=0)
            if len(items) < 1:
                await self.bot.say("Your search terms gave no results.")
            else:
                await self.bot.say(items[0].link)
        elif text[0] != ():
            try:
                if text[1] == "top":
                    imgSort = "top"
                elif text[1] == "new":
                    imgSort = "time"
                else:
                    await self.bot.say("Only top or new is a valid subcommand.")
                    return
                items = imgurclient.subreddit_gallery(text[0], sort=imgSort, window='day', page=0)
                if (len(items) < 3):
                    await self.bot.say("This subreddit section does not exist, try 'funny'")
                else:
                    await self.bot.say("{} {} {}".format(items[0].link, items[1].link, items[2].link))
            except:
                await self.bot.say("Type help imgur for details.")
Exemplo n.º 6
0
class Imgur:
    def __init__(self, bot):
        self.bot = bot

        self.imgur_client = ImgurClient(IMGUR_CLIENT_ID, IMGUR_CLIENT_SECRET)

    @commands.command()
    async def imgur(self, ctx, *, search: str = None):
        await ctx.trigger_typing()
        try:
            if search is not None:
                images = self.imgur_client.gallery_search(search)
                image = choice(images)
                if await self.nsfw_check(image, ctx.message.channel) is True:
                    await ctx.send(image.link)
            else:
                await ctx.send('No search query set.')
        except IndexError as e:
            await ctx.send('Nothing found for: {}'.format(search))

    @commands.command()
    async def memes(self, ctx):
        try:
            await ctx.trigger_typing()
            images = self.imgur_client.default_memes()
            image = choice(images)
            if await self.nsfw_check(image, ctx.message.channel) is True:
                await ctx.send(image.link)
        except IndexError as e:
            await ctx.send('Error: Nothing found.')

    @commands.command(pass_context=True)
    async def sr(self, ctx, *, search: str):
        await ctx.trigger_typing()
        try:
            if search is not None:
                images = self.imgur_client.subreddit_gallery(search)
                image = choice(images)
                if await self.nsfw_check(image, ctx.message.channel) is True:
                    await ctx.send(image.link)
            else:
                await ctx.send('No search query set.')
        except IndexError as e:
            await ctx.send('Nothing found for: {}'.format(search))

    async def nsfw_check(self, image, channel):
        if image.nsfw is False:
            return True
        elif image.nsfw is True and channel.is_nsfw():
            return True
        await channel.send(
            '**NSFW Picture**: Please only lookup nsfw content in **nsfw** channels.'
        )
        return False
Exemplo n.º 7
0
    async def imgur(self, *text):
        """Retrieves a picture from imgur

        imgur search [keyword] - Retrieves first hit of search query.
        imgur [subreddit section] [top or new] - Retrieves top 3 hottest or latest pictures of today for given a subreddit section, e.g. 'funny'."""
        imgurclient = ImgurClient("1fd3ef04daf8cab",
                                  "f963e574e8e3c17993c933af4f0522e1dc01e230")
        if text == ():
            rand = randint(0, 59)  #60 results per generated page
            items = imgurclient.gallery_random(page=0)
            #colour = ''.join([randchoice('0123456789ABCDEF') for x in range(6)])
            #colour = int(colour, 16)
            #embed=discord.Embed(colour=discord.Colour(value=colour))
            #embed.set_author(name="Imgur", icon_url=self.bot.user.avatar_url)
            #embed.set_image(url=items[rand].link)
            #await self.bot.say(embed=embed)
            await self.bot.say(items[rand].link)
        elif text[0] == "search":
            items = imgurclient.gallery_search(" ".join(text[1:len(text)]),
                                               advanced=None,
                                               sort='time',
                                               window='all',
                                               page=0)
            if len(items) < 1:
                await self.bot.say("Your search terms gave no results.")
            else:
                await self.bot.say(items[0].link)
        elif text[0] != ():
            try:
                if text[1] == "top":
                    imgSort = "top"
                elif text[1] == "new":
                    imgSort = "time"
                else:
                    await self.bot.say("Only top or new is a valid subcommand."
                                       )
                    return
                items = imgurclient.subreddit_gallery(text[0],
                                                      sort=imgSort,
                                                      window='day',
                                                      page=0)
                if (len(items) < 3):
                    await self.bot.say(
                        "This subreddit section does not exist, try 'funny'")
                else:
                    await self.bot.say("{} {} {}".format(
                        items[0].link, items[1].link, items[2].link))
            except:
                pass
Exemplo n.º 8
0
def aww(bot, event, *args):
    try:
        client = ImgurClient(imgur_client, imgur_secret)
        funny = client.subreddit_gallery('aww')
        link_image = random.choice(funny).link
        logger.info("getting {}".format(link_image))
        filename = os.path.basename(link_image)
        r = yield from aiohttp.request('get', link_image)
        raw = yield from r.read()
        image_data = io.BytesIO(raw)
        image_id = yield from bot._client.upload_image(image_data, filename=filename)
        yield from bot.coro_send_message(event.conv.id_, None, image_id=image_id)
    except Exception as e:
        msg = _('{} -- {}').format(str(e), event.text)
        yield from bot.coro_send_message(CONTROL, msg)
Exemplo n.º 9
0
def __init__(self, core):
    Plugin.__init__(self, core=core)

    client_id = '7d5a48eb8f3b168'
    client_secret = 'f2886ec020ea9c5a46141bf8d6d7e100c2bc1bb1'
    client = ImgurClient(client_id, client_secret)

    self.images = [image for image in client.subreddit_gallery('animenocontext', sort='time', window='day', page=0)]

    @thread
    @command('animewtf')
    def animewtf(self, message):
        '''Anime shows are wonderful...'''
        self.core.send_message(message.channel, self._get_img())

    def _get_img(self):
        return self.images[randint(0, len(self.images) - 1)].link
Exemplo n.º 10
0
    async def sr(self, *text):
        """sr [keyword] - Retrieves a random picture from subreddit"""
        imgurclient = ImgurClient("ad8952f4d3e875e",
                                  "7438169dd1b096d0dca330e826aeb120fbec6bcc")
        if text[0] != ():
            randpage = randint(0, 9)  #randomize page 0-9
            items = imgurclient.subreddit_gallery(text[0],
                                                  sort='time',
                                                  window='all',
                                                  page=randpage)
            rand = randint(0, len(items))  #randomize result
            if len(items) < 1:
                await self.bot.say("No result for: {}".format(text[0]))
            else:
                await self.bot.say(items[rand].link)

        elif text[0] == ():
            await self.bot.say("Type help sr for details.")
Exemplo n.º 11
0
def get_random_image(sub):
    """
    Returns 15 random images from a random subreddit based in the `sub` param.
    """
    client_id = os.environ.get('IMGUR_CLIENT_ID')
    client_secret = os.environ.get('IMGUR_CLIENT_SECRET')

    if client_id and client_secret:
        client = ImgurClient(client_id, client_secret)

        subreddit_list = get_subreddit_list(sub)
        subreddit = client.subreddit_gallery(random.choice(subreddit_list))

        # Uncomment this if you want just a single image to be returned.
        # return random.choice(subreddit).link

        # We'll return 15 imgur photo links, each in its own line.
        sample = random.sample(subreddit, 15)
        return "\n".join([item.link for item in sample])
Exemplo n.º 12
0
def update_programmer_humor_img(name):
    try:
        client_id = os.environ['CLIENT_ID']
        client_secret = os.environ['CLIENT_SECRET']
        client = ImgurClient(client_id, client_secret)
        items = client.subreddit_gallery(name,
                                         sort='top',
                                         window='week',
                                         page=0)
        for item in items:
            if item.link.endswith(".mp4") or item.link.endswith(".gif"):
                continue
            else:
                return '<a href="https://imgur.com/r/ProgrammerHumor/{}"><img height="400" width="400" src="{}"></a>'.format(
                    item.id, item.link)
        return '<a href="https://imgur.com/r/ProgrammerHumor/{}"><img height="400" width="400" src="https://i.imgur.com/{}"></a>'.format(
            "SV767tT", "SV767tT")
    except ImgurClientError as e:
        print(e.error_message)
Exemplo n.º 13
0
def get_meme():

    
    subreddits = [
        'holdmybeer',
        'funny',
        'whitepeopletwitter',
        'holdmyfries',
        'MemeEconomy',
        'wholesomememes',
        'dankmemes',
        'Whatcouldgowrong',
        'RedneckGifs',
        'gifs'
    ]
    # Get Length of list
    subRedditLength = len(subreddits)
    subRedditKey = randint(0, subRedditLength-1)

    # Plug this into api for a random subreddit
    subReddit = subreddits[subRedditKey]
    
    # Connect to Client
    client = ImgurClient(client_id, client_secret)


    # https://github.com/Imgur/imgurpython
    items = client.subreddit_gallery(subReddit, sort='top', window='day', page=0)


    # Grab the length of the dictionary returned from IMGUR
    imgurLength = len(items)

    if imgurLength != 0:
        # Get random element
        key = randint(0, imgurLength)

        # Grab random meme link
        link = items[key].link

        return link
    else:
        return 'Please try again!'
Exemplo n.º 14
0
def __init__(self, core):
    Plugin.__init__(self, core=core)

    client_id = '7d5a48eb8f3b168'
    client_secret = 'f2886ec020ea9c5a46141bf8d6d7e100c2bc1bb1'
    client = ImgurClient(client_id, client_secret)

    self.images = [
        image for image in client.subreddit_gallery(
            'animenocontext', sort='time', window='day', page=0)
    ]

    @thread
    @command('animewtf')
    def animewtf(self, message):
        '''Anime shows are wonderful...'''
        self.core.send_message(message.channel, self._get_img())

    def _get_img(self):
        return self.images[randint(0, len(self.images) - 1)].link
Exemplo n.º 15
0
def send_message():
    image = Images.query.filter_by(is_sent=0).first()

    if image == None:
        imgur_client = ImgurClient(os.environ.get('IMGUR_CLIENT_ID'),
                                   os.environ.get('IMGUR_CLIENT_SECRET'))
        clarifai_api = ClarifaiApi()

        images = imgur_client.subreddit_gallery(subreddit='aww', page=0)

        for image in images:
            if image.is_album == False and ('jpeg' in image.type):
                try:
                    result = clarifai_api.tag_image_urls(image.link)
                    total_result = result['results'][0]['result']['tag'][
                        'classes']
                    if len(
                            set(total_result).intersection([
                                'dog', 'puppy', 'cat', 'kitten', 'bird'
                            ])) > 0:
                        db.session.add(Images(image.link))
                        db.session.commit()
                except:
                    pass

        image = Images.query.filter_by(is_sent=0).first()

    users = Users.query.filter_by(active=1).all()

    for user in users:
        try:
            client = TwilioRestClient(os.environ.get('TWILIO_ACCOUNT_SID'),
                                      os.environ.get('TWILIO_AUTH_TOKEN'))
            message = client.messages.create(to=user.number,
                                             from_="+19733214779",
                                             media_url=[image.link])
        except:
            pass

    image.is_sent = 1
    db.session.commit()
Exemplo n.º 16
0
    def subreddit(self, source, engine, message, cmd, args):
        engine.telegram.sendChatAction(message.chat_id, telegram.ChatAction.TYPING)
        client = ImgurClient(configurator.get('IMGUR_KEY'), configurator.get('IMGUR_SECRET'))

        gallery = client.subreddit_gallery(source, sort='new', window='all', page=int(random() * 30))
        gallery = filter(lambda item: hasattr(item, 'size') and item.size > 0, gallery)

        print(gallery)

        attempt = 0
        while attempt < 3:
            item = choice(gallery)

            engine.telegram.sendChatAction(message.chat_id, telegram.ChatAction.UPLOAD_PHOTO)

            print(message.chat_id)
            print(item.link)
            print(item.title)

            tf = NamedTemporaryFile(delete=False, suffix=item.link.split('.')[-1])
            img = urllib2.urlopen(item.link).read()
            tf.write(img)
            tf.close()

            try:
                engine.telegram.sendPhoto(
                    chat_id=message.chat_id,
                    photo=open(tf.name, 'r'),
                    # photo='https://www.google.com.ua/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png',
                    # caption=item.title
                )
                os.unlink(tf.name)
                return True
            except:
                os.unlink(tf.name)
                attempt += 1
        engine.telegram.sendMessage(chat_id=message.chat_id, text='Я тричі спробувала отримати картинку, але сталася якась помилка в API telegram :(')

        return True
Exemplo n.º 17
0
def get_imgur_image(text):
    client_id = os.environ.get('IMGUR_CLIENT_ID')
    client_secret = os.environ.get('IMGUR_CLIENT_SECRET')

    if client_id and client_secret:
        client = ImgurClient(client_id, client_secret)

        query_string = query_string_from_text(text)
        subreddit_match = subreddit_pattern.match(query_string)

        if subreddit_match:
            subreddit = subreddit_match.group(1)
            result = client.subreddit_gallery(subreddit)
            result = random_link_from_gallery_list(result, client)
        else:
            result = client.gallery_search(query_string, sort='top')
            result = first_link_from_gallery_list(result, client)

        if not result:
            return "No matching image found"

        return result
Exemplo n.º 18
0
                'INSERT INTO images (name, key, url, description) '
                'VALUES (?, ?, ?, ?);', (title, key, url, description))


RESOURCES = 'resources'

if __name__ == '__main__':
    # TODO: Command line interface
    db = database.make_db('imp.db')
    with open('SECRET', 'r') as f:
        vals = json.loads(f.read())
        client_id = vals['client_id']
        client_secret = vals['client_secret']
        client = ImgurClient(client_id, client_secret)

    vals = client.subreddit_gallery(sys.argv[1])
    for val in vals:
        val.link = val.link.replace('http:', 'https:')
        record_image(val.link, val.title, val.description)

    not_downloaded = db.execute('SELECT * FROM images WHERE file IS NULL;')
    if not os.path.isdir(RESOURCES):
        os.mkdir(RESOURCES)
    for image in not_downloaded.fetchall():
        fname = image['url'].split('/')[-1]
        fname = os.path.join(RESOURCES, fname)
        download_image(image['url'], fname)
        with db:
            db.execute('UPDATE images SET file = ? WHERE id = ?',
                       (fname, image['id']))
            logger.info("UPDATE images SET file = '%s' WHERE id = %s", fname,
Exemplo n.º 19
0
class Plugin(object):
    def __init__(self, pm):
        self.pm = pm
        self.hugs = [
            '(づ ̄ ³ ̄)づ', '(つ≧▽≦)つ', '(つ✧ω✧)つ', '(づ ◕‿◕ )づ', '(⊃。•́‿•̀。)⊃',
            '(つ . •́ _ʖ •̀ .)つ', '(っಠ‿ಠ)っ', '(づ◡﹏◡)づ'
        ]
        self.configPath = 'pluginsconfig/data_config-utils_a.json'
        self.configDB = TinyDB(self.configPath)
        self.macroPath = 'pluginsconfig/data_macro_a.json'
        self.macroDB = TinyDB(self.macroPath)
        self.chaninfoPath = 'pluginsconfig/data_channel-info_a.json'
        self.chaninfDB = TinyDB(self.chaninfoPath)
        #self.converter = CurrencyConverter()
        print("[Noku-utils]Initalizing Imgur Stuff...")
        self.client = ImgurClient("43bdb8ab21d18b9",
                                  "fcba34a83a4650474ac57f6e3f8b0750dd26ecf5")
        print("[Noku-utils]Retrieving Images...")
        self.wmimages = self.client.subreddit_gallery("wholesomememes")
        self.catimages = self.client.subreddit_gallery("catsstandingup")
        self.dogimages = self.client.subreddit_gallery("rarepuppers")
        self.kanye = [
            "I miss the old Kanye, straight from the Go Kanye\nChop up the soul Kanye, set on his goals Kanye",
            "I hate the new Kanye, the bad mood Kanye\nThe always rude Kanye, spaz in the news Kanye",
            "I miss the sweet Kanye, chop up the beats Kanye",
            "I gotta say, at that time I'd like to meet Kanye",
            "See, I invented Kanye, it wasn't any Kanyes\nAnd now I look and look around and there's so many Kanyes",
            "I used to love Kanye, I used to love Kanye\nI even had the pink polo, I thought I was Kanye",
            "What if Kanye made a song about Kanye\nCalled 'I Miss The Old Kanye'? Man, that'd be so Kanye",
            "That's all it was Kanye, we still love Kanye\nAnd I love you like Kanye loves Kanye"
        ]
        self.kanyeOrder = 0
        self.pats = [
            '{1}(ノ_<。)ヾ(´▽`){0}', '{1}。・゚・(ノД`)ヽ( ̄ω ̄ ){0}',
            '{1}ρ(-ω-、)ヾ( ̄ω ̄; ){0}', '{0}ヽ( ̄ω ̄(。。 )ゝ{1}',
            '{0}(*´I`)ノ゚(ノД`゚)゚。{1}', '{0}ヽ(~_~(・_・ )ゝ{1}',
            '{1}(ノ_;)ヾ(´∀`){0}', '{1}(;ω; )ヾ(´∀`* ){0}', '{0}(*´ー)ノ(ノд`){1}',
            '{0}(´-ω-`( _ _ ){1}', '{0}(っ´ω`)ノ(╥ω╥){1}', '{0}(o・_・)ノ”(ノ_<、){1}'
        ]
        self.userqueue = []

    @staticmethod
    def register_events():
        return [
            Events.Command("ping", Ranks.Default,
                           "Pings the bot, nothing special"),
            Events.Command("hug", Ranks.Default,
                           "[@username] Sends a hug to a user."),
            Events.Command("system.purgeAllDM", Ranks.Admin,
                           "(!Admin use only)~~Cause people are paranoid"),
            Events.Command("pat", Ranks.Default,
                           "[@username] Sends a pat to a user."),
            Events.Command("info.set", Ranks.Admin),
            Events.Command("info.delete", Ranks.Admin),
            Events.Command("info", Ranks.Default, "Shows channel info"),
            Events.Command("meme", Ranks.Default, "posts a wholesome meme"),
            Events.Command("exch", Ranks.Default,
                           "[ammount] [from] [to] converts currency"),
            Events.Command("ud", Ranks.Default, "[query] Urban Dictionary"),
            Events.Command("lang", Ranks.Default,
                           "[query] Tries to determine the language"),
            Events.Command("cats", Ranks.Default, "Posts a cat"),
            Events.Command("emotext", Ranks.Default, "Emojifies a text"),
            Events.Command(
                "poll", Ranks.Default,
                "[question]/[item1]/[item2]/[item3]/[item..] posts a poll and its corresponding reactions."
            ),
            Events.Command("dogs", Ranks.Default, "Posts a dog"),
            Events.Command("old", Ranks.Default, "Kanye Kanye Kanye"),
            Events.Command("qjoin", Ranks.Default, "Join Queue"),
            Events.Command("qdone", Ranks.Default, "Finish Queue"),
            Events.Command("qview", Ranks.Default, "View Queue"),
            Events.Command("qkick", Ranks.Admin,
                           "[Admin] Kick user from Queue"),
            Events.Command("qreset", Ranks.Default, "[Admin] Reset Queue"),
            Events.Command("qhelp", Ranks.Default, "View Queue"),
            Events.Command("pins", Ranks.Default,
                           "[#channel] shows pins from a specified channel."),
            Events.Command("print_avatars_to_console", Ranks.Admin,
                           "[secret stuff]"),
            Events.Command("utils.allow", Ranks.Admin),
            Events.Command("restart", Ranks.Admin),
            Events.Command("utils.block", Ranks.Admin)
        ]

    async def handle_command(self, message_object, command, args):

        try:
            print("--{2}--\n[Noku-utils] {0} command from {1} by {3}".format(
                command, message_object.channel.name,
                arrow.now().format('MM-DD HH:mm:ss'),
                message_object.author.name))
        except:
            print("[Noku]Cannot display data, probably emojis.")
        #print(args)
        config = Query()

        if self.configDB.contains(config.chanallow == message_object.channel.id
                                  ) or message_object.channel.is_private:
            if command == "ping":
                await self.ping(message_object, "Pong")
            if command == "system.purgeAllDM":
                await self.purge(message_object)
            elif command == "pins":
                await self.showpins(message_object)
            elif command == "poll":
                await self.makepoll(message_object, args[1])
            elif command == "hug":
                await self.hug(message_object)
            elif command == "pat":
                await self.pat(message_object)
            elif command == "emotext":
                await self.emotext(message_object, args[1])
            elif command == "exch":
                await self.currency(message_object, args[1])
            elif command == "meme":
                await self.postmeme(message_object, self.wmimages)
            elif command == "ud":
                await self.urban(message_object, args[1])
            elif command == "lang":
                await self.lang(message_object, args[1])
            elif command == "cats":
                await self.postmeme(message_object, self.catimages)
            elif command == "dogs":
                await self.postmeme(message_object, self.dogimages)
            elif command == "old":
                await self.old(message_object, args[1])
            elif command == "info.set":
                await self.chaninfo(message_object, args[1], "set")
            elif command == "info.delete":
                await self.chaninfo(message_object, args[1], "delete")
            elif command == "info":
                await self.chaninfo(message_object, args[1], "info")
            elif command == "restart":
                await self.shutdown(message_object)
            elif command == "print_avatars_to_console":
                await self.getuser(message_object)

        if command == "qjoin":
            await self.qjoin(message_object)
        if command == "qdone":
            await self.qdone(message_object)
        if command == "qview":
            await self.qview(message_object)
        if command == "qkick":
            await self.qkick(message_object)
        if command == "qreset":
            await self.qreset(message_object)
        if command == "qhelp":
            await self.qhelp(message_object)

        if command == "utils.allow":
            await self.allowChan(message_object)
        if command == "utils.block":
            await self.blockChan(message_object)

    async def qhelp(self, message_object):
        em = discord.Embed(
            title="Queue Help",
            description=
            "**~qjoin** : _Join Queue_\n**~qdone** : _Finish your turn_\n**~qview** : _Display the users in Queue_\n**~qkick** <@user> : _Kicks user from Queue (Admin only)_\n**~qreset** : _Resets Queue (Admin only)_",
            colour=0x007AFF)
        await self.pm.client.send_message(message_object.channel, embed=em)

    async def qkick(self, message_object):
        try:
            self.userqueue.remove(message_object.mentions[0])
            em = discord.Embed(
                title="Queue",
                description="{0} has been kicked from the Queue!".format(
                    message_object.mentions[0].name),
                colour=0x007AFF)
        except:
            em = discord.Embed(
                title="Queue",
                description=
                "No user specified or the user is not in the queue!",
                colour=0x007AFF)

        await self.pm.client.send_message(message_object.channel, embed=em)

    async def qreset(self, message_object):
        self.userqueue = []
        em = discord.Embed(title="Queue",
                           description="The queue has been emptied!",
                           colour=0x007AFF)
        await self.pm.client.send_message(message_object.channel, embed=em)

    async def qview(self, message_object):
        if len(self.userqueue) > 0:
            display = "There's currently {0} users in the queue.\n---\n".format(
                len(self.userqueue))
            count = 1
            for user in self.userqueue:
                display += "{0}. **{1}**\n".format(count, user.name)
                count += 1

            em = discord.Embed(title="Queue",
                               description=display,
                               colour=0x007AFF)
        else:
            em = discord.Embed(title="Queue",
                               description="The queue is empty!",
                               colour=0x007AFF)

        await self.pm.client.send_message(message_object.channel, embed=em)

    async def qdone(self, message_object):
        try:
            self.userqueue.remove(message_object.author)
            em = discord.Embed(title="Queue",
                               description="You Successfuly left the Queue!",
                               colour=0x007AFF)
        except:
            em = discord.Embed(title="Queue",
                               description="You're not in the Queue!",
                               colour=0x007AFF)

        await self.pm.client.send_message(message_object.channel, embed=em)
        await self.qview(message_object)

    async def qjoin(self, message_object):
        if not message_object.author in self.userqueue:
            self.userqueue.append(message_object.author)
            em = discord.Embed(
                title="Queue",
                description="{0} has been added to the queue!".format(
                    message_object.author.name),
                colour=0x007AFF)
        else:
            em = discord.Embed(
                title="Queue",
                description="{0} is already in the queue!".format(
                    message_object.author.name),
                colour=0x007AFF)

        await self.pm.client.send_message(message_object.channel, embed=em)
        await self.qview(message_object)

    async def currency(self, message_object, args):
        try:
            ammount = int(args.split(" ")[0])
            fr = args.split(" ")[1]
            to = args.split(" ")[2]
            re = requests.get(
                "https://currency-api.appspot.com/api/{0}/{1}.json".format(
                    fr.lower(), to.lower()))
            if re.json()["success"] or re.json()["success"] == "true":
                converted = ammount * float(re.json()["rate"])
                description = ":currency_exchange: **{0:,.2f} {1}** Equals **{2:,.2f} {3}**".format(
                    ammount, fr.upper(), converted, to.upper())
                #em = discord.Embed(title=title, description=wjson["Weather"]["status"],)
                em = discord.Embed(title="Currency Exchange",
                                   description=description,
                                   colour=0x007AFF)
                em.set_footer(text="Current Rate: 1 {0} = {1} {2}".format(
                    fr.upper(),
                    re.json()["rate"], to.upper()))
            else:
                description = ":exclamation: _Invalid currency specified!_"
                #em = discord.Embed(title=title, description=wjson["Weather"]["status"], colour=0x007AFF)
                em = discord.Embed(title="Currency Exchange",
                                   description=description,
                                   colour=0x007AFF)

            await self.pm.client.send_message(message_object.channel, embed=em)
        except:
            description = ":information_source: Usage: [ammount] [from] [to]\nEx. `~exch 100 jpy usd`"
            em = discord.Embed(title="Currency Exchange",
                               description=description,
                               colour=0x007AFF)
            await self.pm.client.send_message(message_object.channel, embed=em)

    async def emotext(self, message_object, args):
        string = ""
        number = [
            "zero", "one", "two", "three", "four", "five", "six", "seven",
            "eight", "nine"
        ]
        for x in args.lower():
            try:
                if x in "qwertyuiopasdfghjklzxcvbnm":
                    string += ":regional_indicator_{0}: ".format(x)
                if x == " ":
                    string += "\n "
                if x in "1234567890":
                    string += ":{0}: ".format(number[int(x)])
            except:
                pass
        await self.pm.client.send_message(message_object.channel, string)

        pass

    async def lang(self, message_object, args):
        iso = langdetect.detect(args)
        x = "```{0}```Language result: {1}[{2}]".format(
            args, iso639.to_name(iso), iso639.to_native(iso))
        await self.pm.client.send_message(message_object.channel, x)

    async def urban(self, message_object, args):
        catalog = urbandict.define(args)
        em = discord.Embed(title='Urban Dictionary',
                           description="Query: " + args,
                           colour=0x007AFF)
        em.set_author(name='{0}\'s Result'.format(message_object.author.name))
        em.set_footer(text="Noku-utils version 0.3",
                      icon_url=self.pm.client.user.avatar_url)
        em.add_field(name="Definiton", value=catalog[0]['def'])
        em.add_field(name="Example", value=catalog[0]['example'])
        await self.pm.client.send_message(message_object.channel, embed=em)

    async def purge(self, message_object):
        print("Purge: A")
        for channels in self.pm.client.private_channels:
            if channels.is_private:
                print("Purge: B")
                #try:
                print("Purge: B.5")
                async for message in self.pm.client.logs_from(channels):
                    print("Purge: C")
                    if message.author == self.pm.client.user:
                        try:
                            print("Purge: D")
                            print("Delete:{0}".format(message.content))
                            await self.pm.client.delete_message(message)
                        except:
                            print("Purge: D.5")
                            pass
                #except:
                #    pass
        pass

    async def makepoll(self, message_object, args):
        reactions = ["🇦", "🇧", "🇨", "🇩", "🇪", "🇫", "🇬", "🇭", "🇮", "🇯"]
        letter = "ABCDEFGHIJ"
        items = args.split("/")
        content = ":pencil:|**{0}**\n".format(items[0])
        count = 0
        for x in items[1:]:
            content += ":black_small_square: **{0}.** `{1}`\n".format(
                letter[count], x)
            count += 1
        message = await self.pm.client.send_message(message_object.channel,
                                                    content)
        for x in range(0, count):
            await self.pm.client.add_reaction(message, reactions[x])
        await self.pm.client.delete_message(message_object)
        pass

    async def ping(self, message_object, reply):
        speed = datetime.datetime.now() - message_object.timestamp
        await self.pm.client.send_message(
            message_object.channel,
            reply + " " + str(round(speed.microseconds / 1000)) + "ms")

    async def old(self, message_object, args):
        if ".order" in args:
            args = args.replace(".order", args)
            await self.pm.client.send_message(
                message_object.channel,
                self.kanye[self.kanyeOrder].replace("Kanye", args))
            self.kanyeOrder = self.kanyeOrder + 1
            if self.kanyeOrder > len(self.kanye) - 1:
                self.kanyeOrder = 0
        else:
            await self.pm.client.send_message(
                message_object.channel,
                random.choice(self.kanye).replace("Kanye", args))

    async def getuser(self, message_object):
        for x in self.pm.client.get_all_members():
            print(x.avatar_url)

    async def hug(self, message_object):
        if len(message_object.mentions) != 0:
            await self.pm.client.send_message(
                message_object.channel,
                "{0} {1} {2}".format(message_object.author.mention,
                                     random.choice(self.hugs),
                                     message_object.mentions[0].mention))
        else:
            await self.pm.client.send_message(
                message_object.channel,
                ":exclamation:`Welp, that\'s not a valid user!`")

    async def pat(self, message_object):
        if len(message_object.mentions) != 0:
            await self.pm.client.send_message(
                message_object.channel,
                random.choice(self.pats).format(
                    message_object.author.mention,
                    message_object.mentions[0].mention))
        else:
            await self.pm.client.send_message(
                message_object.channel,
                ":exclamation:`Welp, that\'s not a valid user!`")

    async def macroadd(self, message_object, args):
        trigger = args.split(" ")[0]
        self.macroDB.insert({'trigger': trigger, 'data': args[len(trigger):]})
        await self.pm.client.send_message(
            message_object.channel,
            ":information_source:`{0} has been added as a macro!`".format(
                trigger))

    async def macrodel(self, message_object, args):
        self.macroDB.remove(Query().trigger == args)
        await self.pm.client.send_message(
            message_object.channel,
            ":information_source:`{0} has been deleted! Probably..`".format(
                args))

    async def helpUtil(self, message_object):
        await self.pm.client.send_message(
            message_object.channel,
            ":information_source: Help detail for Utilities")
        await self.pm.client.send_message(
            message_object.channel,
            "```~hug @user\n~ping\n~macro.add [trigger] [data]\n~macro.delete [trigger]\n~macro [trigger](alt. ~m)\n~macro.assigned```"
        )

    async def macroShow(self, message_object, args):
        try:
            await self.pm.client.send_message(
                message_object.channel,
                self.macroDB.search(Query().trigger == args)[0]["data"])
        except:
            await self.pm.client.send_message(
                message_object.channel,
                ":exclamation:`Welp, that\'s not a valid macro!`")

    async def macroShowAssigned(self, message_object):
        macros = self.macroDB.search(Query().trigger != "")
        x = "```"
        for m in macros:
            x = x + m['trigger'] + " "
        x = x + "```"
        await self.pm.client.send_message(message_object.channel, x)

    async def chaninfo(self, message_object, args, trigger):
        #trigger = args.split(" ")[0]
        if trigger == "set":
            self.chaninfDB.remove(Query().channel == message_object.channel.id)
            self.chaninfDB.insert({
                'channel': message_object.channel.id,
                'data': args
            })
            await self.pm.client.send_message(
                message_object.channel,
                ":information_source:`{0} info has been updated!`".format(
                    trigger))
        elif trigger == "delete":
            self.chaninfDB.remove(Query().channel == message_object.channel.id)
            await self.pm.client.send_message(
                message_object.channel,
                ":information_source:`{0} info has been removed!`".format(
                    trigger))
        else:
            try:
                await self.pm.client.send_message(
                    message_object.channel,
                    self.chaninfDB.search(Query().channel == message_object.
                                          channel.id)[0]["data"])
            except:
                await self.pm.client.send_message(
                    message_object.channel,
                    ":exclamation:No info! `~info set [message]` to set a channel info"
                )

    async def postmeme(self, message_object, imagelist):
        await self.pm.client.send_message(
            message_object.channel,
            "{0}".format(random.choice(imagelist).link))

    async def showpins(self, message_object):
        try:
            if len(message_object.channel_mentions) > 0:
                for x in await self.pm.client.pins_from(
                        message_object.channel_mentions[0]):
                    em = discord.Embed(title="\n",
                                       description=x.content,
                                       colour=0x007AFF)
                    em.set_author(name='{0} - {1}'.format(
                        x.author.name,
                        arrow.get(x.timestamp).format('MM-DD HH:mm')))
                    em.set_thumbnail(url=x.author.avatar_url)
                    await self.pm.client.send_message(message_object.channel,
                                                      embed=em)
                pass
            else:
                await self.pm.client.send_message(
                    message_object.channel,
                    ":exclamation:No channel specified! Usage: `~pins [#channel]`"
                )
        except:
            await self.pm.client.send_message(
                message_object.channel,
                ":exclamation:`Error retrieving pins!`")
            pass

    async def allowChan(self, message_object):
        self.configDB.insert({'chanallow': message_object.channel.id})
        await self.pm.client.send_message(
            message_object.channel,
            ':information_source:`Noku Bot-utils has been allowed access to {0}`'
            .format(message_object.channel.name))

    async def blockChan(self, message_object):
        self.configDB.remove(Query().chanallow == message_object.channel.id)
        await self.pm.client.send_message(
            message_object.channel,
            ':information_source:`Noku Bot-utils has been blocked access to {0}`'
            .format(message_object.channel.name))

    async def shutdown(self, message_object):
        game = discord.Game()
        game.name = "Restarting...".format()
        await self.pm.client.change_presence(game=game, afk=False)
        await self.pm.client.send_message(
            message_object.channel,
            ':information_source:`さようなら {0}! Noku bot is rebooting! <3`'.
            format(message_object.author.name))
        exit()
Exemplo n.º 20
0
class Plugin(object):
    '''
    Noku Image Module
    '''
    def __init__(self, pm):
        self.pm = pm
        self.modulename = 'gallery'
        self.configPath = 'pluginsconfig/data_config-{0}_a.json'.format(
            self.modulename)
        self.configDB = TinyDB(self.configPath)
        self.client = ImgurClient("43bdb8ab21d18b9",
                                  "fcba34a83a4650474ac57f6e3f8b0750dd26ecf5")
        self.imagecache = {}
        self.schcache = {}
        self.buildImagePre()

    @staticmethod
    def register_events():
        return [
            Events.Command(
                "gallery.build", Ranks.Default,
                "Builds the gallery cache, must be run after booting the bot."
            ),
            Events.Command(
                "gallery.add", Ranks.Default,
                "[tag] [subreddit] - scans the subreddit for images and posts a random image."
            ),
            Events.Command("gallery.delete", Ranks.Default,
                           "[tag] Deletes an image tag."),
            Events.Command("subimg", Ranks.Default,
                           "[tag] - Posts a random image from a subreddit."),
            Events.Command("imgs", Ranks.Default,
                           "[query] - Searches imgur for images."),
            Events.Command("gallery.allow", Ranks.Admin),
            Events.Command("gallery.block", Ranks.Admin)
        ]

    async def handle_command(self, message_object, command, args):
        try:
            print("--{2}--\n[Noku-{4}] {0} command from {1} by {3}".format(
                command, message_object.channel.name,
                arrow.now().format('MM-DD HH:mm:ss'),
                message_object.author.name, self.modulename))
        except:
            print("[Noku]Cannot display data, probably emojis.")

        if self.configDB.contains(Query().chanallow == message_object.channel.
                                  id) or message_object.channel.is_private:
            '''
            Add modules checks here
            '''
            if command == "gallery.build":
                await self.buildImage(message_object)
            if command == "gallery.add":
                await self.addImage(message_object, args[1])
            if command == "gallery.delete":
                await self.delImage(message_object, args[1])
            if command == "imgs":
                await self.imgs(message_object, args[1])
            if command == "subimg":
                if args[1] != "":
                    await self.showImage(message_object, args[1])
                else:
                    await self.showGallery(message_object)

        #Do not modify or add anything below it's for permissions
        if command == "{0}.allow".format(self.modulename):
            await self.allowChan(message_object)
        if command == "{0}.block".format(self.modulename):
            await self.blockChan(message_object)

    '''
    Add modules here
    '''

    async def imgs(self, message_object, args):
        await self.pm.client.send_typing(message_object.channel)
        new = True
        while new:
            if args.lower() in self.schcache:
                if len(self.schcache[args]) > 0:
                    image = random.choice(self.schcache[args])
                    if "imgur.com/a/" in image.link:
                        image = random.choice(
                            self.client.get_album_images(image.id)).link
                    else:
                        image = image.link
                else:
                    image = ":information_source:`No results for your query!`"
                print("[Gallery]Sending: {0}".format(image))
                new = False
                await self.pm.client.send_message(message_object.channel,
                                                  image)
            else:
                self.schcache[args.lower()] = self.client.gallery_search(args)

    async def buildImage(self, message_object=None):
        status = await self.pm.client.send_message(
            message_object.channel,
            ':information_source:`Building Cache for Noku-Image`'.format())
        await self.pm.client.send_typing(message_object.channel)
        dbCache = self.configDB.search(Query().tag != "")
        print("[Noku]Building cache")
        if dbCache != 0:
            for item in dbCache:
                print("[Noku]Retrieving Image Cache for {0}".format(
                    item['tag']))
                #self.imagecache[item['tag']] = self.client.subreddit_gallery(item['link'])
                #await self.pm.client.edit_message(status, ':information_source:`Noku-Image: Building {0} cache.`'.format(item['tag']))
                await self.addCache(item['tag'], item['link'])
        #await self.pm.client.send_message(message_object.channel, ':information_source:`Cache Build complete!`'.format())

    def buildImagePre(self, message_object=None):
        #status = await self.pm.client.send_message(message_object.channel, ':information_source:`Building Cache for Noku-Image`'.format())
        #await self.pm.client.send_typing(message_object.channel)
        dbCache = self.configDB.search(Query().tag != "")
        print("[Noku]Building cache")
        if dbCache != 0:
            for item in dbCache:
                print("[Noku]Retrieving Image Cache for {0}".format(
                    item['tag']))
                #self.imagecache[item['tag']] = self.client.subreddit_gallery(item['link'])
                #await self.pm.client.edit_message(status, ':information_source:`Noku-Image: Building {0} cache.`'.format(item['tag']))
                self.imagecache[item['tag']] = self.client.subreddit_gallery(
                    item['link'])

    async def addCache(self, tag, link):
        self.imagecache[tag] = self.client.subreddit_gallery(link)

    async def addImage(self, message_object, args):
        status = await self.pm.client.send_message(
            message_object.channel,
            ':information_source:`Retreiving gallery info for Noku-Image`'.
            format())
        if len(args.split(" ")) > 0:
            tag = args.split(" ")[0]
            subreddit = args.split(" ")[1]
            await self.pm.client.edit_message(
                status,
                ':information_source:`Noku-Image: Building {0} cache.`'.format(
                    tag))
            await self.pm.client.send_typing(message_object.channel)
            self.imagecache[tag] = self.client.subreddit_gallery(subreddit)
            if len(self.imagecache[tag]) > 10:
                self.configDB.insert({'tag': tag, 'link': subreddit})
                await self.pm.client.send_message(
                    message_object.channel,
                    ':information_source:`Successfully generated and added tag!`'
                    .format())
            else:
                await self.pm.client.send_message(
                    message_object.channel,
                    ':exclamation:`Gallery provided is less than 10 images!`'.
                    format())
        else:
            await self.pm.client.send_message(
                message_object.channel,
                ':information_source: Usage:`~addgalery [tag] [subreddit]`'.
                format())

    async def delImage(self, message_object, args):
        self.configDB.remove(Query().tag == args)
        await self.pm.client.send_message(
            message_object.channel,
            ":information_source:`{0} has been deleted! Probably..`".format(
                args))

    async def showImage(self, message_object, args):
        try:
            image = random.choice(self.imagecache[args])
            if "imgur.com/a/" in image.link:
                image = random.choice(self.client.get_album_images(
                    image.id)).link
            else:
                image = image.link

            await self.pm.client.send_message(message_object.channel,
                                              "{0}".format(image))
        except:
            await self.pm.client.send_message(
                message_object.channel,
                ":exclamation:`Welp, that\'s not a valid tag!`")

    async def showGallery(self, message_object):
        macros = self.configDB.search(Query().tag != "")
        x = "```"
        for m in macros:
            x = x + m['tag'] + " "
        x = x + "```"
        await self.pm.client.send_message(message_object.channel, x)

    #Do not modify or add anything below it's for permissions
    async def allowChan(self, message_object):
        self.configDB.insert({'chanallow': message_object.channel.id})
        await self.pm.client.send_message(
            message_object.channel,
            ':information_source:`Noku Bot-{1} has been allowed access to {0}`'
            .format(message_object.channel.name, self.modulename))

    async def blockChan(self, message_object):
        self.configDB.remove(Query().chanallow == message_object.channel.id)
        await self.pm.client.send_message(
            message_object.channel,
            ':information_source:`Noku Bot-{1} has been blocked access to {0}`'
            .format(message_object.channel.name, self.modulename))
Exemplo n.º 21
0
class Imgur:
    """The most awesome images on the internet!
    
    This plugin allows basic searching on Imgur including subreddits.
    
    Warning: Searching on subreddits cannot be easily moderated, therefore it is
    extremely easy for a user to post images from an nsfw subreddit to whatever
    channel the bot is enabled in if this plugin is enabled without modification.
    The subreddit command can be disabled by changing 'enabled=True' to 'enabled=False'
    in the plugin's main file: 'plugins/imgur.py' on line 53.
    """
    def __init__(self, bot):
        self.bot = bot
        self.client = ImgurClient(config["client_id"], config["client_secret"])
    
    @c.group(pass_context=True)
    async def imgur(self, ctx):
        """Search on Imgur!"""
        if ctx.invoked_subcommand is None:
            await self.bot.say("Zoinks! You've taken a wrong turn! Try `help imgur`.")
    
    # Helper function to actually get/post the images
    async def post_image(self, request, query=None):
        case = {
            "subreddit": lambda: self.client.subreddit_gallery(query),
            "search"   : lambda: self.client.gallery_search(query),
            "random"   : lambda: self.client.gallery_random(),
            "top"      : lambda: self.client.gallery("top"),
            "hot"      : lambda: self.client.gallery("hot"),
            "rehost"   : lambda: self.client.upload_from_url(query),
        }
        function = case.get(request, None)
        image = self.bot.loop.run_in_executor(None, function)
        while True:
            await asyncio.sleep(0.25)
            if image.done():
                image = image.result()
                break
        if request == "rehost":
            await self.bot.say(image.get("link", None))
        else:
            await self.bot.say(random.choice(image).link)

    @imgur.command(name="sub", aliases=["subreddit", "reddit", "r/"], enabled=True)
    async def imgur_subreddit(self, subreddit: str):
        """Get an image from a subreddit."""
        await self.post_image("subreddit", subreddit)

    @imgur.command(name="search")
    async def imgur_search(self, *, query: str):
        """Search Imgur for (almost) anything."""
        await self.post_image("search", query)
    
    @imgur.command(name="random")
    async def imgur_random(self):
        """One free random image."""
        await self.post_image("random")
    
    @imgur.command(name="viral")
    async def imgur_viral(self, section: str = "top"):
        """Get one of the most viral images of the day.
        
        Section may be either 'top' or 'hot' and will get an image based on that criteria."""
        section = section.lower()
        if section != "top":
            section = "hot"
        await self.post_image(section)
    
    @imgur.command(name="rehost")
    async def imgur_rehost(self, url: str):
        """Rehost an image from any link to Imgur."""
        await self.post_image("rehost", url)
Exemplo n.º 22
0
 subr = sys.argv[1]
 if not os.path.exists(os.getcwd()+'/nsfw'):
     os.mkdir('nsfw')
 if not os.path.exists(os.getcwd()+'/normal'):
     os.mkdir('normal')
 # Insert your Imgur and Mashape keys/secrets here
 img_client_id = ''
 img_client_secret = ''
 mashape_key = ''
 if mashape_key:
     img_client = ImgurClient(img_client_id, img_client_secret, mashape_key=mashape_key)
 else:
     img_client = ImgurClient(img_client_id, img_client_secret)
 for i in range(1,25):
     data = {}
     for gallery_img in img_client.subreddit_gallery(subr, page=i):
         url = gallery_img.link
         # check if image is in jpg format and has not already been processed
         if len(re.findall('imgur.com/.+\.jpg',url))>0 and found_url.get(url,0)==0:
             print("writing " + url)
             img_id = re.findall('.com.+\.jpg',url)[0][5:-4]
             try:
                 img = img_client.get_image(img_id)
             except:
                 continue
             # get images in m format to make it easier to process for the network
             response = requests.get(url[:-4]+'m.jpg')
             label = img.nsfw
             if label:
                 path = 'nsfw/'
             else:
Exemplo n.º 23
0
                       'VALUES (?, ?, ?, ?);',
                       (title, key, url, description))


RESOURCES = 'resources'

if __name__ == '__main__':
    # TODO: Command line interface
    db = database.make_db('imp.db')
    with open('SECRET', 'r') as f:
        vals = json.loads(f.read())
        client_id = vals['client_id']
        client_secret = vals['client_secret']
        client = ImgurClient(client_id, client_secret)

    vals = client.subreddit_gallery(sys.argv[1])
    for val in vals:
        val.link = val.link.replace('http:', 'https:')
        record_image(val.link, val.title, val.description)

    not_downloaded = db.execute('SELECT * FROM images WHERE file IS NULL;')
    if not os.path.isdir(RESOURCES):
        os.mkdir(RESOURCES)
    for image in not_downloaded.fetchall():
        fname = image['url'].split('/')[-1]
        fname = os.path.join(RESOURCES, fname)
        download_image(image['url'], fname)
        with db:
            db.execute('UPDATE images SET file = ? WHERE id = ?',
                       (fname, image['id']))
            logger.info("UPDATE images SET file = '%s' WHERE id = %s",
Exemplo n.º 24
0
    cl = ImgurClient(client_id, client_secret)
    
    items = cl.get_album_images(album_id)
    image_n = str(len(items))
    i = 1
    for item in items:
        image_url = item.link
        print("Immagine " + str(i) + " su " + image_n + " " + image_url)
        i+=1
        urllib.request.urlretrieve(image_url, path + item.id + image_url[image_url.rfind('/')+1:])

if(options.subreddit != None):
    subreddit = options.subreddit
    print("Download della reddit = " + subreddit)
    print("Destinazione = " + path)
    
    cl = ImgurClient(client_id, client_secret)
    
    j=0
    while(j<=options.page):
        print("Pagina : " + str(j))
        items = cl.subreddit_gallery(subreddit,page=j)
        image_n = str(len(items))
        i = 1
        for item in items:
            image_url = item.link
            print("Immagine " + str(i) + " su " + image_n + " " + image_url)
            urllib.request.urlretrieve(image_url, path + image_url[image_url.rfind('/')+1:])
            i+=1
        j+=1
Exemplo n.º 25
0
from imgurpython import ImgurClient
from credentials import creds
from random import randint
import urllib
import os

client_id = creds['client_id']
client_secret = creds['client_secret']

client = ImgurClient(client_id, client_secret)

items = client.subreddit_gallery('earthporn',
                                 sort='time',
                                 window='week',
                                 page=0)

rand = randint(0, len(items) - 1)
image_id = items[rand].id

url = client.get_image(image_id).link

local_name = 'image.' + url[-3:]

urllib.request.urlretrieve(url, local_name)

os.system(
    'gsettings set org.cinnamon.desktop.background picture-uri "file:///home/john/PythonStuff/backchange/'
    + local_name + '"')
Exemplo n.º 26
0
async def aww(message):
    imgr = ImgurClient(IMGUR_ID, IMGUR_SECRET)
    cmd = message.content.split(" ", 1)
    searche2 = imgr.subreddit_gallery('aww')
    i = random.randint(0, len(searche2) - 1)
    await message.channel.send(searche2[i].link)
Exemplo n.º 27
0
            await client.send_message(message.channel, text)
    
    # !meme
    # Postet ein zufälliges Meme aus Imgur
    elif message.content.startswith('!meme'):
        try:
            memes = imgurclient.memes_subgallery(sort='viral', page=0, window='week')
            await client.send_message(message.channel, random.choice(memes).link)
        except ImgurClientError:
            await client.send_message(message.channel, 'Imgur-Client spinnt. :(')

    # !paragon
    # Postet ein Todd Howard Meme aus Imgur
    elif message.content.startswith('!paragon'):
        try:
            paragon = imgurclient.subreddit_gallery('gayfortodd', sort='time', window='week', page=0)
            await client.send_message(message.channel, random.choice(paragon).link)
        except ImgurClientError:
            await client.send_message(message.channel, 'Imgur-Client spinnt. :(')
    
    # !shibe
    # Postet ein süßes Bild von einem Shiba Inu
    elif message.content.startswith('!shibe'):
        try:
            shibes = imgurclient.subreddit_gallery('shiba', sort='time', window='week', page=0)
            await client.send_message(message.channel, random.choice(shibes).link)
        except ImgurClientError:
            await client.send_message(message.channel, 'Imgur-Client spinnt. :(')

    # !puss
    # Postet ein süßes Bild von einem Kätzchen
Exemplo n.º 28
0
         for i in range(int(roll[0])):
             output += str(random.randint(1,int(roll[1]))) + '\n'
         group.post(output)
 elif(process[0].lower() == "help"):
     group.post("--COMMANDS--")
     group.post("!help")
     group.post("!roll <xdy>")
     group.post("!meme")
     group.post("!joke")
     group.post("!remind <days> <hours> <minutes> <message>")
     group.post("!poll <open/close> <name> <item1> [item2] ...")
     group.post("!vote <name> <item>")
 elif(process[0].lower() == "meme"):
     print("[" + time.strftime("%H:%M:%S") + "] Meme in " + group.name)
     source = random.choice(meme_sources)
     items = client.subreddit_gallery(source, sort='newest')
     post = random.randint(0,len(items)-1)
     group.post(items[post].link)
 elif(process[0].lower() == "joke"):
     group.post(random.choice(jokes))
     print("[" + time.strftime("%H:%M:%S") + "] Joke in " + group.name)
 elif(process[0] == "remind"):
     timetoreminder = int(float(process[1])*24*60*60 + float(process[2])*60*60 + float(process[3])*60 + int(time.time()))
     reminders[group.name][timetoreminder] = " ".join(process[4:])
     group.post("Okay! I will remind you!")
     print("[" + time.strftime("%H:%M:%S") + "] Reminder in " + str(timetoreminder - time.time()) + " in " + group.name)
 elif(process[0] == "doot"):
     print("[" + time.strftime("%H:%M:%S") + "] doot doot in " + group.name)
     group.post("http://i.imgur.com/hoDrij8.gif")
 elif(process[0].lower() == "poll"):
     if(process[1].lower() == "open"):
Exemplo n.º 29
0
import os

# Connect to Imgur
# Grab the first page of Specified Subreddits
# Download everything

imgur = ImgurClient(imgurkey.IMGUR_CLIENT_ID, imgurkey.IMGUR_CLIENT_SECRET)

imgs = []
u = urllib.URLopener()

srcreddits = ('Pics', 'EarthPorn', 'LavaPorn', 'AbandonedPorn', 'SpacePorn')

for sub in srcreddits:
    print "Getting Most Recent Images From Subreddit: r/" + sub
    imgs += imgur.subreddit_gallery(sub, sort='time', window='day', page=0)

for img in imgs:

    # If an album according to API only cover img available when accessed as gallery
    # Use API get_album method to grab all the images in the album

    if img.is_album == True:
        print "Getting album " + img.id
        i = imgur.get_album(img.id)

        for pix in i.images:

            filename = pix['link'].split('/')[-1]

            #print "Album branch, pix['link'] is " + pix['link'] + " file is " + file
Exemplo n.º 30
0
#!/usr/bin/env python3
# encoding: utf-8

import os
from imgurpython import ImgurClient

client_id = '3b362e020b00e29'
client_secret = '76ec3c0b20c1044c24a94b2fbd874c0e3e150079'

client = ImgurClient(client_id, client_secret)

# Example request
subreddit = 'nsfw'
items = client.subreddit_gallery(subreddit, sort='time', window='week', page=1)
for item in items:
    print(item.link)
Exemplo n.º 31
0
def generate_thumb(image_filename):
    size = (300, 300)
    filepath = 'downloads/{}'.format(image_filename)
    thumb_filepath = 'thumbs/{}'.format(image_filename)

    try:
        image = Image.open(filepath)
    except:
        print('Unable to open image.')

    thumb = ImageOps.fit(image, size, Image.ANTIALIAS)
    thumb.save(thumb_filepath)


while still_needs_to_be_processed:
    items = client.subreddit_gallery(subreddit, window='all', page=page_num)
    dupes = 0

    print('Loading the items on page {}...'.format(page_num))

    for item in items:
        title = item.title.encode('utf-8')

        print('Processing "{}"...'.format(title))
        print("We're on page {}, BTW").format(page_num)

        image_source = item.link
        image_width = item.width
        image_height = item.height
        imgur_score = item.score