示例#1
0
        quote = mb.data['quotes'][int(index) - 1]
    except:
        mb.tell(
            nick + ": I got " + str(len(mb.data['quotes'])) + " of those here",
            target)
        return

    mb.tell(quote['quote'], target, True)
    mb.tell("added by {} on {}".format(quote['added by'], quote['date']),
            target)
    return


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


mb.help[
    "quotes"] = "mb add quote <text>, mb read/quote [<index>], mb search <text>, mb random"
print("loaded quotes")
mb.add_command(add_quote, add_quote_func)
mb.add_command(read_quote, read_quote_func)
mb.add_command(search_quote, search_quote_func)
mb.add_command(random_quote, random_quote_func)
示例#2
0
	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')
	
	
mb.add_command(send_message,send_message_func)
mb.add_command(seen,seen_func)		

mb.add_command(hi,hi_func)
mb.add_command(coin,coin_func)	
mb.add_command(thank,thank_func)	
#mb.add_command(daddy,daddy_func,priority=0)	
#mb.add_command(parent,parent_func)	
mb.add_command(yiff,yiff_func)	
mb.add_command(get,get_func)
mb.add_command(save,save_func, level=1)
mb.add_command(help,help_func)
mb.add_command(time,time_func)
mb.add_command(eightball,eightball_func,priority=999)
mb.help['choice'] = "mb choose <list of things separated by , 'or' or 'and'>"
mb.help['seen'] = "mb seen <who>"
示例#3
0
	req=urllib2.Request('https://giphy.p.mashape.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&'+query,headers=headers)
	response=urllib2.urlopen(req).read()
	results=json.loads(response.decode("utf-8"))["data"]
	
	if results==[]:
		mb.tell(nick+": none of that stuff", target)
		return
	if index:
		data=results[int(index)]
	else:
		data=choice(results)
	
	gif="https://media.giphy.com/media/{id}/giphy.gif".format(id=data['id'])

	mb.tell(nick+": "+gif,target,True)

	

		
mb.add_command(show_me,show_me_func,priority=3)
mb.add_command(lewd,lewd_func)
mb.add_command(tumblr,tumblr_func)
mb.help["gifs"]="mb show me <whatever> (searches for <whatever> on giphy), mb lewd <whatever> (searches for gifs in \\tagged of several p**n tumblrs)"
mb.help["tumblr"]="mb tumblr [text|photo](optional) <something>"

print("loaded gifs")



     
示例#4
0
# coding: utf-8
from mbclient import mb
import urllib,urllib2,traceback
import re
prequel="prequel"

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()
		
mb.help["updates"]="mb prequel"		
print("loaded updates")
mb.add_command(prequel,prequel_func)
示例#5
0
    link = "http://www.colourlovers.com/img/" + hex + "/600/600"
    mb.tell(nick + ": " + "#" + hex + ", " + title, target)
    mb.tell(link, target, True)
    return


def what_color_func(nick, match, target):
    color = match.group('hex')
    req = urllib2.Request("http://www.colourlovers.com/api/color/" + color +
                          "?format=json")
    req.add_header('User-Agent', "ColourLovers Browser")
    try:
        response = urllib2.urlopen(req)
        cdict = json.loads(response.read().decode('utf-8'))[0]
    except IndexError:
        mb.tell(nick + ": did you pull that out of your ass?? shove it back")
        return
    title = "'" + cdict['title'] + "'"
    link = "http://www.colourlovers.com/img/" + color + "/600/600"
    mb.tell(nick + ": " + title + " ", target)
    mb.tell(link, target, True)
    return


mb.add_command(what_color, what_color_func)
mb.add_command(keyword_color, keyword_color_func)

mb.help[
    "colors"] = "mb <hex color, e.g. #ff00ff>, mb what's the color of <something>"
