コード例 #1
0
ファイル: youtube.py プロジェクト: cripperz/inumuta-modules
def ytsearch(bot, trigger):
    """
    .youtube <query> - Search YouTube
    """
    if not trigger.group(2):
        return
    uri = 'https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q=' + trigger.group(
        2)
    raw = web.get(uri + '&key=' + bot.config.google.public_key)
    vid = json.loads(raw)['items'][0]['id']['videoId']
    uri = 'https://www.googleapis.com/youtube/v3/videos?id=' + vid + '&part=contentDetails,snippet,statistics'
    video_info = ytget(bot, trigger, uri)
    if video_info is None:
        return

    message = (
        '[YT Search]' + ' Title: ' + video_info['snippet']['title'] +
        ' | Uploader: ' + video_info['snippet']['channelTitle'] +
        ' | Uploaded: ' + video_info['snippet']['publishedAt'] +
        ' | Duration: ' + video_info['contentDetails']['duration'] +
        ' | Views: ' + video_info['statistics']['viewCount'] +
        ' | Comments: ' + video_info['statistics']['commentCount'] + ' | ' +
        color(video_info['statistics']['likeCount'] + '+', colors.GREEN) +
        ' | ' +
        color(video_info['statistics']['dislikeCount'] + '-', colors.RED) +
        ' | Link: https://youtu.be/' + video_info['id'])

    bot.say(message)
コード例 #2
0
def ytsearch(bot, trigger):
    """
    .youtube <query> - Search YouTube
    """
    if not trigger.group(2):
        return
    uri = 'https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q=' + trigger.group(2)
    raw = web.get(uri + '&key=' + bot.config.google.public_key)
    vid = json.loads(raw)['items'][0]['id']['videoId']
    uri = 'https://www.googleapis.com/youtube/v3/videos?id=' + vid + '&part=contentDetails,snippet,statistics'
    video_info = ytget(bot, trigger, uri)
    if video_info is None:
        return

    message = ('[YT Search]' +
              ' Title: ' + video_info['snippet']['title'] +
              ' | Uploader: ' + video_info['snippet']['channelTitle'] +
              ' | Uploaded: ' + video_info['snippet']['publishedAt'] +
              ' | Duration: ' + video_info['contentDetails']['duration'] +
              ' | Views: ' + video_info['statistics']['viewCount'] +
              ' | Comments: ' + video_info['statistics']['commentCount'] +
              ' | ' + color(video_info['statistics']['likeCount'] + '+', colors.GREEN) +
              ' | ' + color(video_info['statistics']['dislikeCount'] + '-', colors.RED) +
              ' | Link: https://youtu.be/' + video_info['id'])

    bot.say(message)
コード例 #3
0
ファイル: adminchannel.py プロジェクト: whonut/willie
def default_mask(trigger):
    welcome = formatting.color('Welcome to:', formatting.colors.PURPLE)
    chan = formatting.color(trigger.sender, formatting.colors.TEAL)
    topic_ = formatting.bold('Topic:')
    topic_ = formatting.color('| ' + topic_, formatting.colors.PURPLE)
    arg = formatting.color('{}', formatting.colors.GREEN)
    return '{} {} {} {}'.format(welcome, chan, topic_, arg)
コード例 #4
0
ファイル: youtube.py プロジェクト: cripperz/inumuta-modules
def ytinfo(bot, trigger, found_match=None):
    """
    Get information about the given youtube video
    """
    match = found_match or trigger
    uri = 'https://www.googleapis.com/youtube/v3/videos?id=' + match.group(
        2) + '&part=contentDetails,snippet,statistics'

    video_info = ytget(bot, trigger, uri)
    if video_info is None:
        return

    message = (
        '[You' + color('Tube', colors.WHITE, colors.RED) + ']' + ' Title: ' +
        video_info['snippet']['title'] + ' | Uploader: ' +
        video_info['snippet']['channelTitle'] + ' | Uploaded: ' +
        video_info['snippet']['publishedAt'] + ' | Duration: ' +
        video_info['contentDetails']['duration'] + ' | Views: ' +
        video_info['statistics']['viewCount'] + ' | Comments: ' +
        video_info['statistics']['commentCount'] + ' | ' +
        color(video_info['statistics']['likeCount'] + '+', colors.GREEN) +
        ' | ' +
        color(video_info['statistics']['dislikeCount'] + '-', colors.RED))

    bot.say(message)
コード例 #5
0
ファイル: osu.py プロジェクト: cripperz/inumuta-modules
def osu_user(bot, trigger):
    """
    .osu [user] - Show information on an osu! user
    """
    data = '?k=%s&u=%s' % (bot.config.osu.api_key, str(trigger.group(2)))
    #bot.say(url)
    raw = web.get('https://osu.ppy.sh/api/get_user' + data)
    response = json.loads(raw)
    if not response:
        bot.say('[' + color('osu!', u'13') + '] ' + 'Invalid user')
        return
    if not response[0]:
        bot.say('[' + color('osu!', u'13') + '] ' + 'Invalid user')
        return
    user = response[0]
    level = 0
    accuracy = 0
    try:
        level = int(float(user['level']))
        accuracy = int(float(user['accuracy']))
    except:
        pass
    output = [
        '[',
        color('osu!', u'13'), '] ',
        str(user['username']), ' | Level ',
        str(level), ' | Rank ',
        str(user['pp_rank']), ' | Play Count ',
        str(user['playcount']), ' | Ranked Score ',
        str(user['ranked_score']), ' | Total Score ',
        str(user['total_score']), ' | Accuracy ~',
        str(accuracy), '%'
    ]
    bot.say(''.join(output))
