async def sendComic(ctx, comic, integer): comicNum = xkcd.getLatestComicNum() comic = await makeComic(ctx, comic, integer) def check(reaction, user): return user == ctx.author and str(reaction.emoji) in ["◀️", "🎲", "▶️"] while True: try: reaction, user = await client.wait_for("reaction_add", timeout=60, check=check) if str(reaction.emoji ) == "▶️" and integer < comicNum and user == ctx.author: integer += 1 await comic.delete() comic = xkcd.getComic(integer) comic = await makeComic(ctx, comic, integer) elif str(reaction.emoji ) == "◀️" and integer > 1 and user == ctx.author: integer -= 1 await comic.delete() comic = xkcd.getComic(integer) comic = await makeComic(ctx, comic, integer) elif str(reaction.emoji) == "🎲" and user == ctx.author: await comic.delete() rand = randrange(1, xkcd.getLatestComicNum()) comic = xkcd.getComic(rand) comic = await makeComic(ctx, comic, rand) except asyncio.TimeoutError: break
async def comic(ctx, integer=xkcd.getLatestComicNum()): comicNum = xkcd.getLatestComicNum() try: integer = int(integer) except ValueError: await invalidComic(ctx, integer) return if integer <= comicNum: comic = xkcd.getComic(integer) await sendComic(ctx, comic, integer) else: await invalidComic(ctx, integer)
async def xkcd(self, ctx, query: int = None): """Queries a random XKCD comic. Do xkcd <number> to pick a specific comic.""" if query == 404: em = discord.Embed(color=discord.Color.red()) em.title = "\N{CROSS MARK} Error" em.description = "Error 404: Comic Not Found" return await ctx.send(embed=em) latest_comic = xkcd.getLatestComicNum() if query: query_req = 1 <= int(query) <= int(latest_comic) if query_req: comic = xkcd.getComic(query) else: em = discord.Embed(color=discord.Color.red()) em.title = "\N{CROSS MARK} Error" em.description = f"It has to be between 1 and {str(latest_comic)}!" return await ctx.send(embed=em) else: comic = xkcd.getRandomComic() embed = discord.Embed(title=f"xkcd {comic.number}: {comic.title}", url=comic.link) embed.set_image(url=comic.imageLink) embed.set_footer(text=comic.altText) await ctx.send(embed=embed)
async def xkcd(self, *, number=None): """xkcd comic""" try: if number == None: a = com.getRandomComic() title = a.getTitle() link = a.getImageLink() exp = a.getExplanation() embed = discord.Embed(title="xkcd", color=0xf5f5dc) embed.add_field(name="Title", value=title, inline=False) embed.set_footer(text=("For explanation refer to: " + exp)) embed.set_image(url=link) await self.bot.say(embed=embed) else: number = int(number) limit = com.getLatestComicNum() if number < 1 or number > limit: await self.bot.say( "Please enter a number between 1 to 1988") else: a = com.getComic(number, silent=True) title = a.getTitle() link = a.getImageLink() exp = a.getExplanation() embed = discord.Embed(title="xkcd", color=0xf5f5dc) embed.add_field(name="Title", value=title, inline=False) embed.set_footer(text=("For explanation refer to: " + exp)) embed.set_image(url=link) await self.bot.say(embed=embed) except Exception as e: await self.bot.say(f'Unable to fetch comic : {e}')
async def getXKCD(self, ctx, comic_number): """ Gets an XKCD comic and returns info about it ;param comic_number: the number of the xkcd comic :return: XKCD comic link, title, alt-text, and image title """ if -1 < int(comic_number) < xkcd.getLatestComicNum( ): # check for valid XKCD comic # get info about XCKD comic comic = xkcd.getComic(comic_number) comic_link = comic.getImageLink() alt_text = comic.getAltText() comic_name = comic.getImageName() comic_title = comic.getTitle() await ctx.send( f'```' f'Here is XKCD comic {comic_number}\nTitle: {comic_title}' f'```') await ctx.send(comic_link) await ctx.send( f'```' f'Alternate text: {alt_text}\nImage file name: {comic_name} ' f'```') else: await ctx.send( f'Invalid comic number. Please enter a number between 0 and {xkcd.getLatestComicNum()}' )
async def getxkcd(self, ctx, comic_number): """ !getxkcd <comic_num> Gets an XKCD comic comic_num and returns various info about it. comic_num = integer """ if -1 < int(comic_number) < xkcd.getLatestComicNum(): # check for valid XKCD comic # get info about XCKD comic comic = xkcd.getComic(comic_number) comic_link = comic.getImageLink() alt_text = comic.getAltText() comic_name = comic.getImageName() comic_title = comic.getTitle() await ctx.send(f'```' f'Here is XKCD comic {comic_number}\nTitle: {comic_title}' f'```') await ctx.send(comic_link) await ctx.send(f'```' f'Alternate text: {alt_text}\nImage file name: {comic_name} ' f'```') else: await ctx.send(f'Invalid comic number. ' f'Please enter a number between 0 and {xkcd.getLatestComicNum()}')
async def xkcd_command(self, ctx, *, number=None): try: if number == None: a = comic.getRandomComic() title = a.getTitle() link = a.getImageLink() exp = a.getExplanation() embed = discord.Embed(title=f"xkcd - {title}", description=f"{a.altText}", color=0xf5f5dc) embed.set_footer(text=("For explanation refer to: " + exp)) embed.set_image(url=link) await ctx.send(embed=embed) else: number = int(number) limit = comic.getLatestComicNum() if number < 1 or number > limit: await ctx.send("Please enter a number between 1 to 1988") else: a = comic.getComic(number, silent=True) title = a.getTitle() link = a.getImageLink() exp = a.getExplanation() embed = discord.Embed(title=f"xkcd - {title}", description=f"{a.altText}", color=0xf5f5dc) embed.set_footer(text=("For explanation refer to: " + exp)) embed.set_image(url=link) await ctx.send(embed=embed) except Exception as e: await ctx.send(f'There was an error trying to fetch comic: {e}')
async def on_xkcd(ctx): num = random.randint(0, xkcd.getLatestComicNum()) comic = xkcd.getComic(num) url = comic.getImageLink() embed = Embed(title="Laugh at this.", description="\u200B") embed.set_image(url=url) await ctx.reply(embed=embed)
def retrieve_comic(): """ Deal with the AJAX request from client-side and returns a JSON response. In case of being requested by the client-side with a POST, change between the different modes. Otherwise, redirects to initial_view. Returns ------- Response (JSON formatted) """ if request.method == 'POST': first_comic_id = 1 max_comic_id = xkcd.getLatestComicNum() json_request = request.get_json(force=True) current_comic_id = int(json_request['id']) mode = json_request['mode'] comic = comic_utils.generate_comic_for_mode(current_comic_id, first_comic_id, max_comic_id, mode) else: return initial_view() comic_data = comic_utils.get_comic_data(comic) response = json.dumps(comic_data) return response
def check_new_comic(): global last_latest latest = xkcd.getLatestComicNum() if latest > last_latest: last_latest = latest return (True, latest) return (False, latest)
def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) # A 'context' is the data that the template can use comic = xkcd.Comic(xkcd.getLatestComicNum()) context.update({ 'inventory_size': Container.objects.filter(is_empty=False).count(), 'xkcd_url': comic.getImageLink(), 'xkcd_alt': comic.getAsciiAltText(), 'xkcd_title': comic.getAsciiTitle() }) # Now put the context together with a template # Look in chemical_inventory/templates/main.html for the actual html # 'request' is the HTTP request submitted by the browser return context
async def makeComic(ctx, comic, integer): comicNum = xkcd.getLatestComicNum() title = comic.getTitle() alt = comic.getAltText() comic = comic.getImageLink() embed = make_embed(title=f"{title}", desc=f"by Randall Munroe\nComic: {integer}/{comicNum}") embed.set_image(url=comic) embed.set_footer(text=alt) comic = await ctx.channel.send(embed=embed) if integer > 1: await comic.add_reaction("◀️") await comic.add_reaction("🎲") if integer < comicNum: await comic.add_reaction("▶️") return comic
def get_latest_or_random_unread_comic(): max_comic_count = xkcd.getLatestComicNum() previous_comic_ids = {} for file_name in os.listdir(image_directory): key = int(file_name.replace(".png", "").replace(".bmp", "")) if key not in previous_comic_ids: previous_comic_ids[key] = True unread_comic_ids = [] for i in range(max_comic_count): i = i + 1 if i not in previous_comic_ids: unread_comic_ids.append(i) if max_comic_count not in previous_comic_ids: print("Fetching latest comic.") return max_comic_count print("No new comics. Fetching random comic.") random.shuffle(unread_comic_ids) return unread_comic_ids[0]
maxPixelWidth = float(512) nStartComic = xkcd.getLatestComic().number try: opts, args = getopt.getopt(sys.argv[1:], "hn:ri:", ["help", "to-print=", "random", "comicid="]) except getopt.GetoptError: print(usageText) sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): print(usageText) sys.exit() elif opt in ("-r", "--random"): nStartComic = randint(1, xkcd.getLatestComicNum()) elif opt in ("-i", "--comicid"): if 0 < int(arg) <= xkcd.getLatestComicNum(): nStartComic = int(arg) else: print( "Error: Comic ID specified is out of valid range. Please specify a comic ID between 1 and " + str(xkcd.getLatestComicNum())) sys.exit(1) elif opt in ("-n", "--to-print"): nComicsToPrint = int(arg) print("Printing " + str(nComicsToPrint) + " comics.") if nComicsToPrint > 1: print("Comic # " + str(nStartComic) + " and " + str(nComicsToPrint - 1) + " previous comics will be printed.")
position = 290+int(image.get_width()/2)+10 else: label_rect = label.get_rect() label_rect.center = (300, 7) image = aspect_scale(image,(460,750)) image.set_colorkey((255, 255, 255)) img_rect = image.get_rect() img_rect.center = (300, 400) position = 300+int(image.get_width()/2)+10 screen.blit(label, label_rect) print(position) for l in textwrap.wrap(comic.getAltText(),80): alttext = myfont2.render(l, 1, black) alttext = pygame.transform.rotate(alttext,90) alttext_rect = alttext.get_rect() alttext_rect.center = (position, 400) screen.blit(alttext, alttext_rect) position+=20 if(position > 600): print('aah!') break screen.blit(image,img_rect) convert_to_raw(screen,i) for m in range(405,xkcd.getLatestComicNum()): try: display(m) except: pass sleep(0.5)
async def latest(ctx): latest = xkcd.getLatestComic() integer = xkcd.getLatestComicNum() await sendComic(ctx, latest, integer)
async def random_xkcd(ctx): integer = randrange(1, xkcd.getLatestComicNum()) comic = xkcd.getComic(integer) await sendComic(ctx, comic, integer)
def update(): latest_num = os.listdir("/mnt/sd/xkcd/") latest_num = [int(x.strip('.raw')) for x in latest_num] latest_num.sort() latest_num = latest_num[-1] if(latest_num == xkcd.getLatestComicNum()): return True for i in range(latest_num,xkcd.getLatestComicNum()+1): print("Downloading comic" + str(i)) pygame.font.init() white = (255, 255, 255) black = (0, 0, 0) gray = (125, 125, 125) screen = pygame.Surface((600, 800)) screen.fill(white) comic=xkcd.Comic(i) print(comic) link = comic.getImageLink() image_raw = urllib2.urlopen(link).read() image_raw2 = io.BytesIO(image_raw) image = pygame.image.load(image_raw2) myfont = pygame.font.Font('/KoboXkcd/KoboRoot/xkcd-Regular.otf', 20) myfont2 = pygame.font.Font('/KoboXkcd/KoboRoot/xkcd-Regular.otf', 13) label = myfont.render('xkcd '+ str(i)+'; '+comic.getTitle(), 1, black) if(image.get_width() > image.get_height()): label = pygame.transform.rotate(label,90) label_rect = label.get_rect() label_rect.center = (7, 400) image = pygame.transform.rotate(image,90) image = aspect_scale(image,(460,750)) image.set_colorkey((255, 255, 255)) img_rect = image.get_rect() img_rect.center = (275, 400) position = 290+int(image.get_width()/2)+10 else: label_rect = label.get_rect() label_rect.center = (300, 7) image = aspect_scale(image,(460,750)) image.set_colorkey((255, 255, 255)) img_rect = image.get_rect() img_rect.center = (300, 400) position = 300+int(image.get_width()/2)+10 screen.blit(label, label_rect) print(position) for l in textwrap.wrap(comic.getAltText(),80): alttext = myfont2.render(l, 1, black) alttext = pygame.transform.rotate(alttext,90) alttext_rect = alttext.get_rect() alttext_rect.center = (position, 400) screen.blit(alttext, alttext_rect) position+=20 if(position > 600): print('aah!') break screen.blit(image,img_rect) convert_to_raw(screen,i)