예제 #1
0
def interview_responses(target):
    if not "suspect" in mb.data['interview'] or not "detective" in mb.data[
            "interview"]:
        mb.tell("there's no game going", target)
        return
    suspect = mb.data['interview']['suspect']
    detective = mb.data['interview']['detective']

    shoot_response = {
        'func': shoot_func,
        'pattern': shoot,
        'nick': suspect + '|' + detective,
        'target': target
    }
    next_response = {
        'func': next_func,
        'pattern': next,
        'nick': detective,
        'target': target
    }

    mb.responses['interview_shoot'] = shoot_response
    print(mb.responses['interview_shoot'])
    mb.responses['interview_next'] = next_response
    mb.tell("ok done", target)
예제 #2
0
def type_in_func(nick,match,target):
		options=re.split(separation,match.group('options'))
		options=[option.upper() for option in options]
		no=match.group("no")
		if "CAPS" in options:
			if no:
				mb.data['options']['caps']=False
			else:
				mb.data['options']['caps']=True
		if "NORMALLY" in options:
			mb.data['options']['quirk']=[]
			mb.data['options']['caps']=False
			mb.data['options']['color']=""
		else:
			quirks=[mb.format[option] for option in options if option in mb.format]
			if no:
				mb.data['options']['quirk']=list(set(mb.data['options']['quirk'])-set(quirks))	
			else:
				mb.data['options']['quirk'].extend(quirks)
				mb.data['options']['quirk']=list(set(mb.data['options']['quirk']))

		for index,color in enumerate(mb.colors):
			if color in options:
				mb.data['options']['color']=chr(0x03)+str(index)
				break
		mb.save('options')
		mb.tell(nick+": I'll try",target)
예제 #3
0
def urban_func(nick, match, target):
    what = urllib.urlencode({"term": match.group("what")})
    s = match.group('s')
    r = match.group('r')
    req = urllib2.Request(
        'https://mashape-community-urban-dictionary.p.mashape.com/define?' +
        what)
    req.add_header("X-Mashape-Key",
                   "6SRh5ZIyhhmshOjLLIEVlfRzZR3Mp1KJgLsjsny2Vq36opmhI6")
    req.add_header("Accept", "text/plain")
    try:
        response = json.loads(urllib2.urlopen(req).read().decode('utf-8'))

        if response['result_type'] == "no_results":
            mb.tell(nick + ": none of that", target)
            return

        if s:
            mb.tell(choice(response['sounds']), target)
        else:
            if r:
                result = choice(response['list'])
            else:
                result = response['list'][0]
            mb.tell(" ".join(result['definition'].splitlines())[:200], target)
            mb.tell(
                "example: " + " ".join(result['example'].splitlines())[:200],
                target)

    except:
        mb.tell(nick + ": whoops.", target)
        traceback.print_exc()
예제 #4
0
def convert_func(nick, match, target):
    amount = match.group('amount')
    if not amount:
        amount = "1"
    what = match.group('what')
    to = match.group('to')
    params = urllib.urlencode(
        {
            "from-type": what,
            "from-value": amount,
            "to-type": to
        }, 'utf-8').encode('utf-8')
    headers = {
        "X-Mashape-Key": "6SRh5ZIyhhmshOjLLIEVlfRzZR3Mp1KJgLsjsny2Vq36opmhI6",
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "application/json"
    }
    request = urllib2.Request(
        "https://community-neutrino-currency-conversion.p.mashape.com/convert",
        headers=headers,
        data=params)
    response = urllib2.urlopen(request).read()
    result = json.loads(response.decode('utf-8'))
    if result['valid'] == True:
        mb.tell(
            nick + ": {} {} is {:.4f} {}".format(amount, what,
                                                 float(result['result']), to),
            target)
    else:
        mb.tell(nick + ": convert these nuts on your chin", target)
    return