コード例 #6
0
def osu_beatmap(bot, trigger):
    data = '?k=%s&%s=%s' % (bot.config.osu.api_key, str(trigger.group(1)), str(trigger.group(2)))
    #bot.say(url)
    raw = web.get('https://osu.ppy.sh/api/get_beatmaps' + data)
    topscore = None
    if trigger.group(1) == 'b':
        rawscore = web.get('https://osu.ppy.sh/api/get_scores' + data)
        topscore = json.loads(rawscore)[0]
    response = json.loads(raw)
    if not response[0]:
        bot.say('[' + color('osu!', u'13') + '] ' + ' Invalid link')
        return
    beatmap = response[0]
    m, s = divmod(int(beatmap['total_length']), 60)
    output = [
        '[', color('osu!', u'13'), '] ',
        beatmap['artist'],
        ' - ',
        beatmap['title'],
        ' (Mapped by ',
        beatmap['creator'],
        ') | ',
        str(m), 'm, ', str(s), 's',
        ' | ',
        beatmap['version'],
        ' | Difficulty: ',
        beatmap['difficultyrating'],
        ' | ',
        beatmap['bpm'],
        ' BPM'
    ]
    if topscore:
        output += (' | High Score: ' + topscore['score'] + ' (' + topscore['rank'] + ') - ' + topscore['username'])
    bot.say(''.join(output))
コード例 #7
0
ファイル: 8ball.py プロジェクト: magicksid/willie-modules
def speakthetruth(bot, trigger, found_match=None):

	n = random.randint(0, 1)

	if n == 0:
		s = []
		s.append("it's pretty obvious the answer is no")
		s.append("negative")
		s.append("NO")
		s.append("obviously not")
		s.append("shake my head to be honest fam")
		s.append("my sources say no")
		msg = color(random.choice(s), '04')

	else:
		s = []
		s.append("that's certainly so")
		s.append("i have no doubt in my mind")
		s.append("YES")
		s.append("of course")
		s.append("it is certain")
		s.append("one would be wise to think so")
		msg = color(random.choice(s), '03')

	bot.action('shakes the magic 8 ball... ' + msg)
コード例 #8
0
ファイル: adminchannel.py プロジェクト: neslinesli93/willie
def default_mask(trigger):
    welcome = formatting.color('Benvenuto su:', formatting.colors.PURPLE)
    chan = formatting.color(trigger.sender, formatting.colors.TEAL)
    topic_ = formatting.bold('Topic:')
    topic_ = formatting.color('| ' + topic_, formatting.colors.PURPLE)
    arg = formatting.color('{}', formatting.colors.GREEN)
    return '{} {} {} {}'.format(welcome, chan, topic_, arg)
コード例 #9
0
def get_data(bot, trigger, URL):
    URL = URL.split('#')[0]
    try:
        raw = fetch_api_endpoint(bot, URL)
        rawLang = fetch_api_endpoint(bot, URL + '/languages')
    except HTTPError:
        bot.say('[Github] API returned an error.')
        return NOLIMIT
    data = json.loads(raw)
    langData = json.loads(rawLang).items()
    langData = sorted(langData, key=operator.itemgetter(1), reverse=True)

    if 'message' in data:
        return bot.say('[Github] %s' % data['message'])

    langColors = deque(['12', '08', '09', '13'])

    max = sum([pair[1] for pair in langData])

    data['language'] = ''
    for (key, val) in langData[:3]:
        data['language'] = data['language'] + color(str("{0:.1f}".format(float(val) / max * 100)) + '% ' + key, langColors[0]) + ' '
        langColors.rotate()

    if len(langData) > 3:
        remainder = sum([pair[1] for pair in langData[3:]])
        data['language'] = data['language'] + color(str("{0:.1f}".format(float(remainder) / max * 100)) + '% Other', langColors[0]) + ' '

    timezone = get_timezone(bot.db, bot.config, None, trigger.nick)
    if not timezone:
        timezone = 'UTC'
    data['pushed_at'] = format_time(bot.db, bot.config, timezone, trigger.nick, trigger.sender, from_utc(data['pushed_at']))

    return data
コード例 #10
0
def ud_search(bot, trigger):
    query = trigger.group(2).strip()
    
    url = 'http://api.urbandictionary.com/v0/define?term=%s' %(query.encode('utf-8'))
    #bot.say(url)
    try:
      response = web.get_urllib_object(url, 20)
    except UnicodeError:
      bot.say('[UrbanDictionary] ENGLISH M**********R, DO YOU SPEAK IT?')
      return
    else:
      data = json.loads(response.read())
      #bot.say(str(data))
    try:
      definition = data['list'][0]['definition'].replace('\n', ' ')
    except KeyError:
      bot.say('[UrbanDictionary] Something went wrong bruh')
    except IndexError:
      bot.say('[UrbanDictionary] No results, do you even spell bruh?')
    else:
      thumbsup = color(str(data['list'][0]['thumbs_up'])+'+', u'03')
      thumbsdown = color(str(data['list'][0]['thumbs_down'])+'-', u'04')
      permalink = data['list'][0]['permalink']
      length = len(thumbsup)+len(thumbsdown)+len(permalink)+35
      ellipsies = ''
      if (len(definition)+length) > 445:
        ellipsies = '...'
      udoutput = "[UrbanDictionary] %s; %.*s%s | %s >> %s %s" % (query, 445-length, definition, ellipsies, permalink, thumbsup, thumbsdown)
      if not "spam spam" in udoutput:
          bot.say(udoutput)
      else:
          bot.say('[UrbanDictionary] Negative ghostrider')
コード例 #11
0
ファイル: osu.py プロジェクト: cripperz/inumuta-modules
def osu_beatmap(bot, trigger):
    data = '?k=%s&%s=%s' % (bot.config.osu.api_key, str(
        trigger.group(1)), str(trigger.group(2)))
    #bot.say(url)
    raw = web.get('https://osu.ppy.sh/api/get_beatmaps' + data)
    topscore = None
    if trigger.group(1) == 'b':
        rawscore = web.get('https://osu.ppy.sh/api/get_scores' + data)
        topscore = json.loads(rawscore)[0]
    response = json.loads(raw)
    if not response[0]:
        bot.say('[' + color('osu!', u'13') + '] ' + ' Invalid link')
        return
    beatmap = response[0]
    m, s = divmod(int(beatmap['total_length']), 60)
    output = [
        '[',
        color('osu!', u'13'), '] ', beatmap['artist'], ' - ', beatmap['title'],
        ' (Mapped by ', beatmap['creator'], ') | ',
        str(m), 'm, ',
        str(s), 's', ' | ', beatmap['version'], ' | Difficulty: ',
        beatmap['difficultyrating'], ' | ', beatmap['bpm'], ' BPM'
    ]
    if topscore:
        output += (' | High Score: ' + topscore['score'] + ' (' +
                   topscore['rank'] + ') - ' + topscore['username'])
    bot.say(''.join(output))
