Example #1
0
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)
Example #2
0
def remind(bot, trigger):
    """Gives you a reminder in the given amount of time."""
    if not trigger.group(2):
        bot.say("Missing arguments for reminder command.")
        return NOLIMIT
    if trigger.group(3) and not trigger.group(4):
        bot.say("No message given for reminder.")
        return NOLIMIT
    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)
Example #3
0
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()
    if nick == bot.nick:
        bot.reply("I'm right here!")
        return
    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))
Example #4
0
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)
Example #5
0
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)

    # Get old format as back-up
    old_format = bot.db.get_channel_value(trigger.sender, 'time_format')

    # Save the new format in the database so we can test it.
    bot.db.set_channel_value(trigger.sender, 'time_format', tformat)

    try:
        timef = format_time(db=bot.db, zone=tz, channel=trigger.sender)
    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_channel_value(trigger.sender, 'time_format', old_format)
        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)
Example #6
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 = list(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
Example #7
0
def execute_main(bot, trigger):
    """Reports when and where the user was last seen."""
    nick = trigger.group(3)
    if not nick:
        osd(bot, trigger.sender, 'say',
            ".seen <nick> - Reports when <nick> was last seen.")
    elif nick == bot.nick:
        bot.reply("I'm right here!")
    else:
        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."
            osd(bot, trigger.sender, 'say', str(trigger.nick) + ': ' + msg)
        else:
            osd(bot, trigger.sender, 'say',
                "Sorry, I haven't seen {} around.".format(nick))
Example #8
0
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()
    if nick == bot.nick:
        bot.reply("I'm right here!")
        return
    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 = "{} {}: ".format(timestamp, nick)
        if Identifier(channel) == trigger.sender:
            msg += message
        else:
            msg = "{} was last seen in another channel on {}.".format(
                nick, timestamp)
        bot.say(str(trigger.nick) + ': ' + msg)
    else:
        bot.say("Sorry, I haven't seen {} around.".format(nick))
Example #9
0
def execute_main(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()
    message = str(trigger.group(0))

    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 tellee.lower() in [u.lower() for u in bot.users]:
        if not message.endswith('please'):
            return bot.reply(
                "Tell %s that yourself you lazy f**k, they're online now." %
                tellee)

    if tellee not in (Identifier(teller), bot.nick, 'me'):
        tz = get_timezone(bot.db, bot.config, None, tellee)
        timenow = format_time(bot.db, bot.config, tz, tellee)
        msg = msg.rstrip('please').rstrip()
        bot.memory['tell_lock'].acquire()
        try:
            if tellee not 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:
        osd(bot, trigger.sender, 'say',
            "You can %s yourself that. I'm not your f*****g secretary." % verb)
    else:
        osd(bot, trigger.sender, 'say',
            "Hey, I'm not as stupid as Monty you know!")

    dumpReminders(bot.tell_filename, bot.memory['reminders'],
                  bot.memory['tell_lock'])  # @@ tell
Example #10
0
File: reddit.py Project: dasu/sopel
def rpost_info(bot, trigger, match=None):
    r = praw.Reddit(
        user_agent=USER_AGENT,
        client_id='6EiphT6SSQq7FQ',
        client_secret=None,
    )
    match = match or trigger
    s = r.submission(id=match.group(2))

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

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

    if s.over_18:
        if subreddit.lower() in spoiler_subs:
            nsfw = bold(color(' [SPOILERS]', colors.RED))
        else:
            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)

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

    bot.say(message)
Example #11
0
def at(bot, trigger):
    """
    Give user a reminder at the given time.

    Time format: hh:mm:ss.
    To see what timezone is used, type .getchanneltz (if setting a reminder
    in an IRC channel) or .gettz (elsewhere)
    """
    if not trigger.group(2):
        bot.say("No arguments given for reminder command.")
        return NOLIMIT
    if trigger.group(3) and not trigger.group(4):
        bot.say("No message was given for the reminder. Perhaps you should "
                "try again?")
        return NOLIMIT
    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, please try again.")
        return NOLIMIT
    hour, minute, second, tz, message = match.groups()
    if not second:
        second = '0'

    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 timezone 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, 'UTC')