예제 #5
0
def whow_func(nick,match,target):
	headers={'X-Mashape-Key': '6SRh5ZIyhhmshOjLLIEVlfRzZR3Mp1KJgLsjsny2Vq36opmhI6',
			'Accept':'application/json'}
	req=urllib2.Request('https://hargrimm-wikihow-v1.p.mashape.com/steps?count=3',headers=headers)
	response=urllib2.urlopen(req).read()
	data=json.loads(response.decode("utf-8"))	
	mb.tell(nick+": 1.{} 2.{} 3.{}".format(data['1'],data['2'],data['3']),target)
예제 #6
0
def purge_aliases_func(nick,match,target):
	name=match.group('name')
	if not name in mb.data['aliases']:
		mb.tell(nick+": literally who",target)
	else:
		del mb.data['aliases'][name]
		mb.save('aliases')
		mb.tell(nick+": bam, done",target)
예제 #7
0
def can_you_speak_func(nick, match, target):
    lang = match.group('lang')
    for code, language in langs.items():
        if re.search("^" + re.escape(lang) + "$", language, re.IGNORECASE):
            mb.tell(nick + ": Yes.", target)
            return
    mb.tell(nick + ": No.", target)
    return
예제 #8
0
def can_you_speak_func(nick,match,target):
	lang=match.group('lang')
	for code,language in langs.items():
		if re.search("^"+re.escape(lang)+"$",language,re.IGNORECASE):
			mb.tell(nick+": Yes.",target)
			return
	mb.tell(nick+": No.",target)
	return
예제 #9
0
def prequel_func(nick,match,target):
	try:
		resp=urllib2.urlopen("http://www.prequeladventure.com/feed").read().decode("utf-8")
		date=re.search("<pubDate>(.*)</pubDate>",resp,re.I).group(1)
		mb.tell(nick+", last update: "+date,target)
	except:
		mb.tell(nick+": ERROЯ",target)
		traceback.print_exc()
예제 #10
0
def add_quote_func(nick,match,target):
	text=match.group('quote')
	date=datetime.date.today().isoformat()
	quote={'quote':text,'added by':nick,'date':date}
	mb.data['quotes'].append(quote)
	mb.save('quotes')
	mb.tell(nick+': added.',target)
	
	return
예제 #11
0
def add_quote_func(nick, match, target):
    text = match.group('quote')
    date = datetime.date.today().isoformat()
    quote = {'quote': text, 'added by': nick, 'date': date}
    mb.data['quotes'].append(quote)
    mb.save('quotes')
    mb.tell(nick + ': added.', target)

    return
예제 #12
0
def help_func(nick,match,target,param=None):
	category=match.group('cat')
	if category in mb.help:
		mb.tell(nick+": "+mb.help[category],target)
	else:
		mb.tell(nick+ ": help with "+", ".join(list(mb.help.keys())),target)
		pattern=re.compile("^(?P<cat>"+"|".join(list(mb.help.keys()))+")$",flags=re.IGNORECASE)
		response={'pattern':pattern,'nick':nick,'target':target,'func':help_func}
		mb.responses['help']=response
예제 #13
0
def on_start_func(nick,match,target):
	channel="#"+match.group('channel')
	if match.group('no'):
		mb.data['options']['to join']=list(set(mb.data['options']['to join'])-set([channel]))
	else:
		mb.data['options']['to join'].append(channel)
		mb.data['options']['to join']=list(set(mb.data['options']['to join']))
	mb.save('options')
	mb.tell(nick+": ok",target)
예제 #14
0
def prequel_func(nick, match, target):
    try:
        resp = urllib2.urlopen(
            "http://www.prequeladventure.com/feed").read().decode("utf-8")
        date = re.search("<pubDate>(.*)</pubDate>", resp, re.I).group(1)
        mb.tell(nick + ", last update: " + date, target)
    except:
        mb.tell(nick + ": ERROЯ", target)
        traceback.print_exc()
예제 #15
0
def add_uncle_func(nick,match,target):
		names=re.split(separation,match.group('names'))
		if match.group('not'):
			mb.data['uncles']=list(set(mb.data['uncles'])-set(names))
			mb.tell(nick+": well thank f**k", target)
		else:

			mb.data['uncles']=list(set(mb.data['uncles']) | set(names))
			mb.tell(nick+": I mean ew but ok", target)
		mb.save('uncles')
