def read_auth(self): config = get_config() config.read('auth.ini') client_id = config.get('credentials', 'client_id') client_secret = config.get('credentials', 'client_secret') client = ImgurClient(client_id, client_secret) self.searchs = (client.gallery_search(self.query))
async def search_imgur(self, ctx: Context, *, query: str): """Imgur search.""" search_id = 0 await self.bot.send_typing(ctx.message.channel) try: client_id = self.settings["imgur"]["id"] client_secret = self.settings["imgur"]["secret"] except KeyError: await self.bot.say("Please set imgur id and secret.") return try: search_id = self.settings["imgur"]["search_id"] except KeyError: self.settings["imgur"]["search_id"] = 0 # count = 0 client = ImgurClient(client_id, client_secret) results = client.gallery_search(query) try: result = next(islice(results, search_id, None)) if result.is_album: img = client.get_image(result.cover) else: img = result await self.bot.say(str(img.link)) search_id += 1 except StopIteration: search_id = 0 self.settings["imgur"]["search_id"] = search_id dataIO.save_json(JSON, self.settings)
def imgur_search(search=""): try: client = ImgurClient(imgur_id, imgur_secret) except ImgurClientError as e: if e.status_code == 403: return u'can i haz valid api keys?' else: return u'sorry i could not reach imgur :/ E_MSG: {0} E_CODE: {1}'.format(e.error_message, e.status_code) try: search_results = client.gallery_search(search, advanced=None, sort='time', window='all', page=0) except ImgurClientError as e: return u'derp, something bad happened: {0}'.format(e.error_message) if len(search_results) > 0: item = random.choice(search_results) if item.is_album: try: search_results = client.get_album_images(item.id) item = search_results[0] except ImgurClientError as e: return u'derp, something bad happened: {0}'.format(e.error_message) # gifs over 10mb get returned with an h appended to their id # shave it off to get the full animated gif if len(item.link) > 7 and item.link[-5] == 'h': gif_link = item.link[0:-5]+item.link[-4:] if DEBUG: print ("""[dankBot] [DEBUG] search="{0}" link="{1}" Large gif link found, modifying link.""").format(search, item.link) else: gif_link = item.link else: gif_link = None if DEBUG: print ("""[dankBot] [DEBUG] search="{0}" resource="{1}" No results found.""").format(search, "imgur") return gif_link
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.")
def imgur_search(search=""): try: client2 = ImgurClient(imgur_id, imgur_secret) except ImgurClientError as e: if e.status_code == 403: return u'can i haz valid api keys?' else: return u'sorry i could not reach imgur :/ E_MSG: {0} E_CODE: {1}'.format(e.error_message, e.status_code) try: search_results = client2.gallery_search(search, advanced=None, sort='time', window='all', page=0) except ImgurClientError as e: return u'derp, something bad happened: {0}'.format(e.error_message) if len(search_results) > 0: item = random.choice(search_results) if item.is_album: try: search_results = client2.get_album_images(item.id) item = search_results[0] except ImgurClientError as e: return u'derp, something bad happened: {0}'.format(e.error_message) # gifs over 10mb get returned with an h appended to their id # shave it off to get the full animated gif if len(item.link) > 7 and item.link[-5] == 'h': gif_link = item.link[0:-5]+item.link[-4:] if DEBUG: print ("""[dankBot] [DEBUG] search="{0}" link="{1}" Large gif link found, modifying link.""").format(search, item.link) else: gif_link = item.link else: gif_link = None if DEBUG: print ("""[dankBot] [DEBUG] search="{0}" resource="{1}" No results found.""").format(search, "imgur") return gif_link
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.")
async def image(ctx, *text: str): import random imgurID = config['imgur']['imgurID'] imgurSecret = config['imgur']['imgurSecret'] client = ImgurClient(imgurID, imgurSecret) rand = random.randint(0, 29) if text == (): searchEmbed = discord.Embed( title="Error:", description= "Please enter a search term. (This does not support optional parameters)", color=0xC73333) await ctx.channel.send(embed=searchEmbed) elif text[0] != (): items = client.gallery_search(" ".join(text[0:len(text)]), advanced=None, sort='viral', window='all', page=0) try: imageRes = items[rand] await ctx.channel.send(imageRes.link) except IndexError: invalidError = discord.Embed( title="Error:", description= "Sorry! I encountered an error somewhere along the way. (Did you include a __**valid**__ subreddit to search?)", color=0xC73333) await ctx.channel.send(embed=invalidError)
def imgur_gifsearch (bot, msg): client = ImgurClient(imgur_client_id, imgur_client_secret) search = re.match('^!gif (.*)$', msg.text, re.I) items = client.gallery_search(search.groups()[0] + ' ext: gif AND animated: 1', advanced=None, sort='top', window='all', page=0) if not items: bot.say(msg.channel,":buch: No results for {0}".format("".join(search.groups()[0]))) else: item = random.choice(items) #item = items[0] bot.say(msg.channel,item.link)
class ImgurPostsProvider(RedditHandler, Generator): def __init__(self): super(ImgurPostsProvider, self).__init__(IMGUR) cm = ConfigManager() self.client = ImgurClient(cm.get('ImgrClientID'), cm.get('ImgrClientSecret')) self.toggled = set() def get_copies(self, url): search_request = "url:\'%s\'" % _get_post_id(url) return list(self.reddit.search(search_request)) def check(self, image): if not image.title or hash(normalize(image.title)) in self.toggled or \ image.height < 500 or image.width < 500: return False copies = self.get_copies(image.id) if len(copies) == 0: return True def process_title(self, title): #todo fix by re if isinstance(title,str): title.replace("my", "") title.replace("My", "") title.replace("MY", "") title.replace("me", "") title.replace("Me", "") title.replace("ME", "") return title def generate_data(self, subreddit, key_words): try:#todo fix rate limit #todo add posts statuses for page in xrange(MAX_PAGES): q = "tag:%s OR title:%s OR album:%s" % (subreddit, subreddit, subreddit) log.info("retrieve for %s at page %s" % (subreddit, page)) for entity in self.client.gallery_search(q=q, sort='time', page=page, window='week'): if entity.is_album: if entity.ups - entity.downs > 0 and entity.ups > MIN_UPS: images = [random.choice(self.client.get_album_images(entity.id))] else: images=[] else: images = [entity] for image in images: if self.check(image): self.toggled.add(hash(normalize(image.title))) yield PostSource(image.link, self.process_title(image.title)) except Exception as e: log.exception(e) return
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
async def pic(self, ctx, text): """Retrieves a picture from the given query """ imgurclient = ImgurClient("7aea8f3499a8c45", "8e47bce5d977e01723a9486a00d784d7286c5346") items = imgurclient.gallery_search(" ".join(text[1:len(text)]), advanced=None, sort='time', window='all', page=0) await ctx.send(items[0].link)
def _imgur_search(conf, query="", filetype='gif', random_result=False): ''' returns an image from imgur ''' # basic api client setup client_id = conf['imgur_client_id'] client_secret = conf['imgur_client_secret'] client = ImgurClient(client_id, client_secret) # get the image url for an imgur album def _get_direct_url(url): scrape_start = '<link rel="image_src"' scrape_end = '"/>' request = urllib.request.Request(url) result = urllib.request.urlopen(request) charset = result.info().get_content_charset() html = result.read().decode(charset) direct_url = html[html.find(scrape_start):] direct_url = direct_url[direct_url.find('href="') + len('href="'):direct_url.find(scrape_end)] return direct_url # handle random if random_result: gifs = [] for item in client.gallery_random(): if item.is_album: direct_url = _get_direct_url(item.link) else: direct_url = item.link if '.gif' in direct_url: gifs.append(direct_url) return random.choice(gifs) # handle queries else: query = query.split(' ') advanced_dict = {'q_all':query, 'q_type':filetype} item = random.choice(client.gallery_search("", advanced=advanced_dict)) if item.is_album: return _get_direct_url(item.link) else: return item.link
def _imgur_search(conf, query="", filetype='gif', random_result=False): ''' returns an image from imgur ''' # basic api client setup client_id = conf['imgur_client_id'] client_secret = conf['imgur_client_secret'] client = ImgurClient(client_id, client_secret) # get the image url for an imgur album def _get_direct_url(url): scrape_start = '<link rel="image_src"' scrape_end = '"/>' request = urllib.request.Request(url) result = urllib.request.urlopen(request) charset = result.info().get_content_charset() html = result.read().decode(charset) direct_url = html[html.find(scrape_start):] direct_url = direct_url[direct_url.find('href="') + len('href="'):direct_url.find(scrape_end)] return direct_url # handle random if random_result: gifs = [] for item in client.gallery_random(): if item.is_album: direct_url = _get_direct_url(item.link) else: direct_url = item.link if '.gif' in direct_url: gifs.append(direct_url) return random.choice(gifs) # handle queries else: query = query.split(' ') advanced_dict = {'q_all': query, 'q_type': filetype} item = random.choice(client.gallery_search("", advanced=advanced_dict)) if item.is_album: return _get_direct_url(item.link) else: return item.link
def getUrl(query): query = query.replace('+', ' ') client = ImgurClient(client_id, client_secret) items = client.gallery_search(query, advanced=None, sort='time', window='all', page=0) links = dropAlbums(items) random = randint(0, len(links)) if len(links) == 0: url = None else: url = links[random-1] return url
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
class ImgurFetcher: def __init__(self, client_id, client_secret): self.client = ImgurClient(client_id, client_secret) def fetch(self, query): # do request to get albums albums = self.client.gallery_search(query) # if got at least one album, pick a random one and return link of random image if len(albums) > 0: album = random.choice(albums) if hasattr(album, 'images') and len(album.images) > 0: index = random.randint(0, len(album.images) - 1) # TODO sometimes link is null return album.images[index]['link']
async def imgur(*search_terms): """ Fetches images from Imgur based on given arguments. Support single and multiple arguments" """ client = ImgurClient(imgur_client_id, imgur_client_secret) search_terms = " ".join(search_terms) images = client.gallery_search(search_terms) if images: image = random.choice(images) if image.is_album == True: await bot.say(client.get_image(image.cover).link) else: await bot.say(image.link) else: await bot.say("Ei löytynyt kuvia termillä " + search_terms)
async def imgur(*search_terms): """ Fetches images from Imgur based on given arguments. Support single and multiple arguments" """ client = ImgurClient(imgur_client_id, imgur_client_secret) search_terms = " ".join(search_terms) images = client.gallery_search(search_terms) if images: image = random.choice(images) if image.is_album == True: await ctx.send(client.get_image(image.cover).link) else: await client.send(image.link) else: await ctx.send("Couldnt find the picture! " + search_terms)
class imgurCommand: """ imgurCommand Class that contains the initialization and runtime logic for imgur command """ def __init__(self): """ __init__ Creates the class variables needed for the client Additionally stores the client for access in a class variable """ self.clientId = 'ebae683a1f7ca07' self.clientSecret = 'c49e4fcb78b0cbe92481c1778a38cb884f9af584' self.imgurClient = ImgurClient(self.clientId, self.clientSecret) async def imgur(self, discordClient, message): """ imgur Main execution logic for the imgur command Leverages the imgurClient to fetch image requests from the user Image request terms fetched from message content """ #Start by stripping the imgur command off the message #messageContent will contain the search request from the user messageContent = message.content[7:] gallery = self.imgurClient.gallery_search(messageContent, sort='best', page=0) if len(gallery) < 1: #There are no images in the gallery #Return an error message imgurError = 'I couldn\'t find anything with that tag!' await discordClient.send_message(message.channel, imgurError) return image = random.choice(gallery) await discordClient.send_message(message.channel, image.link) async def imgurRandom(self, discordClient, message): """ imgurRandom Fetches a random imgur post Returns it in a message to the user's channel """ #Fetch a random gallery and pull a random image from the gallery gallery = self.imgurClient.gallery_random() await discordClient.send_message(message.channel, gallery[0].link)
def query(self): # build our query query = self._build_query() logger.info("Querying imgur with {}".format(query)) # Download gallery data client = ImgurClient(self.client_id, None) data = client.gallery_search(query, sort='time', window='year', page=0) # if we didn't get anything back... tough luck if data is None or len(data) < 1: return None logger.info("Found successful query {}".format(query)) return self._select_image(data)
def query(self): # build our query query = self._build_query() logger.info("Querying imgur with {}".format(query)) # Download gallery data client = ImgurClient(self.client_id, None) data = client.gallery_search(query, sort='time', window='month', page=0) # if we didn't get anything back... tough luck if len(data) < 1: return None logger.info("Found successful query {}".format(query)) return self._select_image(data)
def getFromImgur(**kwargs): if client == None: client = ImgurClient(client_id, client_secret) items = client.gallery_search("loli", advanced=None, sort='time', window='all', page=0) randNum = randint(0, len(items) - 1) if items[randNum]: try: image = client.get_album_images(items[randNum].id)[0] except Exception as e: print(e) return getFromImgur() if image.animated: return {"link": image.mp4, "gif": True} else: return {"link": image.link, "gif": False}
def get_meme(keyword, meme_only): logging.info("Accessing IMGUR API") # create api instance client_id = IMGUR_ID client_secret = IMGUR_SECRET client = ImgurClient(client_id, client_secret) # client authorization debug logging.debug("imgur auth url: " + client.get_auth_url()) # if meme only check box is selected, append meme to the keyword if meme_only == "on": keyword += " meme" # checks if q value is as intended. Keyword if meme only checkbox is unselected, Keyword + " meme" if selected logging.debug("keyword: " + keyword) # search parameters extension = 'jpg' # jpg | png | gif | anigif (animated gif) | album Default: q = keyword + " ext:" + extension # q_type extension only. Use q instead of keyword sort = 'viral' # time | viral | top - defaults to time window = 'all' # Change the date range of the request if the sort is 'top', day | week | month | year | all, defaults to all. page = 0 # integer - the data paging number try: # Search request memes = client.gallery_search(keyword, sort=sort, window=window, page=page) logging.info("IMGUR memes: " + str(len(memes))) return memes except ImgurClientError as e: logging.error(e.error_message) logging.error(e.status_code)
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
async def imgurCommand(message): imgr = ImgurClient(IMGUR_ID, IMGUR_SECRET) cmd = message.content.split(" ", 1) if len(cmd) <= 1: items = imgr.gallery(section='user', sort='time', page=1, window='day', show_viral=False) else: items = imgr.gallery_search(cmd[1], advanced=None, sort='time', window='all', page=0) if len(items) < 1: await message.channel.send("No reults") i = random.randint( 0, len(items) - 1) # Added -1 to prevent list index out of range exceptions await message.channel.send(items[i].link)
def find(criteria): client = ImgurClient(creds.client_id, creds.client_secret) q = criteria.replace("'", "") search = client.gallery_search(q, advanced=None, sort='top', window='all') numresults = len(search) if numresults != 0: if numresults != 1: numb = random.randrange(1, numresults, 1) item = search[numb] imgID = item.id result = client.get_image(imgID) result = result.link return result else: item = search[0] imgID = item.id result = client.get_image(imgID) result = result.link return result else: # use bing if no imgur results return risky(q)
def getMedia(search_query): """ :param search_query: String to search service for :return: """ media_models = [] cfg = json_config.connect("credentials.json") client_id = cfg["imgur"]["clientID"] client_secret = cfg["imgur"]["clientSecret"] client = ImgurClient(client_id, client_secret) items = client.gallery_search(search_query, sort="viral") for item in items: if item.is_album is True: continue created = datetime.fromtimestamp(item.datetime).isoformat() thumbnail_url = re.sub(r"(\.[a-z]{3,4})$", "m\\1", item.link) attrs = { "name": item.title, "service": 'Imgur', "mediaURL": item.link, "source": item.link, "type": 'image', "created": created, "thumbnailURL": thumbnail_url, "credit": 'http://imgur.com/user/' + item.account_url, } media = MediaModel(attrs) media_models.append(media) return media_models
def run(bot, chat_id, user, keyConfig, message, totalResults=1): requestText = message.replace(bot.name, "").strip() client_id = keyConfig.get('Imgur', 'CLIENT_ID') client_secret = keyConfig.get('Imgur', 'CLIENT_SECRET') client = ImgurClient(client_id, client_secret) items = client.gallery_search(q=requestText, sort='top', window='all', page=1) if len(items) > 0: for item in items: bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO) bot.sendDocument(chat_id=chat_id, filename=requestText.encode('utf-8'), document=item.link.encode('utf-8')) return True else: bot.sendMessage(chat_id=chat_id, text='I\'m sorry ' + (user if not user == '' else 'Dave') + ', I\'m afraid I can\'t find any Imgur images for ' + string.capwords(requestText.encode('utf-8')))
def main(tg): # Read keys.ini file at program start (don't forget to put your keys in there!) keyConfig = configparser.ConfigParser() keyConfig.read(["keys.ini", "config.ini", "..\keys.ini", "..\config.ini"]) chat_id = tg.message['chat']['id'] message = tg.message['text'] botName = tg.misc['bot_info']['username'] message = message.replace(botName, "") splitText = message.split(' ', 1) requestText = splitText[1] if ' ' in message else '' bot = telegram.Bot(keyConfig['BOT_CONFIG']['token']) client_id = keyConfig.get('Imgur', 'CLIENT_ID') client_secret = keyConfig.get('Imgur', 'CLIENT_SECRET') client = ImgurClient(client_id, client_secret) items = client.gallery_search(q=string.capwords(requestText), sort='top', window='all') if len(items) > 0: if items[0].link.endswith('.gif'): bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO) return bot.sendDocument(chat_id=chat_id, filename=requestText, document=items[0].link) else: bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO) return bot.sendPhoto(chat_id=chat_id, filename=requestText, photo=items[0].link)
from imgurpython import ImgurClient import json import sys import random if __name__ == "__main__": if len(sys.argv) < 4: sys.exit(1) with open('ImgurGo/imgur.json') as json_file: data = json.load(json_file) client_id = data["id"] client_secret = data["secret"] client = ImgurClient(client_id, client_secret) items = client.gallery_search(sys.argv[3], sort=sys.argv[1], window=sys.argv[2]) if len(items) > 0: index = random.randint(0, len(items) - 1) print(items[index].link)
class Engraver: def __init__(self, bot): self.bot = bot self.client = ImgurClient(imgur_client_id, imgur_client_secret) @commands.command() async def imgur(self, *topic): """ Performs an Imgur search on the given topic. Arguments: - topic: Topic to search for. """ if self.client.credits["ClientRemaining"] < 10: message = "**Error:** Imgur API daily limit exceeded." else: topic = " ".join(topic) search = self.client.gallery_search(topic) if len(search) > 0: item = search.pop() message = item.link else: message = "**Error:** no Imgur search results for {}.".format( topic) await (self.bot.say(message)) @commands.group(name="album", pass_context=True) async def album(self, ctx, name): """ Pulls a random image from a known album. Arguments: - name: Name of album to pull from. """ if ctx.invoked_subcommand is None: if self.client.credits["ClientRemaining"] < 10: message = "**Error:** Imgur API daily limit exceeded." else: sid = ctx.message.server.id if sid == None: message = "**Error:** Cannot use albums by PM." aid = get_album_id(sid, name) if aid == None: message = "**Error:** No known album {}.".format(name) else: album = self.client.get_album_images(aid) if album == None: message = "**Error:** invalid album ID {} for name {}. Contact the administrator.".format( aid, name) message = item.link await (self.bot.say(message)) @album.command(pass_context=True) async def create(self, ctx, name, image=None): """ Creates an album, containing the given image. If the album already exists, Arguments: - name: Name of album to be created to. - image: Link to the image to be added. If this is omitted, will check message for attached file. """ sid = ctx.message.server.id if image == None: if len(ctx.message.attachments) > 0: image = ctx.message.attachments[0].link else: image = "**Error:** No image provided." await (self.bot.say(image))
make sure this file has a right permission -> sudo chmod 755 imgur.py ''' from imgurpython import ImgurClient import cgi import cgitb cgitb.enable() import json import random print 'Content-type: text/javascript; charset=utf-8\n\n' client_id = 'b33a065b7450ff2' client_secret = 'd4509405d194b66b2dbd96af17285e85dad87808' client = ImgurClient(client_id, client_secret) form = cgi.FieldStorage() q = form.getfirst("query", "") #q = 'dog' items = client.gallery_search(q, advanced=None, sort='time', window='all', page=0) index = random.randint(0, len(items) - 1) print json.dumps({'url': items[index].link})
class Client(BaseNamespace): def initialize(self): """Secondary __init__ created for the SocketIO_client instantiation method """ self.voteskips = [] self.response = {} self.route = {} self.userlist = [] self.poll = [] self.media = [] self.init = False self.question = None self.jumble = None self.imgur = None def config(self, config): if 'response' in config: self.response = config['response'] if 'route' in config: self.route = config['route'] if all(k in config for k in ('channel', 'username', 'password')): self.login(config['channel'], config['username'], config['password']) if 'tmdbapi' in config: tmdb.API_KEY = config['tmdbapi'] if 'giphyapi' in config: self.giphy = giphypop.Giphy(api_key=config['giphyapi']) if 'timeout' in config: self.timeout = config['timeout'] if 'cost' in config: self.cost = config['cost'] if 'imgur' in config: self.imgur = ImgurClient(config['imgur']['client_id'], config['imgur']['client_secret']) def login(self, channel, username, password): """Simple login to the websocket. Emits the params to the websocket. Args: channel (str): Channel to join on login username (str): Username of account to login password (str): Password of account to control """ self.username = username self.channel = channel self.emit('initChannelCallbacks') self.emit('joinChannel', {'name': channel}) self.emit('login', {'name': username, 'pw': password}) def chat_voteskip(self, msg, *args): """An example of executing arbitrary messages through chat. Stores all media in `media`. Flags the skips. """ msg.to = msg.username self.emit('voteskip', {}) def pm_kill(self, msg, *args): if (msg.username == 'zim'): exit() def chat_give(self, msg, *args): omsg = msg omsg.body = 'test' if (len(args) > 0): wFrom = Wallet(msg.username) to = args[0][0] amt = int(args[0][1]) if amt <= 0 or (to == msg.username): omsg.to = msg.username omsg.body = 'Bruh, really?' elif (wFrom.balance < amt): omsg.to = msg.username omsg.body = 'Give: Insufficient funds.' else: wTo = Wallet(to) wFrom.transaction(-amt) wTo.transaction(amt) omsg.body = '{} gave {} {} squids!'.format( msg.username, to, amt) else: omsg.body = 'The syntax is !give <username> <amount>' omsg.to = msg.username self.sendmsg(omsg) def chat_help(self, msg, *args): msg.to = msg.username meth = dir(self) lst = [] for cmd in meth: if 'chat_' in cmd: lst.append(cmd[5:]) msg.body = "This is an experimental feature, some of these may not work.\n" msg.body += ', '.join(lst) self.sendmsg(msg) def getUser(self, name): for usr in self.userlist: if 'name' in usr and name in usr['name']: return usr def x_imgur(self, msg, *args): if (args[0]): search = self.imgur.gallery_search(' '.join(args[0]), window='all', sort='time', page=0) else: search = self.imgur.gallery_random() if len(search) > 0: item = random.choice(search) if item.is_album: choice = random.choice(self.imgur.get_album_images(item.id)) choice = choice.link else: choice = item.link else: out = 'There were no results for that request.' self.emit('pm', {'msg': out, 'meta': {}, 'to': msg.to}) def chat_giphy(self, msg, *args): if (args[0]): x = self.giphy.search(' '.join(args[0]), rating='pg-13') for y in x: out = y.media_url + '.pic' self.sendmsg(out) return out = 'There were no PG-13 results for that request.' self.sendmsg(out) def chat_slots(self, msg, *args): if (args[0]): wallet = Wallet(msg.username) timer = Timer(msg.username, 'slots') cost = 0 if args[0][0].isdigit(): cost = -abs(int(args[0][0])) else: self.sendmsg('Please place a numeric bet.') return chk = timer.check(self.timeout['slots']) if (not chk['ready']): timetil = chk['timetil'] / 60 self.sendmsg('Try again in {} minute(s).'.format(timetil)) return else: cost = abs(int(args[0][0])) if wallet.balance >= cost: wallet.transaction(-cost) serverWallet = Wallet('{{server}}') lst = [0] * 5 + [1] * 5 + [2] * 5 + [3] * 5 + [4] * 2 + [5] x, y, z = random.choices(lst, k=3) prizemsg = ":botchat3:" translate = ['♥', '♣', '♠', '♪', '♀', '♦'] prizemsg = "| {} | {} | {} |\n".format( translate[x], translate[y], translate[z]) if 5 in (x, y, z) and (x == y == z): cost = serverWallet.balance wallet.transaction(cost) serverWallet.transaction(-abs(serverWallet.balance)) prizemsg += '{} hit the jackpot! They have earned {} squids!'.format( msg.username, cost) elif (x == y == z) and max(x, y, z) < 4: wallet.transaction(cost * 3) prizemsg += '{} matches 3 (three) fruits! [3x] Multiplyer (Bal: {})'.format( msg.username, wallet.balance) elif 5 in (x, y, z) and len({x, y, z}) == 2: wallet.transaction(cost * 2) prizemsg += '{} got a diamond and two matches. [2x] (Bal: {})'.format( msg.username, wallet.balance) elif 5 in (x, y, z) and len({x, y, z}) == 3: wallet.transaction(cost) prizemsg += '{} breaks even with 1 (one) diamond. [1x] (Bal: {})'.format( msg.username, wallet.balance) elif len({x, y, z}) == 2: wallet.transaction(2 * cost) prizemsg += '{} matches 2! [2x] Multiplyer (Bal: {})'.format( msg.username, wallet.balance) else: serverWallet.transaction(cost) prizemsg += '{}, better luck next time. (Bal: {})'.format( msg.username, wallet.balance) self.sendmsg(prizemsg) timer.setTimer() else: msg.to = msg.username msg.body = 'Slots: Insufficient funds.' self.sendmsg(msg) def chat_trivia(self, msg, *args): if not self.question: r = req.get('https://opentdb.com/api.php?amount=1') self.question = r.json()['results'][0] sub = 'True/False' if any(s in self.question['correct_answer'] for s in ('True', 'False')) else None body = '{}(Category: {}) {}'.format( '[' + sub + ']' if sub else '', self.question['category'], html.unescape(self.question['question'])) self.sendmsg(body) else: sub = 'True/False' if any(s in self.question['correct_answer'] for s in ('True', 'False')) else None body = '{}(Category: {}) {}'.format( '[' + sub + ']' if sub else '', self.question['category'], html.unescape(self.question['question'])) self.sendmsg(body) if (self.question['type'] == 'multiple'): choices = self.question['incorrect_answers'] choices.append(self.question['correct_answer']) random.shuffle(choices) # self.sendmsg("Choices: {}".format(html.unescape(','.join(choices)))) def chat_nq(self, msg, *args): w = Wallet(msg.username) if (w.balance >= 100): w.transaction(-100) self.question = None self.sendmsg('{} spent 100 squids to skip the question.\ ({})'.format(msg.username, w.balance)) def chat_a(self, msg, *args): if (len(args[0]) > 0): ans = html.unescape(' '.join(args[0]).lower()) if (html.unescape( self.question['correct_answer'].lower().rstrip().lstrip()) == ans): w = Wallet(msg.username) w.transaction(100) self.sendmsg('{} got it right! (100 Squids)'.format( msg.username)) self.question = None else: return def chat_hint(self, msg, *args): if self.question: body = ' '.join([ ''.join(random.sample(word, len(word))) for word in html.unescape(self.question['correct_answer']).split() ]) self.sendmsg(body) def chat_love(self, msg, *args): data = {'msg': 'No love.'} if args[0]: args = args[0] to = args[0] if len(args) > 0 else self.username frm = args[1] if len(args) > 1 else msg.username if (msg.username in self.response): data['msg'] = self.response[msg.username].format(to, frm) else: data['msg'] = random.choice(self.response['generic']).format( to, frm) self.sendmsg(Msg(data)) def chat_squids(self, msg, *args): wallet = Wallet(msg.username) self.sendmsg( Msg({ 'body': '{0} has {1} squids.'.format(msg.username, wallet.balance) })) def chat_skin(self, msg, *args): search = tmdb.Search() body = 'No sexual parental guide found' if len(args) > 0: response = search.movie(query=' '.join(args[0])) if search.results: mid = search.results[0]['id'] movie = tmdb.Movies(mid) info = movie.info() if 'imdb_id' in info: t = req.get('https://www.imdb.com/title/' + info['imdb_id'] + '/parentalguide') advise = Soup(t.content).find('section', id='advisory-nudity') if advise: body = '' items = advise.find_all('li', 'ipl-zebra-list__item') for item in items: body += item.contents[0].strip().replace( '\n', '.').replace('-', ' ') msg.body = '/sp ' + body self.sendmsg(msg) def chat_trailers(self, msg, *args): search = tmdb.Search() vids = {} msg.to = msg.username regex = re.compile('[^a-zA-Z ]') for movie in self.poll: movie = movie.replace('.', ' ') movie = regex.sub('', movie) response = search.movie(query=movie) if search.results: mid = search.results[0]['id'] else: break movie = tmdb.Movies(mid) videos = movie.videos() for video in videos: if 'results' in videos: for t in videos['results']: if t['type'] == 'Trailer': vids[search.results[0]['title']] = t['key'] for title, vid in vids.items(): msg.body = title + ': http://youtube.com/watch?v=' + vid self.sendmsg(msg) for user in self.userlist: if (user['name'].lower() == msg.username.lower() and user['rank'] > 1): if any(t['key'] in s for s in self.media): msg.body = title + ' already exists in queue.' self.sendmsg(msg) else: self.queue(vid, True) def pm_debug(self, msg, *args): if msg.username == 'zim': msg.to = 'zim' for x in self.media: msg.body = ''.join(x) self.sendmsg(msg) def chat_choose(self, msg, *args): if args[0]: msg.body = random.choice(args[0]) self.sendmsg(msg) def chat_fuck(self, msg, *args): args = args[0] fmsg = f**k.random(from_=msg.username) if len(args) > 0: fmsg = f**k.random(from_=msg.username, name=args[0]) data = Msg({'msg': fmsg.text}) self.sendmsg(data) return True def chat_rate(self, msg, *args): """TODO: If the socket app does not support media, allow this to wait for a callback; this will let users rate functionality? (SCOPE CREEP)""" if (len(args) > 0): msg.to = msg.username msg.body = 'Thank you for rating, wzrd will be pleased!' self.sendmsg(msg) def chat_j(self, msg, *args): if (len(args[0]) > 0 and self.jumble): if ' '.join(args[0]).lower() == self.jumble: msg.body = "{} solved the jumble: {}. (50 squids)".format( msg.username, self.jumble) wallet = Wallet(msg.username) wallet.transaction(50) self.jumble = None self.sendmsg(msg) else: pass def chat_jumble(self, msg, *args): """Attempts to solve an anagram based on letters parsed from handle_msg Requests calls based on the arguments and the whole Msg. Args: match (str): The anagram which has been parsed from the Msg to be solved to an english word """ if self.jumble: msg.body = ''.join(random.sample(self.jumble, len(self.jumble))) else: word_site = "https://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain" r = req.get(word_site) self.jumble = random.choice(r.text.splitlines()).lower() msg.body = ''.join(random.sample(self.jumble, len(self.jumble))) self.sendmsg(msg) def chat_handout(self, msg, *args): amt = random.randint(1, 100) wallet = Wallet(msg.username) timer = Timer(msg.username, 'handout') chk = timer.check(self.timeout['handout']) if (chk['ready']): wallet.transaction(amt) timer.setTimer() else: timetil = chk['timetil'] / 60 self.sendmsg('Try again in {} minute(s).'.format(timetil)) return balance = wallet.balance if (balance): self.sendmsg('Here' 's {} squids. {} has {} squids!'.format( amt, msg.username, balance)) return def qryCur(self, qry): self.currencyCur.execute(qry) res = self.currencyCur.fetchone() self.currencyConn.commit() return res def chat_catboy(self, msg, *args): self.sendmsg(':catfap:') def chat_auto(self, msg, *args): if (msg.username == 'catboy'): if random.random() < 0.02: self.sendmsg('Meow') def sendmsg(self, msg): if (isinstance(msg, str)): self.emit('chatMsg', {'msg': msg}) elif (msg.to): self.emit('pm', {'msg': msg.body, 'meta': {}, 'to': msg.to}) else: self.emit('chatMsg', {'msg': msg.body, 'meta': msg.meta}) log.debug(msg) def queue(self, url, after=False): data = {"id": url, "type": "yt", "pos": "next", "temp": True} self.emit('queue', data) self.media.append(url) def sendadminmsg(self, msg): msg = {'username': None, 'rank': 0} for y in self.userlist: if (not y['meta']['afk']): if (msg['rank'] < y['rank']): msg['username'] = y['name'] msg['rank'] = y['rank'] @check_init def jackpot_announce(self): timeout = 15 * 60 if ('jackpot' in self.timeout): timeout = self.timeout['jackpot'] t = threading.Timer(timeout, self.jackpot_announce) t.daemon = True t.start() serverWallet = Wallet('{{server}}') self.sendmsg('Current jackpot is: {} squids!'.format( serverWallet.balance)) p = random.random() if p < 0.0002: bal = serverWallet.balance amt = random.randint(int(bal / len(str(bal))), int(bal / 2)) user = random.choice(self.userlist)['name'] serverWallet.transaction(-amt) userWallet = Wallet(user) userWallet.transaction(amt) self.sendmsg( 'The accountant made a mistake and {} got {} squids!'.format( user, amt)) @run_async @check_init def handle_msg(self, msg): chatlog.info(msg) ret = False cmd = '' cnt = False if (self.route): for user in self.route: if (msg.username == user): for func in self.route[user]: match = msg.search_body(self.route[user][func]) if (match): dir_cmd = func args = match cnt = True if (msg.text.startswith('!') and msg.username): cmd = msg.text.split() dir_cmd = cmd[0][1:] args = cmd[1:] cnt = True if (cnt): call = 'chat_' + dir_cmd if (msg.to): # It's a PM call = 'pm_' + dir_cmd try: func = getattr(self, call.lower()) if callable(func): if (dir_cmd in self.cost): wallet = Wallet(msg.username) if (wallet.balance < self.cost[dir_cmd]): self.sendmsg( '{0} costs {1} squids. {2} has {3}'.format( dir_cmd, self.cost[dir_cmd], msg.username, wallet.balance)) return else: wallet.transaction(-self.cost[dir_cmd]) self.sendmsg( Msg({ 'to': msg.username, 'body': 'You spent {0} squids on {1}'.format( self.cost[dir_cmd], dir_cmd) })) log.info('%s : %s' % (func.__name__, msg)) ret = func(msg, args) except Exception as e: log.error('Exception[%s]: %s' % (e, msg)) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] log.error(exc_type, fname, exc_tb.tb_lineno) return ret @run_async def on_chatMsg(self, omsg): msg = Msg(omsg) self.handle_msg(msg) def on_changeMedia(self, *args): try: self.media.remove(args[0]['id']) except Exception as e: return def on_newPoll(self, *args): self.poll = [] for poll in args: if 'options' in poll: for opt in poll['options']: self.poll.append(opt) def on_userlist(self, *args): self.userlist = args[0] self.userlist.append({'name': self.username}) self.init = True def on_queue(self, *args): for arg in args: for media in arg: if 'media' in media: if media['media']['id'] not in self.media: self.media.append(media['media']['id']) def on_pm(self, omsg): msg = Msg(omsg) self.handle_msg(msg) def on_userLeave(self, *args): self.userlist[:] = [ d for d in self.userlist if d['name'] != args[0]['name'] ] def on_addUser(self, *args): self.userlist.append(args[0]) def on_connect(self): log.info('[Connected]') def on_disconnect(self): raise Exception('disconnected') def on_login(self, *args): self.jackpot_announce() if (not args[0]['success']): log.error(args[0]['error']) raise SystemExit def on_event(self, *args): pass def on_emoteList(self, *args): pass def on_channelCSSJS(self, *args): pass def on_setMotd(self, *args): pass def on_setPlaylistMeta(self, *args): pass def on_playlist(self, *args): for arg in args: for media in arg: if 'media' in media: if media['media']['id'] not in self.media: self.media.append(media['media']['id']) log.info('Playlist Loaded') def on_channelOpts(self, *args): pass def on_mediaUpdate(self, *args): pass
class Fun(commands.Cog): def __init__(self, bot): self.imgur_client = ImgurClient(IMGUR_CLIEND_ID, IMGUR_CLIENT_SECRET) @commands.command(aliases=alias("spongebob"), pass_context=True) @commands.cooldown(1, 3, commands.BucketType.user) async def spongebob(self, ctx): await self._blend_images(ctx=ctx, filename="spongebob1.png", attachments=ctx.message.attachments, bg_size=(399, 299), bg_coord=(97, 305)) @commands.command(aliases=alias("ihadtogrind"), pass_context=True) @commands.cooldown(1, 3) async def ihadtogrind(self, ctx): await self._blend_images( ctx=ctx, filename="ihadtogrind.png", attachments=ctx.message.attachments, bg_size=(545, 531), bg_coord=(15, 64), ) @commands.command(aliases=alias("granpatv"), pass_context=True) @commands.cooldown(1, 3) async def granpatv(self, ctx): await self._blend_images( ctx=ctx, filename="granpatv.png", attachments=ctx.message.attachments, bg_size=(430, 243), bg_coord=(45, 253), ) @commands.command(aliases=alias("mrkrupp"), pass_context=True) @commands.cooldown(1, 3) async def mrkrupp(self, ctx): await self._blend_images( ctx=ctx, filename="mrkrupp.png", attachments=ctx.message.attachments, bg_size=(566, 418), bg_coord=(0, 0), ) @commands.command(aliases=alias("spore"), pass_context=True) @commands.cooldown(1, 3) async def spore(self, ctx): await self._blend_images( ctx=ctx, filename="spore.png", attachments=ctx.message.attachments, bg_size=(1024, 1024), bg_coord=(0, 0), ) @commands.command(aliases=alias("spywow"), pass_context=True) @commands.cooldown(1, 3) async def spywow(self, ctx): await self._blend_images( ctx=ctx, filename="spywow.png", attachments=ctx.message.attachments, bg_size=(600, 339), bg_coord=(0, 0), ) @commands.command(aliases=alias("thisguy"), pass_context=True) @commands.cooldown(1, 3) async def thisguy(self, ctx): await self._blend_images( ctx=ctx, filename="thisguy.png", attachments=ctx.message.attachments, bg_size=(520, 451), bg_coord=(0, 191), ) @commands.command(aliases=alias("thiswoman"), pass_context=True) @commands.cooldown(1, 3) async def thiswoman(self, ctx): await self._blend_images( ctx=ctx, filename="thiswoman.png", attachments=ctx.message.attachments, bg_size=(964, 467), bg_coord=(0, 444), ) @commands.command(aliases=alias("icecream"), pass_context=True) @commands.cooldown(1, 3) async def icecream(self, ctx): await self._blend_images( ctx=ctx, filename="icecream.png", attachments=ctx.message.attachments, bg_size=(309, 261), bg_coord=(202, 250), ) @commands.command(aliases=alias("obstetrician"), pass_context=True) @commands.cooldown(1, 3) async def obstetrician(self, ctx): await self._blend_images( ctx=ctx, filename="obstetrician.png", attachments=ctx.message.attachments, bg_size=(962, 727), bg_coord=(22, 13), ) @commands.command(aliases=alias("anus"), pass_context=True) @commands.cooldown(1, 3) async def anus(self, ctx): await self._blend_images( ctx=ctx, filename="anus.png", attachments=ctx.message.attachments, bg_size=(225, 191), bg_coord=(0, 0), ) @commands.command(aliases=alias("dream"), pass_context=True) @commands.cooldown(1, 3) async def dream(self, ctx): await self._blend_images( ctx=ctx, filename="dream.png", attachments=ctx.message.attachments, bg_size=(685, 450), bg_coord=(0, 308), ) @commands.command(aliases=alias("slam"), pass_context=True) @commands.cooldown(1, 3) async def slam(self, ctx): await self._blend_images( ctx=ctx, filename="slam.png", attachments=ctx.message.attachments, bg_size=(315, 447), bg_coord=(338, 14), ) @commands.command(aliases=alias("badmeme"), pass_context=True) @commands.cooldown(1, 3) async def badmeme(self, ctx): try: req = requests.get("https://api.imgflip.com/get_memes") await ctx.send(random.choice(req.json()["data"]["memes"])["url"]) except Exception as err: print(err) @commands.command(aliases=alias("magic"), pass_context=True) @commands.cooldown(2, 5, commands.BucketType.user) # Forked from `NotSoBot` async def magic(self, ctx, scale=3): try: if scale > 10: await ctx.send( tr("The scale argument can't be more than 10", ctx=ctx)) scale = 1 to_send = "Images/Temp/magic.png" url = await self._get_images(ctx) response = requests.get(url) img = Image.open(BytesIO(response.content)) img.save(to_send, "PNG") img = image.Image(filename=to_send) img.liquid_rescale(width=int(img.width * 0.5), height=int(img.height * 0.5), delta_x=int(0.5 * scale) if scale else 1, rigidity=0) img.liquid_rescale(width=int(img.width * 1.5), height=int(img.height * 1.5), delta_x=scale if scale else 2, rigidity=0) img.save(filename=to_send) await ctx.send(file=discord.File(to_send)) os.remove(to_send) except Exception as e: await ctx.send(tr("I pooped myself", ctx=ctx, err=e)) async def _blend_images(self, ctx: str, filename=None, attachments=None, bg_size=None, bg_coord=None, bg_scale_x1=None, bg_scale_y1=None, bg_scale_x2=None, bg_scale_y2=None, bg_resize_w=None, bg_resize_h=None): """ Keyword arguments for "_blend_images" method: Args: filename - background image path attachments - attached urls, default bg_size - background image width and height bg_coord - background image coordinates bg_scale_x1 - rescale image by x1 bg_scale_y1 - rescale image by y1 bg_scale_x2 - rescale image by x2 bg_scale_y2 - rescale image by y2 bg_resize_w - resize image width bg_resize_h - resize image height """ await ctx.trigger_typing() to_send = "Images/Temp/{}".format(filename) response = await self._get_images(ctx) response = requests.get(response) foreground = os.path.join(IMAGES_TEMPLATE_PATH, filename) foreground = Image.open(foreground) background = Image.open(BytesIO(response.content)) if 3000 in background.size: await ctx.send( tr( "Image is too large ({w}x{h})", ctx=ctx, w=background.size[0], h=background.size[1], )) else: background = background.resize(bg_size) blended = Image.new("RGBA", foreground.size) blended.paste(background, bg_coord) blended.paste(foreground, (0, 0), foreground) blended.save(to_send, "PNG") await ctx.send(file=discord.File(to_send)) os.remove(to_send) @commands.command(aliases=alias("impact-meme"), pass_context=True) async def impact_meme(self, ctx, *string): # Forked from: https://github.com/Littlemansmg/Discord-Meme-Generator # Get image from URL try: await ctx.trigger_typing() to_send = "Images/Temp/meme.png" location = await self._get_images(ctx) response = requests.get(location) font_path = FONTS["impact"] if len(string): string_size = len(string) // 2 top_string = " ".join(string[:string_size]) bottom_string = " ".join(string[string_size:]) with Image.open(BytesIO(response.content)) as img: size = img.size font_size = int(size[1] / 5) # font = IFont.truetype(font=font_path, size=font_size) font = ImageFont.truetype(font_path, font_size) edit = ImageDraw.Draw(img) # find biggest font size that works top_text_size = font.getsize(top_string) bottom_text_size = font.getsize(bottom_string) while top_text_size[0] > size[0] - 20 or bottom_text_size[ 0] > size[0] - 20: font_size = font_size - 1 font = ImageFont.truetype(font_path, font_size) top_text_size = font.getsize(top_string) bottom_text_size = font.getsize(bottom_string) # find top centered position for top text top_text_posx = (size[0] / 2) - (top_text_size[0] / 2) top_text_posy = 0 top_text_pos = (top_text_posx, top_text_posy) # find bottom centered position for bottom text bottom_text_posx = (size[0] / 2) - (bottom_text_size[0] / 2) bottom_text_posy = size[1] - bottom_text_size[1] - 10 bottom_text_pos = (bottom_text_posx, bottom_text_posy) # draw outlines # there may be a better way outline_range = int(font_size / 15) for x in range(-outline_range, outline_range + 1): for y in range(-outline_range, outline_range + 1): edit.text( (top_text_pos[0] + x, top_text_pos[1] + y), top_string, (0, 0, 0), font=font) edit.text((bottom_text_pos[0] + x, bottom_text_pos[1] + y), bottom_string, (0, 0, 0), font=font) edit.text(top_text_pos, top_string, (255, 255, 255), font=font) edit.text(bottom_text_pos, bottom_string, (255, 255, 255), font=font) img.save(to_send, "PNG") await ctx.send(file=discord.File(to_send)) os.remove(to_send) else: await ctx.send(tr("Type something", ctx=ctx)) except Exception as err: print(err) async def _get_images(self, ctx, history_limit=None, formats=None): if not history_limit: history_limit = 200 if not formats: formats = ("png", "gif", "jpeg", "jpg") async for c in ctx.history(limit=history_limit): # limit=10 if len(c.attachments) > 0: background_url = c.attachments[0].url background_ext = background_url.split(".")[-1] return background_url if background_ext in formats else None @commands.command(aliases=alias("whois"), pass_context=True) async def whois(self, ctx, *text): try: if text is None: text = "гей" member = await self._get_members(ctx) member = random.choice(member) await ctx.send( tr("I think it's a {member}", ctx=ctx, member=member)) except Exception as err: await ctx.send(tr("I pooped myself", ctx=ctx, err=err)) @commands.command(aliases=alias("when"), pass_context=True) async def when(self, ctx): try: min_year = 1993 max_year = datetime.datetime.now().year start = datetime.datetime(min_year, 1, 1) years = max_year - min_year + 1 end = start + datetime.timedelta(days=365 * years) result = start + (end - start) * random.random() result = datetime.datetime.strftime( result, tr("It happend in '{tf}'", ctx=ctx, tf="%D - %d:%m:%y")) await ctx.send(result) except Exception as err: await ctx.send(tr("I pooped myself", ctx=ctx, err=err)) async def _get_members(self, ctx): return [i.name for i in ctx.guild.members] @commands.command(aliases=alias("imgur"), pass_context=True) @commands.cooldown(2, 5) async def imgur(self, ctx, text): if text is None: load = self.imgur_client.gallery_random(page=0) else: load = self.imgur_client.gallery_search(text, advanced=None, sort="viral", window="all", page=0) rand = random.choice(load) try: if "image/" in rand.type: await ctx.send(rand.link) except AttributeError: if rand.title: title = "**{}**\n".format(rand.title) else: title = "" await ctx.send("{}{}".format(title, rand.link)) @commands.command(aliases=alias("minecraft"), pass_context=True) @commands.cooldown(1, 3) async def minecraft(self, ctx, *text): try: if len(text) == 0: text = "Насрал в штаны" else: text = " ".join(text) symbols = ( u"абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", u"abvgdeejzijklmnoprstufhzcss_y_euaABVGDEEJZIJKLMNOPRSTUFHZCSS_Y_EUA" ) tr = {ord(a): ord(b) for a, b in zip(*symbols)} url = "https://mcgen.herokuapp.com/a.php?i=1&h=%s&t=%s" % ( text.capitalize().translate(tr), str( ctx.message.author.name).translate(tr)) response = requests.get(url) image = Image.open(BytesIO(response.content)) image.save("Images/Temp/minecraft.png", "PNG") await ctx.send(file=discord.File("Images/Temp/minecraft.png")) os.remove("Images/Temp/minecraft.png") except Exception as err: await ctx.send(tr("I pooped myself", ctx=ctx, err=err))
""" install library from here -> https://github.com/Imgur/imgurpython make sure this file has a right permission -> sudo chmod 755 imgur.py """ from imgurpython import ImgurClient import cgi import cgitb cgitb.enable() import json import random print "Content-type: text/javascript; charset=utf-8\n\n" client_id = "b33a065b7450ff2" client_secret = "d4509405d194b66b2dbd96af17285e85dad87808" client = ImgurClient(client_id, client_secret) form = cgi.FieldStorage() q = form.getfirst("query", "") # q = 'dog' items = client.gallery_search(q, advanced=None, sort="time", window="all", page=0) index = random.randint(0, len(items) - 1) print json.dumps({"url": items[index].link})
async def check_sinon(self, message): #orels1 = message.server.get_member("75887934410067968") async def bot_say(text): await self.bot.send_message(message.channel, text) async def s_talk(text, glitch = False, bold = False, extra = None, extra_bold = False): # check text length #get number of lines if text.count('\n') > 0: lines = text.count('\n') else: lines = 0 if not glitch: cover = Image.open('data/sinon/sinon-eyes.png').convert('RGBA') else: cover = Image.open('data/sinon/sinon-glitch.png').convert('RGBA') if extra is None: extra_lines = 0 result = Image.new('RGBA', (600, 172 + 32 * lines), (0,0,0)) process = Image.new('RGBA', (600, 70 + 32 * lines), (0,0,0)) else: extra_lines = extra.count('\n') result = Image.new('RGBA', (600, 242 + 32 * extra_lines), (0,0,0)) process = Image.new('RGBA', (600, 140 + 30 * extra_lines), (0,0,0)) # get a font if not bold: fnt = ImageFont.truetype('data/drawing/font.ttf', 37) else: fnt = ImageFont.truetype('data/drawing/font_bold.ttf', 37) if not extra_bold: fnt_extra = ImageFont.truetype('data/sinon/font_extra.ttf', 26) else: fnt_extra = ImageFont.truetype('data/sinon/font_extra_bold.ttf', 26) # get a drawing context d = ImageDraw.Draw(process) # draw text, half opacity d.rectangle([(0,0),(600,70 + 32 * (lines + extra_lines))], fill=(0,0,0,160)) d.text((25,20), text, font=fnt, fill=(255,255,255,255)) d.rectangle([(10,10),(590, 70 + 32 * lines - 10)], fill=None, outline=(200,200,200,128)) if extra: d.rectangle([(10, 70 + 32 * lines - 10), (590, 70 + 30 * (lines + extra_lines) - 10)], fill=None, outline=(200,200,200,128)) d.text((20,70 + 35 * lines - 10), extra, font=fnt_extra, fill=(255,255,255,255)) result.paste(cover, (0,0)) result.paste(process, (0,102)) result.save('temp.jpg','JPEG', quality=100) await self.bot.send_file(message.channel, 'temp.jpg') os.remove('temp.jpg') if "sinon" in message.content.split() and "s.reload" not in message.content.split(): imgurclient = ImgurClient("1fd3ef04daf8cab", "f963e574e8e3c17993c933af4f0522e1dc01e230") items = imgurclient.gallery_search("sinon", advanced=None, sort='time', window='all', page=0) if len(items) < 1: await self.bot.send_message(message.channel, "Your search terms gave no results.") else: rand = randint(0, len(items) -1) async def check_nsfw(items, num): if items[num].nsfw or items[num].is_album or items[num].ups < 10: num = randint(0, len(items) -1) await check_nsfw(items, num) else: await self.bot.send_message(message.channel,items[num].link) await check_nsfw(items, rand) #the magic starts here, wanna join? if "s?" in message.content.split()[:1]: #await self.bot.send_message(message.channel, "What?...") await s_talk("what?...") def show_shop(): table = [] for item in enumerate(self.rpg["shop"]["items"]): table.append([ item[0], item[1]["name"], "+" + str(item[1]["atk"]), str(item[1]["price"]) + " COL.", item[1]["stock"] ]) resp = "```" resp += tabulate(table, headers = ["#","Item","Attack","Price","In stock"], tablefmt="fancy_grid") resp += "```" return resp #TODO: Combine with show_shop def get_items(char): table = [] for item in enumerate(char["items"]): table.append([ item[0], item[1]["name"], item[1]["atk"], item[1]["stock"] ]) return table def get_chars(user): table = [] print("Getting chars for user "+ str(user)) print(self.rpg["players"][str(user)]) for char in enumerate(self.rpg["players"][str(user)]): print(char) table.append([ char[0], char[1]["name"], char[1]["lvl"], char[1]["stats"]["hp"], char[1]["stats"]["atk"], char[1]["stats"]["def"], str(char[1]["bank"]) + " COL." ]) if char[1]["active"]: table[char[0]][1] = "-> " + table[char[0]][1] return table def create_char(charname): #form char dict char = { "name" : charname, "lvl" : 1, "stats" : { "atk" : 1, "def" : 1, "hp" : 100 }, "active" : False, "bank" : 1000 } #if no chars if str(message.author.id) not in self.rpg["players"].keys(): char["id"] = 0 self.rpg["players"][str(message.author.id)] = [char] #if second+ char else: char["id"] = len(self.rpg["players"][str(message.author.id)]) self.rpg["players"][str(message.author.id)].append(char) async def buy_item(item, char): #copy for local changes player_item = copy(item) #check balance if char["bank"] >= item["price"]: self.rpg["players"][str(message.author.id)][char["id"]]["bank"] -= item["price"] #change shop's stock item["stock"] -= 1 #if no items if "items" not in char.keys(): #modify stock player_item["stock"] = 1 self.rpg["players"][str(message.author.id)][char["id"]]["items"] = [player_item] #if has items else: bought = False #check if duplicate for it in enumerate(char["items"]): if item["name"] == it[1]["name"]: #add one more print("duplicate!") self.rpg["players"][str(message.author.id)][char["id"]]["items"][it[0]]["stock"] += 1 bought = True #if there were np duplicates if not bought: #add just one player_item["stock"] = 1 print(player_item) self.rpg["players"][str(message.author.id)][char["id"]]["items"].append(player_item) await bot_say("everything is fine... " + item["name"] + " is yours now") #save here save(self.rpg) else: await bot_say("you don't have the funds... don't mess around...") def check_login(user): #find logged in char for char in enumerate(self.rpg["players"][user]): if char[1]["active"]: return {"logged_in": True, "char": char[1]} #if not logged in return {"logged_in": False, "char": {}} def upd_stats(char): #safe-check if there are items if "items" in char.keys(): if len(char["items"]) > 0: #calculate total ATK value total_atk = 1 for item in char["items"]: total_atk += item["atk"] #check if is different if not total_atk == char["stats"]["atk"]: char["stats"]["atk"] = total_atk #save here save(self.rpg) async def perform_fight(attacker, victim): table = [ [ attacker["name"], " VS ", victim["name"] ], [ "ATK " + str(attacker["stats"]["atk"]), "", "ATK " + str(victim["stats"]["atk"]) ] ] resp = "seems like we finally have a fight...\n\n" resp += "```" resp += tabulate(table, headers=["NEW","--","FIGHT"], tablefmt="fancy_grid") resp += "```" await bot_say(resp) #calculate luck attack_luck = uniform(0.92,1) victim_luck = uniform(0.92,1) attack_atk = attacker["stats"]["atk"] * attack_luck victim_atk = victim["stats"]["atk"] * victim_luck #show attacks resp = "\n" + attacker["name"] + " hits for " + "%.4f" % round(attack_atk, 4) if (attack_luck >= 0.98): resp += " **CRIT!**" resp += "\n" + victim["name"] + " hits for " + "%.4f" % round(victim_atk, 4) if (victim_luck >= 0.98): resp += " **CRIT!**" resp += "\n\n" #determine winner if attack_atk > victim_atk: resp += "**" + attacker["name"] + " WINS!**" elif attack_atk < victim_atk: resp += "**" + victim["name"] + " WINS!**" else: resp += "**DRAW!**" await bot_say(resp) #save here save(self.rpg) def is_number(s): try: int(s) return True except ValueError: return False def save(state): fileIO("data/sinon/rpg.json", "save", state) answer = await self.bot.wait_for_message(timeout=15, author=message.author) #put it in variable for ease of use a_list = answer.content.lower().split() if "who" in a_list: #get proper name if a_list[-1:][0][-1:] == "?": name = a_list[-1:][0][:-1] else: name = a_list[-1:][0] #check if answer is defined if name in self.rpg["people"].keys(): if name in ["26", "twentysix", "twentysix26"]: await s_talk(self.rpg["people"][name], glitch = True) else: await bot_say(self.rpg["people"][name]) else: await bot_say("i have no interest in that one...") elif "login" in a_list: #check if user have any chars if message.author.id in self.rpg["players"].keys(): #upd stats just in case for char in self.rpg["players"][str(message.author.id)]: upd_stats(char) await s_talk("k... here are your options...") #form chars array chars_list = get_chars(message.author.id) resp = "```" resp += tabulate(chars_list, headers = ["#","Name","LvL","HP","ATK","DEF","Bank"], tablefmt="fancy_grid") resp += "```" await bot_say(resp + "\nwhich one?...") answer = await self.bot.wait_for_message(timeout=15, author=message.author) #check if user entered proper number if is_number(answer.content.lower().split()[0]): char_num = int(answer.content.lower().split()[0]) #check if proper char if char_num <= (len(chars_list) - 1): #check if not already logged in if not self.rpg["players"][str(message.author.id)][char_num]["active"]: await s_talk("logging in with " + chars_list[char_num][1] + "\nhave fun...") #logout of other chars for char in self.rpg["players"][str(message.author.id)]: if char["active"]: char["active"] = False #login into char self.rpg["players"][str(message.author.id)][char_num]["active"] = True #don't forget to save save(self.rpg) else: await s_talk("you are already playing this one...") else: await s_talk("stop fooling around... there is no such char...") else: await s_talk("stop fooling around... there is no such char...") else: await s_talk("no characters... wanna come with me?... yes or no...") answer = await self.bot.wait_for_message(timeout=15, author=message.author) #create new char if "yes" in answer.content.lower(): await s_talk("I will need your name... just one word...") answer = await self.bot.wait_for_message(timeout=15, author=message.author) #add to current dicr create_char(answer.content.split()[0]) #save here save(self.rpg) #all good await s_talk("good... don't forget to login... and good luck...") else: await s_talk("just like I thought...") elif "create" in a_list: await s_talk("wanna come with me?...\nI will need your name... just one word...") answer = await self.bot.wait_for_message(timeout=15, author=message.author) #add to current dict create_char(answer.content.split()[0]) #save here save(self.rpg) #all good await s_talk("good... don't forget to login... and good luck...") elif "shop" in a_list: #get logged in char login = check_login(str(message.author.id)) if self.rpg["shop"]["opened"]: if login["logged_in"]: await bot_say("ok... but be quick...") await asyncio.sleep(1) await bot_say("this is what i have...\n" + show_shop() + "\n interested?...") answer = await self.bot.wait_for_message(timeout=15, author=message.author) #check if user entered proper number if is_number(answer.content.lower().split()[0]): item_num = int(answer.content.lower().split()[0]) #check if proper item if item_num <= (len(self.rpg["shop"]["items"]) - 1): #buy item for char await buy_item(self.rpg["shop"]["items"][item_num], login["char"]) else: await bot_say("stop fooling around... there is no such item...") else: await bot_say("stop fooling around... there is no such item...") else: await bot_say("stop fooling around... login first...") else: await bot_say("my shop is closed for now...") elif "reload" in a_list: self.rpg = fileIO("data/sinon/rpg.json", "load") await s_talk("db reloaded", glitch = True, bold = True) elif "inventory" in a_list: login = check_login(str(message.author.id)) if login["logged_in"]: #upd stats just in case upd_stats(login["char"]) if "items" in login["char"]: resp = "```" resp += tabulate(get_items(login["char"]), headers=["Name","ATK","Stock"], tablefmt="fancy_grid") resp += "```" await bot_say("this is what you got...\n\n" + resp) else: await bot_say("you dont have any items... buy some first...") else: await bot_say("stop fooling around... login first...") elif "char" in a_list: login = check_login(str(message.author.id)) if login["logged_in"]: #upd stats just in case upd_stats(login["char"]) table = [ [str(login["char"]["stats"]["hp"]) + " HP"], [str(login["char"]["stats"]["atk"]) + " ATK"], [str(login["char"]["stats"]["def"]) + " DEF"], [str(login["char"]["bank"]) + " COL."], ] resp = "```" resp += tabulate(table, headers=[login["char"]["name"] + " [LvL. " + str(login["char"]["lvl"]) + "]"], tablefmt="fancy_grid") resp += "```" await bot_say("really?... k... go ahead... admire yourself...\n\n" + resp) else: await bot_say("stop fooling around... login first...") elif "fight" in a_list: login = check_login(str(message.author.id)) if login["logged_in"]: #upd stats just in case upd_stats(login["char"]) #check if in public channel if not message.channel.is_private: #check if has a mention if a_list[-1:][0][:2] == "<@": #check if oppenent is playing if a_list[-1:][0][2:-1] in self.rpg["players"].keys(): attacker = login["char"] victim = check_login(a_list[-1:][0][2:-1])["char"] #upd stats just in case upd_stats(victim) #hand it off to fighting function await perform_fight(attacker, victim) else: await bot_say("that one is too afraid to play with me...") else: await bot_say("choose an opponent...") else: await bot_say("find a public place to fight...") else: await bot_say("stop fooling around... login first...") elif "help" in a_list: login = check_login(str(message.author.id)) #parse commands table = [] for command in self.rpg["commands"]: table.append([command["name"], command["help"]]) #from menu table resp = "SINON RPG-MODE v.0.0.1\n" if login["logged_in"]: resp += "You are logged in as " + login["char"]["name"] else: resp += "You are not logged in atm" await s_talk(resp, glitch=True, bold=True, extra=tabulate(table, tablefmt="grid")) else: await s_talk("whatever...")
cmd = "rm -rf crawledImages" os.system(cmd) cmd = "mkdir crawledImages" os.system(cmd) cmd = "rm -rf crawledGIFImages" os.system(cmd) cmd = "mkdir crawledGIFImages" os.system(cmd) client = ImgurClient(client_id, client_secret) for searchTag in searchTags: currDownload = 0 result=client.gallery_search(searchTag, advanced=None, sort='time', window='all', page=0) for items in result: print "Downloading " + items.link + " ....." if not hasattr(items, "type"): continue extension = items.type extension = extension.replace('image/', '') imgName = searchTag + str(currDownload) imgName = imgName.replace(' ', '_') extension = "." + extension commCount = 0 folder = ""
def sms_reply(): # Gets the SMS sent to the number body = request.values.get('Body', "") check = command_check() resp = MessagingResponse() needshelp = 0 # !echo if check == 1: body = body[6:] # Checks for parameters if body == None: resp.message("!echo requires additional input.") else: resp.message(body) # Echoes return str(resp) # !wiki elif check == 2: body = body[6:] # Checks for parameters if body == None: resp.message("!wiki requires additonal input.") return str(resp) # Search for article try: search = wikipedia.search(body, results=1, suggestion=True) except wikipedia.exceptions.PageError as e: resp.message("Error generating Wikipedia page.") return str(resp) # Removes disambiguation error try: article = wikipedia.page(title=search[0]) except wikipedia.exceptions.DisambiguationError as e: article = wikipedia.page(title=e.options[0]) # Returns article info title = article.title summary = wikipedia.summary(title, sentences=3) url = article.url # Submits article info wiki_stuff = title + "\n\n" + summary + "\n\n" + "Find out more at:" + url resp.message(wiki_stuff) return str(resp) # !stock elif check == 3: body = body[7:] # Checks for parameters if body == None: resp.message("!stock requires additonal input.") body = body.upper() stocklink = "https://finance.google.com/finance?q=" + body + "&output=json" rsp = requests.get(stocklink) if rsp.status_code in (200,): fin_data = json.loads(rsp.content[6:-2].decode('unicode_escape')) openprice = ('Opening Price: ${}'.format(fin_data['op'])) stockname = ('Stock Name: {}'.format(fin_data['name'])) stockinfo = stockname + "\n" + "Symbol: " + body + "\n" + openprice if format(fin_data['op']) == "": stockinfo = "Invalid stock symbol \n\nSymbols: Facebook(FB), Apple(AAPL), Alphabet(GOOG), Yahoo(YHOO), Amazon(AMZN), Coca-Cola(KO), Walmart(WMT), Microsoft(MSFT)\n\nMore at: https://finance.yahoo.com/" resp.message(stockinfo) return str(resp) # !help elif check == 0: return help() # !rand elif check == 4: body = body[6:] # If no parameter is applied if body == None: items = ImgurClient.gallery() randnum = random(0, len(items)-1) img = get_image(items[randnum].image_id) return img else: items = ImgurClient.gallery_search(q=body, advanced=None, sort='time', window='all', page=0) randnum = random(0, len(items)-1) img = get_image(items[randnum].image_id) return img # 5 Failed Commands = !help else: needshelp = needshelp + 1 if needshelp >= 5: needshelp = 0 help() return
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)
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))
class Engraver: def __init__(self, bot): self.bot = bot self.client = ImgurClient(imgur_client_id,imgur_client_secret) @commands.command() async def imgur (self, *topic): """ Performs an Imgur search on the given topic. Arguments: - topic: Topic to search for. """ if self.client.credits["ClientRemaining"] < 10: message = "**Error:** Imgur API daily limit exceeded." else: topic = " ".join(topic) search = self.client.gallery_search(topic) if len(search) > 0: item = search.pop() message = item.link else: message = "**Error:** no Imgur search results for {}.".format(topic) await(self.bot.say(message)) @commands.group(name="album", pass_context=True) async def album (self, ctx, name): """ Pulls a random image from a known album. Arguments: - name: Name of album to pull from. """ if ctx.invoked_subcommand is None: if self.client.credits["ClientRemaining"] < 10: message = "**Error:** Imgur API daily limit exceeded." else: sid = ctx.message.server.id if sid == None: message = "**Error:** Cannot use albums by PM." aid = get_album_id(sid,name) if aid == None: message = "**Error:** No known album {}.".format(name) else: album = self.client.get_album_images(aid) if album == None: message = "**Error:** invalid album ID {} for name {}. Contact the administrator.".format(aid,name) message = item.link await(self.bot.say(message)) @album.command(pass_context=True) async def create (self, ctx, name, image=None): """ Creates an album, containing the given image. If the album already exists, Arguments: - name: Name of album to be created to. - image: Link to the image to be added. If this is omitted, will check message for attached file. """ sid = ctx.message.server.id if image == None: if len(ctx.message.attachments) > 0: image = ctx.message.attachments[0].link else: image = "**Error:** No image provided." await(self.bot.say(image))