예제 #1
0
    def resolve(self, config):
        logger.debug(f"Resolving using config {config!r}")

        search_strings = self.build_search_strings({})
        if not search_strings:
            return

        from imdbparser import IMDb

        imdb = IMDb()

        for title, year in set(search_strings):
            logger.debug(f"Resolving using title:{title} year:{year}")

            if self.search_resolve == "tv":
                metadata = imdb.resolve_tv_show(title, year)
            elif self.search_resolve == "movie":
                metadata = imdb.resolve_movie(title, year)
            else:
                logger.warning(f"Unknown search resolve {self.search_resolve}")
                continue

            if not metadata:
                continue

            return metadata.imdb_id
예제 #2
0
def process(input, entities):
    output = {}
    try:
        movie = entities['movie'][0]['value']

        with requests_cache.enabled('movie_cache', backend='sqlite', expire_after=86400):
            # Make a search request to the API to get the movie's TMDb ID
            r = requests.get('http://api.themoviedb.org/3/search/movie', params={
                'api_key': TMDB_API_KEY,
                'query': movie,
                'include_adult': False
            })
            data = r.json()

            assert (len(data['results']) > 0)
            tmdb_id = str(data['results'][0]['id'])

            # Make another request to the API using the movie's TMDb ID to get the movie's IMDb ID
            r = requests.get('https://api.themoviedb.org/3/movie/' + tmdb_id, params={
                'api_key': TMDB_API_KEY,
                'append_to_response': 'videos'
            })
            data = r.json()

        # Fetch movie rating from IMDb
        ia = IMDb()
        imdb_id = data['imdb_id']
        imdb_movie = ia.get_movie(imdb_id[2:])
        imdb_movie.fetch()

        template = TextTemplate('Title: ' + data['title'] +
                                '\nYear: ' + data['release_date'][:4] +
                                '\nIMDb Rating: ' + str(imdb_movie.__dict__['rating']) + ' / 10' +
                                '\nOverview: ' + data['overview'])
        text = template.get_text()
        template = ButtonTemplate(text)
        template.add_web_url('IMDb Link', 'https://www.imdb.com/title/' + data['imdb_id'] + '/')

        videos = data['videos']['results']
        # Append first Trailer URL if one exists
        for video in videos:
            if video['type'] == 'Trailer' and video['site'] == 'YouTube':
                template.add_web_url('YouTube Trailer', YouTubeUtil.get_video_url(video['key']))
                break

        output['input'] = input
        output['output'] = template.get_message()
        output['success'] = True
    except:
        error_message = 'I couldn\'t find that movie.'
        error_message += '\nPlease ask me something else, like:'
        error_message += '\n  - batman movie'
        error_message += '\n  - iron man 2 movie plot'
        error_message += '\n  - What is the rating of happyness movie?'
        output['error_msg'] = TextTemplate(error_message).get_message()
        output['success'] = False
    return output
예제 #3
0
def corrigir_titulo_serie():
    print('corrigir_titulo_serie Iniciado')
    repetir = False
    for r in db.registros.find({
            'titulo': {
                '$exists': False
            },
            'imdb': {
                '$regex': '.* .*'
            }
    }).limit(1):
        # print(r)
        try:
            im = str(r['imdb']).strip()[2:r['imdb'].index(" ")]
            imdb = IMDb()
            print(int(im))
            movie = imdb.get_movie(int(im))
            movie.fetch()
            print(movie.__dict__['title'])
            print(movie.__dict__['year'])
            print('.*' + str(im) + '.*')
            db.registros.update_many(
                {'imdb': {
                    '$regex': '.*' + str(im) + '.*'
                }}, {
                    "$set": {
                        "titulo": movie.__dict__['title'],
                        "ano": movie.__dict__['year']
                    }
                })
            print('Sem Título: ', im, movie.__dict__['title'])
            repetir = True
        except:
            im = str(r['imdb']).strip()[2:r['imdb'].index(" ")]
            db.registros.update_many(
                {'imdb': {
                    '$regex': '.*' + str(im) + '.*'
                }}, {"$set": {
                    "titulo": 'Título não encontrado',
                    "ano": 0
                }})
            repetir = True
            print('Erro Sem Título: ', im)

    if repetir:
        corrigir_titulo_serie()