예제 #16
0
def calc_func(nick, match, target):
    expr = match.group("expr")
    vpi = re.compile("п|pi", flags=re.IGNORECASE)
    ve = re.compile("(?<!\d)e(?!\d)", flags=re.IGNORECASE)
    expr = re.sub(ve, "math.e", expr)
    expr = re.sub(vpi, "math.pi", expr)
    try:
        mb.tell(nick + ": " + str(eval(expr)), target)
    except:
        mb.tell(nick + ": yeah nah", target)
예제 #17
0
def calc_func(nick,match,target):
	expr=match.group("expr")
	vpi=re.compile("п|pi",flags=re.IGNORECASE)
	ve=re.compile("(?<!\d)e(?!\d)",flags=re.IGNORECASE)
	expr=re.sub(ve,"math.e",expr)
	expr=re.sub(vpi,"math.pi",expr)
	try:
		mb.tell(nick+": "+str(eval(expr)),target)
	except:
		mb.tell(nick+": yeah nah",target)
예제 #18
0
def whow_func(nick, match, target):
    headers = {
        'X-Mashape-Key': '6SRh5ZIyhhmshOjLLIEVlfRzZR3Mp1KJgLsjsny2Vq36opmhI6',
        'Accept': 'application/json'
    }
    req = urllib2.Request(
        'https://hargrimm-wikihow-v1.p.mashape.com/steps?count=3',
        headers=headers)
    response = urllib2.urlopen(req).read()
    data = json.loads(response.decode("utf-8"))
    mb.tell(nick + ": 1.{} 2.{} 3.{}".format(data['1'], data['2'], data['3']),
            target)
예제 #19
0
def interview_stats_func(nick,match,target):
	who=match.group('nick')	
	if not who:
		who=nick
	for player in mb.data['aliases']:
		if who in mb.data['aliases'][player]:
			who=player
			break
	if who in mb.data['interview_stats']:
		stats=mb.data['interview_stats'][who]
		mb.tell(who+": detective: w-{wins}, l-{losses}".format(**stats['as detective'])+"; replicant: w-{wins}, l-{losses}".format(**stats['as replicant']),target)
	else:
		mb.tell(who+" never played interview",target)
예제 #20
0
def seen_func(nick,match,target):
	who = match.group('who')
	
	
	if who in mb.data['logs']:
		date = datetime.now()
		when = mb.data['logs'][who]['date']
		now=shared.time_dict(date)
		
		time=shared.time_diff(now,when)
		mb.tell(nick+": "+who+" was here "+time+", saying '"+mb.data['logs'][who]['message']+"'",target)
	else:
	
		mb.tell(nick+": never heard of that douche",target)
예제 #21
0
def lewd_func(nick,match,target):
	what = match.group('what')
	query = urllib.urlencode({'tag':what})
	
	tumbles = mb.data['stuff']['p**n-blogs']
	shuffle(tumbles)
	posts = []
	

	result = None
	
	
	for tumble in tumbles:
		try:
			req = urllib2.Request("https://api.tumblr.com/v2/blog/"+tumble+".tumblr.com/posts/photo?api_key=oBkePh2f80LWzw0jfO3DEYz2YLfRRCmmz8VM9rsv5cxwa4kGAZ&"+query)
			response = json.loads(urllib2.urlopen(req).read().decode('utf-8'))
		except:
			mb.tell("whoa there hol up something aint right",target)
			traceback.print_exc()
			return
		posts = response['response']['posts']
		shuffle(posts)
		
		if posts == []:
			continue
		else:
			for post in posts:
				photo = choice(post['photos'])['original_size']['url']
				if re.search(".gif$",photo):
					mb.tell(nick+": "+photo,target)
					mb.tell("post: "+post["short_url"],target)
					return
		
	mb.tell(nick+": none of that here, what is wrong with you",target)	
