Exemplo n.º 1
0
class XKCD:
    """A plugin for those on the internet with good humor."""
    def __init__(self, bot):
        self.bot = bot

    # Helper function for getting comics
    async def get_comic(self, comic, number=None):
        case = {
            "latest": lambda: xkcd.getLatestComic(),
            "random": lambda: xkcd.getRandomComic(),
            "number": lambda: xkcd.getComic(number),
        }
        function = case.get(comic, None)
        comic = self.bot.loop.run_in_executor(None, function)
        while True:
            await asyncio.sleep(0.25)
            if comic.done():
                comic = comic.result()
                break
        try:
            link = comic.getImageLink()
            title = comic.getAsciiTitle().decode("ascii")
            alt_text = comic.getAsciiAltText().decode("ascii")
            number = comic.number
            return f"{number} - {link}\n**Title:** {title}\n**Alt:** {alt_text}"
        except AttributeError:
            return "\U00002754 Can't find that comic."
Exemplo n.º 2
0
    async def get_comic(self, comic, number=None) -> Embed:
        """Helper function to get comics"""
        case = {
            "latest": lambda: comics.getLatestComic(),
            "random": lambda: comics.getRandomComic(),
            "number": lambda: comics.getComic(number),
        }

        function = case.get(comic, None)
        exc = self.bot.loop.run_in_executor(None, function)

        while not exc.done():
            await asyncio.sleep(0.1)
        result = exc.result()

        try:
            image_link = result.getImageLink()
            title = result.getAsciiTitle().decode("ascii")
            alt_text = result.getAsciiAltText().decode("ascii")
            number = result.number

            embed = Embed(title=title,
                          url=f"https://xkcd.com/{number}",
                          color=0x96A8C8)
            embed.add_field(name=str(number), value=alt_text)
            embed.set_image(url=image_link)

            return embed
        except AttributeError as error:
            embed = Embed(title="Error", color=0xFF0000)
            embed.add_field(name="Details", value=str(error))
            return embed
Exemplo n.º 3
0
def get_latest(bot, update):
    """Shows the latest XKCD."""
    bot.send_chat_action(chat_id=update.message.chat_id,
                         action=ChatAction.TYPING)
    comic = xkcd.getLatestComic()
    message = "*{title}* [#{number}]({link})\n{altText}".format(
        **comic.__dict__)
    bot.send_message(chat_id=update.message.chat_id,
                     text=message,
                     parse_mode="Markdown")
