Esempio n. 1
0
def add_mal_entry(list_item, on_mal_list):
    if on_mal_list == 'not_on_mal_list':
        logger.warning(
            '[PLEX -> MAL] No MAL entry found for matching season of {}, adding to MAL with status Watching ]'
            .format(list_item.title))

        anime_new = spice.get_blank(spice.get_medium('anime'))
        anime_new.episodes = 0
        spice.add(anime_new, int(list_item.id), spice.get_medium('anime'),
                  mal_credentials)
Esempio n. 2
0
 async def manga(self, ctx, *args):
     """Searches manga to MAL
     
     Usage: f!manga <query>"""
     args = ' '.join(args)
     args = str(args)
     creds = spice_api.init_auth(MALUsername, MALPassword)
     try:
         manga = spice_api.search(args, spice_api.get_medium("manga"),
                                  creds)[0]
     except IndexError:
         await ctx.send("Cannot find that manga from MAL!")
         return
     embed = discord.Embed(
         title=manga.title,
         url="https://myanimelist.net/anime/{}".format(manga.id),
         description="{} | {} volume(s) and {} chapter(s) | Score: {}".
         format(manga.manga_type, manga.volumes, manga.chapters,
                manga.score),
         color=0x2c80d3)
     embed.set_thumbnail(url=manga.image_url)
     if len(manga.synopsis) > 1024:
         embed.add_field(name="Synopsis",
                         value=html.unescape(manga.synopsis[:1000]).replace(
                             "<br />", "") + "...",
                         inline=False)
     else:
         embed.add_field(name="Synopsis",
                         value=html.unescape(manga.synopsis[:1000]).replace(
                             "<br />", ""),
                         inline=False)
     embed.set_footer(text=manga.status)
     await ctx.send(embed=embed)
Esempio n. 3
0
    async def anime2(self, ctx, *args):
        MALaccount = spice_api.init_auth("project99discord","uixnDMv7LqUv")
        arg_str = ' '.join(args)
        anime = spice_api.search(arg_str,spice_api.get_medium("anime"), MALaccount)
        first_result = anime[0]
        embed = discord.Embed(title="Anime", description=first_result.title, color=0x0083d6)
        embed.set_author(name="MyAnimeList Search", icon_url="https://myanimelist.cdn-dena.com/img/sp/icon/apple-touch-icon-256.png")
        embed.set_thumbnail(url=first_result.image_url)
        embed.add_field(name="Score", value=first_result.score)
        embed.add_field(name="Status", value=first_result.status)
        if first_result.dates[1] == '0000-00-00':
            embed.add_field(name="Type", value=first_result.anime_type)
            embed.add_field(name="Episodes", value='?')
            embed.add_field(name="Start Date", value=first_result.dates[0])
            embed.add_field(name="End Date", value='?')
        else:
            embed.add_field(name="Type", value=first_result.anime_type)
            embed.add_field(name="Episodes", value=first_result.episodes)
            embed.add_field(name="Start Date", value=first_result.dates[0])
            embed.add_field(name="End Date", value=first_result.dates[1])

        def remove_html_tags(data):
            p = re.compile(r'<.*?>')
            return p.sub('', data)

        syn = remove_html_tags(html.unescape(first_result.synopsis))
        embed.add_field(name="Synopsis", value=syn, inline=False)
        embed.set_footer(text="Powered by MyAnimeList and the Spice API Wrapper")
        await ctx.send(embed=embed)
Esempio n. 4
0
def get_anime_by_status(status=''):
    mal_user = os.environ['MAL_USER']
    global cached_anime_list
    if cached_anime_list == 0:
        cached_anime_list = spice.get_list(
            spice.get_medium('anime'), mal_user,
            spice.init_auth(mal_user, os.environ['MAL_PASS']))

    watching_list = filter_anime_by_status(cached_anime_list.get_mediums(),
                                           status)

    db = get_db()
    json_watching_list = []
    for anime in watching_list:
        print anime.title.encode('utf-8'), anime.image_url
        json_watching_list.append({
            'id': anime.id,
            'title': anime.title.encode('utf-8'),
            'image_url': anime.image_url,
            'reasons': get_reasons(db, anime.id),
            'status': anime.status
        })

    db.close()
    json_dump = json.dumps(json_watching_list)
    print json_dump
    return json_dump
 def getsearch(self, text, medium):
     try:
         try:
             results = spice.search(text, spice.get_medium(medium),
                                    self.creds)
         except AttributeError:
             checktext = "Search failed. Did you set your login credntials?"
             maxnum = 99
             results = ''
             return checktext, maxnum, results
     except TypeError:
         checktext = "Search failed."
         maxnum = 99
         results = ''
         return checktext, maxnum, results
     retries = 0
     maxnum = 0
     checktext = ''
     while retries <= 9:
         try:
             context = retries + 1
             checktext = checktext + str(
                 context) + ") " + results[retries].title + "\n"
             retries = retries + 1
             maxnum = maxnum + 1
         except IndexError:
             retries = 10
     return checktext, maxnum, results
Esempio n. 6
0
 def getMal(self, i, _type):
     try:
         creds = spice.init_auth(self.bot.mal_un, self.bot.mal_pw)
     except Exception as e:
         creds = None
         log.warning('{}: {}'.format(type(e).__name__, e))
         return Exception
     return spice.search_id(int(i), spice.get_medium(_type), creds)