예제 #22
0
def interview_responses(target):
	if not "suspect" in mb.data['interview'] or not "detective" in mb.data["interview"]:
		mb.tell("there's no game going",target)
		return
	suspect = mb.data['interview']['suspect']
	detective = mb.data['interview']['detective']
	
	shoot_response={'func':shoot_func,'pattern':shoot,'nick':suspect+'|'+detective,'target':target}
	next_response={'func':next_func,'pattern':next,'nick':detective,'target':target}
	
	mb.responses['interview_shoot']=shoot_response
	print(mb.responses['interview_shoot']);
	mb.responses['interview_next']=next_response
	mb.tell("ok done",target)
예제 #23
0
def synonym_func(nick,match,target):
	word=match.group('word')
	synsets=wn.synsets(word)
	synonyms=[]
	for synset in synsets:
		for name in synset.lemma_names():
			if not name in synonyms:
				synonyms.append(name)
	if synonyms==[]:
		response="Your "+choice(("face","butt","dick","t**s","life","mum","worth as a human","balls","social skills","sex life","intellect"))
	else:
		separator=", "
		response=separator.join(synonyms)
	mb.tell(nick+": "+response,target)
	return
예제 #24
0
def show_quiz_stats_func(nick,match,target):
	name=match.group('name')
	if not name:
		name=nick
	
	for player in mb.data['aliases']:
		if name in mb.data['aliases'][player]:
			name=player
	
	if not name in mb.data['quiz_stats']:
		mb.tell('that chump never even played',target)
	else:
		stats=mb.data['quiz_stats'][name]
		mb.tell(name+" stats: "+", ".join("{}:{}".format(key,val) for key,val in stats.items()),target)
	return
예제 #25
0
def yiff_func(nick, match, target):
    who = match.group("who")
    if who == "me":
        who = nick
    elif who in ["yourself", "urself"]:
        who = mb.nickname
    mb.data['yiff']['caller'] = [nick]
    mb.data['yiff']['target'] = [who]
    too_much = 20
    pattern = re.compile("{([|\w_]+)}")
    yiff = choice(mb.data['yiff']['yiff'])
    while re.search("{", yiff) and too_much > 0:
        too_much -= 1
        yiff = re.sub(pattern, yiff_pick, yiff)
    mb.tell(yiff, target, action=True)
예제 #26
0
def search_quote_func(nick,match,target):
	results=[]
	term=match.group('term').strip()
	rgx=".*"+re.sub("\s+","\s+",term)
	print(rgx)
	pattern=re.compile(rgx,flags=re.IGNORECASE)
	
	for index,quote in enumerate(mb.data['quotes']):
		if re.search(pattern,quote['quote']):
			results.append(str(index+1))
	if results==[]:
		mb.tell(nick+": nope, none of that",target)
	else:
		mb.tell(nick+", here's what I found ("+str(len(results))+" results): "+", ".join(results),target)
	return
예제 #27
0
def yiff_func(nick,match,target):
	who=match.group("who")
	if who == "me":
		who = nick
	elif who in ["yourself","urself"]:
		who = mb.nickname
	mb.data['yiff']['caller']=[nick];
	mb.data['yiff']['target']=[who];
	too_much=20
	pattern = re.compile("{([|\w_]+)}")
	yiff = choice(mb.data['yiff']['yiff'])
	while re.search("{",yiff) and too_much>0:
		too_much -= 1	
		yiff=re.sub(pattern,yiff_pick,yiff)
	mb.tell(yiff,target,action=True)
예제 #28
0
def seen_func(nick, match, target):
    who = match.group('who')

    if who in mb.data['logs']:
        date = datetime.now()
        when = mb.data['logs'][who]['date']
        now = shared.time_dict(date)

        time = shared.time_diff(now, when)
        mb.tell(
            nick + ": " + who + " was here " + time + ", saying '" +
            mb.data['logs'][who]['message'] + "'", target)
    else:

        mb.tell(nick + ": never heard of that douche", target)
예제 #29
0
def interview_stats_func(nick, match, target):
    who = match.group('nick')
    if not who:
        who = nick
    for player in mb.data['aliases']:
        if who in mb.data['aliases'][player]:
            who = player
            break
    if who in mb.data['interview_stats']:
        stats = mb.data['interview_stats'][who]
        mb.tell(
            who +
            ": detective: w-{wins}, l-{losses}".format(**stats['as detective'])
            + "; replicant: w-{wins}, l-{losses}".format(
                **stats['as replicant']), target)
    else:
        mb.tell(who + " never played interview", target)