예제 #4
0
def corrigir_titulo_filme():
    print('corrigir_titulo_filme: Iniciado')
    repetir = False
    for r in db.registros.find({
            'titulo': {
                '$exists': False
            },
            'imdb': {
                '$not': {
                    '$regex': '.* .*'
                }
            }
    }).limit(20):
        # print(r)
        try:
            im = str(r['imdb']).strip()[2:]
            imdb = IMDb()
            print(int(im))
            movie = imdb.get_movie(int(im))
            movie.fetch()
            print(movie.__dict__['title'])
            print(movie.__dict__['year'])
            db.registros.update_one({"_id": r['_id']}, {
                "$set": {
                    "titulo": movie.__dict__['title'],
                    "ano": movie.__dict__['year']
                }
            })
            print('Sem Título: ', im, movie.__dict__['title'])
            repetir = True
        except:
            db.registros.update_one(
                {"_id": r['_id']},
                {"$set": {
                    "titulo": 'Título não encontrado',
                    "ano": 0
                }})
            repetir = True
            print('Erro Sem Título: ', im)

    if repetir:
        corrigir_titulo_filme()
        else:
            html = getHTML('https://www.google.co.in/search?q=' + input)
            for cite in html.findAll('cite'):
                if 'imdb.com/title/tt' in cite.text:
                    html = getHTML(cite.text)
                    break
        return getJSON(html)
    except Exception as e:
        print(e)
        return 'Invalid input or Network Error!'


from imdbparser import IMDb

import json
imdb = IMDb()
prefix = 'tt'

userInput = input("Enter the title of the Movie: ")
search_result = imdb.search_movie(userInput)
search_result.fetch()

print("Please wait... we are fetching you the rating")
try:
    movie_id = search_result.results[0].imdb_id
    result = getURL(prefix + movie_id)
    rating = json.loads(result)
    print("Rating: " + rating['rating'])
except Exception as e:
    print("Please provide the correct title of the movie")
예제 #6
0
def process(input, entities):
    output = {}
    try:
        movie = entities['movie'][0]['value']

        with requests_cache.enabled('movie_cache',
                                    backend='sqlite',
                                    expire_after=86400):
            # Make a search request to the API to get the movie's TMDb ID
            r = requests.get('http://api.themoviedb.org/3/search/movie',
                             params={
                                 'api_key': TMDB_API_KEY,
                                 'query': movie,
                                 'include_adult': False
                             })
            data = r.json()

            assert (len(data['results']) > 0)
            tmdb_id = str(data['results'][0]['id'])

            # Make another request to the API using the movie's TMDb ID to get the movie's IMDb ID
            r = requests.get('https://api.themoviedb.org/3/movie/' + tmdb_id,
                             params={
                                 'api_key': TMDB_API_KEY,
                                 'append_to_response': 'videos'
                             })
            data = r.json()

        # Fetch movie rating from IMDb
        ia = IMDb()
        imdb_id = data['imdb_id']
        imdb_movie = ia.get_movie(imdb_id[2:])
        imdb_movie.fetch()

        template = TextTemplate('Title: ' + data['title'] + '\nYear: ' +
                                data['release_date'][:4] + '\nIMDb Rating: ' +
                                str(imdb_movie.__dict__['rating']) + ' / 10' +
                                '\nOverview: ' + data['overview'])
        text = template.get_text()
        template = ButtonTemplate(text)
        template.add_web_url(
            'IMDb Link', 'https://www.imdb.com/title/' + data['imdb_id'] + '/')

        videos = data['videos']['results']
        # Append first Trailer URL if one exists
        for video in videos:
            if video['type'] == 'Trailer' and video['site'] == 'YouTube':
                template.add_web_url('YouTube Trailer',
                                     YouTubeUtil.get_video_url(video['key']))
                break

        output['input'] = input
        output['output'] = template.get_message()
        output['success'] = True
    except:
        error_message = 'I couldn\'t find that movie.'
        error_message += '\nPlease ask me something else, like:'
        error_message += '\n  - batman movie'
        error_message += '\n  - iron man 2 movie plot'
        error_message += '\n  - What is the rating of happyness movie?'
        output['error_msg'] = TextTemplate(error_message).get_message()
        output['success'] = False
    return output
