<commit_before># -*- coding: utf-8 -*-

import json, urllib2

#Update schema
__url__ = 'https://raw.githubusercontent.com/KittyHawkIrc/modules/production/' + __name__ + '.py'
__version__ = 2.0

def declare():
    return {'np': 'privmsg', 'setlastfm': 'privmsg'}

def callback(self):
    key = self.config_get('apikey')
    channel = self.channel
    command = self.command.lower()
    user = self.user.split('!')[0]
    msg = self.msg
    message = self.message.split(command, 1)[1].strip()
    words = message.split()

    if command == 'setlastfm':
        if len(message) > 0:
            try:
                self.locker.lastfm[user.lower()] = words[0]
            except:
                self.locker.lastfm = {user.lower(): words[0]}

            self.cache_save()
            return msg(channel, 'Last.FM for user [%s] set to %s' % (self.user.split('!')[0], message))
        return msg(channel, 'Insufficient input given for %s' % command)
    else:
        url = 'https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user={u}&api_key={k}&format=json'

        if len(words) > 0:
            user = words[0]

        try:
            lastfm_user = self.locker.lastfm[user.lower()]
        except:
            lastfm_user = user

        try:
            r = urllib2.urlopen(url.format(u = lastfm_user, k = key))
            data = json.loads(r.read())['recenttracks']['track'][0]
            r.close()
        except KeyError:
            return msg(channel, 'Data for user [%s] not found.' % user)
        except urllib2.URLError:
            return msg(channel, 'Last.fm unavailable at the moment.')

        np_list = [user]

        if 'name' in data and data['name']:
            np_list.append('🎵 {}'.format(data['name']))

        if ('artist' in data and '#text' in data['artist'] and
            data['artist']['#text']):
            np_list.append('🎤 {}'.format(data['artist']['#text']))

        if ('album' in data and '#text' in data['album'] and
            data['album']['#text']):
            np_list.append('💽 {}'.format(data['album']['#text']))

        np = ' / '.join(np_list)
        return msg(channel, np)

################################ START: Testing ################################
class api:
    def msg(self, channel, text):
        return '[%s] %s' % (channel, text)

class empty:
    pass

if __name__ == '__main__':
    def cache_save():
        print 'Cache saved'
    def config_get(item):
        return '48a737c88c910cb86a38dd012fe27745'
    api = api()
    declares = declare().keys()
    setattr(api, 'cache_save', cache_save)
    setattr(api, 'config_get', config_get)
    setattr(api, 'type', 'privmsg')
    setattr(api, 'channel', '#channel')
    setattr(api, 'locker', empty)
    setattr(api, 'user', 'nick!ident@host')
    setattr(api, 'isop', False)
########################## START: Interactive Testing ##########################
    '''
    while(True):
        _input = raw_input('Enter message here: ')
        input_split = _input.split()<commit_msg>Make it pretty<commit_after># -*- coding: utf-8 -*-

import json, urllib2

#Update schema
__url__ = 'https://raw.githubusercontent.com/KittyHawkIrc/modules/production/' + __name__ + '.py'
__version__ = 2.0

def declare():
    return {'np': 'privmsg', 'setlastfm': 'privmsg'}

def callback(self):
    sep = ' / '

    key = self.config_get('apikey')
    channel = self.channel
    command = self.command.lower()
    user = self.user.split('!')[0]
    msg = self.msg
    message = self.message.split(command, 1)[1].strip()
    words = message.split()

    np = None

    if command == 'setlastfm':
        if len(message) > 0:
            try:
                self.locker.lastfm[user.lower()] = words[0]
            except:
                self.locker.lastfm = {user.lower(): words[0]}

            self.cache_save()
            output = 'Last.FM for user [{u}] set to {w[0]}'
        else:
            output = 'Insufficient input given for {c}'
    else:
        url = 'https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user={u}&api_key={k}&format=json'

        if len(words) > 0:
            user = words[0]

        try:
            lastfm_user = self.locker.lastfm[user.lower()]
        except:
            lastfm_user = user

        try:
            r = urllib2.urlopen(url.format(u = lastfm_user, k = key))
            data = json.loads(r.read())['recenttracks']['track'][0]
            r.close()
        except KeyError:
            return msg(channel, 'Data for user [%s] not found.' % user)
        except urllib2.URLError:
            return msg(channel, 'Last.fm unavailable at the moment.')

        np = []

        if 'name' in data and data['name']:
            np.append('🎵 {}'.format(data['name']))

        if ('artist' in data and '#text' in data['artist'] and
            data['artist']['#text']):
            np.append('🎤 {}'.format(data['artist']['#text']))

        if ('album' in data and '#text' in data['album'] and
            data['album']['#text']):
            np.append('💽 {}'.format(data['album']['#text']))

        np = sep.join(np)
        output = '{u}{s}{np}'
    return msg(channel, output.format(u = user, s = sep, c = command, w = words,
                                      np = np))

################################ START: Testing ################################
class api:
    def msg(self, channel, text):
        return '[%s] %s' % (channel, text)

class empty:
    pass

if __name__ == '__main__':
    def cache_save():
        print 'Cache saved'
    def config_get(item):
        return '48a737c88c910cb86a38dd012fe27745'
    api = api()
    declares = declare().keys()
    setattr(api, 'cache_save', cache_save)
    setattr(api, 'config_get', config_get)
    setattr(api, 'type', 'privmsg')
    setattr(api, 'channel', '#channel')
    setattr(api, 'locker', empty)
    setattr(api, 'user', 'nick!ident@host')
    setattr(api, 'isop', False)
########################## START: Interactive Testing ##########################
    '''
    while(True):
        _input = raw_input('Enter message here: ')
        input_split = _input.split()
{'fraction_non_alphanumeric': 0.19597907813010787, 'fraction_numerical': 0.013076168682576005, 'mean_word_length': 2.4707884288145205, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5018652', 'n_tokens_mistral': 2037, 'n_tokens_neox': 1945, 'n_words': 442}