/
mbwiki.py
33 lines (28 loc) · 973 Bytes
/
mbwiki.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# coding: utf-8
from mbclient import mb
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)