import plugins
import urllib
import urllib2
import json
import lxml.html

url = "https://en.wikipedia.org/w/api.php?%s"

def get_text(tree, xpath):
    return "\n".join(e.text_content() for e in tree.xpath(xpath))

def wiki(connection, channel, nick, cmd, args):
    """Looks up a search term on Wikipedia"""

    if not args:
        return plugins.print_help(connection, channel, nick, None, cmd)

    data = {
        "action" : "opensearch",
        "limit" : 1,
        "format" : "json",
        "search" : plugins.to_utf8(args)
    }
    req = urllib2.Request(url % urllib.urlencode(data))
    pageurl = json.load(urllib2.urlopen(req))[-1]
    txt = "\x0303[Wikipedia]\x03 "

    if not pageurl:
        return plugins.say(connection, channel, txt + "Search didn't find anything.")

    tree = lxml.html.parse(urllib2.urlopen(pageurl[0]))
    title = get_text(tree, "//h1[@id='firstHeading']")
    content = get_text(tree, "//div[@id='mw-content-text']/p")

    if not title or not content:
        return plugins.say(connection, channel, txt + "Something went wrong.")

    if tree.xpath("//div[@id='mw-content-text']//table[@id='disambigbox']"):
        content += " " + ", ".join(tree.xpath("//div[@id='mw-content-text']/ul/li//a[1]/@title"))

    txt += "%s (%s)\n%s" % (title, pageurl[0], plugins.shorten(content, 300))
    plugins.say(connection, channel, txt)

plugins.register_pub_cmd("wiki", wiki)

@@ -208,16 +208,85 @@
 path))%0A%0A
+def wikify(title):%0A    return urllib.quote(title.replace(%22 %22, %22_%22))%0A%0A
 def wiki
@@ -499,19 +499,85 @@
  : %22
-opensearch%22
+query%22,%0A        %22list%22 : %22search%22,%0A        %22srsearch%22 : plugins.to_utf8(args)
 ,%0A  
@@ -583,16 +583,18 @@
        %22
+sr
 limit%22 :
@@ -597,16 +597,39 @@
 t%22 : 1,%0A
+        %22srprop%22 : %22%22,%0A
         
@@ -660,45 +660,64 @@
    %22
-search%22 : plugins.to_utf8(args)%0A    %7D
+continue%22 : %22%22%0A    %7D%0A%0A    txt = %22%5Cx0303%5BWikipedia%5D%5Cx03 %22
 %0A   
@@ -773,19 +773,31 @@
 a))%0A
+%0A
     
-pageurl
+try:%0A        title
  = j
@@ -831,66 +831,49 @@
 q))%5B
--1%5D%0A    txt = %22%5Cx0303%5BWikipedia%5D%5Cx03 %22%0A%0A    if not pageurl
+%22query%22%5D%5B%22search%22%5D%5B0%5D%5B%22title%22%5D%0A    except
 :%0A  
@@ -953,24 +953,90 @@
 nything.%22)%0A%0A
+    pageurl = %22https://en.wikipedia.org/wiki/%25s%22 %25 wikify(title)%0A%0A
     tree = l
@@ -1073,19 +1073,16 @@
 (pageurl
-%5B0%5D
 ))%0A    t
@@ -1526,19 +1526,16 @@
  pageurl
-%5B0%5D
 , plugin

use wiki search instead of opensearch