本文整理汇总了Python中sopel.tools.time.get_timezone函数的典型用法代码示例。如果您正苦于以下问题:Python get_timezone函数的具体用法?Python get_timezone怎么用?Python get_timezone使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_timezone函数的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: f_time
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)
开发者ID:firerogue,项目名称:sopel,代码行数:12,代码来源:clock.py
示例2: update_channel_format
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)
开发者ID:firerogue,项目名称:sopel,代码行数:34,代码来源:clock.py
示例3: seen
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))
开发者ID:piagetbot,项目名称:sopel,代码行数:32,代码来源:seen.py
示例4: update_user_format
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)
开发者ID:firerogue,项目名称:sopel,代码行数:30,代码来源:clock.py
示例5: remind
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)
开发者ID:Ameenekosan,项目名称:Yumiko,代码行数:32,代码来源:remind.py
示例6: get_data
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
开发者ID:CoRD-Dev,项目名称:flutterfuck-github,代码行数:34,代码来源:github.py
示例7: rpost_info
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)
开发者ID:dasu,项目名称:sopel,代码行数:57,代码来源:reddit.py
示例8: f_remind
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
开发者ID:paulmadore,项目名称:funkshelper,代码行数:51,代码来源:tell.py
示例9: f_remind
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
开发者ID:mossarelli,项目名称:Moss-Sopel-Modules,代码行数:49,代码来源:tell.py
示例10: f_remind
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
开发者ID:calzoneman,项目名称:sopel,代码行数:47,代码来源:tell.py
示例11: at
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')
开发者ID:Ameenekosan,项目名称:Yumiko,代码行数:46,代码来源:remind.py
示例12: github_repo
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)
开发者ID:CoRD-Dev,项目名称:flutterfuck-github,代码行数:42,代码来源:github.py
示例13: preformat
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
开发者ID:maxpowa,项目名称:sopel-chanlogs2,代码行数:39,代码来源:formatter.py
示例14: remind_at
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)
开发者ID:sopel-irc,项目名称:sopel,代码行数:36,代码来源:remind.py
注:本文中的sopel.tools.time.get_timezone函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论