コード例 #12
0
ファイル: osu.py プロジェクト: meew0/inumuta-modules
def osu_user(bot, trigger):
    """
    .osu [user] - Show information on an osu! user
    """
    data = '?k=%s&u=%s' % (bot.config.osu.api_key, str(trigger.group(2)))
    #bot.say(url)
    raw = web.get('https://osu.ppy.sh/api/get_user'+data)
    response = json.loads(raw)
    if not response[0]:
        bot.say('['+color('osu!', u'13')+'] '+'Invalid user')
        return
    user = response[0]
    output = [
        '[', color('osu!', u'13'), '] ',
        user['username'],
        ' | Level ',
        str(int(float(user['level']))),
        ' | Rank ',
        user['pp_rank'],
        ' | Play Count ',
        user['playcount'],
        ' | Ranked Score ',
        user['ranked_score'],
        ' | Total Score ',
        user['total_score'],
        ' | Accuracy ~',
        str(int(float(user['accuracy']))),
        '%'
    ]
    bot.say(''.join(output))
コード例 #13
0
ファイル: modsio.py プロジェクト: cripperz/inumuta-modules
def get_page_info(bot, trigger):
    requested = get_info(trigger.group(1))
    if requested is None:
        bot.say('{} Error: Mod does not exist.'.format(get_prefix()))
    message = '{} {} - {} {} Latest: {}'.format(
        get_prefix(), color(requested['mod']['name'],
                            'red'), requested['mod']['tagline'],
        color('|', 'red'), requested['current_version']['name'])
    bot.say(message)
コード例 #14
0
ファイル: rip.py プロジェクト: madprops/willie-modules
def rip(bot, trigger, found_match=None):
    arg = " ".join(trigger[4:50].split()).strip()
    if arg == "":
        return
    bot.say(
        color(u"✞" + " " + u"✞" + " " u"✞" + " " u"✞" + " ", "04", "00")
        + color(" " + arg.upper() + " ", "00", "04")
        + color(" " + u"✞" + " " + u"✞" + " " u"✞" + " " u"✞", "04", "00")
    )
コード例 #15
0
def rpost_info(bot, trigger, match=None):
    r = praw.Reddit(user_agent=USER_AGENT)
    match = match or trigger
    s = r.get_submission(url=match.group(1))

    message = ('[REDDIT] {title} {link}{nsfw} | {points} points ({percent}) | '
               '{comments} comments | Posted by {author} | '
               'Created at {created}')

    if s.is_self:
        link = '(self.{})'.format(s.subreddit.display_name)
    else:
        link = '({}) to r/{}'.format(s.url, s.subreddit.display_name)

    if s.over_18:
        nsfw = bold(color(' [NSFW]', colors.RED))
        sfw = bot.db.get_channel_value(trigger.sender, 'sfw')
        if sfw:
            link = '(link hidden)'
            bot.write([
                'KICK', trigger.sender, trigger.nick,
                'Linking to NSFW content in a SFW channel.'
            ])
    else:
        nsfw = ''

    if s.author:
        author = s.author.name
    else:
        author = '[deleted]'

    tz = time.get_timezone(bot.db, bot.config, None, trigger.nick,
                           trigger.sender)
    time_created = dt.datetime.utcfromtimestamp(s.created_utc)
    created = time.format_time(bot.db, bot.config, tz, trigger.nick,
                               trigger.sender, time_created)

    if s.score > 0:
        point_color = colors.GREEN
    else:
        point_color = colors.RED

    percent = color(unicode(s.upvote_ratio * 100) + '%', point_color)

    h = HTMLParser.HTMLParser()
    message = message.format(title=h.unescape(s.title),
                             link=link,
                             nsfw=nsfw,
                             points=s.score,
                             percent=percent,
                             comments=s.num_comments,
                             author=author,
                             created=created)

    bot.say(message)
コード例 #16
0
def rpost_info(bot, trigger, match=None):
    r = praw.Reddit(user_agent=USER_AGENT)
    match = match or trigger
    s = r.get_submission(url=match.group(1))

    message = (
        "[REDDIT] {title} {link}{nsfw} | {points} points ({percent}) | "
        "{comments} comments | Posted by {author} | "
        "Created at {created}"
    )

    if s.is_self:
        link = "(self.{})".format(s.subreddit.display_name)
    else:
        link = "({}) to r/{}".format(s.url, s.subreddit.display_name)

    if s.over_18:
        nsfw = bold(color(" [NSFW]", colors.RED))
        sfw = bot.db.get_channel_value(trigger.sender, "sfw")
        if sfw:
            link = "(link hidden)"
            bot.write(["KICK", trigger.sender, trigger.nick, "Linking to NSFW content in a SFW channel."])
    else:
        nsfw = ""

    if s.author:
        author = s.author.name
    else:
        author = "[deleted]"

    tz = time.get_timezone(bot.db, bot.config, None, trigger.nick, trigger.sender)
    time_created = dt.datetime.utcfromtimestamp(s.created_utc)
    created = time.format_time(bot.db, bot.config, tz, trigger.nick, trigger.sender, time_created)

    if s.score > 0:
        point_color = colors.GREEN
    else:
        point_color = colors.RED

    percent = color(unicode(s.upvote_ratio * 100) + "%", point_color)

    h = HTMLParser.HTMLParser()
    message = message.format(
        title=h.unescape(s.title),
        link=link,
        nsfw=nsfw,
        points=s.score,
        percent=percent,
        comments=s.num_comments,
        author=author,
        created=created,
    )

    bot.say(message)