예제 #30
0
def antonym_func(nick,match,target):
	word=match.group('word')
	synsets=wn.synsets(word)
	antonym_list=[]
	for synset in synsets:
		for lemma in synset.lemmas():
			for antonym in lemma.antonyms():
				name=antonym.name()
				if not name in antonym_list:
					antonym_list.append(name)
	if antonym_list==[]:
		antonym="Your "+choice(("face","butt","dick","t**s","life","mum","worth as a human","balls","social skills","sex life","intellect"))
	else:
		s=", "
		antonym=s.join(antonym_list)
	mb.tell(nick+": "+antonym,target)
	return
예제 #31
0
def deliver_message_func(nick, match, target):
    if nick not in mb.data['logs']:
        return

    if "messages" in mb.data['logs'][nick]:
        for message in mb.data['logs'][nick]['messages']:
            date = datetime.now()
            now = shared.time_dict(date)
            when = message['date']
            time = shared.time_diff(now, when)

            mb.tell(message['nick'] + " said " + time + ": " + message['text'],
                    nick)

        mb.data['logs'][nick]['messages'] = []
        mb.save('logs')
    return
예제 #32
0
def quiz_answer(nick,match,target,param):
	who=None
	if nick in mb.data['quiz_stats']:
		who=nick
	for player in mb.data['aliases']:
		if nick in mb.data['aliases'][player]:
			who=player
			break

	if who:
		mb.data['quiz_stats'][who]['answers']+=1
	else:
		mb.data['quiz_stats'][nick]={'answers':1}
	del mb.responses['quiz']
	mb.tell(nick+": correct! good job nerd.",target)
	mb.save('quiz_stats')
	return
예제 #33
0
def search_quote_func(nick, match, target):
    results = []
    term = match.group('term').strip()
    rgx = ".*" + re.sub("\s+", "\s+", term)
    print(rgx)
    pattern = re.compile(rgx, flags=re.IGNORECASE)

    for index, quote in enumerate(mb.data['quotes']):
        if re.search(pattern, quote['quote']):
            results.append(str(index + 1))
    if results == []:
        mb.tell(nick + ": nope, none of that", target)
    else:
        mb.tell(
            nick + ", here's what I found (" + str(len(results)) +
            " results): " + ", ".join(results), target)
    return
예제 #34
0
def help_func(nick, match, target, param=None):
    category = match.group('cat')
    if category in mb.help:
        mb.tell(nick + ": " + mb.help[category], target)
    else:
        mb.tell(nick + ": help with " + ", ".join(list(mb.help.keys())),
                target)
        pattern = re.compile("^(?P<cat>" + "|".join(list(mb.help.keys())) +
                             ")$",
                             flags=re.IGNORECASE)
        response = {
            'pattern': pattern,
            'nick': nick,
            'target': target,
            'func': help_func
        }
        mb.responses['help'] = response
예제 #35
0
def send_message_func(nick,match,target):
	who = match.group('who')
	date = datetime.now()
	when=shared.time_dict(date)
	
	message = match.group('what')
	if not who in mb.data['logs']:
		mb.data['logs'][who]={}

	if not 'messages' in mb.data['logs'][who]:	
		mb.data['logs'][who]['messages']=[]
		
	mb.data['logs'][who]['messages'].append({'text':message, 'nick': nick,'date':when})
	

	
	mb.tell(nick+": jeez FINE I'll tell em",target)
	mb.save('logs')
예제 #36
0
def deliver_message_func(nick,match,target):
	if nick not in mb.data['logs']:
		return

	if "messages" in mb.data['logs'][nick]:
		for message in mb.data['logs'][nick]['messages']:
			date = datetime.now()
			now=shared.time_dict(date)
			when = message['date']
			time = shared.time_diff(now,when)
			
			
			mb.tell(message['nick']+" said "+time+": "+message['text'],nick)
			
		
		mb.data['logs'][nick]['messages']=[]
		mb.save('logs')
	return
