Example #1
0
def themoreyouknow(jenni, input):
    from modules.brittbot.helpers import (colors, colorize, colorize_msg)
    themoreyouknow1 = u"The More You Know"
    themoreyouknow2 = u"≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈"
    star = u"★"
    jenni.say(colorize(themoreyouknow1, fg=colors['blue']))
    jenni.say(colorize_msg(themoreyouknow2) + colorize(star, fg=colors['yellow']) )
Example #2
0
def yt_context(jenni, msg):
    import random
    target = msg.groups()[0]
    video_id = parse_qs(urlparse(target).query).get("v")
    obfuscate = parse_qs(urlparse(target).query).get("o")
    if "QrGrOK8oZG8" in video_id and msg.nick == "demophoon":
        obfuscate = True
    if not obfuscate is None:
        video_id = [random.choice([
            # Maru
            "bXtHwvp7jYE",
            "8uDuls5TyNE",
            "jgxL-PwmY7s",
            "euCG3jbefH8",
            "6lC2lbeY_rU",
            "VKQtwvKa-aY",
            "AeJX7fxz-f4",
            # Music videos
            #"gy1B3agGNxw",
        ])]
    if not video_id:
        video_id = [urlparse(target).path[1:]]
    yt = get_video_information(video_id[0], jenni.config.youtube_api_key)
    if yt:
        if not obfuscate is None:
            yt['shorturl'] = "http://youtu.be/" + parse_qs(urlparse(target).query).get("v")[0]
        youtube = colorize("You", fg=colors['black'], bg=colors['white'])
        youtube += colorize("Tube", fg=colors['white'], bg=colors['red'])
        jenni.say("%s \"%s\" (%s) by %s - %s" % (
            youtube,
            yt['title'],
            yt['duration'],
            yt['author'],
            yt['shorturl'],
        ))
Example #3
0
def trivia(jenni, msg):
    global cached_questions
    global last_question_asked
    init_trivia_brain(jenni)
    chan = msg.sender
    if chan not in trivia_rooms:
        if trivia_room not in jenni.channels:
            jenni.write(['JOIN', trivia_room])
            time.sleep(.5)
            jenni.write(['MODE', trivia_room, "+i"])
            jenni.channels.append(trivia_room)
        jenni.reply("Join %s" % (trivia_room))
        jenni.write(['INVITE', msg.nick, trivia_room])
        return
    rooms = jenni.brain['trivia']['rooms']
    if chan not in rooms:
        rooms[chan] = {
            'category': None,
            'question': None,
            'answer': None,
            'hint': [],
            'attempts': 0,
            'noplay': [],
            'noplay_hostmask': [],
        }
    points = None
    if not rooms[chan]['question']:
        while len(cached_questions) <= 1:
            count = 50
            questions = json.loads(
                urllib.urlopen("http://jservice.io/api/random?count=%s" %
                               (count, )).read())
            for question in questions:
                if not question['value']:
                    continue
                if "http" in question['answer']:
                    continue
                cached_questions.append(question)
    if not rooms[chan]['question']:
        last_question_asked = time.time()
        question = cached_questions.pop()
        rooms[chan]['category'] = question['category']['title']
        rooms[chan]['question'] = question['question']
        rooms[chan]['answer'] = question['answer']
        rooms[chan]['attempts'] = 1
        rooms[chan]['hint'] = []
        rooms[chan]['noplay'] = []
        rooms[chan]['noplay_hostmask'] = []
    if not points:
        points = 1000
    print "%s points" % (points, )
    rooms[chan]['answer'] = rooms[chan]['answer'].replace("<i>", "")
    rooms[chan]['answer'] = rooms[chan]['answer'].replace("</i>", "")
    rooms[chan]['answer'] = rooms[chan]['answer'].replace("\"", "")
    reply = "The category is \"%s\". %s" % (
        colorize(rooms[chan]['category'], fg=colors['orange']),
        colorize(rooms[chan]['question'], fg=colors['orange']),
    )
    jenni.write(['PRIVMSG', msg.sender, ":%s" % reply])
    jenni.brain.save()