Esempio n. 7
0
def get_mal_list():
    logger.info('[MAL] Retrieving list...')
    user = mal_settings['username']
    mal_list = spice.get_list(spice.get_medium('anime'), user,
                              mal_credentials).get_mediums()
    items = len(mal_list) if mal_list else 0
    logger.info('[MAL] Found {} shows on list'.format(items))
    return mal_list
Esempio n. 8
0
def get_mal_list():
  logger.info('[MAL] Retrieving list...')
  mal_list = spice.get_list(spice.get_medium('anime'), mal_username, mal_credentials).get_mediums()
  item_count = 0
  if(mal_list is not None):
    item_count = len(mal_list)

  logger.info('[MAL] Found %s shows on list' % (str(item_count)))
  return mal_list
Esempio n. 9
0
 async def manga(self, ctx, *, query):
     try:
         creds = spice.init_auth('gauravgupta', 'gj111999@')
         test = spice.search(query, spice.get_medium('manga'), creds)
         list1 = ''
         count = 1
         for i in test:
             list1 += ((str(count) + '. ') + i.title) + '\n'
             count += 1
         if list1 != '':
             await ctx.send(('```\n' + list1) + '\n```')
             def check(p):
                 return p.author.id == ctx.author.id and p.channel == ctx.channel
             m = await self.bot.wait_for('message', check = check)
             m = int(m.content)
             m = m - 1
             try:
                 await ctx.channel.purge(limit=2)
             except Exception:
                 pass
             ids = test[m].id
             title = test[m].title
             episode = test[m].chapters
             score = float(test[m].score)
             typea = test[m].manga_type
             status = test[m].status
             syno1 = test[m].synopsis
             syno2 = syno1.replace('<br />', '')
             syno3 = syno2.replace('[Written by MAL Rewrite]', '')
             syno4 = syno3.replace('[i]', '')
             syno5 = syno4.replace('[/i]', '')
             syno = syno5.replace('&#039;', "'")
             link = test[m].image_url
             if (score >= 0) and (score < 2):
                 emoji = ':disappointed:'
             elif (score >= 2) and (score < 4):
                 emoji = ':grimacing:'
             elif (score >= 4) and (score < 6):
                 emoji = ':neutral_face:'
             elif (score >= 6) and (score < 9):
                 emoji = ':smiley:'
             else:
                 emoji = ':heart_eyes:'
             embed = discord.Embed(title='{}'.format(title), color=random.randint(0, 16777215))
             embed.add_field(name='Synopsis', value=syno)
             embed.add_field(name='Type', value=typea)
             embed.add_field(name='Chapters', value=episode, inline=True)
             embed.add_field(name='Status', value=status)
             embed.add_field(name='Score', value=(str(score) + ' ') + emoji)
             embed.set_thumbnail(url=link)
             await ctx.send(embed=embed)
         else:
             await ctx.send('Given Manga not found')
     except Exception as e:
         await ctx.send('Service unavailable atm')
         print(e)
Esempio n. 10
0
 def __init__(self, username, password):
     self._creds = spice_api.init_auth(username, password)
     self._med = spice_api.get_medium("anime")
     self._overrides = dict(
         get_blank=dict(medium=self._med),
         get_status=dict(),
     )
     self.logger = logging.getLogger("SpiceWrapper")
     self.logger.setLevel(LOGGING_LEVEL)
     self._item_buffer = dict()
Esempio n. 11
0
def update_mal_list_with_seasons(mal_list_seasoned, plex_shows):
    """
    update_mal_list_with_seasons: complete list with all seasons for watched shows and later compare by season.
    these are seasons defined by MAL. 1 season MIGHT mean a continuous run of many AniDB/TVDB seasons, per MAL standards.
    plex_watched_shows only uses the original name.
    """
    logger.info('[MAL] Retrieving updated list for season matching...')
    mal_list_seasoned_updated = [(x[0], x[1], x[2], 'on_mal_list')
                                 for x in mal_list_seasoned]
    for show, (episodes, season) in plex_shows.items():
        matches_in_mal_list_seasoned = [
            x for x in mal_list_seasoned
            if x[2].lower() == show.title.lower() and x[1] == season
        ]
        if bool(matches_in_mal_list_seasoned) or season == 1:
            continue
        mal_shows = spice.search(show.title, spice.get_medium('anime'),
                                 mal_credentials)
        matched_list = []
        for mal_show in mal_shows:
            try:
                if mal_show.anime_type == 'TV':
                    match = (mal_show, mal_show.dates[1]
                             if mal_show.dates[1] != '0000-00-00' else
                             '9999-99-99')
                    matched_list.append(match)
            except BaseException:
                logger.error(
                    'Error during season date lookup for show: {}'.format(
                        mal_show))
        matched_list.sort(key=lambda x: x[1])

        try:
            original_name = [
                x[0].title for x in matched_list if x[1] != '9999-99-99'
            ]

            # can't do miracles if it's all empty
            original_name_treated = original_name[
                0] if original_name else matched_list[0][0].title
        except BaseException:
            logger.error(
                'Error during original name treatment for show: {}'.format(
                    show.title))
            original_name_treated = show.title

        for i, element in enumerate(matched_list):
            mal_list_seasoned_updated.append(
                (element[0], i + 1, original_name_treated, 'not_on_mal_list'))
    logger.info('[MAL] Retrieving updated list for season matching finished')
    return mal_list_seasoned_updated