Exemplo n.º 4
0
    async def xkcd(self, *, comic):
        comic = comic.lower()
        """Show xkcd comic by number. Use "latest" to show the latest comic, or "random" to show a random comic."""
        if comic == "latest":
            # await self.bot.say("https://xkcd.com/{}/".format(xkcd.getLatestComic().number))
            comicpage = "https://xkcd.com/{}/".format(xkcd.getLatestComic().number)
            page = requests.get(comicpage).content
            soup = BeautifulSoup(page, "html.parser")
            comicImageBlock = soup.find("div",{"id":"comic"})
            comicImageTag = comicImageBlock.find("img")
            comicURL = comicImageTag['src']
            embed = discord.Embed(title='Latest xkcd', description='Here\'s your comic!', color=0xFFFFFF)
            embed.set_image(url='https:{}'.format(comicURL))
            await self.bot.say(embed=embed)

        elif comic == "random":
            # await self.bot.say("https://xkcd.com/{}/".format(xkcd.getRandomComic().number))
            comicpage = "https://xkcd.com/{}/".format(xkcd.getRandomComic().number)
            page = requests.get(comicpage).content
            soup = BeautifulSoup(page, "html.parser")
            comicImageBlock = soup.find("div",{"id":"comic"})
            comicImageTag = comicImageBlock.find("img")
            comicURL = comicImageTag['src']
            embed = discord.Embed(title='Random xkcd', description='Here\'s your comic!', color=0xFFFFFF)
            embed.set_image(url='https:{}'.format(comicURL))
            await self.bot.say(embed=embed)

        elif comic.isdigit():
            # await self.bot.say("https://xkcd.com/{}/".format(xkcd.getComic(comic).number))
            comicpage = "https://xkcd.com/{}/".format(xkcd.getComic(comic).number)
            page = requests.get(comicpage).content
            soup = BeautifulSoup(page, "html.parser")
            comicImageBlock = soup.find("div",{"id":"comic"})
            comicImageTag = comicImageBlock.find("img")
            comicURL = comicImageTag['src']
            embed = discord.Embed(title='xkcd number {}'.format(comic), description='Here\'s your comic!', color=0xFFFFFF)
            embed.set_image(url='https:{}'.format(comicURL))
            await self.bot.say(embed=embed)


        elif comic in self.word_responses:
            # await self.bot.say("https://xkcd.com/{}/".format(xkcd.getComic(self.word_responses[comic]).number))
            comicpage = "https://xkcd.com/{}/".format(xkcd.getComic(self.word_responses[comic]).number)
            page = requests.get(comicpage).content
            soup = BeautifulSoup(page, "html.parser")
            comicImageBlock = soup.find("div",{"id":"comic"})
            comicImageTag = comicImageBlock.find("img")
            comicURL = comicImageTag['src']
            embed = discord.Embed(title='Keyphrase: {}'.format(comic), description='Here\'s your comic!', color=0xFFFFFF)
            embed.set_image(url='https:{}'.format(comicURL))
            await self.bot.say(embed=embed)

        else:
            await self.bot.say("I can't find that one!")
Exemplo n.º 5
0
 def loop(self):
     self.backend.connect()
     while True:
         for event in self.backend.update():
             try:
                 if event["type"] == "text":
                     times = re.search(r"(?P<nm>\d+) times", event["content"].lower())
                     if times:
                         if int(times.group("nm")) > 0:
                             times = min(5,int(times.group("nm")))
                         else:
                             self.backend.say("Okay, I won't say anything... Baka.")
                             continue
                     else:
                         times = 1
                     for i in range(times):
                         if "hi" in detox(event["content"].lower()).split() or "hello" in detox(event["content"].lower()).split():
                             self.backend.say(random.choice(["%s! Tutturuuu!","Hello, %s, so it was you making the noise up there!"]) % event["by"])
                             continue
                         if "nano" in event["content"].lower() or "hakase" in event["content"].lower():
                             self.backend.say("%s%s"%("HAKASE"*len(re.findall("nano", event["content"].lower())),"NANO"*len(re.findall("hakase", event["content"].lower()))))
                             continue
                         if event["mentioned"]:
                             if "roll" in detox(event["content"].lower()).split():
                                 numb = re.search(r"(d|k)(?P<nm>\d+)", event["content"].lower())
                                 if numb and int(numb.group("nm")) > 0:
                                     self.backend.say("Aaaand... %d!" % (random.randrange(1,int(numb.group("nm"))+1)))
                                     continue
                                 else:
                                     self.backend.say("Who do you think you are, rolling impossible dice... Baka.")
                                     continue
                             if "say" in detox(event["content"].lower()).split():
                                 if "something" in detox(event["content"].lower()).split():
                                     tosay = self.mc.generateString()
                                 elif "name" in detox(event["content"].lower()).split():
                                     tosay = self.backend.get_name(event["by"])
                                 self.backend.say(tosay)
                                 continue
                             if "xkcd" in detox(event["content"].lower()).split():
                                 if "random" in detox(event["content"].lower()).split():
                                     x = xkcd.getRandomComic()
                                 else:
                                     numb = re.search(r"(?P<nm>\d+)", event["content"])
                                     if numb:
                                         x = xkcd.Comic(int(numb.group("nm")))
                                     else:
                                         x = xkcd.getLatestComic()
                                 self.backend.say("*%s* - %s - _%s_" % (x.getTitle(), x.getImageLink(), x.getAltText()))
                                 continue
                             self.backend.say("Hmm?")
                             continue
             except:
                 self.backend.say(str(sys.exc_info()[0]))