Example #4
0
def trivia(jenni, msg):
    global cached_questions
    global last_question_asked
    init_trivia_brain(jenni)
    chan = msg.sender
    if chan not in trivia_rooms:
        if trivia_room not in jenni.channels:
            jenni.write(['JOIN', trivia_room])
            time.sleep(.5)
            jenni.write(['MODE', trivia_room, "+i"])
            jenni.channels.append(trivia_room)
        jenni.reply("Join %s" % (trivia_room))
        jenni.write(['INVITE', msg.nick, trivia_room])
        return
    rooms = jenni.brain['trivia']['rooms']
    if chan not in rooms:
        rooms[chan] = {
            'category': None,
            'question': None,
            'answer': None,
            'hint': [],
            'attempts': 0,
            'noplay': [],
            'noplay_hostmask': [],
        }
    points = None
    if not rooms[chan]['question']:
        while len(cached_questions) <= 1:
            count = 50
            questions = json.loads(
                urllib.urlopen("http://jservice.io/api/random?count=%s" % (count, )).read())
            for question in questions:
                if not question['value']:
                    continue
                if "http" in question['answer']:
                    continue
                cached_questions.append(question)
    if not rooms[chan]['question']:
        last_question_asked = time.time()
        question = cached_questions.pop()
        rooms[chan]['category'] = question['category']['title']
        rooms[chan]['question'] = question['question']
        rooms[chan]['answer'] = question['answer']
        rooms[chan]['attempts'] = 1
        rooms[chan]['hint'] = []
        rooms[chan]['noplay'] = []
        rooms[chan]['noplay_hostmask'] = []
    if not points:
        points = 1000
    print "%s points" % (points, )
    rooms[chan]['answer'] = rooms[chan]['answer'].replace("<i>", "")
    rooms[chan]['answer'] = rooms[chan]['answer'].replace("</i>", "")
    rooms[chan]['answer'] = rooms[chan]['answer'].replace("\"", "")
    reply = "The category is \"%s\". %s" % (
        colorize(rooms[chan]['category'], fg=colors['orange']),
        colorize(rooms[chan]['question'], fg=colors['orange']),
    )
    jenni.write(['PRIVMSG', msg.sender, ":%s" % reply])
    jenni.save_brain()
Example #5
0
def format_track(song_obj):
    track = song_obj.title
    artist = song_obj.artist.name
    # album = song_obj.album
    return "%s by %s" % (
        colorize(track, fg=colors['teal']),
        colorize(artist, fg=colors['teal']),
    )
Example #6
0
def format_track(song_obj):
    track = song_obj.title
    artist = song_obj.artist.name
    # album = song_obj.album
    return "%s by %s" % (
        colorize(track, fg=colors['teal']),
        colorize(artist, fg=colors['teal']),
    )
Example #7
0
def current_song(jenni, msg):
    import random
    if 'lastfm' not in jenni.brain:
        jenni.brain['lastfm'] = {}
    username = msg.groups()[0].strip()
    if username.lower() in ["i"]:
        username = msg.nick
    if username.lower() in ["you", "brittbot"]:
        robot_tracks = {
            'Styx': ['Mr. Roboto'],
            'The Flaming Lips': [
                'Yoshimi Battles the Pink Robots, Part 1',
                'Yoshimi Battles the Pink Robots, Part 2',
                'One More Robot/Sympathy 3000-21',
            ],
            'Daft Punk': [
                'Robot Rock',
                'Harder Better Faster Stronger',
                'Derezzed',
            ],
        }
        artist = random.choice(robot_tracks.keys())
        track = random.choice(robot_tracks[artist])
        track = "%s by %s" % (
            colorize(track, fg=colors['teal']),
            colorize(artist, fg=colors['teal']),
        )
        fmsg = "I am listening to %s right now!" % (
            track,
        )
        jenni.say(fmsg)
        return
    elif username in jenni.brain['lastfm']:
        username = jenni.brain['lastfm'][username]
    if not username:
        username = secret['username']
    user = network.get_user(username)
    current_song = user.get_now_playing()
    fmsg = ""
    recent_tracks_count = 3
    if current_song:
        fmsg += "%s is listening to %s right now! " % (
            username,
            format_track(current_song),
        )
        recent_tracks_count -= 1
    recent_tracks = user.get_recent_tracks()
    tracks = ", ".join([
        format_track(x.track) for x in recent_tracks[:recent_tracks_count]
    ])
    fmsg += "%s recent tracks: %s" % (username, tracks)
    jenni.say(fmsg)