Esempio n. 12
0
def update_mal_entry(list_item, plex_title, plex_watched_episode_count,
                     force_update):
    mal_watched_episode_count = int(list_item.episodes)
    mal_show_id = int(list_item.id)
    print(mal_watched_episode_count, mal_show_id)
    if mal_show_id > 0:
        if mal_watched_episode_count < plex_watched_episode_count or force_update:
            anime_new = spice.get_blank(spice.get_medium('anime'))
            anime_new.episodes = plex_watched_episode_count
            new_status = 'watching'

            # If full watched set status to completed, needs additional lookup as total episodes
            # are not exposed in list (mal or spice limitation)
            lookup_show = spice.search_id(mal_show_id,
                                          spice.get_medium('anime'),
                                          mal_credentials)
            if lookup_show:
                if lookup_show.episodes:
                    mal_total_episodes = int(lookup_show.episodes)

                    if plex_watched_episode_count >= mal_total_episodes:
                        new_status = 'completed'

                anime_new.status = spice.get_status(new_status)

            logger.warning(
                '[PLEX -> MAL] Watch count for {} on Plex is {} and MAL is {}, updating MAL watch count to {} and status to {}'
                .format(plex_title, plex_watched_episode_count,
                        mal_watched_episode_count, plex_watched_episode_count,
                        new_status))
            spice.update(anime_new, mal_show_id, spice.get_medium('anime'),
                         mal_credentials)
        else:
            logger.warning(
                '[PLEX -> MAL] Watch count for {} on Plex was equal or higher on MAL so skipping update'
                .format(plex_title))
        pass
Esempio n. 13
0
File: test.py Progetto: skxu/spice
def main():
    creds = spice.load_auth_from_file('auth')
    print(creds)
    results = spice.search('Re:Zero Kara Hajimeru Isekai Seikatsu',
                           spice.get_medium('anime'), creds)
    print(results[0].title)
    souma = spice.search_id(1, spice.get_medium('manga'), creds)
    print(souma.raw_data)
    print(souma.title)
    print(souma.chapters)
    print(souma.volumes)
    re_zero_data = spice.get_blank(spice.get_medium('anime'))
    re_zero_data.episodes = 0
    re_zero_data.status = spice.get_status('reading')
    re_zero_data.score = 8
    re_zero_data.tags = ['this the first time a show that made me cringe']

    shokugeki_data = spice.get_blank(spice.get_medium('manga'))
    shokugeki_data.chapters = 13
    shokugeki_data.volumes = 1
    shokugeki_data.status = 1
    shokugeki_data.score = 8
    spice.update(shokugeki_data, 45757, spice.get_medium('manga'), creds)

    anime_list = spice.get_list(spice.get_medium('ANIME'), 'Utagai-', creds)
    print(anime_list.avg_score())
    print(anime_list.median_score())
    print(anime_list.mode_score())
    print(anime_list.extremes())
    print(anime_list.p_stddev())
    print(anime_list.p_var())
    print(anime_list.get_num_status(1))
    print(anime_list.get_total())
    print(anime_list.get_days())
    print(anime_list.exists(11734))
    print(len(anime_list.get_ids()))
    print(len(anime_list.get_titles()))
    print(anime_list.get_status(1))
    print(anime_list.get_score(10))
    print(anime_list.exists_as_status(11734, 1))
    print(anime_list.score_diff())
    anime_list2 = spice.get_list(spice.get_medium('ANIME'), 'Pickleplatter',
                                 creds)
    print("Similarity coefficient: {}".format(
        anime_list.compatibility(anime_list2)))
Esempio n. 14
0
def test_spice():
    creds = spice.init_auth(os.environ['USERNAME'], os.environ['PASSWORD'])
    results = spice.search('Re:Zero Kara Hajimeru Isekai Seikatsu', 
            spice.get_medium('anime'), creds)
    print(results[0].title)
    souma = spice.search_id(1, spice.get_medium('manga'), creds)
    print(souma.raw_data)
    print(souma.title)
    print(souma.chapters)
    print(souma.volumes)
    re_zero_data = spice.get_blank(spice.get_medium('anime'))
    re_zero_data.episodes = 0
    re_zero_data.status = spice.get_status('reading')
    re_zero_data.score = 8
    re_zero_data.tags = ['this the first time a show that made me cringe']

    shokugeki_data = spice.get_blank(spice.get_medium('manga'))
    shokugeki_data.chapters = 13
    shokugeki_data.volumes = 1
    shokugeki_data.status = 1
    shokugeki_data.score = 8
    spice.update(shokugeki_data, 45757, spice.get_medium('manga'), creds)

    anime_list = spice.get_list(spice.get_medium('ANIME'), 'Utagai-', creds)
    print(anime_list.avg_score())
    print(anime_list.median_score())
    print(anime_list.mode_score())
    print(anime_list.extremes())
    print(anime_list.p_stddev())
    print(anime_list.p_var())
    print(anime_list.get_num_status(1))
    print(anime_list.get_total())
    print(anime_list.get_days())
    print(anime_list.exists(11734))
    print(len(anime_list.get_ids()))
    print(len(anime_list.get_titles()))
    print(anime_list.get_status(1))
    print(anime_list.get_score(10))
    print(anime_list.exists_as_status(11734, 1))
    print(anime_list.score_diff())
    anime_list2 = spice.get_list(spice.get_medium('ANIME'), 'Pickleplatter', creds)
    print("Similarity coefficient: {}".format(anime_list.compatibility(anime_list2)))