コード例 #17
0
def rpost_info(bot, trigger, match=None):
    r = praw.Reddit(user_agent=USER_AGENT)
    match = match or trigger
    s = r.get_submission(url=match.group(1))

    if (comment_regex.match(match.group(0))):
        return rcomment_info(bot, trigger, s)

    message = ('[REDDIT] {title} {link}{nsfw} | {points} points ({percent}) | '
               '{comments} comments | Posted by {author} | '
               'Created at {created}')

    if s.is_self:
        link = '(self.{})'.format(s.subreddit.display_name)
    else:
        link = '({}) to /r/{}'.format(s.url, s.subreddit.display_name)

    if s.over_18:
        nsfw = bold(color(' [NSFW]', colors.RED))
        sfw = bot.db.get_channel_value(trigger.sender, 'sfw')
        if sfw:
            link = '(link hidden)'
            bot.write(['KICK', trigger.sender, trigger.nick,
                       'Linking to NSFW content in a SFW channel.'])
    else:
        nsfw = ''

    if s.author:
        author = s.author.name
    else:
        author = '[deleted]'

    tz = time.get_timezone(bot.db, bot.config, None, trigger.nick,
                           trigger.sender)
    time_created = dt.datetime.utcfromtimestamp(s.created_utc)
    created = time.format_time(bot.db, bot.config, tz, trigger.nick,
                               trigger.sender, time_created)

    if s.score > 0:
        point_color = colors.GREEN
    else:
        point_color = colors.RED

    percent = color(unicode(s.upvote_ratio * 100) + '%', point_color)

    h = HTMLParser.HTMLParser()
    message = message.format(
        title=h.unescape(s.title), link=link, nsfw=nsfw, points=s.score, percent=percent,
        comments=s.num_comments, author=author, created=created)

    bot.say(message)
コード例 #18
0
ファイル: nini.py プロジェクト: madprops/willie-modules
def niniit(bot, trigger, found_match=None):

	gn = "Good night everyone! "

	msgs = []
	msgs.append("May you dream of lolis!")
	msgs.append("Let tomorrow be a great day!")
	msgs.append("Good luck!")
	msgs.append("Sleep tight puppers!")
	msgs.append("Please don't die!")
	msgs.append("I'll be back!")
	msgs.append("It's being fun!")

	msg = gn + random.choice(msgs)

	bot.say(color(u"🌙 ", '06', '00') + color(msg, '06', '00') + color(u" 🌙", '06', '00'))	
コード例 #19
0
ファイル: trump.py プロジェクト: madprops/willie-modules
def trump(bot, trigger, found_match=None):
	arg = trigger.group(2)
	if arg:
		thing = arg.upper()
	else:
		thing = 'AMERICA'
	msg = '  MAKE ' + thing + ' GREAT AGAIN!  T R U M P   2 0 1 6  '
	msg = u'\x02' + color(msg, '04', '00') + u'\x02'
	bot.say(msg)
コード例 #20
0
def announce(type, o, repo):
    name = {'commits': 'Commit', 'issues': 'Bug-Report', 'pull': 'Pull-Request'}
    if "pull_request" in o:
        type = "pull"
    msg = "Neuer " + name[type] + " in " + repo + " von "
    msg += (o.get("user", {}).get("login", None) or o.get("commit", {}).get("author", {}).get("name", None) or "???")
    msg += ": " + formatting.color((o.get("title", None) or o.get("commit", {}).get("message", None) or "?"), "white", "black")
    msg += "( " + o["html_url"] + " )"
    return msg
コード例 #21
0
def ud_search(bot, trigger):
    query = trigger.group(2).strip()

    url = 'http://api.urbandictionary.com/v0/define?term=%s' % (
        query.encode('utf-8'))
    #bot.say(url)
    try:
        response = web.get_urllib_object(url, 20)
    except UnicodeError:
        bot.say('[UrbanDictionary] ENGLISH M**********R, DO YOU SPEAK IT?')
        return
    else:
        data = json.loads(response.read())
        #bot.say(str(data))
    try:
        definition = data['list'][0]['definition'].replace('\n', ' ')
    except KeyError:
        bot.say('[UrbanDictionary] Something went wrong bruh')
    except IndexError:
        bot.say('[UrbanDictionary] No results, do you even spell bruh?')
    else:
        thumbsup = color(str(data['list'][0]['thumbs_up']) + '+', u'03')
        thumbsdown = color(str(data['list'][0]['thumbs_down']) + '-', u'04')
        permalink = data['list'][0]['permalink']
        length = len(thumbsup) + len(thumbsdown) + len(permalink) + 35
        ellipsies = ''
        if (len(definition) + length) > 445:
            ellipsies = '...'
        udoutput = "[UrbanDictionary] %s; %.*s%s | %s >> %s %s" % (
            query, 445 - length, definition, ellipsies, permalink, thumbsup,
            thumbsdown)
        if not "spam spam" in udoutput:
            if not trigger.sender.is_nick() and bot.privileges[trigger.sender][
                    trigger.nick] < VOICE:
                bot.notice(udoutput, recipient=trigger.nick)
            else:
                bot.say(udoutput)
        else:
            if not trigger.sender.is_nick() and bot.privileges[trigger.sender][
                    trigger.nick] < VOICE:
                bot.notice('[UrbanDictionary] Negative ghostrider',
                           recipient=trigger.nick)
            else:
                bot.say('[UrbanDictionary] Negative ghostrider')
