예제 #1
0
파일: clock.py 프로젝트: firerogue/sopel
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)
예제 #2
0
def get_time_created(bot, trigger, entrytime):
    tz = time.get_timezone(bot.db, bot.config, None, trigger.nick,
                           trigger.sender)
    time_created = dt.datetime.utcfromtimestamp(entrytime)
    created = time.format_time(bot.db, bot.config, tz, trigger.nick,
                               trigger.sender, time_created)
    return created
예제 #3
0
파일: seen.py 프로젝트: jezbenson/sopel
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))
예제 #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)
예제 #5
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))
예제 #6
0
def rpost_info(bot, trigger, match=None):
    r = praw.Reddit(user_agent=USER_AGENT)
    match = match or trigger
    s = r.get_submission(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)
예제 #7
0
파일: seen.py 프로젝트: piagetbot/sopel
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))
예제 #8
0
파일: seen.py 프로젝트: reverieeee/sopel
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))
예제 #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 = 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
예제 #10
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.
    """
    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 Exception:  # TODO: Be specific
        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)
예제 #11
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(ERROR_NO_FORMAT)
        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 Exception:  # TODO: Be specific
        bot.reply(ERROR_INVALID_FORMAT)
        # New format doesn't work. Revert save in database.
        bot.db.set_nick_value(trigger.nick, 'time_format', old_format)
        return

    set_command = '%ssettz' % bot.settings.core.help_prefix
    bot.reply('Your time will now appear as %s. '
              '(If the timezone is wrong, you might try the %s command)' %
              (timef, set_command))
예제 #12
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.
    """
    tformat = trigger.group(2)
    if not tformat:
        bot.reply(ERROR_NO_FORMAT)
        return

    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 Exception:  # TODO: Be specific
        bot.reply(ERROR_INVALID_FORMAT)
        # 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)

    help_prefix = bot.settings.core.help_prefix
    set_command = '%ssettz' % help_prefix
    channel_command = '%schanneltz' % help_prefix
    bot.say("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 %s and %s "
            "commands)" % (timef, set_command, channel_command))
예제 #13
0
파일: clock.py 프로젝트: firerogue/sopel
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)
예제 #14
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
예제 #15
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
예제 #16
0
파일: reddit.py 프로젝트: 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)
예제 #17
0
파일: tell.py 프로젝트: sopel-irc/sopel
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('.,:;')

    # all we care about is having at least one non-whitespace
    # character after the name
    if not trigger.group(4):
        bot.reply("%s %s what?" % (verb, tellee))
        return

    msg = _format_safe_lstrip(trigger.group(2).split(' ', 1)[1])

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

    tellee = bot.make_identifier(tellee)

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

    if len(tellee) > bot.isupport.get('NICKLEN', 30):
        bot.reply('That nickname is too long.')
        return

    if tellee[0] == '@':
        tellee = tellee[1:]

    if tellee == bot.nick:
        bot.reply("I'm here now; you can %s me whatever you want!" % verb)
        return

    if tellee not in (bot.make_identifier(teller), bot.nick, 'me'):
        tz = get_timezone(bot.db, bot.config, None, tellee)
        timenow = format_time(bot.db, bot.config, tz, tellee)
        with bot.memory['tell_lock']:
            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))
            # save the reminders
            dump_reminders(bot.tell_filename, bot.memory['reminders'])

        response = "I'll pass that on when %s is around." % tellee
        bot.reply(response)
    elif bot.make_identifier(teller) == tellee:
        bot.reply('You can %s yourself that.' % verb)
    else:
        bot.reply("Hey, I'm not as stupid as Monty you know!")
예제 #18
0
파일: clock.py 프로젝트: reverieeee/sopel
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)
예제 #19
0
파일: clock.py 프로젝트: firerogue/sopel
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)
예제 #20
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 = tools.Identifier(tellee)

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

    if len(tellee) > 30:  # TODO: use server NICKLEN here when available
        bot.reply('That nickname is too long.')
        return

    if tellee[0] == '@':
        tellee = tellee[1:]

    if tellee == bot.nick:
        bot.reply("I'm here now; you can tell me whatever you want!")
        return

    if tellee not in (tools.Identifier(teller), bot.nick, 'me'):
        tz = get_timezone(bot.db, bot.config, None, tellee)
        timenow = format_time(bot.db, bot.config, tz, tellee)
        with bot.memory['tell_lock']:
            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))
            # save the reminders
            dump_reminders(bot.tell_filename, bot.memory['reminders'])

        response = "I'll pass that on when %s is around." % tellee
        bot.reply(response)
    elif tools.Identifier(teller) == tellee:
        bot.reply('You can %s yourself that.' % verb)
    else:
        bot.reply("Hey, I'm not as stupid as Monty you know!")