예제 #7
0
    def populate(self, config):
        from imdbparser import IMDb

        image_cache = config["image_cache"]

        imdb = IMDb()
        movie = imdb.get_movie(self.identifier)
        movie.fetch()

        self.actors.clear()
        self.writers.clear()
        self.directors.clear()
        self.genres.clear()
        self.languages.clear()
        self.countries.clear()

        AlternativeTitle.objects.filter(metadata=self).delete()

        self.title = movie.title
        self.rating = movie.rating
        self.votes = movie.votes
        self.duration = movie.duration
        self.year = movie.year
        self.plot = movie.plot
        self.synopsis = movie.description

        if movie.cover:
            self.cover = movie.cover
            image_cache.get_image_path(self.cover)

        person_target_map = [
            (movie.actors, self.actors),
            (movie.writers, self.writers),
            (movie.directors, self.directors),
        ]

        for persons, target in person_target_map:
            for p in persons:
                person, _ = Person.objects.get_or_create(
                    identifier=p.imdb_id, defaults={"name": p.name})
                if p.name != person.name:
                    person.name = p.name
                    person.save()

                target.add(person)

        for genre in movie.genres:
            genre, _ = Genre.objects.get_or_create(name=genre)
            self.genres.add(genre)

        primary_language = None
        for language in movie.languages:
            language, _ = Language.objects.get_or_create(name=language)
            if not primary_language:
                primary_language = language
            self.languages.add(language)

        self.primary_language = primary_language

        for country in movie.countries:
            country, _ = Country.objects.get_or_create(name=country)
            self.countries.add(country)

        for alt_title in movie.alternative_titles:
            if alt_title:
                AlternativeTitle.objects.create(title=alt_title, metadata=self)
예제 #8
0
def act(c,msg,sender,mem):
    r = ""

    #basic text response
    if c in mwaaa.reply:
        r = mwaaa.reply[c]

    #song
    elif c == "?song":
        try:
            req = requests.get("http://letty.tk:8000/rds-xml.xsl")
            h = HTMLParser()
            r = h.unescape(req.content[29:-9])
	    if len(r) < 3:
		r = "I don't hear anything."			
			
        except:
            r = "not now " + sender
        #r = "This feature is disabled :("

    #text replacement
    elif c == "?/":
        if msg[-1] == '/':
            msg = msg[:-1]
        mfull = msg[msg.find("?/")+2:]
        mbad = mfull[:mfull.find("/")]
        mgood = mfull[mfull.find("/")+1:]
        try:
            for m in reversed(mem[:-1]):
                if m.find(mbad) != -1 and m.find("?/") == -1:   
                    oldSender = m[:m.find("??")]
                    mes = m[len(oldSender)+2:]
                    if mes.startswith("\x01ACTION"): # /me
                        mes = mes[8:-1]
                        action = True
                    else:
                        action = False
                    preBad = mes[:mes.find(mbad)]
                    postBad = mes[mes.find(mbad)+len(mbad):]
                    fixed = preBad + mgood + postBad
                    if action:
                        fixed = "* \x02"+oldSender+"\x02 "+fixed
                    else:
                        fixed = '"'+fixed+'"'
                    r = "\x02"+oldSender+"\x02 meant: " +fixed
                    if sender != oldSender:
                        r = "\x02"+sender+'\x02 thinks ' + r
                    return r
        except:
	    r = "well that didn't work :/"

    #urban dictionary
    elif c == "?ud":
        query = msg[msg.find("?ud") + 4:].replace('"',"'")
        try:
            defs = ud.define(query)
            for d in defs[:3]:
                r += d.definition.replace('\n', ' ').replace('\r', ' ')
        except:
            r = "well that didn't work :/"

    #wikipedia
    elif c == "?wiki":
        query = msg[msg.find("?wiki") + 6:]
        try:
            r = wikipedia.summary(query, sentences=3)
        except wikipedia.exceptions.DisambiguationError as e:
            if len(e.options) > 2:
                r = e.options[0]+", "+e.options[1]+", or "+e.options[2]+"?"
            else:
                r = e.options[0]+" or "+e.options[1]+"?"
        except wikipedia.exceptions.PageError as e2:
            r = "Didn't find anything"

    #IMDb
    elif c == "?imdb":
        imdb = IMDb()
        title = msg[msg.find("?imdb") + 6:]
        try:
	    searchResult = imdb.search_movie(title)
	    searchResult.fetch()
	    movie = searchResult.results[0]
	    movie.fetch()
	    if len(searchResult.results) < 1:
		r = "I didn't find anything"
	    else:
		r = movie.title+" ("+str(movie.year)+") -- "+movie.plot
	except:
	    r = "something went wrong :/"
	    
    #bot driver
    if c == "PRIVMSG "+mwaaa.nick and sender in mwaaa.admins:
        r = msg[msg.find("PRIVMSG "+mwaaa.nick)+15:]
    elif c == "PRIVMSG "+mwaaa.nick and msg.find("?say") != -1:
        r = msg[msg.find("?say")+5:]
    
    #quit
    if c == "?bye" and sender in mwaaa.admins:
        exit(0)

    if c == mwaaa.updateKey:
        reload(mwaaa)

    return r.encode('utf-8')