コード例 #22
0
ファイル: bombbot.py プロジェクト: Phr33d0m/willie-BombBot
def start(bot, trigger):
    """
    Put a bomb in the specified user's pants. They will be kicked if they
     don't guess the right wire fast enough.
    """
    if not trigger.group(3):
        bot.say("Who do you want to bomb?")
        return NOLIMIT
    if bot.db.get_channel_value(trigger.sender, 'bombs_disabled'):
        bot.notice("An admin has disabled bombing in %s." % trigger.sender, trigger.nick)
        return NOLIMIT
    since_last = time_since_bomb(bot, trigger.nick)
    if since_last < TIMEOUT and not trigger.admin:
        bot.notice("You must wait %.0f seconds before you can bomb someone again." % (TIMEOUT - since_last),
                   trigger.nick)
        return
    global BOMBS
    target = Identifier(trigger.group(3))
    target_unbombable = bot.db.get_nick_value(target, 'unbombable')
    if target == bot.nick:
        bot.say("You thought you could trick me into bombing myself?!")
        return NOLIMIT
    if target == trigger.nick:
        bot.say("%s pls. Bomb a friend if you have to!" % trigger.nick)
        return NOLIMIT
    if target.lower() not in bot.privileges[trigger.sender.lower()]:
        bot.say("You can't bomb imaginary people!")
        return NOLIMIT
    if target_unbombable and not trigger.admin:
        bot.say("I'm not allowed to bomb %s, sorry." % target)
        return NOLIMIT
    if bot.db.get_nick_value(trigger.nick, 'unbombable'):
        bot.say("Try again when you're bombable yourself, %s." % trigger.nick)
        return NOLIMIT
    with lock:
        if target.lower() in BOMBS:
            bot.say("I can't fit another bomb in %s's pants!" % target)
            return NOLIMIT
        wires = [COLORS[i] for i in sorted(sample(xrange(len(COLORS)), randrange(3, 5)))]
        num_wires = len(wires)
        wires_list = [formatting.color(str(wire), str(wire)) for wire in wires]
        wires_list = ", ".join(wires_list[:-2] + [" and ".join(wires_list[-2:])]).replace('Light_', '')
        wires = [wire.replace('Light_', '') for wire in wires]
        color = choice(wires)
        bot.say("Hey, %s! I think there's a bomb in your pants. %s timer, %d wires: %s. "
                "Which wire would you like to cut? (respond with %scutwire color)"
                % (target, FUSE_TEXT, num_wires, wires_list, bot.config.core.help_prefix or '.'))
        bot.notice("Hey, don't tell %s, but it's the %s wire." % (target, color), trigger.nick)
        if target_unbombable:
            bot.notice("Just so you know, %s is marked as unbombable." % target, trigger.nick)
        timer = Timer(FUSE, explode, (bot, trigger))
        BOMBS[target.lower()] = (wires, color, timer, target)
        timer.start()
    bombs_planted = bot.db.get_nick_value(trigger.nick, 'bombs_planted') or 0
    bot.db.set_nick_value(trigger.nick, 'bombs_planted', bombs_planted + 1)
    bot.db.set_nick_value(trigger.nick, 'bomb_last_planted', time.time())
コード例 #23
0
ファイル: fun.py プロジェクト: andrejsavikin/inumuta-modules
def rainbow(bot, trigger):
    text = trigger.group(2)
    if not text:
        text = 'rainbow'
    rainbow = [4, 7, 8, 3, 12, 2, 6]
    out = ''
    for c in text:
        out += color(c, rainbow[0])
        rainbow = rotate(rainbow, 1)
    bot.say(out)
コード例 #24
0
def rainbow(bot, trigger):
    text = trigger.group(2)
    if not text:
        text = 'rainbow'
    rainbow = [4, 7, 8, 3, 12, 2, 6]
    out = ''
    for c in text:
        out += color(c, rainbow[0])
        rainbow = rotate(rainbow, 1)
    bot.say(out)
コード例 #25
0
def error(bot, msg):
    print("{}: {}".format(str(datetime.datetime.now()), msg))

    if "initialized" in bot.memory:
        if "last_error_msg" not in bot.memory["ff"] or bot.memory["ff"]["last_error_msg"] != msg:
            bot.memory["ff"]["last_error_msg"] = msg
            bot.msg(
                bot.config.freifunk.change_announce_target,
                formatting.color("{}: {}".format(formatting.bold("[ERROR]"), msg), formatting.colors.RED),
            )
コード例 #26
0
def get_data(bot, trigger, URL):
    URL = URL.split("#")[0]
    try:
        raw = fetch_api_endpoint(bot, URL)
        rawLang = fetch_api_endpoint(bot, URL + "/languages")
    except HTTPError:
        bot.say("[Github] API returned an error.")
        return NOLIMIT
    data = json.loads(raw)
    langData = json.loads(rawLang).items()
    langData = sorted(langData, key=operator.itemgetter(1), reverse=True)

    if "message" in data:
        return bot.say("[Github] %s" % data["message"])

    langColors = deque(["12", "08", "09", "13"])

    max = sum([pair[1] for pair in langData])

    data["language"] = ""
    for (key, val) in langData[:3]:
        data["language"] = (
            data["language"] + color(str("{0:.1f}".format(float(val) / max * 100)) + "% " + key, langColors[0]) + " "
        )
        langColors.rotate()

    if len(langData) > 3:
        remainder = sum([pair[1] for pair in langData[3:]])
        data["language"] = (
            data["language"]
            + color(str("{0:.1f}".format(float(remainder) / max * 100)) + "% Other", langColors[0])
            + " "
        )

    timezone = get_timezone(bot.db, bot.config, None, trigger.nick)
    if not timezone:
        timezone = "UTC"
    data["pushed_at"] = format_time(
        bot.db, bot.config, timezone, trigger.nick, trigger.sender, from_utc(data["pushed_at"])
    )

    return data
コード例 #27
0
def rpost_info(bot, trigger, match=None):
    r = praw.Reddit(user_agent=USER_AGENT)
    match = match or trigger
    s = r.get_submission(url=match.group(1))

    message = ('[REDDIT] {title} {link}{nsfw} | {points} points ({percent}) | '
               '{comments} comments | Posted by {author}')

    if s.is_self:
        link = '(self.{})'.format(s.subreddit.display_name)
    else:
        link = '({}) to r/{}'.format(s.url, s.subreddit.display_name)

    if s.over_18:
        nsfw = bold(color(' [NSFW]', colors.RED))
        #TODO implement per-channel settings db, and make this able to kick
    else:
        nsfw = ''

    if s.author:
        author = s.author.name
    else:
        author = '[deleted]'
    #TODO add creation time with s.created

    if s.score > 0:
        point_color = colors.GREEN
    else:
        point_color = colors.RED

    percent = color(unicode(s.upvote_ratio * 100) + '%', point_color)

    message = message.format(title=s.title,
                             link=link,
                             nsfw=nsfw,
                             points=s.score,
                             percent=percent,
                             comments=s.num_comments,
                             author=author)
    bot.say(message)