Example #8
0
def current_song(jenni, msg):
    import random
    if 'lastfm' not in jenni.brain:
        jenni.brain['lastfm'] = {}
    username = msg.groups()[0].strip()
    if username.lower() in ["i"]:
        username = msg.nick
    if username.lower() in ["you", "brittbot"]:
        robot_tracks = {
            'Styx': ['Mr. Roboto'],
            'The Flaming Lips': [
                'Yoshimi Battles the Pink Robots, Part 1',
                'Yoshimi Battles the Pink Robots, Part 2',
                'One More Robot/Sympathy 3000-21',
            ],
            'Daft Punk': [
                'Robot Rock',
                'Harder Better Faster Stronger',
                'Derezzed',
            ],
        }
        artist = random.choice(robot_tracks.keys())
        track = random.choice(robot_tracks[artist])
        track = "%s by %s" % (
            colorize(track, fg=colors['teal']),
            colorize(artist, fg=colors['teal']),
        )
        fmsg = "I am listening to %s right now!" % (track, )
        jenni.say(fmsg)
        return
    elif username in jenni.brain['lastfm']:
        username = jenni.brain['lastfm'][username]
    if not username:
        username = secret['username']
    user = network.get_user(username)
    current_song = user.get_now_playing()
    fmsg = ""
    recent_tracks_count = 3
    if current_song:
        fmsg += "%s is listening to %s right now! " % (
            username,
            format_track(current_song),
        )
        recent_tracks_count -= 1
    recent_tracks = user.get_recent_tracks()
    tracks = ", ".join(
        [format_track(x.track) for x in recent_tracks[:recent_tracks_count]])
    fmsg += "%s recent tracks: %s" % (username, tracks)
    jenni.say(fmsg)
Example #9
0
def ping_users(jenni, msg):
    import random
    from modules.brittbot.helpers import (colors, colorize)
    setup_brain(jenni, msg)
    topic = msg.groups()[0].strip()
    normalized_topic = topic.lower()
    if normalized_topic not in jenni.brain['ping'][msg.sender]:
        jenni.reply('Invalid topic')
        return
    jenni.brain['ping'][msg.sender][normalized_topic] = list(
        set(jenni.brain['ping'][msg.sender][normalized_topic]))
    pings = ', '.join(jenni.brain['ping'][msg.sender][normalized_topic])
    replies = [
        "IT IS TIME FOR {topic}, ",
        "{topic}?",
        "You all have been summoned for {topic}.",
        "Join me on a quest for {topic}.",
        "{topic}! {topic}! {topic}!",
        "I cannot hear you over the sound of my {topic}.",
        "Ring ring! {topic} is calling!",
        "Anybody want some {topic}?",
        "TACO BELL! uh.. I mean {topic}...",
        "May the {topic} be with you.",
        "Show me the {topic}.",
        "Needs more {topic}.",
        "You can't handle the {topic}!",
        "We're gonna need a bigger {topic}.",
        "BEEP BOOP {topic}!",
        "I feel the need, the need for {topic}!",
    ]
    reply = random.choice(replies) + " {users}"
    jenni.say(
        reply.format(topic=colorize(topic, fg=colors['cyan']), users=pings))
Example #10
0
def ping_users(jenni, msg):
    import random
    from modules.brittbot.helpers import (colors, colorize)
    setup_brain(jenni, msg)
    topic = msg.groups()[0].strip()
    if topic not in jenni.brain['ping'][msg.sender]:
        jenni.reply('Invalid topic')
        return
    pings = ', '.join(jenni.brain['ping'][msg.sender][topic])
    replies = [
        "IT IS TIME FOR {topic}, ",
        "{topic}?",
        "You all have been summoned for {topic}.",
        "Join me on a quest for {topic}.",
        "{topic}! {topic}! {topic}!",
        "I cannot hear you over the sound of my {topic}.",
        "Ring ring! {topic} is calling!",
        "Anybody want some {topic}?",
        "TACO BELL! uh.. I mean {topic}...",
        "May the {topic} be with you.",
        "Show me the {topic}.",
        "Needs more {topic}.",
        "You can't handle the {topic}!",
        "We're gonna need a bigger {topic}.",
        "BEEP BOOP {topic}!",
        "I feel the need, the need for {topic}!",
    ]
    reply = random.choice(replies) + " {users}"
    jenni.say(reply.format(topic=colorize(topic, fg=colors['cyan']), users=pings))
Example #11
0
def yt_context(jenni, input):
    target = input.groups()[0]
    print target
    video_id = parse_qs(urlparse(target).query).get("v")
    if not video_id:
        video_id = [urlparse(target).path[1:]]
    yt = get_video_information(video_id[0], jenni.config.youtube_api_key)
    if yt:
        youtube = colorize("You", fg=colors['black'], bg=colors['white'])
        youtube += colorize("Tube", fg=colors['white'], bg=colors['red'])
        jenni.say("%s \"%s\" (%s) by %s - %s" % (
            youtube,
            yt['title'],
            yt['duration'],
            yt['author'],
            yt['shorturl'],
        ))