예제 #9
0
def act(c, msg, sender, mem):
    '''
    c is a command from commands list defined above
    msg is the whole message send that contains the command trigger
    sender is part of msg, the nick for the sender
    mem is a list or strings containing the last few 'msg's
    '''
    with open('callLog', 'a') as f:
        f.write(sender + ": " + c + "\n" + msg + "\n\n")

    r = ""

    ##  Basic text response.
    if c in mwaaa.reply:
        r = mwaaa.reply[c]

    ##  Song.
    elif c == "?song":
        try:
            req = requests.get("http://letty.tk:8000/rds-xml.xsl")
            h = HTMLParser()
            r = h.unescape(req.content[29:-9])
            if len(r) < 3:
                r = "I don't hear anything."
        except:
            r = "not now " + sender
            #r = "This feature is disabled :("

    ##  get answer from yahoo answers.
    elif c == "?ask":
        try:
            question = msg[msg.find("?ask") + 5:]
            if len(question) > 1:
                h = HTMLParser()
                req = requests.get("http://api.haxed.net/answers/?b&q=" +
                                   question)
                r = h.unescape(req.content)
            if len(r) < 3:
                r = "no answer"
        except:
            r = "error getting answer"
            #r = "This feature is disabled :("

    ## Slap
    elif c == "?slap":
        audience = msg[msg.find("?slap") + 6:]
        if len(audience) > 1:
            r = sender + " slaps themself for the amusement of " + audience
        else:
            r = sender + " slaps themself."

    ##  Coin Flip
    elif c == "?coin":
        r = random.sample(["heads", "tails"], 1)
        r = r[0]

    ##  Text replacement.
    elif c == "?/" and msg.find(" :?/") > 1:
        if msg[-1] == '/':
            msg = msg[:-1]
        mfull = msg[msg.find("?/") + 2:]
        mbad = mfull[:mfull.find("/")]
        mgood = '\x02' + mfull[mfull.find("/") + 1:] + '\x02'
        try:
            for m in reversed(mem[:-1]):
                if m.find(mbad) != -1 and m.find("?/") == -1:
                    oldSender = m[:m.find("??")]
                    mes = m[len(oldSender) + 2:]
                    if mes.startswith("\x01ACTION"):  # /me
                        mes = mes[8:-1]
                        action = True
                    else:
                        action = False
                    preBad = mes[:mes.find(mbad)]
                    postBad = mes[mes.find(mbad) + len(mbad):]
                    fixed = preBad + mgood + postBad
                    if action:
                        fixed = "* \x02" + oldSender + "\x02 " + fixed
                    else:
                        fixed = '"' + fixed + '"'
                    r = "\x02" + oldSender + "\x02 meant: " + fixed
                    if sender != oldSender:
                        r = "\x02" + sender + '\x02 thinks ' + r
                    return r
        except:
            r = "well that didn't work :/"

    ##  Urban Dictionary.
    elif c == "?ud":
        try:
            query = msg[msg.find("?ud") + 4:].replace('"', "'")
            defs = ud.define(query)
            for d in defs[:3]:
                r += d.definition.replace('\n', ' ').replace('\r', ' ')
        except:
            r = "well that didn't work :/"

    ##  Wikipedia.
    elif c == "?wiki":
        try:
            query = msg[msg.find("?wiki") + 6:]
            r = wikipedia.summary(query, sentences=3)
        except wikipedia.exceptions.DisambiguationError as e:
            optionCount = min(len(e.options), 14)
            for c, value in enumerate(e.options[:optionCount - 1]):
                r += value + ", "
            r += "or " + e.options[optionCount - 1] + "?"
        except wikipedia.exceptions.PageError as e2:
            r = "Didn't find anything"

    ##  IMDb.
    elif c == "?imdb":
        imdb = IMDb()
        title = msg[msg.find("?imdb") + 6:]
        try:
            searchResult = imdb.search_movie(title)
            searchResult.fetch()
            movie = searchResult.results[0]
            movie.fetch()
            if len(searchResult.results) < 1:
                r = "I didn't find anything"
            else:
                r = movie.title + " (" + str(movie.year) + ") " + '-'.join(
                    movie.genres) + " [" + str(
                        movie.rating) + "/10] " + movie.plot
        except:
            r = "something went wrong :/"

    return r.encode('utf-8')