print("loaded colors")
示例#6
0
		
	faces=[]
	for result in response:
		emotion_list = [{"emotion":emotion,"score":score} for emotion,score in result["scores"].items()]
		emotion_list = sorted(emotion_list, key = lambda k: k["score"])
		
		
		scores = [entry["emotion"] for entry in emotion_list][-2:]
		face = {"emotion": " and ".join(scores), "left": result["faceRectangle"]["left"]}
		faces.append(face)
	
	faces_ordered = sorted(faces, key = lambda k: k["left"])
	emotions= [face["emotion"] for face in faces_ordered]
	
	answer = nick+": "
	if len(response)>1:
		answer+="from left to right: "
	
	
	mb.tell(answer+", ".join(emotions),target)
	
		
		
	
	return
	
mb.add_command(emotion,emotion_func)	
mb.add_command(nsfw,nsfw_func)
mb.add_command(tags,tags_func)
mb.help['recognition']="mb tags <picture url>, mb nsfw <picture url>, mb emotion <picture url>"
print('loaded recognition')
示例#7
0
		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
	

def  last_message_func(nick,match,target):		
	date = datetime.now()
	when=shared.time_dict(date)
	
	message = match.group(0)
	if not nick in mb.data['logs']:
		mb.data['logs'][nick]={}
	mb.data['logs'][nick]['message'] = message
	mb.data['logs'][nick]['date'] = when
	mb.save('logs')
	
	
print("loaded passive functions")
#mb.add_command(picture,picture_func,call=False, passive= True,priority=6)	
mb.add_command(anything,last_message_func,call=False, passive=True,priority=5)	
mb.add_command(anything,deliver_message_func,call=False,passive=True,priority=5)
示例#8
0
def next_func(nick, match, target, param=None):
    if len(mb.data['interview']['questions']) > 2:
        mb.tell(
            nick + ": you only get three questions pal, now make up your mind",
            target)
        return
    detective = mb.data['interview']['detective']
    while True:
        question = choice(mb.data["interview_questions"])
        if question not in mb.data['interview']['questions']:
            break
    mb.data['interview']['questions'].append(question)
    mb.save('interview')
    mb.tell("Here's another one:", detective)
    mb.tell(question, detective)


def reset_func(nick, match, target):
    mb.tell(nick + ": fun cancelled, gotcha", target)
    mb.data['interview'] = {'players': []}
    mb.save('interview')


mb.help[
    "interview"] = "'mb interview' to start\join the game, once you're playing: 'shoot' or 'bam' or 'bang' to shoot the opponent, 'dismiss' or 'you can go' to dismiss, 'next' or 'next question' to get another question"
mb.add_command(interview_champion, interview_champion_func, level=1)
mb.add_command(reset, reset_func, level=1)
mb.add_command(interview_init, interview_init_func)
mb.add_command(interview, interview_func)
mb.add_command(interview_stats, interview_stats_func)
print("loaded interview")
示例#9
0
	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

mb.add_command(define,define_func, priority=8)
mb.add_command(antonym,antonym_func)
mb.add_command(synonym,synonym_func)
mb.add_command(measure,measure_func)
mb.help['dictionary']="mb define <word or sentence>, mb analyze <word or sentence> mb what's the opposite of <word>,mb what's the other word for <word>"
mb.help['measurement']="mb how <adjective> is\are <word or sentence>"
print("loaded dictionary")
示例#10
0
            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


mb.add_command(translate, translate_func)
mb.add_command(languages, languages_func)
mb.add_command(can_you_speak, can_you_speak_func)
mb.help[
    'translation'] = "mb languages, mb do you speak <language>, mb translate from <language> to <language> <text to translate> (languages default to english if not specified)"
print("loaded translation")
示例#11
0
	else:
		mb.tell(nick+", here's what I found ("+str(len(results))+" results): "+", ".join(results),target)
	return