Example #12
0
def rainbowizebg(jenni, msg):
    rmsg = msg.groups()[0]
    final = unicode()
    rainbow = ["red", "orange", "yellow", "green", "cyan", "blue", "purple"]
    starting_index = random.choice(range(len(rainbow)))
    for index, char in enumerate(rmsg):
        rindex = index + starting_index
        final += colorize(char, fg=colors["black"], bg=colors[rainbow[rindex % len(rainbow)]])
    jenni.write(["PRIVMSG", msg.sender, u":{}".format(final)])
Example #13
0
def g(jenni, input):
    """Queries Google for the specified input."""
    from modules.brittbot.helpers import (
        colorize,
        colors,
    )
    query = input.group(2)
    if not query:
        return jenni.reply('.g what?')
    query = query.encode('utf-8')
    uri = google_search(query)
    if uri:
        if 'wikipedia.org/' in uri:
            uri = uri.replace('http:', 'https:')
        jenni.reply("{}: {}".format(
            colorize("G", fg=colors['light blue']) +
            colorize("o", fg=colors['red']) +
            colorize("o", fg=colors['yellow']) +
            colorize("g", fg=colors['light blue']) +
            colorize("l", fg=colors['light green']) +
            colorize("e", fg=colors['red']), uri))
        if not hasattr(jenni, 'last_seen_uri'):
            jenni.bot.last_seen_uri = {}
        jenni.bot.last_seen_uri[input.sender] = uri
    elif uri is False:
        jenni.reply("Problem getting data from Google.")
    else:
        jenni.reply("No results found for '%s'." % query)
Example #14
0
def g(jenni, input):
    """Queries Google for the specified input."""
    from modules.brittbot.helpers import (
        colorize,
        colors,
    )
    query = input.group(2)
    if not query:
        return jenni.reply('.g what?')
    query = query.encode('utf-8')
    uri = google_search(query)
    if uri:
        if 'wikipedia.org/' in uri:
            uri = uri.replace('http:', 'https:')
        jenni.reply("{}: {}".format(
            colorize("G", fg=colors['light blue']) +
            colorize("o", fg=colors['red']) +
            colorize("o", fg=colors['yellow']) +
            colorize("g", fg=colors['light blue']) +
            colorize("l", fg=colors['light green']) +
            colorize("e", fg=colors['red']),
            uri))
        if not hasattr(jenni, 'last_seen_uri'):
            jenni.bot.last_seen_uri = {}
        jenni.bot.last_seen_uri[input.sender] = uri
    elif uri is False:
        jenni.reply("Problem getting data from Google.")
    else:
        jenni.reply("No results found for '%s'." % query)
Example #15
0
def yt_context(jenni, msg):
    import random
    target = msg.groups()[0]
    video_id = parse_qs(urlparse(target).query).get("v")
    obfuscate = parse_qs(urlparse(target).query).get("o")
    if video_id and "QrGrOK8oZG8" in video_id and msg.nick == "demophoon":
        obfuscate = True
    if not obfuscate is None:
        video_id = [
            random.choice([
                # Maru
                "bXtHwvp7jYE",
                "8uDuls5TyNE",
                "jgxL-PwmY7s",
                "euCG3jbefH8",
                "6lC2lbeY_rU",
                "VKQtwvKa-aY",
                "AeJX7fxz-f4",
                # Music videos
                #"gy1B3agGNxw",
            ])
        ]
    if not video_id:
        video_id = [urlparse(target).path[1:]]
    yt = get_video_information(video_id[0], jenni.config.youtube_api_key)
    if yt:
        if not obfuscate is None:
            yt['shorturl'] = "http://youtu.be/" + parse_qs(
                urlparse(target).query).get("v")[0]
        youtube = colorize("You", fg=colors['black'], bg=colors['white'])
        youtube += colorize("Tube", fg=colors['white'], bg=colors['red'])
        jenni.say("%s \"%s\" (%s) by %s - %s" % (
            youtube,
            yt['title'],
            yt['duration'],
            yt['author'],
            yt['shorturl'],
        ))