예제 #10
0
def act(c, msg, sender, mem):
    '''
    c is a command from commands list defined above
    msg is the whole message send that contains the command trigger
    sender is part of msg, the nick for the sender
    mem is a list or strings containing the last few 'msg's
    '''
    with open('callLog', 'a') as f:
        f.write(sender + ": " + c + "\n" + msg + "\n\n")

    r = ""

    if sender not in ignoreList:

        ##  Basic text response.
        if c in mwaaa.reply:
            r = mwaaa.reply[c]

        ##  Song.
        elif c == "?song":
            global currentSong
            global shutUp
            try:
                req = requests.get("http://letty.tk:8000/status-json.xsl")

                j = json.loads(req.text)
                l = str(j["icestats"]["source"]["listeners"])
                t = j["icestats"]["source"]["title"]
                r = t + " -- " + l + " listeners"

                if r != currentSong:
                    shutUp = False

                if shutUp == True and sender not in details.admins:
                    r = ""
                elif r == currentSong and sender not in details.admins:
                    r = "it's still the same song"
                    shutUp = True
                else:
                    shutUp = False
                    currentSong = r
                    '''
                    response = urllib2.urlopen("http://letty.tk/likes.txt")              
                    songList = []
                    
                    cr = csv.reader(response, delimiter="|")
                    for row in cr:
                        songList.append([row[2],row[4]])
                    
                    likes = 0
                    dislikes = 0
                    
                    for song in songList:
                        if song[1] == r:
                            if song[0] == "like":
                                likes += 1
                            else:
                                dislikes += 1
                    if likes > 0 or dislikes > 0:
                        r += " ["                    
                        if likes > 0:
                            r += "+" + str(likes)
                            if dislikes > 0:
                                r += " "
                        if dislikes > 0:
                            r += "-" + str(dislikes)
                        r += "]"                  
                    '''
                    if len(r) < 3:
                        r = "I don't hear anything."
            except:
                r = "not now " + sender

        ## Weather
        elif c == "?weather":
            place = msg[msg.find("?weather") + 9:].split(" ")
            countryState = place.pop()
            city = "_".join(place)
            url = "http://api.wunderground.com/api/" + details.wuAPI_key + "/conditions/forecast/q/"
            url += countryState + "/" + city + ".json"
            try:
                j = json.loads(urllib2.urlopen(url).read())
                if "results" in j["response"]:
                    r = "Could you be more specific?"
                elif "error" in j["response"]:
                    r = j["response"]["error"]["description"]
                else:
                    try:
                        f = j["forecast"]["txt_forecast"]["forecastday"]
                        c = j["current_observation"]
                        location = c["display_location"]["full"]

                        #ask for fahrenhiet in US
                        if c["display_location"]["country"] in ["US"]:
                            scale = "fcttext"
                        else:
                            scale = "fcttext_metric"

                        weather = c["weather"] + " " + str(
                            c["temp_f"]) + "F/" + str(c["temp_c"]) + "C"

                        forecast = ""
                        for i in range(2):
                            if f[i][scale] != "":
                                forecast += f[i]["title"] + ": "
                                forecast += f[i][scale] + " "

                        r = " :: ".join([location, weather, forecast])
                    except:
                        pass
            except:
                r = "something terrible happened but I'm not sure what..."

        ## Dictionary
        elif c == "?dict":
            words = msg[msg.find("?dict") + 6:].lower().split()
            if len(words) > 2:
                r = "?dict <word> [partOfSpeech]"
            elif len(words) == 2:
                definitions = wordApi.getDefinitions(
                    words[0],
                    partOfSpeech=words[1],
                    sourceDictionaries='ahd-legacy')
                if definitions != None:
                    r = "[" + definitions[0].partOfSpeech + "] " + definitions[
                        0].text
                else:
                    r = "[" + words[1] + "] *" + words[
                        0] + "* not found in dictionary"
            else:
                definitions = wordApi.getDefinitions(
                    words[0], sourceDictionaries='ahd-legacy')
                if definitions != None:
                    r = "[" + definitions[0].partOfSpeech + "] " + definitions[
                        0].text
                else:
                    r = "*" + words[0] + "* not found in dictionary"
        ## Poll
        elif c == "?poll":
            poll = msg[msg.find("?poll") + 6:]
            if poll.find("close #") != -1:
                # close and send results if starter or admin
                pass

            elif poll.find("remove") != -1 and sender in details.admins:
                # if starter or admin, remove poll
                try:
                    l = poll.find("remove") + 6
                    pollNum = poll[l:l + 2]
                    n = int(pollNum)
                    pollList.pop(n - 1)
                except:
                    r = "aint no poll #" + pollNum

            elif len(poll) > 1:
                #create new poll
                pollList.append([poll, sender, {}])
                n = len(pollList)
                r = "new poll created #" + str(n)
            else:
                # display active polls (maybe)
                pass

        ## Vote
        elif c == "?vote":
            m = msg[msg.find("?vote") + 5:]
            try:
                n = re.search(r'\d+', m).group()
                if m.replace("#", "").find(n) > 1:
                    r = 'which number poll?'
                else:
                    pollNum = int(n) - 1
                    if pollNum < 0 or pollNum >= len(pollList):
                        r = "#" + n + " is not an active poll"
                    else:
                        if len(m[m.find(n) + len(n):]) == 0:
                            r = "but what is your vote?"
                        else:
                            vote = m[m.find(n) + len(n) + 1:]
                            if vote[-1] == " ":
                                vote = vote[:-1]
                            voteDict = pollList[pollNum][2]
                            voteDict[sender] = vote

            except:
                r = 'but, which number poll?'
            saveStatus()

        ## Poll Results
        elif c == "?results":
            m = msg[msg.find("?results") + 8:]
            try:
                n = re.search(r'\d+', m).group()
                pollNum = int(n) - 1
                if len(pollList) < int(n):
                    r = "There is no poll #" + str(n)
                else:
                    voteDict = pollList[pollNum][2]
                    countDict = defaultdict(int)
                    for key, value in voteDict.iteritems():
                        countDict[value] += 1
                    r += pollList[pollNum][0] + " -- "
                    for key, value in countDict.iteritems():
                        r += str(key) + ":" + str(value) + ", "
                    r = r[:-2]
            except:
                print('?results failure')

        ##  get answer from yahoo answers.
        elif c == "?ask":
            try:
                question = msg[msg.find("?ask") + 5:]
                if len(question) > 1:
                    h = HTMLParser()
                    req = requests.get("http://api.haxed.net/answers/?b&q=" +
                                       question)
                    r = h.unescape(req.content)
                if len(r) < 3 or r.find("<br />") >= 0 or r.find(
                        "<!DOCTYPE") >= 0:
                    r = "Who knows?"
            except:
                r = "error getting answer"
                #r = "This feature is disabled :("

        ## List of Commands
        elif c == "?list" and msg[-5:] == "?list":
            r = " ".join(listCommands)

        ## Calculator
        elif c == "?calc":
            equation = msg[msg.find("?calc") + 6:].replace("^", "**")
            try:
                n = round(eval(equation), 4)
                if n.is_integer():
                    n = int(n)
                r = str(n)
            except:
                r = "Is that even math?"

        ## Slap
        elif c == "?slap":
            audience = msg[msg.find("?slap") + 6:]
            if len(audience) > 1:
                r = sender + " slaps him or herself for the amusement of " + audience
            else:
                r = sender + " slaps him or herself."

        ## Ted Bundy
        elif c == "?ftb":
            ted = msg[msg.find("?ftb") + 5:]
            r = "Funny thing about " + ted + ": She turned out to be Ted Bundy right after murdering someone."
        elif c == "?tb":
            ted = msg[msg.find("?tb") + 4:]
            r = "Funny thing about " + ted + ": He turned out to be Ted Bundy right after murdering someone."

        ##  Coin Flip
        elif c == "?coin":
            r = random.sample(["heads", "tails"], 1)
            r = r[0]

        ##  Dice
        elif c == "?roll":
            r = "you rolled a "
            r += random.sample(["1", "2", "3", "4", "5", "6"], 1)[0]

        ##  Urban Dictionary.
        elif c == "?ud":
            try:
                query = msg[msg.find("?ud") + 4:].replace('"', "'")
                defs = ud.define(query)
                for d in defs[:3]:
                    r += d.definition.replace('\n', ' ').replace('\r', ' ')
            except:
                r = "well that didn't work :/"
            if r == "":
                r = "I didn't find anything for '" + query + "'"

        ##  Wikipedia.
        elif c == "?wiki":
            query = msg[msg.find("?wiki") + 6:]
            if len(query) > 1:
                try:
                    r = wikipedia.summary(query, sentences=3)
                except wikipedia.exceptions.DisambiguationError as e:
                    optionCount = min(len(e.options), 14)
                    for c, value in enumerate(e.options[:optionCount - 1]):
                        r += value + ", "
                    r += "or " + e.options[optionCount - 1] + "?"
                except wikipedia.exceptions.PageError as e2:
                    r = "Didn't find anything"
            else:
                r = "look up what?"

        ##  IMDb.
        elif c == "?imdb":
            imdb = IMDb()
            title = msg[msg.find("?imdb") + 6:]
            try:
                searchResult = imdb.search_movie(title)
                searchResult.fetch()
                movie = searchResult.results[0]
                movie.fetch()
                if len(searchResult.results) < 1:
                    r = "I didn't find anything"
                else:
                    r = movie.title + " (" + str(movie.year) + ") " + '-'.join(
                        movie.genres) + " [" + str(
                            movie.rating) + "/10] " + str(movie.plot)

            except:
                r = "something went wrong :/"

        ### ADMIN FEATURES
        ## Save Status and exit
        elif c == "?bye" and sender in details.admins:
            print('goodbye')
            saveStatus()
            exit(0)

        ## Ignore abusers
        elif c == "?ignore" and sender in details.admins:
            person = msg[msg.find("?ignore") + 8:]
            if len(person) == 0:
                pass
            elif person[-1] == " ":
                person = person[:-1]
            if person in ignoreList:
                ignoreList.remove(person)
                print(ignoreList)
            else:
                ignoreList.append(person)
                print(ignoreList)
        ##  Save Status
        elif c == "?save" and sender in details.admins:
            print('status saved to llamaStatus.pkl')
            saveStatus()

        ## Send Ignore List
        elif c == "?ignoring" and sender in details.admins:
            r = ' '.join(ignoreList)

    return r.encode('utf-8')