def read_quote_func(nick,match,target):
	index=match.group('index')
	try:
		quote=mb.data['quotes'][int(index)-1]
	except:
		mb.tell(nick+": I got "+str(len(mb.data['quotes']))+" of those here",target)
		return
		
	mb.tell(quote['quote'],target,True)
	mb.tell("added by {} on {}".format(quote['added by'],quote['date']),target)
	return

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
mb.help["quotes"]="mb add quote <text>, mb read/quote [<index>], mb search <text>, mb random"
print("loaded quotes")
mb.add_command(add_quote,add_quote_func)
mb.add_command(read_quote,read_quote_func)
mb.add_command(search_quote,search_quote_func)
mb.add_command(random_quote,random_quote_func)
示例#12
0
    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


print("loaded conversion")
mb.add_command(convert, convert_func, priority=10)
mb.help[
    "convert"] = "mb [convert] <number (defaults to 1)> <units> to/in/into <units>"
示例#13
0
	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
mb.add_command(translate,translate_func)
mb.add_command(languages,languages_func)
mb.add_command(can_you_speak,can_you_speak_func)
mb.help['translation']="mb languages, mb do you speak <language>, mb translate from <language> to <language> <text to translate> (languages default to english if not specified)"
print("loaded translation")
示例#14
0
# coding: utf-8
from mbclient import mb
import json,urllib2
whow="^how.*"

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)
	
	
	

mb.add_command(whow,whow_func,priority=99)

mb.help["wikihow"]="mb how <whatever> (random steps from wikihow)"


print("loaded wikihow")


示例#15
0
        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')


mb.add_command(send_message, send_message_func)
mb.add_command(seen, seen_func)

mb.add_command(hi, hi_func)
mb.add_command(coin, coin_func)
mb.add_command(thank, thank_func)
#mb.add_command(daddy,daddy_func,priority=0)
#mb.add_command(parent,parent_func)
mb.add_command(yiff, yiff_func)
mb.add_command(get, get_func)
mb.add_command(save, save_func, level=1)
mb.add_command(help, help_func)
mb.add_command(time, time_func)
mb.add_command(eightball, eightball_func, priority=999)
mb.help['choice'] = "mb choose <list of things separated by , 'or' or 'and'>"
mb.help['seen'] = "mb seen <who>"
示例#16
0
			mb.tell(nick+": no idea",target)
			return
		title="'"+cdict['title']+"'"
		hex=cdict['hex']
		link="http://www.colourlovers.com/img/"+hex+"/600/600"
		mb.tell(nick+": "+"#"+hex+", "+title,target)
		mb.tell(link, target,True)
		return

def what_color_func(nick,match,target):
	color=match.group('hex')
	req=urllib2.Request("http://www.colourlovers.com/api/color/"+color+"?format=json")
	req.add_header('User-Agent', "ColourLovers Browser")
	try:
		response=urllib2.urlopen(req)
		cdict=json.loads(response.read().decode('utf-8'))[0]
	except IndexError:
		mb.tell(nick+": did you pull that out of your ass?? shove it back")
		return
	title="'"+cdict['title']+"'"
	link="http://www.colourlovers.com/img/"+color+"/600/600"
	mb.tell(nick+": "+title+" ",target)
	mb.tell(link,target,True)
	return

mb.add_command(what_color,what_color_func)
mb.add_command(keyword_color,keyword_color_func)

mb.help["colors"]="mb <hex color, e.g. #ff00ff>, mb what's the color of <something>"
print("loaded colors")
示例#17
0
# coding: utf-8
from mbclient import mb
import math
import re
calc="calc\s+(?P<expr>[\de*()пpi+-/]+)"

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)


mb.add_command(calc,calc_func)
mb.help['calculator']="mb calc <expression to calculate>"
print('loaded calculator')
示例#18
0
			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)
		