コード例 #28
0
ファイル: github.py プロジェクト: cripperz/inumuta-modules
def get_data(bot, trigger, URL):
    URL = URL.split('#')[0]
    try:
        raw = fetch_api_endpoint(bot, URL)
        rawLang = fetch_api_endpoint(bot, URL + '/languages')
    except HTTPError:
        bot.say('[Github] API returned an error.')
        return NOLIMIT
    data = json.loads(raw)
    langData = json.loads(rawLang).items()
    langData = sorted(langData, key=operator.itemgetter(1), reverse=True)

    if 'message' in data:
        return bot.say('[Github] %s' % data['message'])

    langColors = deque(['12', '08', '09', '13'])

    max = sum([pair[1] for pair in langData])

    data['language'] = ''
    for (key, val) in langData[:3]:
        data['language'] = data['language'] + color(
            str("{0:.1f}".format(float(val) / max * 100)) + '% ' + key,
            langColors[0]) + ' '
        langColors.rotate()

    if len(langData) > 3:
        remainder = sum([pair[1] for pair in langData[3:]])
        data['language'] = data['language'] + color(
            str("{0:.1f}".format(float(remainder) / max * 100)) + '% Other',
            langColors[0]) + ' '

    timezone = get_timezone(bot.db, bot.config, None, trigger.nick)
    if not timezone:
        timezone = 'UTC'
    data['pushed_at'] = format_time(bot.db, bot.config, timezone,
                                    trigger.nick, trigger.sender,
                                    from_utc(data['pushed_at']))

    return data
コード例 #29
0
def ytinfo(bot, trigger, found_match=None):
    """
    Get information about the given youtube video
    """
    match = found_match or trigger
    uri = 'https://www.googleapis.com/youtube/v3/videos?id=' + match.group(2) + '&part=contentDetails,snippet,statistics'

    video_info = ytget(bot, trigger, uri)
    if video_info is None:
        return

    message = ('[You' + color('Tube', colors.WHITE, colors.RED) + ']' +
              ' Title: ' + video_info['snippet']['title'] +
              ' | Uploader: ' + video_info['snippet']['channelTitle'] +
              ' | Uploaded: ' + video_info['snippet']['publishedAt'] +
              ' | Duration: ' + video_info['contentDetails']['duration'] +
              ' | Views: ' + video_info['statistics']['viewCount'] +
              ' | Comments: ' + video_info['statistics']['commentCount'] +
              ' | ' + color(video_info['statistics']['likeCount'] + '+', colors.GREEN) +
              ' | ' + color(video_info['statistics']['dislikeCount'] + '-', colors.RED))

    bot.say(message)
コード例 #30
0
ファイル: fun.py プロジェクト: meew0/inumuta-modules
def rainbow(bot, trigger):
    text = trigger.group(2)
    if not text:
        text = 'rainbow'
    num = 2
    out = ''
    for c in text:
        out += color(c, num)
        if num < 15:
            num += 1
        else:
            num = 2
    bot.say(out)
コード例 #31
0
    def __str__(self):
        global config
        out = []

        if self.hostname:
            out.append(formatting.color(self.hostname, formatting.colors.RED))
        else:
            out.append(ormatting.color(self.node_id, formatting.colors.RED))

        if self.hardware:
            out.append(formatting.color(self.hardware, formatting.colors.GREEN))

        if self.firmware_base and self.firmware_release:
            out.append(
                formatting.color(
                    "{0:s}/{1:s}".format(self.firmware_base, self.firmware_release), formatting.colors.PURPLE
                )
            )

        if self.lat and self.lon:
            out.append(config.meshviewer_uri.format(id=self.node_id))

        return ", ".join(out)
コード例 #32
0
def get_page_info(bot, trigger):
    requested = None
    try:
        requested = get_info(trigger.group(1))
    except:
        return
    if requested is None:
        bot.say('{} Error: Mod does not exist.'.format(get_prefix()))
    
    try:
        message = '{} {} - {} downloads {} Latest: {}'.format(get_prefix(), color(requested['title'], 'lime'), requested['downloads']['total'], color('|', 'yellow'), requested['download']['name'])
        bot.say(message)
    except:
        return
コード例 #33
0
ファイル: reddit.py プロジェクト: defcronyke/cs-pricebot
def rpost_info(bot, trigger, match=None):
    r = praw.Reddit(user_agent=USER_AGENT)
    match = match or trigger
    s = r.get_submission(url=match.group(1))

    message = (
        "[REDDIT] {title} {link}{nsfw} | {points} points ({percent}) | " "{comments} comments | Posted by {author}"
    )

    if s.is_self:
        link = "(self.{})".format(s.subreddit.display_name)
    else:
        link = "({}) to r/{}".format(s.url, s.subreddit.display_name)

    if s.over_18:
        nsfw = bold(color(" [NSFW]", colors.RED))
        # TODO implement per-channel settings db, and make this able to kick
    else:
        nsfw = ""

    if s.author:
        author = s.author.name
    else:
        author = "[deleted]"
    # TODO add creation time with s.created

    if s.score > 0:
        point_color = colors.GREEN
    else:
        point_color = colors.RED

    percent = color(unicode(s.upvote_ratio * 100) + "%", point_color)

    message = message.format(
        title=s.title, link=link, nsfw=nsfw, points=s.score, percent=percent, comments=s.num_comments, author=author
    )
    bot.say(message)
コード例 #34
0
ファイル: reddit.py プロジェクト: josephdunn/willie
def rpost_info(bot, trigger, match=None):
    r = praw.Reddit(user_agent=USER_AGENT)
    match = match or trigger
    s = r.get_submission(url=match.group(1))

    message = ('[REDDIT] {title} {link}{nsfw} | {points} points ({percent}) | '
               '{comments} comments | Posted by {author} {ago}')

    if s.is_self:
        link = '(self.{})'.format(s.subreddit.display_name)
    else:
        link = '({}) to r/{}'.format(s.url, s.subreddit.display_name)

    if s.over_18:
        nsfw = bold(color(' [NSFW]', colors.RED))
        #TODO implement per-channel settings db, and make this able to kick
    else:
        nsfw = ''

    if s.author:
        author = s.author.name
    else:
        author = '[deleted]'

    if s.score > 0:
        point_color = colors.GREEN
    else:
        point_color = colors.RED

    percent = color(unicode(s.upvote_ratio * 100) + '%', point_color)

    posted_ago = human(datetime.datetime.utcnow() - datetime.datetime.utcfromtimestamp(int(s.created_utc)))

    message = message.format(
        title=s.title, link=link, nsfw=nsfw, points=s.score, percent=percent,
        comments=s.num_comments, author=author, ago=posted_ago)
    bot.say(message)
