Example #1
0
def send_xkcd(room):
    """Downloads random xkcd comic, uploads it to the server and sends the link into room.

    :param room: Matrix room where the XKCD was requested
    """
    print('Sending XKCD')
    xkcd.getRandomComic().download(output='.', outputFile='xkcd.jpg')
    with open("xkcd.jpg", "rb") as f:
        data = f.read()
    url = client.upload(data, 'image/jpeg')
    room.send_image(url, 'xkcd.jpg')
Example #2
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."
Example #3
0
 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}')
Example #4
0
 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}')
Example #5
0
 async def comic(self,ctx, user : discord.Member =None):
     async with ctx.typing():
         if not user:
             user=ctx.author
         await ctx.send("Here's your comic "+user.mention)
         url = xkcd.Comic.getImageLink(xkcd.getRandomComic())
         await ctx.send(url)
Example #6
0
def reply(bot, message, intent, entities):
    if intent == 'xkcd':
        random_comic = xkcd.getRandomComic()
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        markup.add(types.KeyboardButton('Check out another xkcd comic!'))
        bot.send_photo(message.chat.id, random_comic.getImageLink(), caption='*' +
                       random_comic.getTitle() + '*\n' + random_comic.getAltText() +
                       '\n' + random_comic.getExplanation(), parse_mode='Markdown',
                       reply_to_message_id=message.message_id, reply_markup=markup)
    elif intent == 'hello':
        greetings = [
            'Hello there!',
            'Hey!',
            'Hi!',
            'Oh hello!'
        ]
        greeting = random.choice(greetings)
        bot.reply_to(message, greeting)
    else:
        title = "Unhandled+query:+" + message.text
        body = "What's+the+expected+result?+PLACEHOLDER_TEXT"
        markup = types.InlineKeyboardMarkup()
        markup.add(types.InlineKeyboardButton(text='Report', url="https://github.com/the-vision/jarvis-telegram/issues/new?title=" + title + "&body=" + body))
        bot.send_message(message.chat.id, text="Sorry, this feature isn't available yet!",
                         parse_mode='Markdown', reply_to_message_id=message.message_id, reply_markup=markup)
Example #7
0
def cmd_xkcd(replies):
    """Send ramdom XKCD comic."""
    comic = xkcd.getRandomComic()
    image = io.BytesIO(urlopen(comic.imageLink).read())
    text = "#{} - {}\n\n{}".format(comic.number, comic.title, comic.altText)
    # we could omit bytefile and only send filename with a path to a file
    replies.add(text=text, filename=comic.imageName, bytefile=image)
Example #8
0
    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)
Example #9
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
Example #10
0
def hello():
    random = xkcd.getRandomComic()
    response = {
        "imageLink": random.getImageLink(),
        "imageTitle": random.getTitle(),
        "altText": random.getAltText()
    }
    return json.dumps(response)
Example #11
0
 async def comic(self, ctx):
     """xkcd Comics"""
     async with ctx.typing():
         c = xkcd.getRandomComic()
     embed = discord.Embed(title=c.getTitle())
     embed.set_image(url=c.getImageLink())
     embed.set_footer(text=c.getAltText())
     await ctx.send(embed=embed)
Example #12
0
def randomxkcd(bot, update):
    update.message.reply_text("One random XKCD comic, coming right up!", quote=False)
    randomcomic = xkcd.getRandomComic()
    getlink = randomcomic.getImageLink()
    comlink = str(getlink)
    update.message.reply_photo(comlink, caption="%s.\nReply with /xkcd_explain for an explanation."% (randomcomic.getTitle()),quote=False)
    global xkcdexplanation
    xkcdexplanation = str(randomcomic.getExplanation())
    return
Example #13
0
    def get_comic(self, number):
        if number == None:
            comic = xkcd.getRandomComic()
        else:
            comic = xkcd.getComic(number)

        embed = Embed(description=comic.getAltText())
        embed.set_author(name=comic.getTitle())
        embed.set_image(url=comic.getImageLink())
        return embed