Esempio n. 15
0
def main():
    creds = spice.load_auth_from_file('auth')
    print(creds)
    results = spice.search('Spice and Wolf', spice.get_medium('anime'))
    print(results[0].title)
    saw_novel = spice.search_id(9115, spice.get_medium('manga'))
    print(saw_novel.raw_data)
    print(saw_novel.title)
    print(saw_novel.chapters)
    print(saw_novel.volumes)

    saw_data = spice.get_blank(spice.get_medium('anime'))
    saw_data.episodes = 10
    saw_data.status = spice.get_status('watching')
    saw_data.score = 9
    saw_data.tags = ['holo is the best']
    spice.update(saw_data, 2966, spice.get_medium('anime'))

    #shokugeki_data = spice.get_blank(spice.get_medium('manga'))
    #shokugeki_data.chapters = 13
    #shokugeki_data.volumes = 1
    #shokugeki_data.status = 1
    #shokugeki_data.score = 8
    #spice.update(shokugeki_data, 45757, spice.get_medium('manga'))

    anime_list = spice.get_list(spice.get_medium('ANIME'))
    print(anime_list.avg_score())
    #print(anime_list.median_score())
    #print(anime_list.mode_score())
    #print(anime_list.extremes())
    #print(anime_list.p_stddev())
    print(anime_list.p_var())
    print(anime_list.get_num_status(spice.get_status_num('reading')))
    #print(anime_list.get_total())
    #print(anime_list.get_days())
    #print(anime_list.exists(11734))
    #print(len(anime_list.get_ids()))
    #print(len(anime_list.get_titles()))
    #print(anime_list.get_status(1))
    #print(anime_list.get_score(10))
    #print(anime_list.exists_as_status(11734, 1))
    #print(anime_list.score_diff())
    anime_list2 = spice.get_list(spice.get_medium('ANIME'), 'Pickleplatter')
    print("Similarity coefficient: {}".format(
        anime_list.compatibility(anime_list2)))
Esempio n. 16
0
def send_watched_to_mal(mal_list, plex_title, plex_watched_episode_count):
    show_in_mal_list = False
    mal_watched_episode_count = 0
    mal_show_id = 0

    # check if show is already on MAL list
    for list_item in mal_list:
        #logger.debug('Comparing %s with %s' % (list_item.title, plex_title))
        mal_id = int(list_item.id)
        mal_title = list_item.title
        mal_title_english = ""

        if (list_item.english is not None):
            mal_title_english = list_item.english
            #logger.debug('Comparing original: %s | english: %s with %s' % (mal_title, mal_title_english, plex_title))
        else:
            #logger.debug('Comparing original: %s with %s' % (mal_title, plex_title))
            pass

        if (mal_title.lower() == plex_title.lower()
                or mal_title_english.lower() == plex_title.lower()):
            #logger.debug('%s [%s] was already in list => status = %s | watch count = %s' % (plex_title, list_item.id, spice.get_status(list_item.status), list_item.episodes))
            mal_watched_episode_count = int(list_item.episodes)
            mal_show_id = int(list_item.id)
            show_in_mal_list = True

            if (mal_watched_episode_count > 0 and mal_show_id > 0):
                if (mal_watched_episode_count < plex_watched_episode_count):
                    anime_new = spice.get_blank(spice.get_medium('anime'))
                    anime_new.episodes = plex_watched_episode_count
                    new_status = 'watching'

                    # if full watched set status to completed, needs additional
                    # lookup as total episodes are not exposed in list (mal or
                    # spice limitation)
                    lookup_show = spice.search_id(mal_id,
                                                  spice.get_medium('anime'),
                                                  mal_credentials)
                    if (lookup_show):
                        if (lookup_show.episodes is not None):
                            mal_total_episodes = int(lookup_show.episodes)

                            if (plex_watched_episode_count >=
                                    mal_total_episodes):
                                new_status = 'completed'

                    anime_new.status = spice.get_status(new_status)

                    logger.warn(
                        '[PLEX -> MAL] Watch count for %s on Plex is %s and MAL is %s, updating MAL watch count to %s and status to %s ]'
                        % (plex_title, plex_watched_episode_count,
                           mal_watched_episode_count,
                           plex_watched_episode_count, new_status))
                    spice.update(anime_new, mal_show_id,
                                 spice.get_medium('anime'), mal_credentials)
                else:
                    logger.warning(
                        '[PLEX -> MAL] Watch count for %s on Plex was equal or higher on MAL so skipping update'
                        % (plex_title))
                    pass

    # if not listed in list lookup on MAL
    if (not show_in_mal_list):
        found_result = False
        update_list = True
        on_mal_list = False
        logger.info(
            '[PLEX -> MAL] %s not in MAL list, searching for show on MAL' %
            (plex_title))

        mal_shows = spice.search(plex_title, spice.get_medium('anime'),
                                 mal_credentials)
        for mal_show in mal_shows:
            mal_title = mal_show.title.lower()
            mal_title_english = ''
            mal_show_id = int(mal_show.id)
            mal_total_episodes = int(mal_show.episodes)

            if (mal_show.english is not None):
                mal_title_english = mal_show.english.lower()
                #logger.debug('Comparing original: %s | english: %s with %s' % (mal_title, mal_title_english, plex_title.lower()))
            else:
                #logger.debug('Comparing original: %s with %s' % (mal_title, plex_title.lower()))
                pass

            if (mal_title == plex_title.lower()
                    or mal_title_english == plex_title.lower()):
                found_result = True

                # double check against MAL list using id to see if matches and
                # update is required
                for list_item in mal_list:
                    mal_list_id = int(list_item.id)
                    mal_list_watched_episode_count = int(list_item.episodes)

                    if (mal_list_id == mal_show_id):
                        on_mal_list = True
                        if (plex_watched_episode_count ==
                                mal_list_watched_episode_count):
                            logger.warning(
                                '[PLEX -> MAL] show was found in current MAL list using id lookup however watch count was identical so skipping update'
                            )
                            update_list = False
                        break

                if (update_list):
                    anime_new = spice.get_blank(spice.get_medium('anime'))
                    anime_new.episodes = plex_watched_episode_count

                    if (plex_watched_episode_count >= mal_total_episodes):
                        logger.warn(
                            '[PLEX -> MAL] Found match on MAL and setting state to completed as watch count equal or higher than total episodes'
                        )
                        anime_new.status = spice.get_status('completed')
                        if (on_mal_list):
                            spice.update(anime_new, mal_show.id,
                                         spice.get_medium('anime'),
                                         mal_credentials)
                        else:
                            spice.add(anime_new, mal_show.id,
                                      spice.get_medium('anime'),
                                      mal_credentials)
                    else:
                        logger.warn(
                            '[PLEX -> MAL] Found match on MAL and setting state to watching with watch count: %s'
                            % (plex_watched_episode_count))
                        anime_new.status = spice.get_status('watching')
                        if (on_mal_list):
                            spice.update(anime_new, mal_show.id,
                                         spice.get_medium('anime'),
                                         mal_credentials)
                        else:
                            spice.add(anime_new, mal_show.id,
                                      spice.get_medium('anime'),
                                      mal_credentials)
                break

        if (not found_result):
            logger.error('[PLEX -> MAL] Failed to find %s on MAL' %
                         (plex_title))