Example #12
0
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)
        
        lnk = str("left the following message for you:")

        bot.memory['tell_lock'].acquire()
        try:
            if not tellee in bot.memory['reminders']:
                bot.memory['reminders'][tellee] = [(teller, lnk, timenow, msg)]
            else:
                bot.memory['reminders'][tellee].append((teller, lnk, timenow, msg))
        finally:
            bot.memory['tell_lock'].release()

              
        response = "Skilam. Ohr an remmag \"%s\" %s fur leib." % (msg, 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
Example #13
0
def f_remind(bot, trigger):
    """Give someone a message the next time they're seen"""
    teller = trigger.nick
    verb = trigger.group(1)

    if trigger.group(2) is None:
        bot.notice('No arguments given for command.', trigger.nick)
        bot.notice('Usage: .tell username message.', trigger.nick)
        return 1

    tellee = trigger.group(3).rstrip('.,:;')
    msg = trigger.group(2).lstrip(tellee).lstrip()

    if not msg:
        bot.notice('Argument missing: message.', trigger.nick)
        bot.notice('Usage: .tell username message.', trigger.nick)
        return 1

    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
Example #14
0
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 quien?" % verb)
        return

    tellee = trigger.group(3).rstrip('.,:;')
    msg = trigger.group(2).lstrip(tellee).lstrip()

    if not msg:
        bot.reply("%s %s que?" % (verb, tellee))
        return

    tellee = Identifier(tellee)

    if not os.path.exists(bot.tell_filename):
        return

    if len(tellee) > 30:
        return bot.reply('That nickname is too long.')
    if tellee == bot.nick:
        return bot.reply("Estoy aqui ahora, decime lo que querras!")

    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 = "Ya se lo digo cuando %s ande en este lugar decadente." % tellee

        bot.reply(response)
    elif Identifier(teller) == tellee:
        bot.say('Podes %s decirtelo a vos mismo.' % 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
Example #15
0
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
Example #16
0
def at(bot, trigger):
    """
    Gives you a reminder at the given time. Takes hh:mm:ssTimezone
    message. Timezone is any timezone Sopel takes elsewhere; the best choices
    are those from the tzdb; a list of valid options is available at
    http://sopel.chat/tz . The seconds and timezone are optional.
    """
    if not trigger.group(2):
        bot.say("No arguments given for reminder command.")
        return NOLIMIT
    if trigger.group(3) and not trigger.group(4):
        bot.say("No message given for reminder.")
        return NOLIMIT
    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'

    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, 'UTC')
Example #17
0
def github_repo(bot, trigger, match=None):
    match = match or trigger
    repo = match.group(2) or match.group(1)

    if repo.lower() == 'version':
        return bot.say('[idlerpg] Version {} by {}, report issues at {}'.format(
            github.__version__, github.__author__, github.__repo__))

    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)
Example #18
0
def preformat(bot, trigger, channel):
    # Get default timezone from the config
    timezone = get_timezone(bot.db, bot.config)
    if not timezone:
        timezone = 'UTC'
    tz = pytz.timezone(timezone)

    # Set default now value, then try to pull from trigger (sopel 6.3+)
    now = datetime.datetime.now(tz)
    if hasattr(trigger, 'time'):
        now = trigger.time.replace(tzinfo=pytz.utc).astimezone(tz)

    # Strip off microseconds so more things understand the ISO format
    now = now.replace(microsecond=0)

    event = {
        'channel': channel,
        'type': trigger.event,
        'message': trigger.match.string,
        'nick': trigger.nick,
        'ident': trigger.user,
        'host': trigger.host,
        'sender': trigger.sender,
        'datetime': now.isoformat(),
        'date': now.date().isoformat(),
        'time': now.time().isoformat(),
        'args': trigger.args,
        'args_str': ' '.join(trigger.args[1:]),
        'tags': trigger.tags,
        'intent': None
    }

    if event['message'].startswith(
            "\001ACTION ") and event['message'].endswith("\001"):
        event['type'] = 'ACTION'
        event['message'] = event['message'][8:-1]

    if 'intent' in trigger.tags:
        event['intent'] = trigger.tags['intent']
    return event