Exemplo n.º 6
0
 async def xkcd(self, ctx: KurisuContext, *, comic):
     """Show xkcd comic by number. Use "latest" to show the latest comic, or "random" to show a random comic."""
     comic = comic.lower()
     if comic == "latest":
         await ctx.send("https://xkcd.com/{}/".format(xkcd.getLatestComic().number))
     elif comic == "random":
         await ctx.send("https://xkcd.com/{}/".format(xkcd.getRandomComic().number))
     elif comic.isdecimal():
         await ctx.send("https://xkcd.com/{}/".format(xkcd.getComic(comic).number))
     elif comic in self.word_responses:
         await ctx.send("https://xkcd.com/{}/".format(xkcd.getComic(self.word_responses[comic]).number))
     else:
         await ctx.send("I can't find that one!")
Exemplo n.º 7
0
 async def xkcd(self, *, comic):
     comic = comic.lower()
     """Show xkcd comic by number. Use "latest" to show the latest comic, or "random" to show a random comic."""
     if comic == "latest":
         await self.bot.say("", embed=await self.embed_xkcd_comic(xkcd.getLatestComic()))
     elif comic == "random":
         await self.bot.say("", embed=await self.embed_xkcd_comic(xkcd.getRandomComic()))
     elif comic.isdigit():
         await self.bot.say("", embed=await self.embed_xkcd_comic(xkcd.getComic(comic)))
     elif comic in self.word_responses:
         await self.bot.say("", embed=await self.embed_xkcd_comic(xkcd.getComic(self.word_responses[comic])))
     else:
         await self.bot.say("I can't find that one!")
Exemplo n.º 8
0
 async def xkcd(self, *, comic):
     comic = comic.lower()
     """Show xkcd comic by number. Use "latest" to show the latest comic, or "random" to show a random comic."""
     if comic == "latest":
         await self.bot.say("https://xkcd.com/{}/".format(xkcd.getLatestComic().number))
     elif comic == "random":
         await self.bot.say("https://xkcd.com/{}/".format(xkcd.getRandomComic().number))
     elif comic.isdigit():
         await self.bot.say("https://xkcd.com/{}/".format(xkcd.getComic(comic).number))
     elif comic in self.word_responses:
         await self.bot.say("https://xkcd.com/{}/".format(xkcd.getComic(self.word_responses[comic]).number))
     else:
         await self.bot.say("I can't find that one!")
Exemplo n.º 9
0
 async def xkcd(self, comicnum):
     """Show xkcd comic by number. Use "latest" to show the latest comic, or "random" to show a random comic."""
     if comicnum == "latest":
         await self.bot.say("",
                            embed=await
                            self.embed_xkcd_comic(xkcd.getLatestComic()))
     elif comicnum == "random":
         await self.bot.say("",
                            embed=await
                            self.embed_xkcd_comic(xkcd.getRandomComic()))
     else:
         await self.bot.say("",
                            embed=await
                            self.embed_xkcd_comic(xkcd.getComic(comicnum)))
Exemplo n.º 10
0
def xkcd_response(text):
    match = re.match(r'!xkcd ?(\w+)? ?(\w+)?', text)
    if not match:
        return False

    option = match.group(1)
    link = match.group(2)
    comic = xkcd.getRandomComic()
    if option:
        if option == 'today':
            comic = xkcd.getLatestComic()
        elif option.isdigit():
            comic = xkcd.getComic(int(option))
    if link == 'link':
        return comic.link + '\n' + (EXPLAIN + str(comic.number))
    else:
        return comic.title + '\n' + comic.imageLink + '\n' + comic.altText + '\n' + (EXPLAIN + str(comic.number))
