nemubot/modules/syno.py

77 lines
2.2 KiB
Python
Raw Normal View History

2012-06-30 15:51:50 +00:00
# coding=utf-8
import http.client
import re
import socket
from urllib.parse import quote
2012-11-04 14:32:39 +00:00
nemubotversion = 3.3
2012-06-30 15:51:50 +00:00
def help_tiny ():
return "Find french synonyms"
def help_full ():
2012-11-04 14:32:39 +00:00
return "!syno <word>: give a list of synonyms for <word>."
2012-06-30 15:51:50 +00:00
def load(context):
from hooks import Hook
add_hook("cmd_hook", Hook(cmd_syno, "syno"))
add_hook("cmd_hook", Hook(cmd_syno, "synonyme"))
2012-06-30 15:51:50 +00:00
def cmd_syno(msg):
2012-11-04 14:32:39 +00:00
if 1 < len(msg.cmds) < 6:
for word in msg.cmds[1:]:
synos = get_synos(word)
if synos is None:
return Response(msg.sender,
"Une erreur s'est produite durant la recherche"
" d'un synonyme de %s" % word, msg.channel)
elif len(synos) > 0:
2012-11-04 14:32:39 +00:00
return Response(msg.sender, synos, msg.channel,
title="Synonymes de %s" % word)
else:
return Response(msg.sender,
"Aucun synonymes de %s n'a été trouvé" % word,
msg.channel)
return False
def get_synos(word):
(res, page) = getPage(word)
if res == http.client.OK:
synos = list()
for line in page.decode().split("\n"):
2012-06-30 15:51:50 +00:00
if re.match("[ \t]*<tr[^>]*>.*</tr>[ \t]*</table>.*", line) is not None:
for elt in re.finditer(">&[^;]+;([^&]*)&[^;]+;<", line):
synos.append(elt.group(1))
return synos
else:
return None
2012-06-30 15:51:50 +00:00
def getPage(terms):
2012-07-27 16:18:13 +00:00
conn = http.client.HTTPConnection("www.crisco.unicaen.fr", timeout=5)
2012-06-30 15:51:50 +00:00
try:
conn.request("GET", "/des/synonymes/%s" % quote(terms))
except socket.gaierror:
print ("impossible de récupérer la page Wolfram|Alpha.")
return (http.client.INTERNAL_SERVER_ERROR, None)
res = conn.getresponse()
data = res.read()
conn.close()
return (res.status, data)
if __name__ == "__main__":
import sys
if len(sys.argv) == 0:
print ("Usage: ./syno.py word [word ...]")
else:
for word in sys.argv:
synos = get_synos(word)
if synos is not None:
print ("Synonyme de %s : %s" % (word, ', '.join(synos)))