async def login_mal(self, ctx, username, password):
     """Set the MAL login.
     
     Code copied from Mash's IMDB apikey_imdb command"""
     user = ctx.message.author
     if self.settings["username"] != "":
         await self.bot.say(
             "{} ` MAL Login found, overwrite it? y/n`".format(user.mention)
         )
         response = await self.bot.wait_for_message(
             author=ctx.message.author)
         if response.content.lower().strip() == "y":
             usernamecheck = username
             usernamepassword = password
             self.creds = spice.init_auth(usernamecheck, usernamepassword)
             self.settings["username"] = usernamecheck
             self.settings["password"] = usernamepassword
             fileIO(SETTINGS, "save", self.settings)
             await self.bot.say("{} ` MAL Login saved...`".format(
                 user.mention))
         else:
             await self.bot.say(
                 "{} `Canceled API key opertation...`".format(user.mention))
     else:
         usernamecheck = username
         usernamepassword = password
         self.creds = spice.init_auth(usernamecheck, usernamepassword)
         self.settings["username"] = usernamecheck
         self.settings["password"] = usernamepassword
         fileIO(SETTINGS, "save", self.settings)
         await self.bot.say("{} ` MAL Login saved...`".format(user.mention))
     self.settings = fileIO(SETTINGS, "load")
예제 #2
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
예제 #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)
예제 #4
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)
예제 #5
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)
예제 #6
0
def mal_authenticate():
    user = mal_settings['username']
    password = mal_settings['password']
    mal = spice.init_auth(user, password)
    # Failed
    if not mal:
        logger.critical('[MAL] Failed to authenticate, exiting...')
        sys.exit()
    return mal
예제 #7
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)
예제 #8
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()
예제 #9
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)))
예제 #10
0
파일: test_spice.py 프로젝트: Utagai/spice
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)))
예제 #11
0
import spice_api as spice

# Logger
logger = logging.getLogger('PlexMALSync')

# Enable this if you want to also log all messages coming from imported libraries
# coloredlogs.install(level='DEBUG')

coloredlogs.install(fmt='%(asctime)s %(message)s', logger=logger)

mal_username = sys.argv[1]
mal_password = sys.argv[2]
plex_title = sys.argv[3]
watched_episode_count = sys.argv[4]

mal_credentials = spice.init_auth(mal_username, mal_password)


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


def send_watched_to_mal(mal_list, plex_title, plex_watched_episode_count):
예제 #12
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)
예제 #13
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)
예제 #14
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.')