Esempio n. 17
0
def send_watched_to_mal(plex_watched_shows, mal_list, mal_list_seasoned):
    for show, value in plex_watched_shows.items():
        plex_title = show.title
        plex_watched_episode_count, plex_watched_episode_season = value
        show_in_mal_list = False
        force_update = False
        #logger.debug('%s => watch count = %s' % (plex_title, watched_episode_count))

        if plex_watched_episode_count <= 0:
            continue

        # All shows with season > 1 were previously searched and are part of
        # the mal_list_seasoned object
        if plex_watched_episode_season > 1:
            force_update = True
            for anime, season, original_name, on_mal_list in mal_list_seasoned:
                if original_name.lower() == plex_title.lower():
                    try:
                        correct_item = [
                            value[0]
                            for index, value in enumerate(mal_list_seasoned)
                            if value[1] == plex_watched_episode_season
                            and value[2] == original_name
                        ][0]
                    except BaseException:
                        # Search failed to properly match seasons, e.g. Card Captor Sakura Clear Card is s4 on TVDB and s2 here
                        # assume most recent available season
                        # TODO: search by ID of the correct season
                        if force_update:
                            correct_item = spice.search_id(
                                int(mal_list_seasoned[-1][0].id),
                                spice.get_medium('anime'), mal_credentials)
                            on_mal_list = 'not_on_mal_list'
                        else:
                            break
                    # Trying to add before doens't really break anything and
                    # works for new series, since mal_list_seasoned includes
                    # things you haven't watched yet
                    add_mal_entry(correct_item, on_mal_list)
                    update_mal_entry(correct_item, plex_title,
                                     plex_watched_episode_count, force_update)
                    break
            continue

        # check if show is already on MAL list
        for list_item in mal_list:
            #logger.debug('Comparing %s with %s' % (list_item.title, plex_title))
            mal_title = list_item.title
            mal_title_english = ""
            if list_item.english is not None:
                mal_title_english = list_item.english
                #logger.debug('Comparing original: %s | english: %s with %s' % (mal_title, mal_title_english, plex_title))
            else:
                #logger.debug('Comparing original: %s with %s' % (mal_title, plex_title))
                pass

            if mal_title.lower() == plex_title.lower(
            ) or mal_title_english.lower() == plex_title.lower():
                show_status = spice.get_status(list_item.status)
                logger.debug(
                    '{} [{}] was already in list => status = {} | watch count = {}'
                    .format(plex_title, list_item.id, show_status,
                            list_item.episodes))
                show_in_mal_list = True
                update_mal_entry(list_item, plex_title,
                                 plex_watched_episode_count, force_update)

        # If not listed in list lookup on MAL
        if not show_in_mal_list:
            found_result = False
            update_list = True
            on_mal_list = False
            logger.info(
                '[PLEX -> MAL] {} not in MAL list, searching for show on MAL'.
                format(plex_title))

            potential_titles = [
                plex_title.lower(),
                guessit(plex_title)['title'].lower()
            ]
            for title in potential_titles:
                mal_shows = spice.search(title, spice.get_medium('anime'),
                                         mal_credentials)
                if len(mal_shows) >= 1:
                    break

            for mal_show in mal_shows:
                mal_title = mal_show.title.lower()
                mal_title_english = ''
                mal_show_id = int(mal_show.id)
                mal_total_episodes = int(mal_show.episodes)

                if mal_show.english:
                    mal_title_english = mal_show.english.lower()
                    #logger.debug('Comparing original: %s | english: %s with %s' % (mal_title, mal_title_english, plex_title.lower()))
                else:
                    #logger.debug('Comparing original: %s with %s' % (mal_title, plex_title.lower()))
                    pass

                if mal_title in potential_titles or mal_title_english in potential_titles:
                    found_result = True

                    # double check against MAL list using id to see if matches
                    # and update is required
                    for list_item in mal_list:
                        mal_list_id = int(list_item.id)
                        mal_list_watched_episode_count = int(
                            list_item.episodes)

                        if mal_list_id == mal_show_id:
                            on_mal_list = True
                            if plex_watched_episode_count == mal_list_watched_episode_count:
                                logger.warning(
                                    '[PLEX -> MAL] show was found in current MAL list using id lookup however watch count was identical so skipping update'
                                )
                                update_list = False
                            break

                    if update_list:
                        logger.warning(
                            '[PLEX -> MAL] Found match on MAL and setting state to watching with watch count: {}'
                            .format(plex_watched_episode_count))
                        anime_new = spice.get_blank(spice.get_medium('anime'))
                        anime_new.episodes = plex_watched_episode_count

                        if plex_watched_episode_count >= mal_total_episodes:
                            anime_new.status = spice.get_status('completed')
                            if on_mal_list:
                                spice.update(anime_new, mal_show.id,
                                             spice.get_medium('anime'),
                                             mal_credentials)
                            else:
                                spice.add(anime_new, mal_show.id,
                                          spice.get_medium('anime'),
                                          mal_credentials)
                        else:
                            anime_new.status = spice.get_status('watching')
                            if on_mal_list:
                                spice.update(anime_new, mal_show.id,
                                             spice.get_medium('anime'),
                                             mal_credentials)
                            else:
                                spice.add(anime_new, mal_show.id,
                                          spice.get_medium('anime'),
                                          mal_credentials)
                    break

            if not found_result:
                logger.error('[PLEX -> MAL] Failed to find {} on MAL'.format(
                    plex_title))