예제 #11
0
def act(c, msg, sender, mem):
    '''
    c is a command from commands list defined above
    msg is the whole message send that contains the command trigger
    sender is part of msg, the nick for the sender
    mem is a list or strings containing the last few 'msg's
    '''
    with open('callLog', 'a') as f:
        f.write(sender + ": " + c + "\n" + msg + "\n\n")

    r = ""

    ##  Basic text response.
    if c in mwaaa.reply:
        r = mwaaa.reply[c]

    ##  Song.
    elif c == "?song":
        try:
            req = requests.get("http://letty.tk:8000/rds-xml.xsl")
            h = HTMLParser()
            r = h.unescape(req.content[29:-9])
            if len(r) < 3:
                r = "I don't hear anything."
        except:
            r = "not now " + sender
            #r = "This feature is disabled :("

    ##  Text replacement.
    elif c == "?/":
        if msg[-1] == '/':
            msg = msg[:-1]
        mfull = msg[msg.find("?/") + 2:]
        mbad = mfull[:mfull.find("/")]
        mgood = mfull[mfull.find("/") + 1:]
        try:
            for m in reversed(mem[:-1]):
                if m.find(mbad) != -1 and m.find("?/") == -1:
                    oldSender = m[:m.find("??")]
                    mes = m[len(oldSender) + 2:]
                    if mes.startswith("\x01ACTION"):  # /me
                        mes = mes[8:-1]
                        action = True
                    else:
                        action = False
                    preBad = mes[:mes.find(mbad)]
                    postBad = mes[mes.find(mbad) + len(mbad):]
                    fixed = preBad + mgood + postBad
                    if action:
                        fixed = "* \x02" + oldSender + "\x02 " + fixed
                    else:
                        fixed = '"' + fixed + '"'
                    r = "\x02" + oldSender + "\x02 meant: " + fixed
                    if sender != oldSender:
                        r = "\x02" + sender + '\x02 thinks ' + r
                    return r
        except:
            r = "well that didn't work :/"

    ##  Urban Dictionary.
    elif c == "?ud":
        query = msg[msg.find("?ud") + 4:].replace('"', "'")
        try:
            defs = ud.define(query)
            for d in defs[:3]:
                r += d.definition.replace('\n', ' ').replace('\r', ' ')
        except:
            r = "well that didn't work :/"

    ##  Wikipedia.
    elif c == "?wiki":
        query = msg[msg.find("?wiki") + 6:]
        try:
            r = wikipedia.summary(query, sentences=3)
        except wikipedia.exceptions.DisambiguationError as e:
            optionCount = min(len(e.options), 14)
            for c, value in enumerate(e.options[:optionCount - 1]):
                r += value + ", "
            r += "or " + e.options[optionCount - 1] + "?"
        except wikipedia.exceptions.PageError as e2:
            r = "Didn't find anything"

    ##  IMDb.
    elif c == "?imdb":
        imdb = IMDb()
        title = msg[msg.find("?imdb") + 6:]
        try:
            searchResult = imdb.search_movie(title)
            searchResult.fetch()
            movie = searchResult.results[0]
            movie.fetch()
            if len(searchResult.results) < 1:
                r = "I didn't find anything"
            else:
                r = movie.title + " (" + str(movie.year) + ") -- " + movie.plot
        except:
            r = "something went wrong :/"
    """
    ##  Bot driver.
    ##  This will need to be redone in llamabot.py
    if c == "PRIVMSG "+mwaaa.nick and sender in mwaaa.admins:
        r = msg[msg.find("PRIVMSG "+mwaaa.nick)+15:]
    elif c == "PRIVMSG "+mwaaa.nick and msg.find("?say") != -1:
        r = msg[msg.find("?say")+5:]

    """

    ##  Quit.
    if c == "?bye" and sender in mwaaa.admins:
        exit(0)
    if c == mwaaa.updateKey:
        reload(mwaaa)

    return r.encode('utf-8')