Esempio n. 1
0
def slack_message():

    token = 'YOUR_LEGACY_TOKEN'
    sc = SlackClient(token)

    #acquire past messages on desired channel
    history = sc.api_call(
        "channels.history", channel="CA2R3V1L5"
    )  #channel = "YOUR_CHANNEL_ID" (code to find, available below while loop)

    command = history['messages'][0]['text']
    if 'moar' in command:  #if user wants more comics

        #account for constantly increasing size of XKCD comics, and accordingly find random comic
        d1 = datetime.date(2012, 11, 6)
        now = datetime.datetime.now()
        d0 = datetime.date(now.year, now.month, now.day)
        upper = (d0 - d1).days

        rno = random.randint(1, upper)

        img_chosen = xkcd.Comic(rno)
        path = img_chosen.getImageLink()

        #push message to channel
        sc.api_call('chat.postMessage',
                    channel='general',
                    text=path,
                    username='******',
                    icon_emoji=':robot_face:')
        return 1  #success!
    return 0
Esempio n. 2
0
def show_comic(_, msg):
    """Show XKCD comic details."""
    for number in REGEX.findall(msg.text):
        try:
            comic = xkcd.Comic(int(number))
            reply = f"XKCD#{int(number)} | '{comic.getTitle()}' | {comic.getImageLink()} | {comic.getAltText()}"
            msg.respond(reply)
        except urllib.error.HTTPError:
            pass
Esempio n. 3
0
 async def explain(self, ctx, *args):
     """explain random xkcd comic"""
     if len(args) and args[0].isdigit():
         comic = xkcd.Comic(args[0])
         await ctx.send(
             f"Explanations for xkcd #{args[0]} **{comic.getTitle()}**: {comic.getExplanation()}"
         )
         return
     else:
         async for m in ctx.channel.history(limit=50):
             if m.author.bot and m.content[:6] == "xkcd #":
                 id = m.content.split("#")[-1].split(" ")[0]
                 if id.isdigit():
                     comic = xkcd.Comic(id)
                     await ctx.send(
                         f"Explanations for xkcd #{id} **{comic.getTitle()}**: {comic.getExplanation()}"
                     )
                     return
     await ctx.send("No xkcd found in this channel recent history")
Esempio n. 4
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()}*")
Esempio n. 5
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)
Esempio n. 6
0
 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
Esempio n. 7
0
    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)
            df.loc[n] = [comic.title, comic.altText]
            new = True
        except:
            print 'Failed to import #%d' % n

# Save new data to CSV
if new:
    df.to_csv('xkcd.csv', encoding='utf-8')
     
def score(row, query=()):
    """scoring function to be applied to DF row"""
    query = [q.lower() for q in query]
    try:
        title_matches = [w for w in row.title.lower().split() if w in query]
    except:
Esempio n. 8
0
def get_comic():
    comic_num = int(xkcd.getRandomComic().link.replace("https://www.xkcd.com/",
                                                       "").strip())
    comic_img_url = xkcd.Comic(comic_num).getImageLink()
    return comic_img_url
Esempio n. 9
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)
Esempio n. 10
0
#!/usr/bin/env python
# coding: utf-8

# note: in Python, it is recommended to specify the encoding of the file you use. On Python 3 it is automatic.

# this indicates we will use the module xkcd, it is not included in Python, you need to download this library
import xkcd

if __name__ == "__main__":
    print("Opening xkcd joke on web browser...")
    xkcd.Comic(353).show()

    # FYI, you can achieve the same result with the built-in easter egg in python by calling
    # import antigravity (remove comment...)