Example #16
0
def rainbowizebg(jenni, msg):
    rmsg = msg.groups()[0]
    final = unicode()
    rainbow = [
        'red',
        'orange',
        'yellow',
        'green',
        'cyan',
        'blue',
        'purple',
    ]
    starting_index = random.choice(range(len(rainbow)))
    for index, char in enumerate(rmsg):
        rindex = index + starting_index
        final += colorize(
            char,
            fg=colors['black'],
            bg=colors[rainbow[rindex % len(rainbow)]],
        )
    jenni.write(['PRIVMSG', msg.sender, ":{}".format(final)])
Example #17
0
def rainbowizebg(jenni, msg):
    rmsg = msg.groups()[0]
    final = unicode()
    rainbow = [
        'red',
        'orange',
        'yellow',
        'green',
        'cyan',
        'blue',
        'purple',
    ]
    starting_index = random.choice(range(len(rainbow)))
    for index, char in enumerate(rmsg):
        rindex = index + starting_index
        final += colorize(
            char,
            fg=colors['black'],
            bg=colors[rainbow[rindex % len(rainbow)]],
        )
    jenni.write(['PRIVMSG', msg.sender, u":{}".format(final)])
Example #18
0
def xofthey(jenni, msg):
    now = datetime.datetime.utcnow()
    durations = {
        'millisecond': relativedelta(microseconds=1),
        'microsecond': relativedelta(microseconds=1),
        'second': relativedelta(seconds=1),
        'minute': relativedelta(minutes=1),
        'hour': relativedelta(hours=1),
        'day': relativedelta(days=1),
        'week': relativedelta(weeks=1),
        'month': relativedelta(months=1),
        'year': relativedelta(years=1),
        'decade': relativedelta(years=10),
        'century': relativedelta(years=100),
        'millennium': relativedelta(years=1000),
    }
    x = msg.groups()[0].strip()
    y = msg.groups()[1].strip()
    item = msg.groups()[2]
    if x == 'gay':
        return
    if 'ofthe' not in jenni.brain:
        jenni.brain['ofthe'] = {}
    rekt_dict = jenni.brain['ofthe']
    if x not in rekt_dict:
        rekt_dict[x] = {}
    if y not in rekt_dict[x]:
        rekt_dict[x][y] = {}
    if msg.sender not in rekt_dict[x][y]:
        rekt_dict[x][y][msg.sender] = []
    expires = None
    if durations.get(y):
        expires = now + durations.get(y)
    if item:
        if expires:
            rekt_dict[x][y][msg.sender].append({
                'item': item.strip(),
                'created': time.mktime(now.timetuple()),
                'expires': time.mktime(expires.timetuple()),
            })
        else:
            rekt_dict[x][y][msg.sender].append(item.strip())
        jenni.brain.save()
    try:
        rekt = jenni.brain['ofthe'][x][y][msg.sender][-1]
        expires = None
        if isinstance(rekt, dict):
            expires = rekt['expires']
            if time.mktime(now.timetuple()) > expires:
                reply = "I need a new {} of the {}. It was {}.".format(
                    x,
                    y,
                    colorize(rekt['item'], fg=colors['red']),
                )
                jenni.write(['PRIVMSG', msg.sender, ":{}".format(reply)])
                return
            rekt = rekt['item']
    except Exception:
        return
    reply = "The {} of the {} is {}.".format(
        x,
        y,
        colorize(rekt, fg=colors['red']),
    )
    if expires:
        reply += ' (Expires in {})'.format(
            elapsed(expires - time.mktime(now.timetuple())).strip()
        )
    jenni.write(['PRIVMSG', msg.sender, ":{}".format(reply)])
