def f_time(bot, trigger): """Returns the current time.""" if trigger.group(2): zone = get_timezone(bot.db, bot.config, trigger.group(2).strip(), None, None) if not zone: bot.say('Could not find timezone %s.' % trigger.group(2).strip()) return else: zone = get_timezone(bot.db, bot.config, None, trigger.nick, trigger.sender) time = format_time(bot.db, bot.config, zone, trigger.nick, trigger.sender) bot.say(time)
def remind(bot, trigger): """Gives you a reminder in the given amount of time.""" duration = 0 message = filter(None, re.split('(\d+(?:\.\d+)? ?(?:(?i)' + periods + ')) ?', trigger.group(2))[1:]) reminder = '' stop = False for piece in message: grp = re.match('(\d+(?:\.\d+)?) ?(.*) ?', piece) if grp and not stop: length = float(grp.group(1)) factor = scaling.get(grp.group(2).lower(), 60) duration += length * factor else: reminder = reminder + piece stop = True if duration == 0: return bot.reply("Sorry, didn't understand the input.") if duration % 1: duration = int(duration) + 1 else: duration = int(duration) timezone = get_timezone( bot.db, bot.config, None, trigger.nick, trigger.sender) create_reminder(bot, trigger, duration, reminder, timezone)
def update_channel_format(bot, trigger): """ Sets your preferred format for time. Uses the standard strftime format. You can use http://strftime.net or your favorite search engine to learn more. """ if bot.privileges[trigger.sender][trigger.nick] < OP: return tformat = trigger.group(2) if not tformat: bot.reply("What format do you want me to use? Try using" " http://strftime.net to make one.") tz = get_timezone(bot.db, bot.config, None, None, trigger.sender) try: timef = format_time(zone=tz) except: bot.reply("That format doesn't work. Try using" " http://strftime.net to make one.") return bot.db.set_channel_value(trigger.sender, 'time_format', tformat) bot.reply("Got it. Times in this channel will now appear as %s " "unless a user has their own format set. (If the timezone" " is wrong, you might try the settz and channeltz " "commands)" % timef)
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
def update_user_format(bot, trigger): """ Sets your preferred format for time. Uses the standard strftime format. You can use http://strftime.net or your favorite search engine to learn more. """ tformat = trigger.group(2) if not tformat: bot.reply("What format do you want me to use? Try using" " http://strftime.net to make one.") return tz = get_timezone(bot.db, bot.config, None, trigger.nick, trigger.sender) # Get old format as back-up old_format = bot.db.get_nick_value(trigger.nick, 'time_format') # Save the new format in the database so we can test it. bot.db.set_nick_value(trigger.nick, 'time_format', tformat) try: timef = format_time(db=bot.db, zone=tz, nick=trigger.nick) except: bot.reply("That format doesn't work. Try using" " http://strftime.net to make one.") # New format doesn't work. Revert save in database. bot.db.set_nick_value(trigger.nick, 'time_format', old_format) return bot.reply("Got it. Your time will now appear as %s. (If the " "timezone is wrong, you might try the settz command)" % timef)
def seen(bot, trigger): """Reports when and where the user was last seen.""" if not trigger.group(2): bot.say(".seen <nick> - Reports when <nick> was last seen.") return nick = trigger.group(2).strip() timestamp = bot.db.get_nick_value(nick, 'seen_timestamp') if timestamp: channel = bot.db.get_nick_value(nick, 'seen_channel') message = bot.db.get_nick_value(nick, 'seen_message') action = bot.db.get_nick_value(nick, 'seen_action') tz = get_timezone(bot.db, bot.config, None, trigger.nick, trigger.sender) saw = datetime.datetime.utcfromtimestamp(timestamp) timestamp = format_time(bot.db, bot.config, tz, trigger.nick, trigger.sender, saw) msg = "I last saw {} at {}".format(nick, timestamp) if Identifier(channel) == trigger.sender: if action: msg = msg + " in here, doing " + nick + " " + message else: msg = msg + " in here, saying " + message else: msg += " in another channel." bot.say(str(trigger.nick) + ': ' + msg) else: bot.say("Sorry, I haven't seen {} around.".format(nick))
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)
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)
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)
def github_repo(bot, trigger, match=None): match = match or trigger repo = match.group(2) or match.group(1) if repo.lower() == "status": current = json.loads(web.get("https://status.github.com/api/status.json")) lastcomm = json.loads(web.get("https://status.github.com/api/last-message.json")) status = current["status"] if status == "major": status = "\x02\x034Broken\x03\x02" elif status == "minor": status = "\x02\x037Shakey\x03\x02" elif status == "good": status = "\x02\x033Online\x03\x02" lstatus = lastcomm["status"] if lstatus == "major": lstatus = "\x02\x034Broken\x03\x02" elif lstatus == "minor": lstatus = "\x02\x037Shakey\x03\x02" elif lstatus == "good": lstatus = "\x02\x033Online\x03\x02" timezone = get_timezone(bot.db, bot.config, None, trigger.nick) if not timezone: timezone = "UTC" lastcomm["created_on"] = format_time( bot.db, bot.config, timezone, trigger.nick, trigger.sender, from_utc(lastcomm["created_on"]) ) return bot.say( "[Github] Current Status: " + status + " | Last Message: " + lstatus + ": " + lastcomm["body"] + " (" + lastcomm["created_on"] + ")" ) elif repo.lower() == "rate-limit": return bot.say(fetch_api_endpoint(bot, "https://api.github.com/rate_limit")) if "/" not in repo: repo = trigger.nick.strip() + "/" + repo URL = "https://api.github.com/repos/%s" % (repo.strip()) fmt_response(bot, trigger, URL)
def f_remind(bot, trigger): """Give someone a message the next time they're seen""" teller = trigger.nick verb = trigger.group(1) if not trigger.group(3): bot.reply("%s whom?" % verb) return tellee = trigger.group(3).rstrip('.,:;') msg = trigger.group(2).lstrip(tellee).lstrip() if not msg: bot.reply("%s %s what?" % (verb, tellee)) return tellee = Identifier(tellee) if not os.path.exists(bot.tell_filename): return if len(tellee) > 20: return bot.reply('That nickname is too long.') if tellee == bot.nick: return bot.reply("I'm here now, you can tell me whatever you want!") if not tellee in (Identifier(teller), bot.nick, 'me'): tz = get_timezone(bot.db, bot.config, None, tellee) timenow = format_time(bot.db, bot.config, tz, tellee) bot.memory['tell_lock'].acquire() try: if not tellee in bot.memory['reminders']: bot.memory['reminders'][tellee] = [(teller, verb, timenow, msg) ] else: bot.memory['reminders'][tellee].append( (teller, verb, timenow, msg)) finally: bot.memory['tell_lock'].release() response = "I'll pass that on when %s is around." % tellee bot.reply(response) elif Identifier(teller) == tellee: bot.say('You can %s yourself that.' % verb) else: bot.say("Hey, I'm not as stupid as Monty you know!") dumpReminders(bot.tell_filename, bot.memory['reminders'], bot.memory['tell_lock']) # @@ tell
def f_remind(bot, trigger): """Give someone a message the next time they're seen""" teller = trigger.nick verb = trigger.group(1) if not trigger.group(3): bot.reply("%s whom?" % verb) return tellee = trigger.group(3).rstrip('.,:;') msg = trigger.group(2).lstrip(tellee).lstrip() if not msg: bot.reply("%s %s what?" % (verb, tellee)) return tellee = Identifier(tellee) if not os.path.exists(bot.tell_filename): return if len(tellee) > 20: return bot.reply('That nickname is too long.') if tellee == bot.nick: return bot.reply("I'm here now, you can tell me whatever you want!") if not tellee in (Identifier(teller), bot.nick, 'me'): tz = get_timezone(bot.db, bot.config, None, tellee) timenow = format_time(bot.db, bot.config, tz, tellee) bot.memory['tell_lock'].acquire() try: if not tellee in bot.memory['reminders']: bot.memory['reminders'][tellee] = [(teller, verb, timenow, msg)] else: bot.memory['reminders'][tellee].append((teller, verb, timenow, msg)) finally: bot.memory['tell_lock'].release() response = "I'll pass that on when %s is around." % tellee bot.reply(response) elif Identifier(teller) == tellee: bot.say('You can %s yourself that.' % verb) else: bot.say("Hey, I'm not as stupid as Monty you know!") dumpReminders(bot.tell_filename, bot.memory['reminders'], bot.memory['tell_lock']) # @@ tell
def format_count(bot, trigger): if trigger.is_privmsg: return user = Identifier(trigger.group(2) or trigger.nick) user = Identifier(user.strip()) count = get_count(bot, user, trigger.sender) since = bot.memory['pls_count_time'] timezone = get_timezone(bot.db, bot.config, None, trigger.nick) if not timezone: timezone = 'UTC' time = format_time(bot.db, bot.config, timezone, trigger.nick, trigger.sender, datetime.datetime.fromtimestamp(since)) bot.say('{} has said pls in {} {} time(s) since {}'.format(user, trigger.sender, count, time))
def at(bot, trigger): """ Gives you a reminder at the given time. Takes hh:mm:ssTimezone message. Timezone is any timezone Willie takes elsewhere; the best choices are those from the tzdb; a list of valid options is available at http://dft.ba/-tz . The seconds and timezone are optional. """ regex = re.compile(r'(\d+):(\d+)(?::(\d+))?([^\s\d]+)? (.*)') match = regex.match(trigger.group(2)) if not match: bot.reply("Sorry, but I didn't understand your input.") return NOLIMIT hour, minute, second, tz, message = match.groups() if not second: second = '0' timezone = 'UTC' if pytz: timezone = get_timezone(bot.db, bot.config, tz, trigger.nick, trigger.sender) if not timezone: timezone = 'UTC' now = datetime.now(pytz.timezone(timezone)) at_time = datetime(now.year, now.month, now.day, int(hour), int(minute), int(second), tzinfo=now.tzinfo) timediff = at_time - now else: if tz and tz.upper() != 'UTC': bot.reply("I don't have timzeone support installed.") return NOLIMIT now = datetime.now() at_time = datetime(now.year, now.month, now.day, int(hour), int(minute), int(second)) timediff = at_time - now duration = timediff.seconds if duration < 0: duration += 86400 create_reminder(bot, trigger, duration, message, timezone)
def github_repo(bot, trigger, match=None): match = match or trigger repo = match.group(2) or match.group(1) if repo.lower() == 'status': current = json.loads( web.get('https://status.github.com/api/status.json')) lastcomm = json.loads( web.get('https://status.github.com/api/last-message.json')) status = current['status'] if status == 'major': status = "\x02\x034Broken\x03\x02" elif status == 'minor': status = "\x02\x037Shakey\x03\x02" elif status == 'good': status = "\x02\x033Online\x03\x02" lstatus = lastcomm['status'] if lstatus == 'major': lstatus = "\x02\x034Broken\x03\x02" elif lstatus == 'minor': lstatus = "\x02\x037Shakey\x03\x02" elif lstatus == 'good': lstatus = "\x02\x033Online\x03\x02" timezone = get_timezone(bot.db, bot.config, None, trigger.nick) if not timezone: timezone = 'UTC' lastcomm['created_on'] = format_time(bot.db, bot.config, timezone, trigger.nick, trigger.sender, from_utc(lastcomm['created_on'])) return bot.say('[Github] Current Status: ' + status + ' | Last Message: ' + lstatus + ': ' + lastcomm['body'] + ' (' + lastcomm['created_on'] + ')') elif repo.lower() == 'rate-limit': return bot.say( fetch_api_endpoint(bot, 'https://api.github.com/rate_limit')) if '/' not in repo: repo = trigger.nick.strip() + '/' + repo URL = 'https://api.github.com/repos/%s' % (repo.strip()) fmt_response(bot, trigger, URL)
def format_count(bot, trigger): if trigger.is_privmsg: return user = Identifier(trigger.group(2) or trigger.nick) user = Identifier(user.strip()) count = get_count(bot, user, trigger.sender) since = bot.memory['pls_count_time'] timezone = get_timezone(bot.db, bot.config, None, trigger.nick) if not timezone: timezone = 'UTC' time = format_time(bot.db, bot.config, timezone, trigger.nick, trigger.sender, datetime.datetime.fromtimestamp(since)) bot.say('{} has said pls in {} {} time(s) since {}'.format( user, trigger.sender, count, time))
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
def remind(bot, trigger): """Gives you a reminder in the given amount of time.""" duration = 0 trggrp = trigger.group(2) mfix = re.split('(\d.*?)\s',trggrp) if(len(mfix) == 1): if(mfix[0].isdigit()): trggrp = trggrp + "m" else: trggrp = trigger.group(2) elif(mfix[1].isdigit() and (len(mfix) > 1)): if(len(mfix) is 3 and mfix[2] in (periods.split('|'))): trggrp = ''.join(mfix) else: trggrp = mfix[1]+'m '+''.join(mfix[2:]) else: trggrp = trigger.group(2) message = filter(None, re.split('(\d+(?:\.\d+)? ?(?:(?i)' + periods + ')) ?', trggrp)[1:]) reminder = '' stop = False for piece in message: grp = re.match('(\d+(?:\.\d+)?) ?(.*) ?', piece) if grp and not stop: length = float(grp.group(1)) factor = scaling.get(grp.group(2).lower(), 60) duration += length * factor else: reminder = reminder + piece stop = True if duration == 0: return bot.reply("Sorry, didn't understand the input.") if duration % 1: duration = int(duration) + 1 else: duration = int(duration) timezone = get_timezone( bot.db, bot.config, None, trigger.nick, trigger.sender) create_reminder(bot, trigger, duration, reminder, timezone)
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)
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
def github_repo(bot, trigger, match=None): match = match or trigger repo = match.group(2) or match.group(1) if repo.lower() == 'status': current = json.loads(web.get('https://status.github.com/api/status.json')) lastcomm = json.loads(web.get('https://status.github.com/api/last-message.json')) status = current['status'] if status == 'major': status = "\x02\x034Broken\x03\x02" elif status == 'minor': status = "\x02\x037Shakey\x03\x02" elif status == 'good': status = "\x02\x033Online\x03\x02" lstatus = lastcomm['status'] if lstatus == 'major': lstatus = "\x02\x034Broken\x03\x02" elif lstatus == 'minor': lstatus = "\x02\x037Shakey\x03\x02" elif lstatus == 'good': lstatus = "\x02\x033Online\x03\x02" timezone = get_timezone(bot.db, bot.config, None, trigger.nick) if not timezone: timezone = 'UTC' lastcomm['created_on'] = format_time(bot.db, bot.config, timezone, trigger.nick, trigger.sender, from_utc(lastcomm['created_on'])) return bot.say('[Github] Current Status: ' + status + ' | Last Message: ' + lstatus + ': ' + lastcomm['body'] + ' (' + lastcomm['created_on'] + ')') elif repo.lower() == 'rate-limit': return bot.say(fetch_api_endpoint(bot, 'https://api.github.com/rate_limit')) if '/' not in repo: repo = trigger.nick.strip() + '/' + repo URL = 'https://api.github.com/repos/%s' % (repo.strip()) fmt_response(bot, trigger, URL)