askcompu

Untitled

Apr 2nd, 2016
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.99 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """
  3. episode.py - Phenny MLP Episodes Module
  4.  
  5. """
  6.  
  7. import re
  8. import web
  9. import json
  10. import string
  11. import ast
  12. import calendar
  13. import time
  14.  
  15. class Grab(web.urllib.request.URLopener):
  16.     def __init__(self, *args):
  17.         self.version = 'Mozilla/5.0 (CompuBot)'
  18.         web.urllib.request.URLopener.__init__(self, *args)
  19.         self.addheader('Referer', 'https://github.com/sbp/phenny')
  20.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  21.         return web.urllib.addinfourl(fp, [headers, errcode], "http:" + url)
  22.  
  23. def episode_find(query, phenny):
  24.     query = query.replace('!', '')
  25.     if re.compile('(?i)(season \d+(,)? episode \d+)').match(query):
  26.         regex = re.compile('(?i)season (\d+)(?:,)? episode (\d+)')
  27.         numbers = regex.findall(query)
  28.         results = [int(i) for i in numbers[0]]
  29.         snum = str(int(results[0]))
  30.         enum = str(int(results[1]))
  31.         uri = 'https://ponyapi.apps.xeserv.us/season/' + snum + '/episode/' + enum
  32.         nl = query
  33.         issearch = False
  34.         isnextlast = False
  35.     elif re.compile('(?i)((s|se)\d+(, | |,)?(e|ep)\d+)').match(query):
  36.         regex = re.compile('(?i)(?:s|se)(\d+)(?:, | |,)?(?:e|ep)(\d+)')
  37.         numbers = regex.findall(query)
  38.         results = [int(i) for i in numbers[0]]
  39.         snum = str(int(results[0]))
  40.         enum = str(int(results[1]))
  41.         uri = 'https://ponyapi.apps.xeserv.us/season/' + snum + '/episode/' + enum
  42.         nl = query
  43.         issearch = False
  44.         isnextlast = False
  45.     elif re.compile('(?i)next').match(query):
  46.         uri = 'https://ponyapi.apps.xeserv.us/newest'
  47.         nl = 'next'
  48.         issearch = False
  49.         isnextlast = True
  50.     elif re.compile('(?i)last').match(query):
  51.         uri = 'https://ponyapi.apps.xeserv.us/last_aired'
  52.         nl = 'last'
  53.         issearch = False
  54.         isnextlast = True
  55.     elif re.compile('(?i)(movie)( )?\d+').match(query):
  56.         regex = re.compile('(?i)movie(?: )?(\d+)')
  57.         numbers = regex.findall(query)
  58.         results = [int(i) for i in numbers[0]]
  59.         mnum = str(int(results[0]))
  60.         uri = 'https://ponyapi.apps.xeserv.us/season/99/episode/' + mnum
  61.         nl = query
  62.         issearch = False
  63.         isnextlast = False
  64.     else:
  65.         webquery = web.quote(query)
  66.         uri = 'https://ponyapi.apps.xeserv.us/search?q=' + webquery
  67.         nl = query
  68.         issearch = True
  69.         isnextlast = False
  70.                    
  71.     try:
  72.         rec_bytes = web.get(uri)
  73.     except:
  74.         if isnextlast is True:
  75.             return 'nope$' + nl
  76.         else:
  77.             return
  78.     try:
  79.         jsonstring = json.loads(rec_bytes)
  80.     except:
  81.         return
  82.     try:
  83.         jsonstring['episodes'][0]
  84.     except:
  85.         try:
  86.             jsonstring['episodes']['name']
  87.         except:
  88.             try:
  89.                 jsonstring['episode']['name']
  90.             except:
  91.                 return 'nope$' + nl
  92.     try:
  93.         epname = jsonstring['episodes'][0]['name']
  94.         eps = str(jsonstring['episodes'][0]['season'])
  95.         epe = str(jsonstring['episodes'][0]['episode'])
  96.         etimeun = jsonstring['episodes'][0]['air_date']
  97.         movie = jsonstring['episodes'][0]['is_movie']
  98.         epnumbered = True
  99.     except:
  100.         try:
  101.             epname = jsonstring['episodes']['name']
  102.             eps = str(jsonstring['episodes']['season'])
  103.             epe = str(jsonstring['episodes']['episode'])
  104.             etimeun = jsonstring['episodes']['air_date']
  105.             movie = jsonstring['episodes']['is_movie']
  106.             epnumbered = False
  107.         except:
  108.             epname = jsonstring['episode']['name']
  109.             eps = str(jsonstring['episode']['season'])
  110.             epe = str(jsonstring['episode']['episode'])
  111.             etimeun = jsonstring['episode']['air_date']
  112.             movie = jsonstring['episode']['is_movie']
  113.             epnumbered = False
  114.     etimegmt = time.gmtime(etimeun)
  115.     etimeus = time.strftime('%A %B %d, %Y at %I:%M:%S %p',etimegmt)
  116.     if epnumbered is True and issearch is True:
  117.         try:
  118.             epname2 = jsonstring['episodes'][1]['name']
  119.             eps2 = str(jsonstring['episodes'][1]['season'])
  120.             epe2 = str(jsonstring['episodes'][1]['episode'])
  121.             etimeun2 = jsonstring['episodes'][1]['air_date']
  122.             movie2 = jsonstring['episodes'][1]['is_movie']
  123.             epsecond = True
  124.             etimegmt2 = time.gmtime(etimeun2)
  125.             etimeus2 = time.strftime('%A %B %d, %Y at %I:%M:%S %p',etimegmt2)
  126.         except:
  127.             epsecond = False
  128.     else:
  129.         epsecond = False
  130.     if epsecond is True:
  131.         if movie is True:
  132.             if etimeun < time.time():
  133.                 euntil = timecompare(etimeun, False)
  134.                 return epname + ' aired on ' + etimeus + ' GMT (' + etimeun + ' ago)'
  135.             elif etimeun > time.time():
  136.                 euntil = timecompare(etimeun, True)
  137.                 return epname + ' will air on ' + etimeus + ' GMT (' + etimeun + ' from now)'
  138.         else:
  139.             if etimeun < time.time():
  140.                 euntil = timecompare(etimeun, False)
  141.                 response = 'Season ' + eps + ', Episode ' + epe + ', ' + epname + ' aired on ' + etimeus + ' GMT (' + euntil + ' ago) and Season ' + eps2 + ', '
  142.                 if etimeun2 > time.time():
  143.                     euntil2 = timecompare(etimeun2, True)
  144.                     response = response + 'Episode ' + epe2 + ', ' + epname2 + ' will air on ' + etimeus2 + ' GMT (' + euntil2 + ' from now)'
  145.                 elif etimeun2 < time.time():
  146.                     euntil2 = timecompare(etimeun2, False)
  147.                     response = response + 'Episode ' + epe2 + ', ' + epname2 + ' aired on ' + etimeus2 + ' GMT (' + euntil2 + ' ago)'
  148.                 return response
  149.             elif etimeun > time.time():
  150.                 euntil = timecompare(etimeun, True)
  151.                 response =  'Season ' + eps + ', Episode ' + epe + ', ' + epname + ' will air on ' + etimeus + ' GMT (' + etimeun + ' from now) and Season ' + eps2 + ', '
  152.                 if etimeun2 > time.time():
  153.                     euntil2 = timecompare(etimeun2, True)
  154.                     response = response + 'Episode ' + epe2 + ', ' + epname2 + ' will air on ' + etimeus2 + ' GMT (' + euntil2 + ' from now)'
  155.                 elif etimun2 < time.time():
  156.                     euntil2 = timecompare(etimeun2, False)
  157.                     response = response + 'Episode ' + epe2 + ', ' + epname2 + ' aired on ' + etimeus2 + ' GMT (' + euntil2 + ' ago)'
  158.                 return response
  159.                    
  160.                    
  161.     else:
  162.         if movie is True:
  163.             if etimeun < time.time():
  164.                 euntil = timecompare(etimeun, False)
  165.                 return epname + ' aired on ' + etimeus + ' GMT (' + etimeun + ' ago)'
  166.             elif etimeun > time.time():
  167.                 euntil = timecompare(etimeun, True)
  168.                 return epname + ' will air on ' + etimeus + ' GMT (' + etimeun + ' from now)'
  169.         else:
  170.             if etimeun < time.time():
  171.                 euntil = timecompare(etimeun, False)
  172.                 return 'Season ' + eps + ', Episode ' + epe + ', ' + epname + ' aired on ' + etimeus + ' GMT (' + euntil + ' ago)'
  173.             elif etimeun > time.time():
  174.                 euntil = timecompare(etimeun, True)
  175.                 return 'Season ' + eps + ', Episode ' + epe + ', ' + epname + ' will air on ' + etimeus + ' GMT (' + euntil + ' from now)'
  176. def episode(phenny, input):
  177.     """Finds MLP Episodes. Commands can be .ep season 2 episode 1 or .ep s2e1 or .ep return of harmony or .ep next or .ep last or .ep movie 3"""
  178.     query = input.group(2)
  179.     if not query: return phenny.reply('.ep what?')
  180.  
  181.     uri = episode_find(query, phenny)
  182.     if uri:
  183.         if uri.startswith('nope'):
  184.             uris = uri.split('$')
  185.             return phenny.say("Sorry " + input.nick + ", I couldn't find the " + uris[1] + " episode.")
  186.         else:
  187.             phenny.say("Here's what I got, " + input.nick + ": " + uri)
  188.             if not hasattr(phenny.bot, 'last_seen_uri'):
  189.                 phenny.bot.last_seen_uri = {}
  190.             phenny.bot.last_seen_uri[input.sender] = uri
  191.     else: phenny.say("Sorry " + input.nick + ", I couldn't find any episodes for '%s'." % query)
  192. episode.commands = ['ep','episode']
  193.  
  194. def duration(seconds, _maxweeks=99999999999):
  195.     return ', '.join('%d %s' % (num, unit)
  196.              for num, unit in zip([(seconds // d) % m
  197.                        for d, m in ((604800, _maxweeks),
  198.                                                         (86400, 7), (3600, 24),
  199.                                                         (60, 60), (1, 60))],
  200.                       ['weeks', 'days', 'hours', 'minutes', 'seconds'])
  201.              if num)
  202.  
  203. def timecompare(etimeun, eairfuture):
  204.     if eairfuture == True:
  205.         compareun = etimeun - time.time()
  206.     if eairfuture == False:
  207.         compareun = time.time() - etimeun
  208.     return duration(compareun)
  209.    
  210.    
  211.    
  212.  
  213. if __name__ == '__main__':
  214.     print(__doc__.strip())
Advertisement
Add Comment
Please, Sign In to add comment