Example #14
0
def get_xkcd():
    """
    Get xkcd images from the website. The images are downloaded
    to the images folder. The images folder will have maximum of
    2 images. Once 2 images are available in the images folder, the
    older image will be unlinked and the new one would be downloaded
    to the images folder.

    Assumption made: the file downloaded per url is unique from xkcd.
    
    If that's not the case, I would implement the solution with md5 or
    sha256 on the files. Since its an xkcd image the file size I see is
    very minimal and in such case md5 or sha256 would not hurt.
    """

    random_comic = xkcd.getRandomComic()

    filaname = "xkcd-" + str(
        random_comic.number) + "-" + random_comic.imageName

    if not os.path.exists("images"):
        os.mkdir("images")

    local_images = ["images/" + file for file in os.listdir("images")]
    local_images.sort(key=os.path.getmtime)

    if filaname in local_images:
        for _ in range(5):
            random_comic = xkcd.getRandomComic()
            new_image_filename = ("xkcd-" + str(random_comic.number) + "-" +
                                  random_comic.imageName)
            if new_image_filename not in local_images:
                break

            time.sleep(5)

    if len(os.listdir("images")) < 2:
        random_comic.download("images", "")
    else:
        os.unlink(local_images.pop(0))
        random_comic.download("images", "")

    print("Image downloaded")
Example #15
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!")
Example #16
0
def getRandomXkcdImage():
    try:
        randomComic = xkcd.getRandomComic()
        print(randomComic)
        return [
            randomComic.getTitle(),
            randomComic.getAltText(),
            randomComic.getImageLink()
        ]
    except Exception as e:
        return None
Example #17
0
def initial_view():
    """
    Loads the initial view of the application.

    Returns
    -------
    A rendered_template with the comic data to fill HTML
        
    """
    comic = xkcd.getRandomComic()
    comic_data = comic_utils.get_comic_data(comic)
    return render_template('view.html', data=comic_data)
Example #18
0
def xkcd_get(payload: str, message: Message, replies: Replies) -> None:
    """Get the comic with the given number or a ramdom comic if no number is provided."""
    if not payload:
        comic = xkcd.getRandomComic()
    elif payload.isdigit():
        comic = xkcd.getComic(int(payload))
    else:
        comic = None
    if comic is None or comic.number == -1:
        replies.add(text="❌ Invalid comic number", quote=message)
    else:
        replies.add(**_get_reply(comic))
Example #19
0
 async def xkcd(self, ctx, *args):
     """gives random xkcd comic"""
     if len(args) and args[0].isdigit():
         comic = xkcd.Comic(args[0])
         id = args[0]
     else:
         comic = xkcd.getRandomComic()
         id = comic.getExplanation().split("/")[-1]
     await ctx.send(
         f"xkcd #{id} **{comic.getTitle()}** {comic.getImageLink()}")
     await asyncio.sleep(15)
     await ctx.send(f"*{comic.getAltText()}*")
Example #20
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]))
Example #21
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!")
Example #22
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!")
Example #23
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!")
Example #24
0
    async def xkcd(self, ctx, *args):
        """gives random xkcd comic"""
        if len(args) and args[0].isdigit():
            comic = xkcd.Comic(args[0])
            id = args[0]
        else:
            comic = xkcd.getRandomComic()
            id = comic.getExplanation().split("/")[-1]

        eb = Embed(description=f'[{comic.getTitle()} #{id}]({comic.getExplanation()})', color=my_blue)
        eb.set_image(url=comic.getImageLink())
        eb.set_footer(text=comic.getAltText())
        await ctx.send(embed=eb)
Example #25
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)))
Example #26
0
def getRandomXkcd():

    randomComic = {}

    randomComicObj = xkcd.getRandomComic()

    randomComic["title"] = randomComicObj.getAsciiTitle().decode('ascii')
    randomComic["imgUrl"] = randomComicObj.getAsciiImageLink().decode('ascii')

    imageTitle = "<a href=\"https://xkcd.com/\">XKCD : " + randomComic[
        "title"] + "</a>"

    imageObj = Image(imageTitle, randomComic["imgUrl"])

    return imageObj
def reply(bot, message, intent, entities):
    if intent == 'xkcd':
        random_comic = xkcd.getRandomComic()
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        markup.add(types.KeyboardButton('Check out another xkcd comic!'))
        bot.send_photo(message.chat.id,
                       random_comic.getImageLink(),
                       caption='*' + random_comic.getTitle() + '*\n' +
                       random_comic.getAltText() + '\n' +
                       random_comic.getExplanation(),
                       parse_mode='Markdown',
                       reply_to_message_id=message.message_id,
                       reply_markup=markup)
    else:
        bot.reply_to(message, message.text)