예제 #21
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("To whom should I send the memo to?" % verb)
        return

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

    if not msg:
        bot.reply("What should be in the content of the memo?" %
                  (verb, tellee))
        return

    tellee = Identifier(tellee)

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

    if len(tellee) > 30:  # TODO: use server NICKLEN here when available
        return bot.reply('That nickname is too long.')
    if tellee == bot.nick:
        return bot.reply("I cannot send a memo to myself")

    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)
        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 = "Memo sent to %s successfully" % tellee

        bot.reply(response)
    elif Identifier(teller) == tellee:
        bot.say('I will not send a memo to you' % 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
예제 #22
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
예제 #23
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(
            requests.get('https://status.github.com/api/status.json').text)
        lastcomm = json.loads(
            requests.get(
                'https://status.github.com/api/last-message.json').text)

        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)
예제 #24
0
파일: remind.py 프로젝트: r4f4/sopel
def remind_at(bot, trigger):
    """Gives you a reminder at the given time.

    Takes ``hh:mm:ssTimezone Date message`` where seconds, Timezone, and Date
    are optional.

    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 Date can be expressed in one of these formats: YYYY-mm-dd, dd-mm-YYYY,
    dd-mm-YY, or dd-mm. The separator can be ``.``, ``-``, or ``/``.
    """
    if not trigger.group(2):
        bot.reply("No arguments given for reminder command.")
        return module.NOLIMIT
    if trigger.group(3) and not trigger.group(4):
        bot.reply("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

    default_timezone = get_timezone(bot.db, bot.config, None,
                                    trigger.nick, trigger.sender)

    reminder = parse_regex_match(match, default_timezone)

    try:
        duration = reminder.get_duration()
    except ValueError as error:
        bot.reply(
            "Sorry, but I didn't understand your input: %s" % str(error))
        return module.NOLIMIT

    # save reminder
    timestamp = create_reminder(bot, trigger, duration, reminder.message)

    if duration >= 60:
        human_time = format_time(
            bot.db,
            bot.config,
            reminder.timezone.zone,
            trigger.nick,
            trigger.sender,
            datetime.utcfromtimestamp(timestamp))
        bot.reply('Okay, will remind at %s' % human_time)
    else:
        bot.reply('Okay, will remind in %s secs' % duration)
예제 #25
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
예제 #26
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
예제 #27
0
파일: tell.py 프로젝트: calzoneman/sopel
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
예제 #28
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
예제 #29
0
def remind_in(bot, trigger):
    """Gives you a reminder in the given amount of time."""
    if not trigger.group(2):
        bot.reply("Missing arguments for reminder command.")
        return plugin.NOLIMIT
    if trigger.group(3) and not trigger.group(4):
        bot.reply("No message given for reminder.")
        return plugin.NOLIMIT
    duration = 0
    message = filter(None, re.split(r'(\d+(?:\.\d+)? ?(?:(?i)' + PERIODS + ')) ?',
                                    trigger.group(2))[1:])
    reminder = ''
    stop = False
    for piece in message:
        grp = re.match(r'(\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:
        bot.reply("Sorry, didn't understand the input.")
        return plugin.NOLIMIT

    if duration % 1:
        duration = int(duration) + 1
    else:
        duration = int(duration)
    timezone = get_timezone(
        bot.db, bot.config, None, trigger.nick, trigger.sender)
    timestamp = create_reminder(bot, trigger, duration, reminder)

    if duration >= 60:
        human_time = format_time(
            bot.db,
            bot.config,
            timezone,
            trigger.nick,
            trigger.sender,
            datetime.utcfromtimestamp(timestamp))
        bot.reply('Okay, will remind at %s' % human_time)
    else:
        bot.reply('Okay, will remind in %s secs' % duration)
예제 #30
0
def create_reminder(bot, trigger, duration, message, timezone):
    """Create a reminder into the ``bot``'s database and reply to the sender"""
    timestamp = int(time.time()) + duration
    reminder = (trigger.sender, trigger.nick, message)
    try:
        bot.rdb[timestamp].append(reminder)
    except KeyError:
        bot.rdb[timestamp] = [reminder]

    dump_database(bot.rfn, bot.rdb)

    if duration >= 60:
        human_time = format_time(bot.db, bot.config, timezone, trigger.nick,
                                 trigger.sender,
                                 datetime.utcfromtimestamp(timestamp))
        bot.reply('Okay, will remind at %s' % human_time)
    else:
        bot.reply('Okay, will remind in %s secs' % duration)
예제 #31
0
def create_reminder(bot, trigger, duration, message, tz):
    t = int(time.time()) + duration
    reminder = (trigger.sender, trigger.nick, message)
    try:
        bot.rdb[t].append(reminder)
    except KeyError:
        bot.rdb[t] = [reminder]

    dump_database(bot.rfn, bot.rdb)

    if duration >= 60:
        remind_at = datetime.utcfromtimestamp(t)
        timef = format_time(bot.db, bot.config, tz, trigger.nick,
                            trigger.sender, remind_at)

        bot.reply('Okay, will remind at %s' % timef)
    else:
        bot.reply('Okay, will remind in %s secs' % duration)
예제 #32
0
def create_reminder(bot, trigger, duration, message, tz):
    """Create reminder within specified period of time and message."""
    t = int(time.time()) + duration
    reminder = (trigger.sender, trigger.nick, message)
    try:
        bot.rdb[t].append(reminder)
    except KeyError:
        bot.rdb[t] = [reminder]

    dump_database(bot.rfn, bot.rdb)

    if duration >= 60:
        remind_at = datetime.utcfromtimestamp(t)
        timef = format_time(bot.db, bot.config, tz, trigger.nick,
                            trigger.sender, remind_at)

        bot.reply('Okay, I will set the reminder for: %s' % timef)
    else:
        bot.reply('Okay, I will send the reminder in %s secs' % duration)
예제 #33
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)
예제 #34
0
def f_time_zone(bot, trigger):
    """Return the current time in a timezone.

    Unlike the ``time`` command, it requires an argument, and that argument
    must be a valid timezone.
    """
    argument = trigger.group(2)
    if not argument:
        bot.reply(ERROR_NO_TIMEZONE)
        return

    zone = None
    argument = argument.strip()
    try:
        zone = validate_timezone(argument)
    except ValueError:
        bot.reply(ERROR_INVALID_TIMEZONE % argument)
        return

    time = format_time(bot.db, bot.config, zone, trigger.nick, trigger.sender)
    bot.say(time)
예제 #35
0
파일: remind.py 프로젝트: sopel-irc/sopel
def create_reminder(bot, trigger, duration, message, timezone):
    """Create a reminder into the ``bot``'s database and reply to the sender"""
    timestamp = int(time.time()) + duration
    reminder = (trigger.sender, trigger.nick, message)
    try:
        bot.rdb[timestamp].append(reminder)
    except KeyError:
        bot.rdb[timestamp] = [reminder]

    dump_database(bot.rfn, bot.rdb)

    if duration >= 60:
        human_time = format_time(
            bot.db,
            bot.config,
            timezone,
            trigger.nick,
            trigger.sender,
            datetime.utcfromtimestamp(timestamp))
        bot.reply('Okay, will remind at %s' % human_time)
    else:
        bot.reply('Okay, will remind in %s secs' % duration)
예제 #36
0
def f_time_zone(bot, trigger):
    """Return the current time in a timezone.

    Unlike the ``.t`` command, it requires an argument, and that argument
    must be a valid timezone.
    """
    argument = trigger.group(2)
    if not argument:
        bot.say('Please provide a timezone.')
        return

    zone = None
    argument = argument.strip()
    try:
        zone = validate_timezone(argument)
    except ValueError:
        bot.say('Cannot display time: "%s" is not a valid timezone.' %
                argument)
        return

    time = format_time(bot.db, bot.config, zone, trigger.nick, trigger.sender)
    bot.say(time)
예제 #37
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
예제 #38
0
def test_format_time(time_arg, result):
    assert time.format_time(time=time_arg) == result
예제 #39
0
def f_time(bot, trigger):
    """Return the current time.

    The command takes an optional parameter: it will try to guess if it's a
    nick, a channel, or a timezone (in that order).

    If it's a known nick or channel but there is no configured timezone, then
    it will complain. If nothing can be found, it'll complain that the argument
    is not a valid timezone.

    .. seealso::

        Function :func:`~sopel.tools.time.format_time` is used to format
        the current datetime according to the timezone (if found).

    """
    argument = trigger.group(2)

    if not argument:
        # get default timezone from nick, or sender, or bot, or UTC
        zone = get_timezone(bot.db, bot.config, None, trigger.nick,
                            trigger.sender)
    else:
        # guess if the argument is a nick, a channel, or a timezone
        zone = None
        argument = argument.strip()
        channel_or_nick = tools.Identifier(argument)

        # first, try to get nick or channel's timezone
        help_prefix = bot.config.core.help_prefix
        if channel_or_nick.is_nick():
            zone = get_nick_timezone(bot.db, channel_or_nick)
            if zone is None and channel_or_nick in bot.users:
                # zone not found for a known nick: error case
                set_command = '%ssettz <zone>' % help_prefix
                if channel_or_nick != trigger.nick:
                    bot.say('Could not find a timezone for this nick. '
                            '%s can set a timezone with `%s`' %
                            (argument, set_command))
                else:
                    bot.say('Could not find a timezone for you. '
                            'You can set your timezone with `%s`' %
                            set_command)
                return
        else:
            zone = get_channel_timezone(bot.db, channel_or_nick)
            if zone is None and channel_or_nick in bot.channels:
                # zone not found for an existing channel: error case
                set_command = '%ssetctz <zone>' % help_prefix
                bot.say('Could not find timezone for channel %s. '
                        'It can be set with `.setctz <zone>`. '
                        '(requires OP privileges)' % argument)
                return

        # then, fallback on timezone detection
        if zone is None:
            # argument not found as nick or channel timezone
            try:
                zone = validate_timezone(argument)
            except ValueError:
                bot.say('Could not find timezone "%s".' % argument)
                return

    time = format_time(bot.db, bot.config, zone, trigger.nick, trigger.sender)
    bot.say(time)