예제 #37
0
def interview_champion_func(nick, match, target):
    champs = []
    record = 0
    for name, user in mb.data['interview_stats'].items():
        d_w = user['as detective']['wins']
        r_w = user['as replicant']['wins']
        d_l = user['as detective']['losses']
        r_l = user['as replicant']['losses']
        score = d_w + r_w - r_l - d_l
        if score > record:
            record = score
            champs = [name]
        elif score == record:
            champs.append(name)

    if record == 0:
        mb.tell(nick + ": no champion you all suck", target)
    else:
        mb.tell(nick + ": " + ", ".join(champs), target)
예제 #38
0
def interview_champion_func(nick,match,target):
	champs=[]
	record=0
	for name,user in mb.data['interview_stats'].items():
		d_w=user['as detective']['wins']
		r_w=user['as replicant']['wins']
		d_l=user['as detective']['losses']
		r_l=user['as replicant']['losses']
		score=d_w+r_w-r_l-d_l
		if score>record:
			record=score
			champs=[name]
		elif score==record:
			champs.append(name)
	
	if record==0:
		mb.tell(nick+": no champion you all suck",target)
	else:
		mb.tell(nick+": "+", ".join(champs),target)
예제 #39
0
def add_aliases_func(nick,match,target):
	
	name=match.group('name')
	no=match.group('no')
	aliases=re.split(separation,match.group('aliases'))
	
	if no:
		if name in mb.data['aliases']:
			mb.data['aliases'][name]=list(set(mb.data['aliases'][name])-set(aliases))
		else:
			mb.tell(nick+": who?...",target)
			return
	else:
		if name in mb.data['aliases']:
			mb.data['aliases'][name]=list(set(mb.data['aliases'][name])| set(aliases))
		else:
			mb.data['aliases'][name]=aliases
	mb.save('aliases')
	mb.tell(nick+": alright done",target)
예제 #40
0
def aka_func(nick,match,target):
	who=match.group('who')
	lst=None
	if not who:
		who=nick
	if who in mb.data['aliases']:
		lst=mb.data['aliases'][who]
	else:
		for player in mb.data['aliases']:
			if who in mb.data['aliases'][player]:
				lst=mb.data['aliases'][player]
				who=player
				break
			
	if not lst:
		lst=['big nerd']
	mb.tell("{}, a.k.a {}".format(who,", ".join(lst)),target)
	
	return
예제 #41
0
def send_message_func(nick, match, target):
    who = match.group('who')
    date = datetime.now()
    when = shared.time_dict(date)

    message = match.group('what')
    if not who in mb.data['logs']:
        mb.data['logs'][who] = {}

    if not 'messages' in mb.data['logs'][who]:
        mb.data['logs'][who]['messages'] = []

    mb.data['logs'][who]['messages'].append({
        'text': message,
        'nick': nick,
        'date': when
    })

    mb.tell(nick + ": jeez FINE I'll tell em", target)
    mb.save('logs')
예제 #42
0
def convert_func(nick,match,target):
	amount=match.group('amount')
	if not amount:
		amount="1";
	what=match.group('what')
	to=match.group('to')
	params=urllib.urlencode({"from-type": what,
								"from-value": amount,
								"to-type": to},'utf-8').encode('utf-8')
	headers={"X-Mashape-Key": "6SRh5ZIyhhmshOjLLIEVlfRzZR3Mp1KJgLsjsny2Vq36opmhI6",
			"Content-Type": "application/x-www-form-urlencoded",
			"Accept": "application/json"}
	request = urllib2.Request("https://community-neutrino-currency-conversion.p.mashape.com/convert",headers=headers,data=params)
	response=urllib2.urlopen(request).read()
	result=json.loads(response.decode('utf-8'))
	if result['valid']==True:
		mb.tell(nick+": {} {} is {:.4f} {}".format(amount,what,float(result['result']),to),target)
	else:
		mb.tell(nick+": convert these nuts on your chin",target)							
	return 
