Skip to content

Instantly share code, notes, and snippets.

@avidal
Created December 18, 2010 03:58
Show Gist options
  • Save avidal/746133 to your computer and use it in GitHub Desktop.
Save avidal/746133 to your computer and use it in GitHub Desktop.
weechat plugin to pull player counts from wotmud.org
import datetime
import re
import time
import urllib2
import weechat
weechat.register("wotmud_playerinfo", "Alex Vidal", "1.0", "MIT", "Fetches WoTMUD Player Info", "", "")
ungettext = lambda single, plural, n: single if n == 1 else plural
ugettext = lambda s: s
def timesince(d, now=None):
"""
Takes two datetime objects and returns the time between d and now
as a nicely formatted string, e.g. "10 minutes". If d occurs after now,
then "0 minutes" is returned.
Units used are years, months, weeks, days, hours, and minutes.
Seconds and microseconds are ignored. Up to two adjacent units will be
displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are
possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.
Adapted from http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
"""
chunks = (
(60 * 60 * 24 * 365, lambda n: ungettext('year', 'years', n)),
(60 * 60 * 24 * 30, lambda n: ungettext('month', 'months', n)),
(60 * 60 * 24 * 7, lambda n : ungettext('week', 'weeks', n)),
(60 * 60 * 24, lambda n : ungettext('day', 'days', n)),
(60 * 60, lambda n: ungettext('hour', 'hours', n)),
(60, lambda n: ungettext('minute', 'minutes', n))
)
# Convert datetime.date to datetime.datetime for comparison.
if not isinstance(d, datetime.datetime):
d = datetime.datetime(d.year, d.month, d.day)
if now and not isinstance(now, datetime.datetime):
now = datetime.datetime(now.year, now.month, now.day)
if not now:
now = datetime.datetime.now()
# ignore microsecond part of 'd' since we removed it from 'now'
delta = now - (d - datetime.timedelta(0, 0, d.microsecond))
since = delta.days * 24 * 60 * 60 + delta.seconds
if since <= 0:
# d is in the future compared to now, stop processing.
return u'0 ' + ugettext('minutes')
for i, (seconds, name) in enumerate(chunks):
count = since // seconds
if count != 0:
break
s = ugettext('%(number)d %(type)s') % {'number': count, 'type': name(count)}
if i + 1 < len(chunks):
# Now get the second item
seconds2, name2 = chunks[i + 1]
count2 = (since - (seconds * count)) // seconds2
if count2 != 0:
s += ugettext(', %(number)d %(type)s') % {'number': count2, 'type': name2(count2)}
return s
def timeuntil(d, now=None):
"""
Like timesince, but returns a string measuring the time until
the given time.
"""
if not now:
now = datetime.datetime.now()
return timesince(now, d)
LAST_UPDATE = None
CACHED_COUNT = 0
def get_players():
global LAST_UPDATE, CACHED_COUNT
if LAST_UPDATE:
delta = datetime.datetime.now() - LAST_UPDATE
if delta.days or delta.seconds > 60*5:
pass
else:
return CACHED_COUNT
url = 'http://www.wotmud.org/num.php'
try:
content = urllib2.urlopen(url).read()
players_re = r'There are currently (\d+) players on the game.'
match = re.search(players_re, content)
players = match.groups()[0]
LAST_UPDATE = datetime.datetime.now()
CACHED_COUNT = int(players)
return players
except:
return None
def do_wmtopic(data=None, buffer=None, args=None, fromtimer=False):
global CACHED_COUNT
cache = CACHED_COUNT
topic_re = r'There are currently (\d+) player(?:\(s\)|s)? on the game.'
default_topic = "There are currently %(player_count)d player(s) on the game."
wm_buf = weechat.buffer_search("irc", "freenode.##wotmud")
if fromtimer:
# called from the timer
args = '-keep'
if args.strip() == '-keep':
# find the current topic
topic = weechat.buffer_get_string(wm_buf, "title")
elif args:
topic = args
topic = re.sub(topic_re, '', topic)
topic += default_topic
try:
player_count = int(get_players())
topic = topic % dict(player_count=player_count)
weechat.command(wm_buf, "/topic %s" % topic)
except:
print "Error running command."
return weechat.WEECHAT_RC_OK
weechat.hook_command("wmtopic", "Sets the current player info in the topic.",
"[topic]",
"[topic] - current channel topic",
"%(irc_channel_topic)",
"do_wmtopic", "")
def do_wmtopic_timer(*args, **kwargs):
return do_wmtopic(fromtimer=True)
weechat.hook_timer(1000 * 60 * 30, 0, 0, "do_wmtopic_timer", "")
def reply_player_count(data, buffer, date, tags, displayed, highlight, prefix, message):
global LAST_UPDATE
# make sure it's the ##wotmud channel
if not message.startswith('!players'):
return weechat.WEECHAT_RC_OK
wm_buf = weechat.buffer_search("irc", "freenode.##wotmud")
if wm_buf != buffer:
return weechat.WEECHAT_RC_OK
# good to go
try:
player_count = int(get_players())
except ValueError:
weechat.command(buffer, "/say Error loading player count.")
return weechat.WEECHAT_RC_OK
weechat.command(buffer, "/say %d players online (updated %s ago)" % (player_count, timesince(LAST_UPDATE)))
return weechat.WEECHAT_RC_OK
weechat.hook_print("", "", "!players", 1, "reply_player_count", "")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment