remove more needless plugins

This commit is contained in:
Christine Dodrill 2015-11-08 12:46:27 -08:00
parent fea780997d
commit 7e3e11fb3b
7 changed files with 0 additions and 708 deletions

View File

@ -1,89 +0,0 @@
"""
dice.py: written by Scaevolus 2008, updated 2009
simulates dicerolls
"""
import re
import random
from util import hook
whitespace_re = re.compile(r'\s+')
valid_diceroll = r'^([+-]?(?:\d+|\d*d(?:\d+|F))(?:[+-](?:\d+|\d*d(?:\d+|F)))*)( .+)?$'
valid_diceroll_re = re.compile(valid_diceroll, re.I)
sign_re = re.compile(r'[+-]?(?:\d*d)?(?:\d+|F)', re.I)
split_re = re.compile(r'([\d+-]*)d?(F|\d*)', re.I)
def nrolls(count, n):
"roll an n-sided die count times"
if n == "F":
return [random.randint(-1, 1) for x in xrange(min(count, 100))]
if n < 2: # it's a coin
if count < 5000:
return [random.randint(0, 1) for x in xrange(count)]
else: # fake it
return [int(random.normalvariate(.5 * count, (.75 * count) ** .5))]
else:
if count < 5000:
return [random.randint(1, n) for x in xrange(count)]
else: # fake it
return [int(random.normalvariate(.5 * (1 + n) * count,
(((n + 1) * (2 * n + 1) / 6. - (.5 * (1 + n)) ** 2) * count) ** .5))]
@hook.command('roll')
#@hook.regex(valid_diceroll, re.I)
@hook.command
def dice(inp):
".dice <diceroll> -- simulates dicerolls, e.g. .dice 2d20-d5+4 roll 2 " \
"D20s, subtract 1D5, add 4"
try: # if inp is a re.match object...
(inp, desc) = inp.groups()
except AttributeError:
(inp, desc) = valid_diceroll_re.match(inp).groups()
if "d" not in inp:
return
spec = whitespace_re.sub('', inp)
if not valid_diceroll_re.match(spec):
return "Invalid diceroll"
groups = sign_re.findall(spec)
total = 0
rolls = []
for roll in groups:
count, side = split_re.match(roll).groups()
count = int(count) if count not in " +-" else 1
if side.upper() == "F": # fudge dice are basically 1d3-2
for fudge in nrolls(count, "F"):
if fudge == 1:
rolls.append("\x033+\x0F")
elif fudge == -1:
rolls.append("\x034-\x0F")
else:
rolls.append("0")
total += fudge
elif side == "":
total += count
else:
side = int(side)
try:
if count > 0:
dice = nrolls(count, side)
rolls += map(str, dice)
total += sum(dice)
else:
dice = nrolls(-count, side)
rolls += [str(-x) for x in dice]
total -= sum(dice)
except OverflowError:
return "Thanks for overflowing a float, jerk >:["
if desc:
return "%s: %d (%s=%s)" % (desc.strip(), total, inp, ", ".join(rolls))
else:
return "%d (%s=%s)" % (total, inp, ", ".join(rolls))

View File

@ -1,108 +0,0 @@
import re
from util import hook, http
@hook.command('u')
@hook.command
def urban(inp):
'''.u/.urban <phrase> -- looks up <phrase> on urbandictionary.com'''
url = 'http://www.urbandictionary.com/iphone/search/define'
page = http.get_json(url, term=inp, headers={'Referer': 'http://m.urbandictionary.com'})
defs = page['list']
if page['result_type'] == 'no_results':
return 'not found.'
out = defs[0]['word'] + ': ' + defs[0]['definition'].replace('\r\n', ' ')
if len(out) > 400:
out = out[:out.rfind(' ', 0, 400)] + '...'
return out
# define plugin by GhettoWizard & Scaevolus
@hook.command('dictionary')
@hook.command
def define(inp):
".define/.dictionary <word> -- fetches definition of <word>"
url = 'http://ninjawords.com/'
h = http.get_html(url + http.quote_plus(inp))
definition = h.xpath('//dd[@class="article"] | '
'//div[@class="definition"] |'
'//div[@class="example"]')
if not definition:
return 'No results for ' + inp
def format_output(show_examples):
result = '%s: ' % h.xpath('//dt[@class="title-word"]/a/text()')[0]
correction = h.xpath('//span[@class="correct-word"]/text()')
if correction:
result = 'definition for "%s": ' % correction[0]
sections = []
for section in definition:
if section.attrib['class'] == 'article':
sections += [[section.text_content() + ': ']]
elif section.attrib['class'] == 'example':
if show_examples:
sections[-1][-1] += ' ' + section.text_content()
else:
sections[-1] += [section.text_content()]
for article in sections:
result += article[0]
if len(article) > 2:
result += ' '.join('%d. %s' % (n + 1, section)
for n, section in enumerate(article[1:]))
else:
result += article[1] + ' '
synonyms = h.xpath('//dd[@class="synonyms"]')
if synonyms:
result += synonyms[0].text_content()
result = re.sub(r'\s+', ' ', result)
result = re.sub('\xb0', '', result)
return result
result = format_output(True)
if len(result) > 450:
result = format_output(False)
if len(result) > 450:
result = result[:result.rfind(' ', 0, 450)]
result = re.sub(r'[^A-Za-z]+\.?$', '', result) + ' ...'
return result
@hook.command('e')
@hook.command
def etymology(inp):
".e/.etymology <word> -- Retrieves the etymology of chosen word"
url = 'http://www.etymonline.com/index.php'
h = http.get_html(url, term=inp)
etym = h.xpath('//dl')
if not etym:
return 'No etymology found for ' + inp
etym = etym[0].text_content()
etym = ' '.join(etym.split())
if len(etym) > 400:
etym = etym[:etym.rfind(' ', 0, 400)] + ' ...'
return etym

View File

@ -1,11 +0,0 @@
# for crusty old rotor
from util import hook
@hook.command
def profile(inp):
".profile <username> -- links to <username>'s profile on SA"
return 'http://forums.somethingawful.com/member.php?action=getinfo' + \
'&username=' + '+'.join(inp.split())

View File

@ -1,34 +0,0 @@
import re
from util import hook, http
search_url = "http://search.atomz.com/search/?sp_a=00062d45-sp00000000"
@hook.command
def snopes(inp):
".snopes <topic> -- searches snopes for an urban legend about <topic>"
search_page = http.get_html(search_url, sp_q=inp, sp_c="1")
result_urls = search_page.xpath("//a[@target='_self']/@href")
if not result_urls:
return "no matching pages found"
snopes_page = http.get_html(result_urls[0])
snopes_text = snopes_page.text_content()
claim = re.search(r"Claim: .*", snopes_text).group(0).strip()
status = re.search(r"Status: .*", snopes_text)
if status is not None:
status = status.group(0).strip()
else: # new-style statuses
status = "Status: %s." % re.search(r"FALSE|TRUE|MIXTURE|UNDETERMINED",
snopes_text).group(0).title()
claim = re.sub(r"[\s\xa0]+", " ", claim) # compress whitespace
status = re.sub(r"[\s\xa0]+", " ", status)
return "%s %s %s" % (claim, status, result_urls[0])

View File

@ -1,46 +0,0 @@
from util import hook, http
@hook.command
def stock(inp):
'''.stock <symbol> -- gets stock information'''
url = ('http://query.yahooapis.com/v1/public/yql?format=json&'
'env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys')
parsed = http.get_json(url, q='select * from yahoo.finance.quotes '
'where symbol in ("%s")' % inp) # heh, SQLI
quote = parsed['query']['results']['quote']
# if we dont get a company name back, the symbol doesn't match a company
if quote['Change'] is None:
return "unknown ticker symbol %s" % inp
price = float(quote['LastTradePriceOnly'])
change = float(quote['Change'])
if quote['Open'] and quote['Bid'] and quote['Ask']:
open_price = float(quote['Open'])
bid = float(quote['Bid'])
ask = float(quote['Ask'])
if price < bid:
price = bid
elif price > ask:
price = ask
change = price - open_price
quote['LastTradePriceOnly'] = "%.2f" % price
quote['Change'] = ("+%.2f" % change) if change >= 0 else change
if change < 0:
quote['color'] = "5"
else:
quote['color'] = "3"
quote['PercentChange'] = 100 * change / (price - change)
ret = "%(Name)s - %(LastTradePriceOnly)s " \
"\x03%(color)s%(Change)s (%(PercentChange).2f%%)\x03 " \
"Day Range: %(DaysRange)s " \
"MCAP: %(MarketCapitalization)s" % quote
return ret

View File

@ -1,315 +0,0 @@
# -*- coding: utf-8 -*-
import math
import random
import re
import threading
from util import hook
def sanitize(s):
return re.sub(r'[\x00-\x1f]', '', s)
@hook.command
def munge(inp, munge_count=0):
reps = 0
for n in xrange(len(inp)):
rep = character_replacements.get(inp[n])
if rep:
inp = inp[:n] + rep.decode('utf8') + inp[n + 1:]
reps += 1
if reps == munge_count:
break
return inp
class PaginatingWinnower(object):
def __init__(self):
self.lock = threading.Lock()
self.last_input = []
self.recent = set()
def winnow(self, inputs, limit=400, ordered=False):
"remove random elements from the list until it's short enough"
with self.lock:
# try to remove elements that were *not* removed recently
inputs_sorted = sorted(inputs)
if inputs_sorted == self.last_input:
same_input = True
else:
same_input = False
self.last_input = inputs_sorted
self.recent.clear()
combiner = lambda l: u', '.join(l)
suffix = ''
while len(combiner(inputs)) >= limit:
if same_input and any(inp in self.recent for inp in inputs):
if ordered:
for inp in self.recent:
if inp in inputs:
inputs.remove(inp)
else:
inputs.remove(
random.choice([inp for inp in inputs if inp in self.recent]))
else:
if ordered:
inputs.pop()
else:
inputs.pop(random.randint(0, len(inputs) - 1))
suffix = ' ...'
self.recent.update(inputs)
return combiner(inputs) + suffix
winnow = PaginatingWinnower().winnow
def add_tag(db, chan, nick, subject):
match = db.execute('select * from tag where lower(nick)=lower(?) and'
' chan=? and lower(subject)=lower(?)',
(nick, chan, subject)).fetchall()
if match:
return 'already tagged'
db.execute('replace into tag(chan, subject, nick) values(?,?,?)',
(chan, subject, nick))
db.commit()
return 'tag added'
def delete_tag(db, chan, nick, del_tag):
count = db.execute('delete from tag where lower(nick)=lower(?) and'
' chan=? and lower(subject)=lower(?)',
(nick, chan, del_tag)).rowcount
db.commit()
if count:
return 'deleted'
else:
return 'tag not found'
def get_tag_counts_by_chan(db, chan):
tags = db.execute("select subject, count(*) from tag where chan=?"
" group by lower(subject)"
" order by lower(subject)", (chan,)).fetchall()
tags.sort(key=lambda x: x[1], reverse=True)
if not tags:
return 'no tags in %s' % chan
return winnow(['%s (%d)' % row for row in tags], ordered=True)
def get_tags_by_nick(db, chan, nick):
tags = db.execute("select subject from tag where lower(nick)=lower(?)"
" and chan=?"
" order by lower(subject)", (nick, chan)).fetchall()
if tags:
return 'tags for "%s": ' % munge(nick, 1) + winnow([
tag[0] for tag in tags])
else:
return ''
def get_nicks_by_tagset(db, chan, tagset):
nicks = None
for tag in tagset.split('&'):
tag = tag.strip()
current_nicks = db.execute("select nick from tag where " +
"lower(subject)=lower(?)"
" and chan=?", (tag, chan)).fetchall()
if not current_nicks:
return "tag '%s' not found" % tag
if nicks is None:
nicks = set(current_nicks)
else:
nicks.intersection_update(current_nicks)
nicks = [munge(x[0], 1) for x in sorted(nicks)]
if not nicks:
return 'no nicks found with tags "%s"' % tagset
return 'nicks tagged "%s": ' % tagset + winnow(nicks)
@hook.command
def tag(inp, chan='', db=None):
'.tag <nick> <tag> -- marks <nick> as <tag> {related: .untag, .tags, .tagged, .is}'
db.execute('create table if not exists tag(chan, subject, nick)')
add = re.match(r'(\S+) (.+)', inp)
if add:
nick, subject = add.groups()
if nick.lower() == 'list':
return 'tag syntax has changed. try .tags or .tagged instead'
elif nick.lower() == 'del':
return 'tag syntax has changed. try ".untag %s" instead' % subject
return add_tag(db, chan, sanitize(nick), sanitize(subject))
else:
tags = get_tags_by_nick(db, chan, inp)
if tags:
return tags
else:
return tag.__doc__
@hook.command
def untag(inp, chan='', db=None):
'.untag <nick> <tag> -- unmarks <nick> as <tag> {related: .tag, .tags, .tagged, .is}'
delete = re.match(r'(\S+) (.+)$', inp)
if delete:
nick, del_tag = delete.groups()
return delete_tag(db, chan, nick, del_tag)
else:
return untag.__doc__
@hook.command
def tags(inp, chan='', db=None):
'.tags <nick>/list -- get list of tags for <nick>, or a list of tags {related: .tag, .untag, .tagged, .is}'
if inp == 'list':
return get_tag_counts_by_chan(db, chan)
tags = get_tags_by_nick(db, chan, inp)
if tags:
return tags
else:
return get_nicks_by_tagset(db, chan, inp)
@hook.command
def tagged(inp, chan='', db=None):
'.tagged <tag> [& tag...] -- get nicks marked as <tag> (separate multiple tags with &) {related: .tag, .untag, .tags, .is}'
return get_nicks_by_tagset(db, chan, inp)
@hook.command('is')
def is_tagged(inp, chan='', db=None):
'.is <nick> <tag> -- checks if <nick> has been marked as <tag> {related: .tag, .untag, .tags, .tagged}'
args = re.match(r'(\S+) (.+)$', inp)
if args:
nick, tag = args.groups()
found = db.execute("select 1 from tag"
" where lower(nick)=lower(?)"
" and lower(subject)=lower(?)"
" and chan=?", (nick, tag, chan)).fetchone()
if found:
return 'yes'
else:
return 'no'
else:
return is_tagged.__doc__
def distance(lat1, lon1, lat2, lon2):
deg_to_rad = math.pi / 180
lat1 *= deg_to_rad
lat2 *= deg_to_rad
lon1 *= deg_to_rad
lon2 *= deg_to_rad
R = 6371 # km
d = math.acos(math.sin(lat1) * math.sin(lat2) +
math.cos(lat1) * math.cos(lat2) *
math.cos(lon2 - lon1)) * R
return d
@hook.command(autohelp=False)
def near(inp, nick='', chan='', db=None):
try:
loc = db.execute("select lat, lon from location where chan=? and nick=lower(?)",
(chan, nick)).fetchone()
except db.OperationError:
loc = None
if loc is None:
return 'use .weather <loc> first to set your location'
lat, lon = loc
db.create_function('distance', 4, distance)
nearby = db.execute("select nick, distance(lat, lon, ?, ?) as dist from location where chan=?"
" and nick != lower(?) order by dist limit 20", (lat, lon, chan, nick)).fetchall()
in_miles = 'mi' in inp.lower()
out = '(km) '
factor = 1.0
if in_miles:
out = '(mi) '
factor = 0.621
while nearby and len(out) < 200:
nick, dist = nearby.pop(0)
out += '%s:%.0f ' % (munge(nick, 1), dist * factor)
return out
character_replacements = {
'a': 'ä',
# 'b': 'Б',
'c': 'ċ',
'd': 'đ',
'e': 'ë',
'f': 'ƒ',
'g': 'ġ',
'h': 'ħ',
'i': 'í',
'j': 'ĵ',
'k': 'ķ',
'l': 'ĺ',
# 'm': 'ṁ',
'n': 'ñ',
'o': 'ö',
'p': 'ρ',
# 'q': 'ʠ',
'r': 'ŗ',
's': 'š',
't': 'ţ',
'u': 'ü',
# 'v': '',
'w': 'ω',
'x': 'χ',
'y': 'ÿ',
'z': 'ź',
'A': 'Å',
'B': 'Β',
'C': 'Ç',
'D': 'Ď',
'E': 'Ē',
# 'F': 'Ḟ',
'G': 'Ġ',
'H': 'Ħ',
'I': 'Í',
'J': 'Ĵ',
'K': 'Ķ',
'L': 'Ĺ',
'M': 'Μ',
'N': 'Ν',
'O': 'Ö',
'P': 'Р',
# 'Q': '',
'R': 'Ŗ',
'S': 'Š',
'T': 'Ţ',
'U': 'Ů',
# 'V': 'Ṿ',
'W': 'Ŵ',
'X': 'Χ',
'Y': '',
'Z': 'Ż'}