예제 #43
0
def quiz_champ_func(nick,match,target):
	max=0
	champs=[]
	for name,score in mb.data['quiz_stats'].items():
		if score['answers']==max:
			champs.append(name)
		elif score['answers']>max:
			champs=[name]
			max=score['answers']
	if max==0:
		tell("{}: there are none, you're all losers".format(nick))
		return
	if len(champs)==1:
		plural=""
		be="IS"
	else:
		plural="S"
		be="ARE"
	mb.tell("{}: the current quiz champion{} {} {} with {} answers".format(nick,plural,be,", ".join(champs),str(max)),target)
	return
예제 #44
0
def points_func(nick,match,target):
	do=match.group('do')
	who=None
	name=match.group('name')
	number=int(match.group('number'))
	if name in mb.data['quiz_stats']:
		who=name
	else:
		for player in mb.data['aliases']:
			if who in mb.data['aliases'][player] and player in mb.data['quiz_stats']:
				who=player
	if not who:
		mb.tell(nick+": what points you f**k",target)
		return
	if match.group('do').upper()=='GIVE':
		mb.data["quiz_stats"][who]["answers"]+=number
	else:
		mb.data["quiz_stats"][who]["answers"]-=number
	mb.save("quiz_stats")
	mb.tell(nick+": aight, done",target)
예제 #45
0
def measure_func(nick,match,target):
	who=match.group('who')
	if not who:
		who=""
	adjective=match.group('adjective').upper()
	be=match.group('be').upper()
	what=match.group('what').upper()
	if re.search("^my|mine$|^me$",who,flags=re.IGNORECASE):
		who=nick+"'s"
	elif re.search("^your$|^ur$|^yer$",who,flags=re.IGNORECASE):
		who="my"
	if re.search("^you$|^u$",what,flags=re.IGNORECASE):
		what="I"
		be="am"
	elif re.search("^me$|^I$",what,flags=re.IGNORECASE):
		what="you"
		be="are"
	id=hash(who.rstrip('S').rstrip('\'').rstrip("'")+"'S"+re.sub("\s*","",what))/9223372036854775808.;
	if id>0.5:
		antonym=None
		synsets=wn.synsets(adjective)
		antonym=None
		for synset in synsets:
			for lemma in synset.lemmas():
				antonyms=lemma.antonyms()
				if antonyms!=[]:
					antonym=lemma.antonyms()[0].name()
					break
					break
		if antonym:
			adjective=antonym
	index=floor(id*len(mb.data['stuff']['degrees']))
	response=mb.data['stuff']['degrees'][int(index)]
	if who!="":
		what=who+" "+what
	response=response.replace("<what>",what)
	response=response.replace("<be>",be)
	response=response.replace("<adjective>",adjective)
	
	mb.tell(nick+": "+response,target)
	return
예제 #46
0
def translate_func(nick,match,target):
	
	token=auth(target)
	if not token:
		return None
	data={}
	lang_from=match.group('from')
	lang_to=match.group('to')
	if not lang_from:
		lang_from='en'
	if not lang_to:
		lang_to='en'	

	lang_to=lang_to.strip()
	lang_from=lang_from.strip()
	for code,language in langs.items():
		if re.search("^"+re.escape(lang_from)+"$",language,re.IGNORECASE):
			lang_from=code
		if re.search("^"+re.escape(lang_to)+"$",language,re.IGNORECASE):
			lang_to=code
		

	data['from']=lang_from
	data['to']=lang_to
	data['text']=match.group('text')
	
	
	url='http://api.microsofttranslator.com/v2/Http.svc/Translate?'+urllib.urlencode(data)
	print("Translation url request: "+url)
	req=urllib2.Request(url)
	req.add_header('Authorization','Bearer '+token)
	try:
		response=urllib2.urlopen(req)
	except urllib2.HTTPError as e:
		mb.tell("Erroя.",target)
		print(e.read())
		return None
	pattern=re.compile(".*>(?P<tr>.+)<",flags=re.IGNORECASE)
	m=re.match(pattern,response.read().decode('utf-8'))
	mb.tell(nick+": "+m.group('tr'),target)
	return None