Example #28
0
 async def getRandomComic(self, context):
     """
     Gets a random xkcd comic
     """
     comic = xkcd.getRandomComic()
     comic_title = comic["title"]
     comic_text = comic["alt"]
     comic_picture = comic["img"]
     await context.send(
         f"{context.author.mention}, here is a random xkcd comic! (#{comic['num']})"
     )
     comic_message = discord.Embed(title=comic_title,
                                   description=comic_text)
     comic_message.add_field(name="Image url", value=comic_picture)
     comic_message.set_image(url=comic_picture)
     await context.send(embed=comic_message)
Example #29
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))
Example #30
0
    async def execute_command(self, client, msg, content):
        image_url = ""
        title = ""
        alt_text = ""
        if len(content) == 0:
            comic = xkcd.getRandomComic()
            image_url = comic.getImageLink()
            title = comic.getTitle()
            alt_text = comic.getAltText()
        elif content.isnumeric():
            try:
                comic = xkcd.getComic(int(content), silent=False)
                image_url = comic.getImageLink()
                title = comic.getTitle()
                alt_text = comic.getAltText()
            except:
                await utils.delay_send(
                    msg.channel,
                    client.messages["no_xkcd_found"].format(content))
                return
        else:
            async with utils.get_aiohttp().post(
                    "https://relevant-xkcd-backend.herokuapp.com/search",
                    data={"search": content},
            ) as request:
                text = await request.text()
            response = json.loads(text)

            if not response["success"] or len(response["results"]) == 0:
                await utils.delay_send(
                    msg.channel,
                    client.messages["no_xkcd_found"].format(content))
                return

            image_url = response["results"][0]["image"]
            title = response["results"][0]["title"]
            alt_text = response["results"][0]["titletext"]

        msg_to_send = "**" + title + ":** " + alt_text
        tmp_file = BytesIO()
        async with utils.get_aiohttp().get(image_url) as r:
            tmp_file.write(await r.read())
        tmp_file.seek(0)
        await msg.channel.send(msg_to_send,
                               file=discord.File(tmp_file, "xkcd.png"))
def process_query(message):
    if message.text == 'xkcd':
        random_comic = xkcd.getRandomComic()
        markup = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)
        markup.add(
            telebot.types.KeyboardButton('Check out another xkcd comic!'))
        bot.send_photo(message.chat.id,
                       random_comic.getImageLink(),
                       caption='*' + random_comic.getTitle() + '*\n' +
                       random_comic.getAltText() + '\n' +
                       random_comic.getExplanation(),
                       parse_mode='Markdown',
                       reply_to_message_id=message.message_id,
                       reply_markup=markup)
    elif message.text == 'Hi':
        bot.reply_to(message, 'Hi, What\'s your name?')
    else:
        bot.reply_to(message, message.text)
Example #32
0
    async def xkcd(self, ctx, number=None):
        """Sends the link of a random xkcd comic to the chat.
        if a number is specified, send the comic referring to that number."""

        if number:
            comic = xkcd.getComic(number)
        else:
            comic = xkcd.getRandomComic()

        comicurl = comic.getImageLink()

        embed = discord.Embed(description=f'[Image Link]({comicurl})')
        embed.set_image(url=comicurl)
        embed.colour = 0x42c2f4

        try:
            await ctx.channel.send(embed=embed)
        except:
            pass
Example #33
0
    def send_repeat(self, chat_id, text):

        # If '好安静' then send a random xkcd comic
        if text == u'好安静':
            comic = xkcd.getRandomComic()
            log.info('Triggered repeat, sending comic(id=%s) to %s'
                     % (comic.number, chat_id))
            text = '{}: {}\n{}'.format(comic.number, comic.getTitle(), comic.getImageLink())
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [
                    InlineKeyboardButton(text='xkcd', url=comic.link),
                    InlineKeyboardButton(text='explain', url=comic.getExplanation()),
                ]
            ])
            self.bot.sendMessage(chat_id=chat_id, text=text, reply_markup=keyboard)

        else:

            log.info('Triggered repeat, sending msg to %s' % chat_id)
            self.bot.sendMessage(chat_id=chat_id, text=text)
Example #34
0
def xkcd():
	import xkcd
	comic = xkcd.getRandomComic().link
	data = 'http://'+comic[-13:]
	return data
Example #35
0
File: milu.py Project: zunc/milubot
def randXkcd():
	comic = xkcd.getRandomComic()
	url = comic.getImageLink()
	return url
def get_comic_text(request):
    comic = xkcd.getRandomComic()
    text = comic.getAltText()
    return Response(text)
Example #37
0
 def xkcd_random(self, msg, matches):
     comic = xkcd.getRandomComic()
     return self.return_comic(msg, comic)