Example #19
0
def preformat(bot, trigger, channel):
    # Get default timezone from the config
    timezone = get_timezone(bot.db, bot.config)
    if not timezone:
        timezone = 'UTC'
    tz = pytz.timezone(timezone)

    # Set default now value, then try to pull from trigger (sopel 6.3+)
    now = datetime.datetime.now(tz)
    if hasattr(trigger, 'time'):
        now = trigger.time.replace(tzinfo=pytz.utc).astimezone(tz)

    # Strip off microseconds so more things understand the ISO format
    now = now.replace(microsecond=0)

    event = {
        'channel':  channel,
        'type':     trigger.event,
        'message':  trigger.match.string,
        'nick':     trigger.nick,
        'ident':    trigger.user,
        'host':     trigger.host,
        'sender':   trigger.sender,
        'datetime': now.isoformat(),
        'date':     now.date().isoformat(),
        'time':     now.time().isoformat(),
        'args':     trigger.args,
        'args_str': ' '.join(trigger.args[1:]),
        'tags':     trigger.tags,
        'intent':   None
    }

    if event['message'].startswith("\001ACTION ") and event['message'].endswith("\001"):
        event['type'] = 'ACTION'
        event['message'] = event['message'][8:-1]

    if 'intent' in trigger.tags:
        event['intent'] = trigger.tags['intent']
    return event
Example #20
0
def remind_at(bot, trigger):
    """
    Gives you a reminder at the given time. Takes `hh:mm:ssTimezone message`.
    Timezone is any timezone Sopel takes elsewhere; the best choices are those
    from the tzdb; a list of valid options is available at
    <https://sopel.chat/tz>. The seconds and timezone are optional.
    """
    if not trigger.group(2):
        bot.say("No arguments given for reminder command.")
        return module.NOLIMIT
    if trigger.group(3) and not trigger.group(4):
        bot.say("No message given for reminder.")
        return module.NOLIMIT
    match = REGEX_AT.match(trigger.group(2))
    if not match:
        bot.reply("Sorry, but I didn't understand your input.")
        return module.NOLIMIT
    hour, minute, second, timezone, message = match.groups()
    if not second:
        second = '0'

    timezone = get_timezone(bot.db, bot.config, timezone,
                            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
    duration = timediff.seconds

    if duration < 0:
        duration += 86400
    create_reminder(bot, trigger, duration, message, timezone)
Example #21
0
def rpost_info(bot, trigger, match):
    match = match or trigger
    try:
        r = praw.Reddit(
            user_agent=USER_AGENT,
            client_id='6EiphT6SSQq7FQ',
            client_secret=None,
        )
        s = r.submission(id=match.group(1))

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

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

        nsfw = ''
        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.kick(trigger.nick, trigger.sender,
                         'Linking to NSFW content in a SFW channel.')
        if s.spoiler:
            nsfw += ' ' + bold(color('[SPOILER]', colors.GRAY))

            spoiler_free = bot.db.get_channel_value(trigger.sender,
                                                    'spoiler_free')
            if spoiler_free:
                link = '(link hidden)'
                bot.kick(
                    trigger.nick, trigger.sender,
                    'Linking to spoiler content in a spoiler-free channel.')

        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)

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

        bot.say(message)
    except prawcore.exceptions.NotFound:
        bot.say('No such post.')
        return NOLIMIT