Example #19
0
def trivia_answer(jenni, msg):
    global last_question_asked
    if time.time() - last_question_asked < 2:
        return
    import string
    hint_chars = string.letters + string.digits + " "
    hostmask = (msg.nick, msg.origin.user, msg.origin.host)
    chan = msg.sender
    if chan not in trivia_rooms:
        return
    rooms = jenni.brain['trivia']['rooms']
    init_user_brain(jenni, msg.nick)

    if chan not in rooms:
        return
    if not rooms[chan]['question']:
        return
    ignored_words = [
        'the',
        'i',
        'a',
        'an',
        'accepted',
        'or',
        'he',
        'his',
        'her',
        'hers',
        'and',
    ]
    pattern = re.compile("[\W]+")

    if jenni.brain['trivia']['users'][msg.nick]['banned'] > 1:
        return
    guess = msg.groups()[0].lower()
    guess = ''.join(x for x in guess if x in hint_chars)
    guess = [pattern.sub('', y) for y in guess.split(" ") if y not in ignored_words]
    guess = [x for x in guess if x]
    answer = rooms[chan]['answer'].lower()
    answer = ''.join(x for x in answer if x in hint_chars)
    answer = [pattern.sub('', y)
              for y in answer.split(" ") if y not in ignored_words]
    correct = float(sum([x in answer for x in guess]))
    correct = max(correct, float(sum([x in ''.join(answer) for x in guess])))

    drop_lol = ['drop', 'table', 'answers']
    if all([x in drop_lol for x in guess]) and msg.admin:
        reply = "Shutting down."
        jenni.write(['NOTICE', msg.sender, ":%s" % reply])
        exit()
        return

    correctness_threshold = .5

    if correct / len(answer) >= correctness_threshold:
        if msg.nick in rooms[chan]['noplay']:
            jenni.reply("Thanks for ruining the game."
                        " Yes. The answer is \"%s\" but you "
                        "cheated to find out. This is your last warning." %
                        (rooms[chan]['answer']))
            jenni.brain['trivia']['users'][msg.nick]['banned'] += 1
            if jenni.brain['trivia']['users'][msg.nick]['banned'] > 1:
                kickmsg = "No cheating allowed. Contact `demophoon` to be forgiven"
                jenni.write(['MODE', msg.sender, "+b", "%s!%s@%s" % hostmask])
                jenni.write(['KICK', msg.sender, msg.nick, ":%s" % kickmsg])
            rooms[chan]['question'] = None
        else:
            jenni.reply("You are %s! The answer is %s. W/L %d/%d" % (
                colorize("correct", fg=colors['green']),
                rooms[chan]['answer'],
                jenni.brain['trivia']['users'][msg.nick]['correct'],
                jenni.brain['trivia']['users'][msg.nick]['incorrect'],
            ))
            rooms[chan]['question'] = None
            jenni.brain['trivia']['users'][msg.nick]['correct'] += 1
    elif rooms[chan]['attempts'] <= 0:
        jenni.reply("You are %s. The correct answer is %s" % (
            colorize("incorrect", fg=colors['red']),
            rooms[chan]['answer']
        ))
        jenni.brain['trivia']['users'][msg.nick]['incorrect'] += 1
        rooms[chan]['question'] = None
    else:
        jenni.reply("You are %s. %s more attempts" % (
            colorize("incorrect", fg=colors['red']),
            rooms[chan]['attempts']
        ))
        jenni.brain['trivia']['users'][msg.nick]['incorrect'] += 1
        rooms[chan]['attempts'] -= 1
    if msg.sender in trivia_rooms and not rooms[chan]['question']:
        trivia(jenni, msg)
    jenni.brain.save()
Example #20
0
def trivia(jenni, msg):
    init_trivia_brain(jenni)
    chan = msg.sender
    if chan not in trivia_rooms:
        if trivia_room not in jenni.channels:
            jenni.write(['JOIN', trivia_room])
            time.sleep(.5)
            jenni.write(['MODE', trivia_room, "+i"])
            jenni.channels.append(trivia_room)
        jenni.reply("Join %s" % (trivia_room))
        jenni.write(['INVITE', msg.nick, trivia_room])
        return
    rooms = jenni.brain['trivia']['rooms']
    if chan not in rooms:
        rooms[chan] = {
            'category': None,
            'question': None,
            'answer': None,
            'attempts': 0,
            'noplay': [],
            'noplay_hostmask': [],
        }
    points = None
    if not rooms[chan]['question']:
        while not rooms[chan]['question']:
            count = 1
            if chan != trivia_room:
                count = 25
                count = 1
            questions = json.loads(
                urllib.urlopen("http://jservice.io/api/random?count=%s" % (count, )).read())
            for question in questions:
                if not question['value']:
                    continue
                if not points:
                    points = int(question['value'])
                current_points = int(question['value'])
                if chan != trivia_room:
                    current_points *= float(len(question['question']))
                    current_points += len(question['answer'].split(' '))
                    current_points /= len(question['answer'])
                if current_points >= points:
                    points = current_points
                    rooms[chan]['category'] = question['category']['title']
                    rooms[chan]['question'] = question['question']
                    rooms[chan]['answer'] = question['answer']
                    rooms[chan]['attempts'] = 1
        rooms[chan]['noplay'] = []
        rooms[chan]['noplay_hostmask'] = []
    if not points:
        points = 1000
    print "%s points" % (points, )
    rooms[chan]['answer'] = rooms[chan]['answer'].replace("<i>", "")
    rooms[chan]['answer'] = rooms[chan]['answer'].replace("</i>", "")
    rooms[chan]['answer'] = rooms[chan]['answer'].replace("\"", "")
    reply = "The category is \"%s\". %s" % (
        colorize(rooms[chan]['category'], fg=colors['orange']),
        colorize(rooms[chan]['question'], fg=colors['orange']),
    )
    jenni.write(['PRIVMSG', msg.sender, ":%s" % reply])
    jenni.save_brain()