View File

@ -1,105 +0,0 @@
" tell.py: written by sklnd in July 2009"
" 2010.01.25 - modified by Scaevolus"
import time
from util import hook, timesince
def db_init(db):
"check to see that our db has the tell table and return a dbection."
db.execute("create table if not exists tell"
"(user_to, user_from, message, chan, time,"
"primary key(user_to, message))")
db.commit()
return db
def get_tells(db, user_to):
return db.execute("select user_from, message, time, chan from tell where"
" user_to=lower(?) order by time",
(user_to.lower(),)).fetchall()
@hook.singlethread
@hook.event('PRIVMSG')
def tellinput(paraml, input=None, db=None):
if 'showtells' in input.msg.lower():
return
db_init(db)
tells = get_tells(db, input.nick)
if tells:
user_from, message, time, chan = tells[0]
reltime = timesince.timesince(time)
reply = "%s said %s ago in %s: %s" % (user_from, reltime, chan,
message)
if len(tells) > 1:
reply += " (+%d more, .showtells to view)" % (len(tells) - 1)
db.execute("delete from tell where user_to=lower(?) and message=?",
(input.nick, message))
db.commit()
input.pm(reply)
@hook.command(autohelp=False)
def showtells(inp, nick='', chan='', pm=None, db=None):
".showtells -- view all pending tell messages (sent in PM)."
db_init(db)
tells = get_tells(db, nick)
if not tells:
pm("You have no pending tells.")
return
for tell in tells:
user_from, message, time, chan = tell
past = timesince.timesince(time)
pm("%s said %s ago in %s: %s" % (user_from, past, chan, message))
db.execute("delete from tell where user_to=lower(?)",
(nick,))
db.commit()
@hook.command
def tell(inp, nick='', chan='', db=None, conn=None):
".tell <nick> <message> -- relay <message> to <nick> when <nick> is around"
query = inp.split(' ', 1)
if len(query) != 2:
return tell.__doc__
user_to = query[0].lower()
message = query[1].strip()
user_from = nick
if chan.lower() == user_from.lower():
chan = 'a pm'
if user_to in (user_from.lower(), conn.nick.lower()):
return "No."
db_init(db)
if db.execute("select count() from tell where user_to=?",
(user_to,)).fetchone()[0] >= 5:
return "That person has too many things queued."
try:
db.execute("insert into tell(user_to, user_from, message, chan,"
"time) values(?,?,?,?,?)", (user_to, user_from, message,
chan, time.time()))
db.commit()
except db.IntegrityError:
return "Message has already been queued."
return "I'll pass that along."