mb.add_command(last_picture,last_picture_func)	
mb.add_command(console,console_func,level=2)
#mb.add_command(shut_down,shut_down_func,level=2)			
#mb.add_command(list_uncles,list_uncles_func)			
mb.add_command(reload,reload_func,level=2)		
#mb.add_command(add_uncle,add_uncle_func,level=2)
mb.add_command(type_in,type_in_func,level=1)
mb.add_command(font_options,font_options_func,level=1)
mb.add_command(join,join_func,level=2)
mb.add_command(leave,leave_func,level=2)
mb.add_command(on_start,on_start_func,level=2)
print("loaded commands")
示例#19
0
# coding: utf-8
from mbclient import mb
import json,urllib,urllib2,os
bing="bing\s+(?P<query>.+)"
def bing_func(nick,match,target):
	query=urllib.urlencode({"Query":"'"+match.group('query')+"'"})
	try:
		key=mb.data['passwords']['bing']['key']
		req=urllib2.Request("https://api.datamarket.azure.com/Bing/SearchWeb/v1/Web?"+query+"&$top=1&$format=json&Market=%27en-US%27&Adult=%27Off%27")
		req.add_header("Authorization","Basic "+key)
		response=urllib2.urlopen(req).read()
		data=json.loads(response.decode("utf-8"))['d']['results'][0]
		mb.tell(data['Description'],target)
		mb.tell(data['Url'],target,True)	
	except urllib2.HTTPError as er:
		print(er)
		mb.tell("ERROЯ",target)
mb.add_command(bing,bing_func)
print("loaded bing search")
mb.help['bing']="mb bing <text>"
示例#20
0
                    nick)

        mb.data['logs'][nick]['messages'] = []
        mb.save('logs')
    return


def last_message_func(nick, match, target):
    date = datetime.now()
    when = shared.time_dict(date)

    message = match.group(0)
    if not nick in mb.data['logs']:
        mb.data['logs'][nick] = {}
    mb.data['logs'][nick]['message'] = message
    mb.data['logs'][nick]['date'] = when
    mb.save('logs')


print("loaded passive functions")
#mb.add_command(picture,picture_func,call=False, passive= True,priority=6)
mb.add_command(anything,
               last_message_func,
               call=False,
               passive=True,
               priority=5)
mb.add_command(anything,
               deliver_message_func,
               call=False,
               passive=True,
               priority=5)
示例#21
0
# coding: utf-8
from mbclient import mb
import json,urllib

convert="(?:convert\s+)?(?P<amount>[0-9,e\.\-+\(\)*\/]+)?\s*(?P<what>(?!as\s+)[a-z°'\"]+)\s+(in|to|into)\s+(?P<to>[a-z°'\"]+)\s*$"

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 
	
print("loaded conversion")
mb.add_command(convert,convert_func,priority=10)
mb.help["convert"]="mb [convert] <number (defaults to 1)> <units> to/in/into <units>"
示例#22
0
        lat = float(data['lat'])
        lon = float(data['lon'])

        if lat < 0:
            lat = str(int(-lat)) + "S"
        else:
            lat = str(int(lat)) + "N"

        if lon < 0:
            lon = str(int(-lon)) + "W"
        else:
            lon = str(int(lon)) + "E"

        data['lat'] = lat
        data['lon'] = lon

        answer = "{lat} {lon}: {description}, {clouds}% cloudy, temp: {min}-{max}{degrees}, humidity: {humidity}%, wind:{wind}{speed}".format(
            **data)
    except:
        mb.tell(nick + ": Ouch, you broke something", target)
        traceback.print_exc()
        return
    mb.tell(nick + ": " + answer, target)
    return


mb.add_command(weather, weather_func)

print("loaded weather")
mb.help[
    "weather"] = "mb weather [f] [tomorrow|in a week|in a month|in N days] <city>"
示例#23
0
	return
	
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
mb.help["quiz"]="mb quiz, mb quiz stats [for <name>], mb quiz champion, mb aliases [for <name>]"
mb.add_command(add_aliases,add_aliases_func,level=2)
mb.add_command(purge_aliases,purge_aliases_func,level=2)
mb.add_command(points,points_func,level=2)
mb.add_command(aka,aka_func)
mb.add_command(quiz,quiz_func)
mb.add_command(show_quiz_stats,show_quiz_stats_func)
mb.add_command(quiz_champ,quiz_champ_func)
print("loaded quiz")
示例#24
0
        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()