Esempio n. 18
0
    async def anime(self, ctx, *, msg: str = None):
        """Search the anime database. Ex: >mal anime Steins;Gate"""
        if msg:
            loop = asyncio.get_event_loop()
            config = load_optional_config()
            fetch = await self.bot.send_message(ctx.message.channel,
                                                bot_prefix + 'Searching...')
            if msg.startswith('[link]'):
                msg = msg[6:]
                link = True
            else:
                link = False

            found, result = await self.google_results('anime', msg)

            if found:
                anime_id = re.findall('/anime/(.*)/', result)
                results = await loop.run_in_executor(
                    None, spice.search_id, int(anime_id[0]),
                    spice.get_medium('anime'),
                    spice.init_auth(config['mal_username'],
                                    config['mal_password']))
                gc.collect()

            else:
                allresults = await loop.run_in_executor(
                    None, spice.search, msg.strip(), spice.get_medium('anime'),
                    spice.init_auth(config['mal_username'],
                                    config['mal_password']))
                gc.collect()
                results = allresults[0]

            # No results found for specified tags
            if not results:
                await self.bot.send_message(ctx.message.channel,
                                            bot_prefix + 'No results.')
                await self.bot.delete_message(fetch)
                return await self.bot.delete_message(ctx.message)

            if not embed_perms(ctx.message) or link is True:
                await self.bot.send_message(
                    ctx.message.channel, bot_prefix +
                    'https://myanimelist.net/anime/%s' % results.id)
                await self.bot.delete_message(fetch)
                return await self.bot.delete_message(ctx.message)

            # Formatting embed
            selection = results
            synopsis = BeautifulSoup(selection.synopsis, 'lxml')

            em = discord.Embed(description='{}'.format(
                'https://myanimelist.net/anime/%s' % selection.id),
                               colour=0x0066CC)

            try:
                english = selection.english
                if english:
                    em.add_field(name='English Title',
                                 value=english,
                                 inline=False)
            except:
                pass
            em.add_field(name='Type', value=selection.anime_type)
            if selection.episodes == '0':
                episodes = 'Unknown'
            else:
                episodes = selection.episodes
            em.add_field(name='Episodes', value=episodes)
            em.add_field(name='Score', value=selection.score + '/10')
            em.add_field(name='Status', value=selection.status)
            try:
                synop = synopsis.get_text()[:400].split('.')
                text = ''
                for i in range(0, len(synop) - 1):
                    text += synop[i] + '.'
            except:
                text = synopsis.get_text()
            em.add_field(name='Synopsis',
                         value=text +
                         ' [Read more »](https://myanimelist.net/anime/%s)' %
                         selection.id)

            if selection.status == "Publishing":
                date = selection.raw_data.start_date.text + " -"
            else:
                date = selection.raw_data.start_date.text + "  -  " + selection.raw_data.end_date.text
            if date:
                em.add_field(name='Airing Time:', value=date)
            em.set_thumbnail(url=selection.image_url)
            em.set_author(
                name=selection.title,
                icon_url=
                'https://myanimelist.cdn-dena.com/img/sp/icon/apple-touch-icon-256.png'
            )
            em.set_footer(text='MyAnimeList')

            await self.bot.send_message(ctx.message.channel, embed=em)
            await self.bot.delete_message(fetch)
            await self.bot.delete_message(ctx.message)
        else:
            await self.bot.send_message(
                ctx.message.channel,
                bot_prefix + 'Specify an anime to search for.')