Exemplo n.º 11
0
def showComicHTML(comic, comicId=-1):
    try:
        title = comic.getTitle()
        imageUrl = comic.getImageLink()
        # Get the source url
        sourceUrl = comic.getExplanation().replace("explain", "")
        # Get the current comicId from sourceUrl using re
        if (comicId == -1):
            comicId = int(re.search(r'\d+', sourceUrl).group())

    except Exception as e:
        # If comic does not exist the latest is returned
        return showComicHTML(xkcd.getLatestComic())
    return render_template('showComic.html',
                           title=title,
                           sourceUrl=sourceUrl,
                           imageUrl=imageUrl,
                           comicId=comicId)
Exemplo n.º 12
0
def xkcdR(content):
    import xkcd
    print("Loading xkcd")
    print(content)
    if content == "random":
        print("Getting Random")
        comic = xkcd.getRandomComic()
    elif content == "latest":
        print("Getting latest")
        comic = xkcd.getLatestComic()
    else:
        print("Getting by id")
        comic = xkcd.getComic(int(content))
    print("Downloading Comic")
    comic.download(output="/home/victor/PycharmProjects/wppchatbot/",
                   outputFile="xkcd.png")
    altText = comic.getAltText()
    print(altText)
    return "!xkcd.png|" + altText
Exemplo n.º 13
0
def xkcd_response(text):
    """!xkcd (#|today|random)? 'link'?: returns an xkcd comic. default random"""
    match = re.match(r'!xkcd ?(\w+)? ?(\w+)?', text)
    if not match:
        return False

    option = match.group(1)
    link = match.group(2)
    comic = xkcd.getRandomComic()
    if option:
        if option == 'today':
            comic = xkcd.getLatestComic()
        elif option.isdigit():
            comic = xkcd.getComic(int(option))
    if link == 'link':
        return comic.link + '\n' + (EXPLAIN + str(comic.number))
    else:
        return comic.title + '\n' + comic.imageLink + '\n' + comic.altText + '\n' + (
            EXPLAIN + str(comic.number))
Exemplo n.º 14
0
 async def getxkcd(self, ctx, call='random'):
     """Functions that call to xkcd comics API"""
     if call == 'random':
         comic = xkcd.getRandomComic()
     elif call == 'latest':
         comic = xkcd.getLatestComic()
     elif call.isdigit():
         comic = xkcd.getComic(call)
     else:
         await ctx.send('Hmm... I can\'t find a comic with that parameter.')
     ctitle = comic.getTitle()
     catext = comic.getAltText()
     curl = comic.getImageLink()
     cimgn = comic.getImageName()
     cnumber = str(comic)[38:]
     # Embed and say message
     embed = discord.Embed(title=ctitle, description=catext)
     embed.set_image(url=curl)
     embed.set_footer(text='xkcd issue {}: {}'.format(cnumber, cimgn))
     await ctx.send(embed=embed)
Exemplo n.º 15
0
class XKCD(commands.Cog):
    """A plugin to retrieve XKCD comics."""
    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self.name = "xkcd"

    # Helper function for getting comics
    async def get_comic(self, comic, number=None) -> Embed:
        case = {
            "latest": lambda: xkcd.getLatestComic(),
            "random": lambda: xkcd.getRandomComic(),
            "number": lambda: xkcd.getComic(number)
        }

        function = case.get(comic, None)
        exc = self.bot.loop.run_in_executor(None, function)

        while not exc.done():
            await asyncio.sleep(0.1)
        exc = exc.result()

        try:
            image_link = exc.getImageLink()
            title = exc.getAsciiTitle().decode("ascii")
            alt_text = exc.getAsciiAltText().decode("ascii")
            number = exc.number

            embed = Embed(title=title, url=link, color=0x96A8C8)
            embed.add_field(name=str(number), value=alt_text)
            embed.set_image(image_link)

            return embed
        except AttributeError as error:
            embed = Embed(title="Error", color=0xff0000)
            embed.add_field(name="Details", value=str(error))
            return embed