コード例 #35
0
ファイル: youtube.py プロジェクト: meew0/inumuta-modules
def ytinfo(bot, trigger, found_match=None):
    """
    Get information about the latest video uploaded by the channel provided.
    """
    match = found_match or trigger
    #Grab info from YT API
    uri = 'https://gdata.youtube.com/feeds/api/videos/' + match.group(2) + '?v=2&alt=json'

    video_info = ytget(bot, trigger, uri)
    if video_info is 'err':
        return

    #combine variables and print
    message = '[You' + color('Tube', colors.WHITE, colors.RED) + ']' + \
              ' Title: ' + video_info['title'] + \
              ' | Uploader: ' + video_info['uploader'] + \
              ' | Uploaded: ' + video_info['uploaded'] + \
              ' | Duration: ' + video_info['length'] + \
              ' | Views: ' + video_info['views'] + \
              ' | Comments: ' + video_info['comments'] + \
              ' | ' + color(video_info['likes'] + '+',colors.GREEN) + \
              ' | ' + color(video_info['dislikes'] + '-',colors.RED)

    bot.say(HTMLParser().unescape(message))
コード例 #36
0
ファイル: reddit-info.py プロジェクト: Jhyrachy/willie
def rpost_info(bot, trigger, match=None):
    r = praw.Reddit(user_agent='Willie IRC bot - see dft.ba/-williesource for more')
    match = match or trigger
    s = r.get_submission(url=match.group(1))

    message = ('[REDDIT] {title} {link}{nsfw} | {points} points ({percent}) | '
               '{comments} comments | Posted by {author}')

    if s.is_self:
        link = '(self.{})'.format(s.subreddit.display_name)
    else:
        link = '({}) to r/{}'.format(s.url, s.subreddit.display_name)

    if s.over_18:
        nsfw = bold(color(' [NSFW]', colors.RED))
        #TODO implement per-channel settings db, and make this able to kick
    else:
        nsfw = ''

    if s.author:
        author = s.author.name
    else:
        author = '[deleted]'
    #TODO add creation time with s.created

    if s.score > 0:
        point_color = colors.GREEN
    else:
        point_color = colors.RED

    percent = color(unicode(s.upvote_ratio * 100) + '%', point_color)

    message = message.format(
        title=s.title, link=link, nsfw=nsfw, points=s.score, percent=percent,
        comments=s.num_comments, author=author)
    bot.say(message)
コード例 #37
0
ファイル: botnet.py プロジェクト: madprops/willie-modules
def botnet(bot, trigger, found_match=None):

	text = trigger[8:]

	result = ''

	for c in text:
		if c == ' ':
			result += c
		else:
			result += color(c, get_color())

	bot.say(result)

	global pos
	pos = 0
コード例 #38
0
def printNodeinfo(bot, recp, node):
    bot.msg(
        recp,
        "{} ist {}".format(
            formatting.color(node.hostname, formatting.colors.WHITE),
            "online ({} Clients)".format(node.clientcount) if node.online else "offline",
        ),
    )
    bot.msg(recp, "Hardware:    {}".format(node.hardware))
    bot.msg(recp, "Firmware:    {}/{}".format(node.firmware_base, node.firmware_release))
    bot.msg(recp, "Autoupdater: {}".format("on (" + str(node.branch) + ")" if node.autoupdate else "off"))
    if node.contact:
        bot.msg(recp, "Contact:     {}".format(str(node.contact)))
    if node.lastseen:
        bot.msg(recp, "Lastseen:    {}".format(node.lastseen.strftime("%d.%m.%y %H:%M")))
    if node.lat and node.lon:
        bot.msg(recp, "Map:         {}".format(bot.config.freifunk.meshviewer_uri.format(id=node.node_id)))
    bot.msg(
        recp, "Graphana:    http://s.ffka.net/g/{}".format(re.sub(r"[^a-zA-Z0-9_.-]", "", node.mac.replace(":", "")))
    )
コード例 #39
0
def rcomment_info(bot, trigger, s):
    message = ('[REDDIT] Comment on {link}{nsfw} | {created} | {points} points | '
               '{author}: {message}')

    if (s.comments[0] == None):
        return

    c = s.comments[0]
    
    if s.is_self:
        link = '(self.{})'.format(s.subreddit.display_name)
    else:
        link = '({}) to /r/{}'.format(s.url, s.subreddit.display_name)

    if s.over_18:
        nsfw = bold(color(' [NSFW]', colors.RED))
        sfw = bot.db.get_channel_value(trigger.sender, 'sfw')
        if sfw:
            link = '(link hidden)'
            bot.write(['KICK', trigger.sender, trigger.nick,
                       'Linking to NSFW content in a SFW channel.'])
    else:
        nsfw = ''

    if c.author:
        author = c.author.name
    else:
        author = '[deleted]'

    tz = time.get_timezone(bot.db, bot.config, None, trigger.nick,
                           trigger.sender)
    time_created = dt.datetime.utcfromtimestamp(c.created_utc)
    created = time.format_time(bot.db, bot.config, tz, trigger.nick,
                               trigger.sender, time_created)

    h = HTMLParser.HTMLParser()
    message = message.format(
        title=h.unescape(s.title), link=s.short_link, nsfw=nsfw, points=c.score,
        author=author, created=created, message=c)

    bot.say(message)
コード例 #40
0
ファイル: kernel.py プロジェクト: cripperz/inumuta-modules
def kernel(bot, trigger):
    """
    .kernel [branch] - Show the latest linux kernel
    """
    contents = web.get('https://www.kernel.org/releases.json')
    parsed = json.loads(contents)
    versions = []

    regex = False
    if trigger.group(2):
        regex = re.compile(r'^.*' + re.escape(trigger.group(2)) + r'.*$', re.I)

    for branch in parsed['releases']:
        if regex:
            if not regex.match(branch['moniker']) and not regex.match(branch['version']):
                continue
        versions.append(u'{} ({}|{})'.format(color(branch['version'], 3),
            branch['moniker'], branch['released']['isodate']))

    message = "Linux kernel versions: "
    message += ", ".join(versions)
    bot.say(message)
コード例 #41
0
ファイル: dogrio.py プロジェクト: zncb/willie-module-dogrio
 def colorize(self,mesg):
     cols = [formatting.colors.BLUE,
             formatting.colors.BROWN,
             formatting.colors.CYAN,
             formatting.colors.FUCHSIA,
             formatting.colors.GREEN,
             formatting.colors.GREY,
             formatting.colors.LIGHT_BLUE,
             formatting.colors.LIGHT_CYAN,
             formatting.colors.LIGHT_GREEN,
             formatting.colors.LIGHT_GREY,
             formatting.colors.LIGHT_PURPLE,
             formatting.colors.ORANGE,
             formatting.colors.PURPLE,
             formatting.colors.RED,
             formatting.colors.TEAL,
             formatting.colors.WHITE,
             formatting.colors.YELLOW];
     l = []
     for c in mesg:
         col = random.choice(cols)
         l.append(formatting.color(c,col))
     return ''.join(l)
コード例 #42
0
def url_handler(bot, trigger):
    """ Check for malicious URLs """
    check = True  # Enable URL checking
    strict = False  # Strict mode: kick on malicious URL
    positives = 0  # Number of engines saying it's malicious
    total = 0  # Number of total engines
    use_vt = True  # Use VirusTotal
    if bot.config.has_section('safety'):
        check = bot.config.safety.enabled_by_default
        if check is None:
            # If not set, assume default
            check = True
        else:
            check = bool(check)
    # DB overrides config:
    setting = bot.db.get_channel_value(trigger.sender, 'safety')
    if setting is not None:
        if setting == 'off':
            return  # Not checking
        elif setting in ['on', 'strict', 'local', 'local strict']:
            check = True
        if setting == 'strict' or setting == 'local strict':
            strict = True
        if setting == 'local' or setting == 'local strict':
            use_vt = False

    if not check:
        return  # Not overriden by DB, configured default off

    netloc = urlparse(trigger).netloc
    if any(regex.search(netloc) for regex in known_good):
        return  # Whitelisted

    apikey = bot.config.safety.vt_api_key
    try:
        if apikey is not None and use_vt:
            payload = {
                'resource': unicode(trigger),
                'apikey': apikey,
                'scan': '1'
            }

            if trigger not in bot.memory['safety_cache']:
                result = web.post(vt_base_api_url + 'report', payload)
                if sys.version_info.major > 2:
                    result = result.decode('utf-8')
                result = json.loads(result)
                age = time.time()
                data = {
                    'positives': result['positives'],
                    'total': result['total'],
                    'age': age
                }
                bot.memory['safety_cache'][trigger] = data
                if len(bot.memory['safety_cache']) > 1024:
                    _clean_cache(bot)
            else:
                print('using cache')
                result = bot.memory['safety_cache'][trigger]
            positives = result['positives']
            total = result['total']
    except Exception as e:
        LOGGER.debug('Error from checking URL with VT.', exc_info=True)
        pass  # Ignoring exceptions with VT so MalwareDomains will always work

    if unicode(netloc).lower() in malware_domains:
        # malwaredomains is more trustworthy than some VT engines
        # therefor it gets a weight of 10 engines when calculating confidence
        positives += 10
        total += 10

    if positives > 1:
        # Possibly malicious URL detected!
        confidence = '{}%'.format(round((positives / total) * 100))
        msg = 'link posted by %s is possibliy malicious ' % bold(trigger.nick)
        msg += '(confidence %s - %s/%s)' % (confidence, positives, total)
        bot.say('[' + bold(color('WARNING', 'red')) + '] ' + msg)
        if strict:
            bot.write([
                'KICK', trigger.sender, trigger.nick, 'Posted a malicious link'
            ])
コード例 #43
0
def get_prefix():
    prefix = color('[', 'grey') + 'deviant' + bold('art') + color(']', 'grey')
    return prefix
コード例 #44
0
ファイル: github.py プロジェクト: cripperz/inumuta-modules
def fmt_branch(s, row=None):
    if not row:
        row = current_row
    return color(s, fg=row[8])
コード例 #45
0
ファイル: modsio.py プロジェクト: cripperz/inumuta-modules
def get_prefix():
    prefix = color('[', 'grey') + 'mods' + color('.io', 'red') + color(
        ']', 'grey')
    return prefix
コード例 #46
0
def format_status(status):
    return status.replace('red', color(u'\u2718', 'red')).replace(
        'green', color(u'\u2713', 'green')).replace('yellow',
                                                    color(u'~', 'yellow'))
コード例 #47
0
ファイル: github.py プロジェクト: cripperz/inumuta-modules
def fmt_hash(s, row=None):
    if not row:
        row = current_row
    return color(s, fg=row[7])
コード例 #48
0
ファイル: github.py プロジェクト: cripperz/inumuta-modules
def fmt_name(s, row=None):
    if not row:
        row = current_row
    return color(s, fg=row[6])
コード例 #49
0
ファイル: github.py プロジェクト: cripperz/inumuta-modules
def fmt_url(s, row=None):
    if not row:
        row = current_row
    return color(s, fg=row[3])
コード例 #50
0
def get_prefix():
    prefix = color('[', 'grey') + bold(color('Curse', 'yellow')) + color(']', 'grey')
    return prefix
コード例 #51
0
ファイル: github.py プロジェクト: cripperz/inumuta-modules
def fmt_repo(s, row=None):
    if not row:
        row = current_row
    return color(s, fg=row[5])
コード例 #52
0
ファイル: github.py プロジェクト: cripperz/inumuta-modules
def fmt_tag(s, row=None):
    if not row:
        row = current_row
    return color(s, fg=row[4])