Esempio n. 19
0
 def getMal(self, i, _type):
     creds = spice.init_auth(self.config.get('mal_username', []),
                             self.config.get('mal_password', []))
     return spice.search_id(int(i), spice.get_medium(_type), creds)
Esempio n. 20
0
    async def anime(self, ctx, *, msg: str):
        try:
            link = False
            fetch = await self.bot.send_message(ctx.message.channel,
                                                isBot + 'Searching...')
            try:

                if msg.startswith('[link]'):
                    msg = msg[6:]
                    link = True
                # Search google for the anime under site:myanimelist.net
                searchUrl = "https://www.googleapis.com/customsearch/v1?q=site:myanimelist.net anime " + msg.strip() + "&start=" + '1' + "&key=" + \
                            config['google_api_key'] + "&cx=" + config[
                                'custom_search_engine']
                r = requests.get(searchUrl)
                response = r.content.decode('utf-8')
                result = json.loads(response)
                animeID = re.findall('/anime/(.*)/',
                                     str(result['items'][0]['link']))
                results = spice.search_id(
                    int(animeID[0]), spice.get_medium('anime'),
                    spice.init_auth(config['mal_username'],
                                    config['mal_password']))

                # If no results found or daily api limit exceeded, use spice's search
                if not results:
                    allresults = spice.search(
                        msg.strip(), spice.get_medium('anime'),
                        spice.init_auth(config['mal_username'],
                                        config['mal_password']))
                    results = allresults[0]

            # On any exception, search spice instead
            except:
                allresults = spice.search(
                    msg.strip(), spice.get_medium('anime'),
                    spice.init_auth(config['mal_username'],
                                    config['mal_password']))
                results = allresults[0]

            # No results found for specified tags
            if not results:
                await self.bot.send_message(ctx.message.channel,
                                            isBot + 'No results.')
                await self.bot.delete_message(fetch)
                await self.bot.delete_message(ctx.message)
                return

            if not embed_perms(ctx.message) or link is True:
                await self.bot.send_message(
                    ctx.message.channel,
                    isBot + 'https://myanimelist.net/anime/%s' % results.id)
                await self.bot.delete_message(fetch)
                await self.bot.delete_message(ctx.message)
                return

            # Formatting embed
            selection = results
            synopsis = BeautifulSoup(selection.synopsis, 'lxml')

            em = discord.Embed(description='{}'.format(
                'https://myanimelist.net/anime/%s' % selection.id),
                               colour=0x0066CC)

            try:
                english = selection.english
                if english:
                    em.add_field(name='English Title',
                                 value=english,
                                 inline=False)
            except:
                pass
            em.add_field(name='Type', value=selection.anime_type)
            if selection.episodes == '0':
                episodes = 'Unknown'
            else:
                episodes = selection.episodes
            em.add_field(name='Episodes', value=episodes)
            em.add_field(name='Score', value=selection.score + '/10')
            em.add_field(name='Status', value=selection.status)
            try:
                synop = synopsis.get_text()[:400].split('.')
                text = ''
                for i in range(0, len(synop) - 1):
                    text += synop[i] + '.'
            except:
                text = synopsis.get_text()
            em.add_field(name='Synopsis',
                         value=text +
                         ' [Read more »](https://myanimelist.net/anime/%s)' %
                         selection.id)

            if selection.status == "Publishing":
                date = selection.raw_data.start_date.text + " -"
            else:
                date = selection.raw_data.start_date.text + "  -  " + selection.raw_data.end_date.text
            if date:
                em.add_field(name='Airing Time:', value=date)
            em.set_thumbnail(url=selection.image_url)
            em.set_author(
                name=selection.title,
                icon_url=
                'https://myanimelist.cdn-dena.com/img/sp/icon/apple-touch-icon-256.png'
            )

            await self.bot.send_message(ctx.message.channel, embed=em)
            await self.bot.delete_message(fetch)
            await self.bot.delete_message(ctx.message)
        except:
            await self.bot.send_message(ctx.message.channel,
                                        isBot + 'No results')
            await self.bot.delete_message(fetch)
Esempio n. 21
0
# else:
#     for arg in sys.argv:
#         manga_directories.append(arg)

mal_username = ""
mal_password = ""
credentials = spice.init_auth(mal_username, mal_password)