Exemplo n.º 16
0
async def latest(ctx):
    latest = xkcd.getLatestComic()
    integer = xkcd.getLatestComicNum()
    await sendComic(ctx, latest, integer)
Exemplo n.º 17
0
def index():
    # At start we get the latest comic
    return showComicHTML(xkcd.getLatestComic())
Exemplo n.º 18
0
 async def xkcd(self, ctx):
     """Displays latest xkcd comic."""
     if ctx.invoked_subcommand is None:
         await self.bot.say(xkcd.getLatestComic().getImageLink())
Exemplo n.º 19
0
#!/usr/bin/env python2

# NOTE: this example requires PyAudio because it uses the Microphone class

import speech_recognition as sr
import xkcd
import webbrowser
import pandas as pd

## Update database of xkcd comics
# retrieve latest comic
try:
    last = xkcd.getLatestComic()
    nmax = last.number
except:
    nmax = 0

# Load databas from CSV    
try:
    df = pd.DataFrame.from_csv('xkcd.csv')
except:
    df = pd.DataFrame(columns=['title', 'alt'])
    df.index.name = 'n'

# Try to download missing/new comics
new = False
for n in xrange(1,nmax):
    print '\r', n,
    if n not in df.index:
        try:
            comic = xkcd.Comic(n)
Exemplo n.º 20
0
async def xkcdlast():
    comic = XKCD.getLatestComic()
    comment = "{0}\n{1}".format(comic.getTitle(), comic.getImageLink())
    await bot.say(comment)
    time.sleep(2)
    await bot.say(comic.getAltText())