print("loaded urban")
mb.add_command(urban, urban_func)
mb.help['urban'] = "mb urban <something>"
示例#25
0
			
		
		lat = float(data['lat'])
		lon = float(data['lon'])

		if lat<0:
			lat = str(int(-lat))+"S"
		else:
			lat = str(int(lat))+"N"
			
		if lon<0:
			lon = str(int(-lon))+"W"
		else:
			lon = str(int(lon))+"E"	
			
		data['lat'] = lat
		data['lon'] = lon
		
		answer = "{lat} {lon}: {description}, {clouds}% cloudy, temp: {min}-{max}{degrees}, humidity: {humidity}%, wind:{wind}{speed}".format(**data)
	except:
		mb.tell(nick+": Ouch, you broke something",target)
		traceback.print_exc()
		return
	mb.tell(nick+": "+answer,target)
	return


mb.add_command(weather,weather_func)

print("loaded weather")
mb.help["weather"] = "mb weather [f] [tomorrow|in a week|in a month|in N days] <city>"
示例#26
0
from random import choice
import re,json,urllib,urllib2,traceback
wiki="wiki\s+(?P<r>random\s+)?(?P<what>.+)"
html_tags = re.compile(r'<[^>]+>')

def wiki_func(nick,match,target):
	what = urllib.urlencode({"srsearch":match.group("what")})
	r=match.group('r')
	req = urllib2.Request('https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext&list=search&'+what)
	try:
		response = json.loads(urllib2.urlopen(req).read().decode('utf-8'))['query']
		if response['searchinfo']['totalhits']==0:
			mb.tell(nick+": none of that", target)
			return
		else:
			if r:
				result = choice(response['search'])
			else:
				result = response['search'][0]
			mb.tell(result['title'],target)
			mb.tell(re.sub(html_tags,"",result['snippet']),target)

	except:
		mb.tell(nick+": whoops.",target)
		traceback.print_exc()


print("loaded wiki")
mb.help['wiki']="mb wiki <whatever>"
mb.add_command(wiki,wiki_func)
示例#27
0
# coding: utf-8
from mbclient import mb
import math
import re
calc = "calc\s+(?P<expr>[\de*()пpi+-/]+)"


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)


mb.add_command(calc, calc_func)
mb.help['calculator'] = "mb calc <expression to calculate>"
print('loaded calculator')
示例#28
0

def next_func(nick,match,target,param=None):
	if len(mb.data['interview']['questions'])>2:
		mb.tell(nick+": you only get three questions pal, now make up your mind",target)
		return
	detective=mb.data['interview']['detective']
	while True:
		question=choice(mb.data["interview_questions"])
		if question not in mb.data['interview']['questions']:
			break
	mb.data['interview']['questions'].append(question)
	mb.save('interview')
	mb.tell("Here's another one:", detective)
	mb.tell(question, detective)
	

	
def reset_func(nick,match,target):
	mb.tell(nick+": fun cancelled, gotcha",target)
	mb.data['interview']={'players':[]}
	mb.save('interview')
	

mb.help["interview"]="'mb interview' to start\join the game, once you're playing: 'shoot' or 'bam' or 'bang' to shoot the opponent, 'dismiss' or 'you can go' to dismiss, 'next' or 'next question' to get another question"
mb.add_command(interview_champion,interview_champion_func,level=1)
mb.add_command(reset,reset_func,level=1)
mb.add_command(interview_init,interview_init_func)
mb.add_command(interview,interview_func)
mb.add_command(interview_stats,interview_stats_func)
print("loaded interview")
示例#29
0
# coding: utf-8
from mbclient import mb
import json, urllib2
whow = "^how.*"


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)


mb.add_command(whow, whow_func, priority=99)

mb.help["wikihow"] = "mb how <whatever> (random steps from wikihow)"

print("loaded wikihow")
示例#30
0
# coding: utf-8
from mbclient import mb
import urllib, urllib2, traceback
import re
prequel = "prequel"


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()


mb.help["updates"] = "mb prequel"
print("loaded updates")
mb.add_command(prequel, prequel_func)