for directory in manga_directories:
    no_results = []
    processed = []
    already_processed = []
    for manga in os.listdir(directory):
        if not "folder.jpg" in os.listdir(directory + "\\" +
                                          manga) and manga != "desktop.ini":
            search_results = spice.search(manga, spice.get_medium('manga'),
                                          credentials)
            if len(search_results) > 0:
                image_url = search_results[0].image_url
                image_directory = directory + "\\" + manga + "\\" + "folder.jpg"
                image_file = open(image_directory, 'wb')  # create file locally
                image_file.write(requests.get(image_url).content)
                image_file.close()
                processed.append(manga)
            else:
                no_results.append(manga)
print(already_processed)
print("The following manga covers were downloaded:")
for manga in processed:
    print(manga)
print(
Esempio n. 22
0
def send_watched_to_mal(watched_shows, mal_list):
    for key, value in watched_shows.items():
        plex_title = key
        watched_episode_count = value
        show_in_mal_list = False
        #print('%s => watch count = %s' % (plex_title, watched_episode_count))

        if(watched_episode_count <= 0):
            continue

        mal_watched_episode_count = 0
        mal_show_id = 0

        # check if show is already on MAL list
        for list_item in mal_list:
            #print('Comparing %s with %s' % (list_item.title, plex_title))
            mal_id = int(list_item.id)
            mal_title = list_item.title
            mal_title_english = ""

            if(list_item.english is not None):
                mal_title_english = list_item.english
                #print('Comparing original: %s | english: %s with %s' % (mal_title, mal_title_english, plex_title))
            else:
                #print('Comparing original: %s with %s' % (mal_title, plex_title))
                pass

            if(mal_title.lower() == plex_title.lower() or mal_title_english.lower() == plex_title.lower()):
                #print('%s [%s] was already in list => status = %s | watch count = %s' % (plex_title, list_item.id, spice.get_status(list_item.status), list_item.episodes))
                mal_watched_episode_count = int(list_item.episodes)
                mal_show_id = int(list_item.id)
                show_in_mal_list = True

                if(mal_watched_episode_count > 0 and mal_show_id > 0):
                    if(mal_watched_episode_count < watched_episode_count):
                        anime_new = spice.get_blank(spice.get_medium('anime'))
                        anime_new.episodes = watched_episode_count
                        new_status = 'watching'

                        # if full watched set status to completed, needs additional lookup as total episodes are not exposed in list (mal or spice limitation)
                        lookup_show = spice.search_id(
                            mal_id, spice.get_medium('anime'), mal_credentials)
                        if(lookup_show):
                            if(lookup_show.episodes is not None):
                                mal_total_episodes = int(lookup_show.episodes)

                                if(watched_episode_count >= mal_total_episodes):
                                    new_status = 'completed'

                        anime_new.status = spice.get_status(new_status)

                        print(Back.MAGENTA + '[PLEX -> MAL] Watch count for %s on Plex is %s and MAL is %s, gonna update MAL watch count to %s and status to %s ]' % (plex_title, watched_episode_count,
                                                                                                                                                                      mal_watched_episode_count, watched_episode_count, new_status))
                        spice.update(anime_new, mal_show_id,
                                     spice.get_medium('anime'), mal_credentials)
                    else:
                        print(
                            Back.GREEN + '[PLEX -> MAL] Watch count for %s on Plex was equal or higher on MAL so skipping update' % (plex_title))
                        pass

        # if not listed in list lookup on MAL
        if(not show_in_mal_list):
            found_result = False
            update_list = True
            on_mal_list = False
            print(
                Back.CYAN + '[PLEX -> MAL] %s not in MAL list, gonna search for show on MAL' % (plex_title))

            mal_shows = spice.search(
                plex_title, spice.get_medium('anime'), mal_credentials)
            for mal_show in mal_shows:
                mal_title = mal_show.title.lower()
                mal_title_english = ''
                mal_show_id = int(mal_show.id)
                mal_total_episodes = int(mal_show.episodes)

                if(mal_show.english is not None):
                    mal_title_english = mal_show.english.lower()
Esempio n. 23
0
def get_mal_list():
    mal_list = spice.get_list(spice.get_medium(
        'anime'), mal_username, mal_credentials).get_mediums()

    return mal_list
Esempio n. 24
0
                        mal_list_id = int(list_item.id)
                        mal_list_watched_episode_count = int(
                            list_item.episodes)

                        if(mal_list_id == mal_show_id):
                            on_mal_list = True
                            if(watched_episode_count == mal_list_watched_episode_count):
                                print(
                                    Back.GREEN + '[PLEX -> MAL] show was found in current MAL list using id lookup however watch count was identical so skipping update')
                                update_list = False
                            break

                    if(update_list):
                        print(
                            Back.MAGENTA + '[PLEX -> MAL] Found match on MAL and setting state to watching with watch count: %s' % (watched_episode_count))
                        anime_new = spice.get_blank(spice.get_medium('anime'))
                        anime_new.episodes = watched_episode_count

                        if(watched_episode_count >= mal_total_episodes):
                            anime_new.status = spice.get_status('completed')
                            if(on_mal_list):
                                spice.update(anime_new, mal_show.id, spice.get_medium(
                                    'anime'), mal_credentials)
                            else:
                                spice.add(anime_new, mal_show.id, spice.get_medium(
                                    'anime'), mal_credentials)
                        else:
                            anime_new.status = spice.get_status('watching')
                            if(on_mal_list):
                                spice.update(anime_new, mal_show.id, spice.get_medium(
                                    'anime'), mal_credentials)