Exemplo n.º 21
0
    def generate_image(self):
        """Generate image for this module"""

        # Create tmp path
        tmpPath = '/tmp/inkycal_xkcd/'

        try:
            os.mkdir(tmpPath)
        except OSError:
            print("Creation of tmp directory %s failed" % path)
        else:
            print("Successfully created tmp directory %s " % path)

        # Define new image size with respect to padding
        im_width = int(self.width - (2 * self.padding_left))
        im_height = int(self.height - (2 * self.padding_top))
        im_size = im_width, im_height
        logger.info('image size: {} x {} px'.format(im_width, im_height))

        # Create an image for black pixels and one for coloured pixels (required)
        im_black = Image.new('RGB', size=im_size, color='white')
        im_colour = Image.new('RGB', size=im_size, color='white')

        # Check if internet is available
        if internet_available() == True:
            logger.info('Connection test passed')
        else:
            raise Exception('Network could not be reached :/')

        # Set some parameters for formatting feeds
        line_spacing = 1
        line_height = self.font.getsize('hg')[1] + line_spacing
        line_width = im_width
        max_lines = (im_height // (self.font.getsize('hg')[1] + line_spacing))

        logger.debug(f"max_lines: {max_lines}")

        # Calculate padding from top so the lines look centralised
        spacing_top = int(im_height % line_height / 2)

        # Calculate line_positions
        line_positions = [(0, spacing_top + _ * line_height)
                          for _ in range(max_lines)]

        logger.debug(f'line positions: {line_positions}')

        logger.info(f'getting xkcd comic...')

        if self.mode == 'random':
            xkcdComic = xkcd.getRandomComic()
        else:
            xkcdComic = xkcd.getLatestComic()

        xkcdComic.download(output=tmpPath, outputFile='xkcdComic.png')

        logger.info(f'got xkcd comic...')
        title_lines = []
        title_lines.append(xkcdComic.getTitle())

        comicSpace = Image.new('RGBA', (im_width, im_height),
                               (255, 255, 255, 255))
        comicImage = Image.open(tmpPath + '/xkcdComic.png')
        headerHeight = int(line_height * 3 / 2)
        comicImage.thumbnail((im_width, im_height - headerHeight),
                             Image.BICUBIC)
        centerPos = int((im_width / 2) - (comicImage.width / 2))
        comicSpace.paste(comicImage, (centerPos, headerHeight))
        logger.info(f'added comic image')

        im_black.paste(comicSpace)

        # Write/Draw something on the black image
        for _ in range(len(title_lines)):
            if _ + 1 > max_lines:
                logger.error('Ran out of lines for title_lines_black')
                break
            write(im_black,
                  line_positions[_], (line_width, line_height),
                  title_lines[_],
                  font=self.font,
                  alignment='center')

        # Save image of black and colour channel in image-folder
        return im_black, im_colour
Exemplo n.º 22
0
 def xkcd_latest(self, msg, matches):
     comic = xkcd.getLatestComic()
     return self.return_comic(msg, comic)
Exemplo n.º 23
0
    def onMessage(self, author_id, message_object, thread_id, thread_type,
                  **kwargs):
        # Check for blank (picture, for one) messages
        if message_object.text == None:
            return

        if message_object.text.startswith('@swftbot time'):
            time_remaining = datetime.datetime(2018, 6, 6, 13,
                                               54) - datetime.datetime.now()
            self.send(Message(
                text="About {} days, {} hours, and {} minutes left!".format(
                    time_remaining.days, time_remaining.seconds //
                    3600, time_remaining.seconds % 3600 // 60)),
                      thread_id=thread_id,
                      thread_type=thread_type)
        elif message_object.text.startswith('@swftbot hours'):
            time_remaining = datetime.datetime(2018, 6, 6, 13,
                                               54) - datetime.datetime.now()
            self.send(
                Message(text="About {} hours and {} minutes left!".format(
                    int(time_remaining.total_seconds() //
                        3600), time_remaining.seconds % 3600 // 60)),
                thread_id=thread_id,
                thread_type=thread_type)
        elif message_object.text.startswith('@swftbot hello'):
            self.send(Message(text='Hello World!'),
                      thread_id=thread_id,
                      thread_type=thread_type)
        elif message_object.text.startswith('@swftbot insult'):
            insultee = message_object.text[16:]
            if insultee.startswith("Cha") or insultee.startswith("cha"):
                self.send(Message("Chandler is great! Can't insult him... :D"),
                          thread_id=thread_id,
                          thread_type=thread_type)
            else:
                self.send(Message(text=insultee + " smells funny!"),
                          thread_id=thread_id,
                          thread_type=thread_type)
        elif message_object.text.startswith('@swftbot xkcd'):
            xkcd_command = message_object.text[14:]
            xkcd_comic = None
            if xkcd_command == "help":
                self.send(
                    Message("Usage: @swftbot xkcd <1234|random|latest|help>"),
                    thread_id=thread_id,
                    thread_type=thread_type)
                return
            elif xkcd_command == "random":
                xkcd_comic = xkcd.getRandomComic()
            elif xkcd_command == "latest":
                xkcd_comic = xkcd.getLatestComic()
            else:
                try:
                    xkcd_number = int(xkcd_command)
                except:
                    msg_text = "Error parsing command."
                    self.send(Message(text=msg_text),
                              thread_id=thread_id,
                              thread_type=thread_type)
                    return
                xkcd_comic = xkcd.Comic(xkcd_number)
            self.sendRemoteImage(xkcd_comic.getImageLink(),
                                 message=Message(text=xkcd_comic.getAltText()),
                                 thread_id=thread_id,
                                 thread_type=thread_type)
        elif message_object.text.startswith('@swftbot wikipedia'):
            global sections
            global num_sections
            try:
                query = message_object.text[19:]
                if query == "next":
                    if len(sections) > 0:
                        self.send(Message(sections.pop(0)),
                                  thread_id=thread_id,
                                  thread_type=thread_type)
                        self.send(Message(
                            "Section %i of %i" %
                            (num_sections - len(sections), num_sections)),
                                  thread_id=thread_id,
                                  thread_type=thread_type)
                    else:
                        print('No more sections!')
                else:
                    current_page = wikipedia.WikipediaPage(query)
                    if current_page is None:
                        print("No page found")
                    else:
                        sections = current_page.content.split("\n\n\n")
                        num_sections = len(sections)
                        self.send(Message(sections.pop(0)),
                                  thread_id=thread_id,
                                  thread_type=thread_type)
                        self.send(Message(
                            "Section %i of %i" %
                            (num_sections - len(sections), num_sections)),
                                  thread_id=thread_id,
                                  thread_type=thread_type)
            except:
                self.send(Message("Wikipedia Error"),
                          thread_id=thread_id,
                          thread_type=thread_type)
        elif message_object.text.startswith('@swftbot'):
            msg_text = (
                "swftbot usage:\n"
                "@swftbot hello: displays \"Hello World!\"\n"
                "@swftbot insult <name>: Sends an insult to <name>\n"
                "@swftbot xkcd <1234|random|latest|help>: Adds an XKCD to the chat"
                "@swftbot help: displays this help text")
            self.send(Message(text=msg_text),
                      thread_id=thread_id,
                      thread_type=thread_type)
Exemplo n.º 24
0
printer using the python-escpos module"""
import escpos
import escpos.printer
import xkcd
import textwrap
import sys
import getopt
from random import randint
from PIL import Image

usageText = 'Usage: xkcdprint.py [-n <number of comics to print>] [-r] [-i <comicid>]\nDefaults to printing latest comic.'
nComicsToPrint = 1
nComicsPrinted = 0
comicRandom = False
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"):
Exemplo n.º 25
0
  def generate_image(self):
    """Generate image for this module"""   

    # Create tmp path
    tmpPath = '/tmp/inkycal_xkcd/'

    try:
        os.mkdir(tmpPath)
    except OSError:
        print ("Creation of tmp directory %s failed" % path)
    else:
        print ("Successfully created tmp directory %s " % path)

    # Define new image size with respect to padding
    im_width = int(self.width - (2 * self.padding_left))
    im_height = int(self.height - (2 * self.padding_top))
    im_size = im_width, im_height
    logger.info('image size: {} x {} px'.format(im_width, im_height))

    # Create an image for black pixels and one for coloured pixels (required)
    im_black = Image.new('RGB', size = im_size, color = 'white')
    im_colour = Image.new('RGB', size = im_size, color = 'white')

    # Check if internet is available
    if internet_available() == True:
      logger.info('Connection test passed')
    else:
      raise Exception('Network could not be reached :/')

    # Set some parameters for formatting feeds
    line_spacing = 1
    line_height = self.font.getsize('hg')[1] + line_spacing
    line_width = im_width
    max_lines = (im_height // (self.font.getsize('hg')[1] + line_spacing))

    logger.debug(f"max_lines: {max_lines}")

    # Calculate padding from top so the lines look centralised
    spacing_top = int( im_height % line_height / 2 )

    # Calculate line_positions
    line_positions = [(0, spacing_top + _ * line_height ) for _ in range(max_lines)]

    logger.debug(f'line positions: {line_positions}')
      
    logger.info(f'getting xkcd comic...')
    
    if self.mode == 'random':
        if self.scale_filter == 'no':
            xkcdComic = xkcd.getRandomComic()
            xkcdComic.download(output=tmpPath, outputFile='xkcdComic.png')
        else:
            perc = (2.1,0.4)
            url = "test variable, not a real comic"
            while max(perc) > 1.75:
                print("looking for another comic, old comic was: ",perc, url)
                xkcdComic = xkcd.getRandomComic()
                xkcdComic.download(output=tmpPath, outputFile='xkcdComic.png')
                actual_size = Image.open(tmpPath+'/xkcdComic.png').size
                perc = (actual_size[0]/im_width,actual_size[1]/im_height)
                url = xkcdComic.getImageLink()
            print("found one! perc: ",perc, url)
    else:
        xkcdComic = xkcd.getLatestComic()
        xkcdComic.download(output=tmpPath, outputFile='xkcdComic.png')

    logger.info(f'got xkcd comic...')
    title_lines = []
    title_lines.append(xkcdComic.getTitle())
    
    altOffset = int(line_height*1)
    
    if self.alt == "yes":
        alt_text = xkcdComic.getAltText() # get the alt text, too (I break it up into multiple lines later on)
   
        # break up the alt text into lines
        alt_lines = []
        current_line = ""
        for _ in alt_text.split(" "):
            # this breaks up the alt_text into words and creates each line by adding
            # one word at a time until the line is longer than the width of the module
            # then it appends the line to the alt_lines array and starts testing a new line
            if self.font.getsize(current_line + _ + " ")[0] < im_width:
                current_line = current_line + _ + " "
            else:
                alt_lines.append(current_line)
                current_line = _ + " "
        alt_lines.append(current_line) # this adds the last line to the array (or the only line, if the alt text is really short)
        altHeight = int(line_height*len(alt_lines)) + altOffset
    else:
        altHeight = 0 # this is added so that I don't need to add more "if alt is yes" conditionals when centering below. Now the centering code will work regardless of whether they want alttext or not
      
    comicSpaceBlack = Image.new('RGBA', (im_width, im_height), (255,255,255,255))  
    comicSpaceColour = Image.new('RGBA', (im_width, im_height), (255,255,255,255)) 
      
    im = Images()
    im.load(tmpPath+'xkcdComic.png')
    im.remove_alpha()
    
    imageAspectRatio = im_width / im_height
    comicAspectRatio = im.image.width / im.image.height
        
    if comicAspectRatio > imageAspectRatio:
        imageScale = im_width / im.image.width
    else:
        imageScale = im_height / im.image.height        
        
    comicHeight = int(im.image.height * imageScale)      
    
    headerHeight = int(line_height*3/2)    
    
    if comicHeight + (headerHeight+altHeight) > im_height:
        comicHeight -= (headerHeight+altHeight)
    
    im.resize( width=int(im.image.width * imageScale), height= comicHeight)        
    
    im_comic_black, im_comic_colour = im.to_palette(self.palette)  

    headerCenterPosY = int((im_height/2)-((im.image.height+headerHeight+altHeight)/2))
    comicCenterPosY = int((im_height/2)-((im.image.height+headerHeight+altHeight)/2)+headerHeight)
    altCenterPosY = int((im_height/2)-((im.image.height+headerHeight+altHeight)/2)+headerHeight+im.image.height)
    
    centerPosX = int((im_width/2)-(im.image.width/2))
    
    comicSpaceBlack.paste(im_comic_black, (centerPosX, comicCenterPosY))
    im_black.paste(comicSpaceBlack)
    
    comicSpaceColour.paste(im_comic_colour, (centerPosX, comicCenterPosY))
    im_colour.paste(comicSpaceColour)
    
    im.clear()
    logger.info(f'added comic image')    
   
    # Write the title on the black image 
    write(im_black, (0, headerCenterPosY), (line_width, line_height),
              title_lines[0], font = self.font, alignment= 'center')    
    
    if self.alt == "yes":
        # write alt_text
        for _ in range(len(alt_lines)):
          write(im_black, (0, altCenterPosY+_*line_height + altOffset), (line_width, line_height),
                    alt_lines[_], font = self.font, alignment='left')

    # Save image of black and colour channel in image-folder
    return im_black, im_colour  
Exemplo n.º 26
0
def xkcd_latest(replies: Replies) -> None:
    """Get the latest comic released in xkcd.com."""
    replies.add(**_get_reply(xkcd.getLatestComic()))