Example #21
0
def xofthey(jenni, msg):
    now = datetime.datetime.utcnow()
    durations = {
        'millisecond': relativedelta(microseconds=1),
        'microsecond': relativedelta(microseconds=1),
        'second': relativedelta(seconds=1),
        'minute': relativedelta(minutes=1),
        'hour': relativedelta(hours=1),
        'day': relativedelta(days=1),
        'week': relativedelta(weeks=1),
        'month': relativedelta(months=1),
        'year': relativedelta(years=1),
        'decade': relativedelta(years=10),
        'century': relativedelta(years=100),
        'millennium': relativedelta(years=1000),
    }
    x = msg.groups()[0].strip()
    y = msg.groups()[1].strip()
    item = msg.groups()[2]
    if x == 'gay':
        return
    if 'ofthe' not in jenni.brain:
        jenni.brain['ofthe'] = {}
    rekt_dict = jenni.brain['ofthe']
    if x not in rekt_dict:
        rekt_dict[x] = {}
    if y not in rekt_dict[x]:
        rekt_dict[x][y] = {}
    if msg.sender not in rekt_dict[x][y]:
        rekt_dict[x][y][msg.sender] = []
    expires = None
    if durations.get(y):
        expires = now + durations.get(y)
    if item:
        if expires:
            rekt_dict[x][y][msg.sender].append({
                'item': item.strip(),
                'created': time.mktime(now.timetuple()),
                'expires': time.mktime(expires.timetuple()),
            })
        else:
            rekt_dict[x][y][msg.sender].append(item.strip())
        jenni.brain.save()
    try:
        rekt = jenni.brain['ofthe'][x][y][msg.sender][-1]
        expires = None
        if isinstance(rekt, dict):
            expires = rekt['expires']
            if time.mktime(now.timetuple()) > expires:
                reply = "I need a new {} of the {}. It was {}.".format(
                    x,
                    y,
                    colorize(rekt['item'], fg=colors['red']),
                )
                jenni.write(['PRIVMSG', msg.sender, ":{}".format(reply)])
                return
            rekt = rekt['item']
    except Exception:
        return
    reply = "The {} of the {} is {}.".format(
        x,
        y,
        colorize(rekt, fg=colors['red']),
    )
    if expires:
        reply += ' (Expires in {})'.format(
            elapsed(expires - time.mktime(now.timetuple())).strip()
        )
    jenni.write(['PRIVMSG', msg.sender, ":{}".format(reply)])
Example #22
0
def trivia_answer(jenni, msg):
    global last_question_asked
    if time.time() - last_question_asked < 2:
        return
    import string
    hint_chars = string.letters + string.digits + " "
    hostmask = (msg.nick, msg.origin.user, msg.origin.host)
    chan = msg.sender
    if chan not in trivia_rooms:
        return
    rooms = jenni.brain['trivia']['rooms']
    init_user_brain(jenni, msg.nick)

    if chan not in rooms:
        return
    if not rooms[chan]['question']:
        return
    ignored_words = [
        'the',
        'i',
        'a',
        'an',
        'accepted',
        'or',
        'he',
        'his',
        'her',
        'hers',
        'and',
    ]
    pattern = re.compile("[\W]+")

    if jenni.brain['trivia']['users'][msg.nick]['banned'] > 1:
        return
    guess = msg.groups()[0].lower()
    guess = ''.join(x for x in guess if x in hint_chars)
    guess = [
        pattern.sub('', y) for y in guess.split(" ") if y not in ignored_words
    ]
    guess = [x for x in guess if x]
    answer = rooms[chan]['answer'].lower()
    answer = ''.join(x for x in answer if x in hint_chars)
    answer = [
        pattern.sub('', y) for y in answer.split(" ") if y not in ignored_words
    ]
    correct = float(sum([x in answer for x in guess]))
    correct = max(correct, float(sum([x in ''.join(answer) for x in guess])))

    drop_lol = ['drop', 'table', 'answers']
    if all([x in drop_lol for x in guess]) and msg.admin:
        reply = "Shutting down."
        jenni.write(['NOTICE', msg.sender, ":%s" % reply])
        exit()
        return

    correctness_threshold = .5

    if correct / len(answer) >= correctness_threshold:
        if msg.nick in rooms[chan]['noplay']:
            jenni.reply("Thanks for ruining the game."
                        " Yes. The answer is \"%s\" but you "
                        "cheated to find out. This is your last warning." %
                        (rooms[chan]['answer']))
            jenni.brain['trivia']['users'][msg.nick]['banned'] += 1
            if jenni.brain['trivia']['users'][msg.nick]['banned'] > 1:
                kickmsg = "No cheating allowed. Contact `demophoon` to be forgiven"
                jenni.write(['MODE', msg.sender, "+b", "%s!%s@%s" % hostmask])
                jenni.write(['KICK', msg.sender, msg.nick, ":%s" % kickmsg])
            rooms[chan]['question'] = None
        else:
            jenni.reply("You are %s! The answer is %s. W/L %d/%d" % (
                colorize("correct", fg=colors['green']),
                rooms[chan]['answer'],
                jenni.brain['trivia']['users'][msg.nick]['correct'],
                jenni.brain['trivia']['users'][msg.nick]['incorrect'],
            ))
            rooms[chan]['question'] = None
            jenni.brain['trivia']['users'][msg.nick]['correct'] += 1
    elif rooms[chan]['attempts'] <= 0:
        jenni.reply(
            "You are %s. The correct answer is %s" %
            (colorize("incorrect", fg=colors['red']), rooms[chan]['answer']))
        jenni.brain['trivia']['users'][msg.nick]['incorrect'] += 1
        rooms[chan]['question'] = None
    else:
        jenni.reply(
            "You are %s. %s more attempts" %
            (colorize("incorrect", fg=colors['red']), rooms[chan]['attempts']))
        jenni.brain['trivia']['users'][msg.nick]['incorrect'] += 1
        rooms[chan]['attempts'] -= 1
    if msg.sender in trivia_rooms and not rooms[chan]['question']:
        trivia(jenni, msg)
    jenni.brain.save()
Example #23
0
def xofthey(jenni, msg):
    now = datetime.datetime.utcnow()
    durations = {
        "millisecond": relativedelta(microseconds=1),
        "microsecond": relativedelta(microseconds=1),
        "second": relativedelta(seconds=1),
        "minute": relativedelta(minutes=1),
        "hour": relativedelta(hours=1),
        "day": relativedelta(days=1),
        "week": relativedelta(weeks=1),
        "month": relativedelta(months=1),
        "year": relativedelta(years=1),
        "decade": relativedelta(years=10),
        "century": relativedelta(years=100),
        "millennium": relativedelta(years=1000),
    }
    x = msg.groups()[0].strip()
    y = msg.groups()[1].strip()
    item = msg.groups()[2]
    if x == "gay":
        return
    if "ofthe" not in jenni.brain:
        jenni.brain["ofthe"] = {}
    rekt_dict = jenni.brain["ofthe"]
    if x not in rekt_dict:
        rekt_dict[x] = {}
    if y not in rekt_dict[x]:
        rekt_dict[x][y] = {}
    if msg.sender not in rekt_dict[x][y]:
        rekt_dict[x][y][msg.sender] = []
    expires = None
    if durations.get(y):
        expires = now + durations.get(y)
    if item:
        if expires:
            rekt_dict[x][y][msg.sender].append(
                {
                    "item": item.strip(),
                    "created": time.mktime(now.timetuple()),
                    "expires": time.mktime(expires.timetuple()),
                }
            )
        else:
            rekt_dict[x][y][msg.sender].append(item.strip())
        jenni.brain.save()
    try:
        rekt = jenni.brain["ofthe"][x][y][msg.sender][-1]
        expires = None
        if isinstance(rekt, dict):
            expires = rekt["expires"]
            if time.mktime(now.timetuple()) > expires:
                reply = "I need a new {} of the {}. It was {}.".format(x, y, colorize(rekt["item"], fg=colors["red"]))
                jenni.write(["PRIVMSG", msg.sender, ":{}".format(reply)])
                return
            rekt = rekt["item"]
    except Exception:
        return
    reply = "The {} of the {} is {}.".format(x, y, colorize(rekt, fg=colors["red"]))
    if expires:
        reply += " (Expires in {})".format(elapsed(expires - time.mktime(now.timetuple())).strip())
    jenni.write(["PRIVMSG", msg.sender, ":{}".format(reply)])