Fill help in some modules

This commit is contained in:
nemunaire 2015-10-05 23:54:38 +02:00
commit a6a10b78d1
6 changed files with 150 additions and 97 deletions

View file

@ -16,11 +16,6 @@ from nemubot.tools.xmlparser.node import ModuleState
from more import Response from more import Response
# HELP ################################################################
def help_full():
return "Pour créer un alias, adressez-vous à moi en disant quelque chose comme : \"nouvel alias XX : YY\", où YY sera la commande équivalente à XX. Vous pouvez ajouter des variables comme ${1}, ${2}, ... correspondant aux éventuels arguments.\nDe l'aide supplémentaire existe pour les commandes !alias, !listalias, !unalias, !set et !listvars"
# LOADING ############################################################# # LOADING #############################################################
def load(context): def load(context):
@ -161,38 +156,47 @@ def replace_variables(cnts, msg=None):
## Variables management ## Variables management
@hook("cmd_hook", "listvars") @hook("cmd_hook", "listvars",
help="list defined variables for substitution in input commands",
help_usage={
None: "List all known variables",
"USER": "List variables created by USER"})
def cmd_listvars(msg): def cmd_listvars(msg):
if len(msg.args): if len(msg.args):
res = list() res = list()
for user in msg.args: for user in msg.args:
als = [v["alias"] for v in list_variables(user)] als = [v["alias"] for v in list_variables(user)]
if len(als) > 0: if len(als) > 0:
res.append("Variables créées par %s : %s" % (user, ", ".join(als))) res.append("%s's variables: %s" % (user, ", ".join(als)))
else: else:
res.append("%s n'a pas encore créé de variable" % user) res.append("%s didn't create variable yet." % user)
return Response(" ; ".join(res), channel=msg.channel) return Response(" ; ".join(res), channel=msg.channel)
elif len(context.data.getNode("variables").index): elif len(context.data.getNode("variables").index):
return Response("Variables connues : %s." % return Response("Known variables: %s." %
", ".join(list_variables()), ", ".join(list_variables()),
channel=msg.channel) channel=msg.channel)
else: else:
return Response("No variable are currently stored.", channel=msg.channel) return Response("There is currently no variable stored.", channel=msg.channel)
@hook("cmd_hook", "set") @hook("cmd_hook", "set",
help="Create or set variables for substitution in input commands",
help_usage={"KEY VALUE": "Define the variable named KEY and fill it with VALUE as content"})
def cmd_set(msg): def cmd_set(msg):
if len(msg.args) < 2: if len(msg.args) < 2:
raise IRCException("!set prend au minimum deux arguments : " raise IRCException("!set take two args: the key and the value.")
"le nom de la variable et sa valeur.")
set_variable(msg.args[0], " ".join(msg.args[1:]), msg.nick) set_variable(msg.args[0], " ".join(msg.args[1:]), msg.nick)
return Response("Variable \$%s définie avec succès." % msg.args[0], return Response("Variable \$%s successfully defined." % msg.args[0],
channel=msg.channel) channel=msg.channel)
## Alias management ## Alias management
@hook("cmd_hook", "listalias") @hook("cmd_hook", "listalias",
help="List registered aliases",
help_usage={
None: "List all registered aliases",
"USER": "List all aliases created by USER"})
def cmd_listalias(msg): def cmd_listalias(msg):
aliases = [a for a in list_alias(None)] + [a for a in list_alias(msg.channel)] aliases = [a for a in list_alias(None)] + [a for a in list_alias(msg.channel)]
if len(aliases): if len(aliases):
@ -202,35 +206,37 @@ def cmd_listalias(msg):
return Response("There is no alias currently.", channel=msg.channel) return Response("There is no alias currently.", channel=msg.channel)
@hook("cmd_hook", "alias") @hook("cmd_hook", "alias",
help="Display the replacement command for a given alias")
def cmd_alias(msg): def cmd_alias(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("!alias prend en argument l'alias à étendre.") raise IRCException("!alias takes as argument an alias to extend.")
res = list() res = list()
for alias in msg.args: for alias in msg.args:
if alias[0] == "!": if alias[0] == "!":
alias = alias[1:] alias = alias[1:]
if alias in context.data.getNode("aliases").index: if alias in context.data.getNode("aliases").index:
res.append("!%s correspond à %s" % (alias, context.data.getNode("aliases").index[alias]["origin"])) res.append("!%s correspond to %s" % (alias, context.data.getNode("aliases").index[alias]["origin"]))
else: else:
res.append("!%s n'est pas un alias" % alias) res.append("!%s is not an alias" % alias)
return Response(res, channel=msg.channel, nick=msg.nick) return Response(res, channel=msg.channel, nick=msg.nick)
@hook("cmd_hook", "unalias") @hook("cmd_hook", "unalias",
help="Remove a previously created alias")
def cmd_unalias(msg): def cmd_unalias(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Quel alias voulez-vous supprimer ?") raise IRCException("Which alias would you want to remove?")
res = list() res = list()
for alias in msg.args: for alias in msg.args:
if alias[0] == "!" and len(alias) > 1: if alias[0] == "!" and len(alias) > 1:
alias = alias[1:] alias = alias[1:]
if alias in context.data.getNode("aliases").index: if alias in context.data.getNode("aliases").index:
context.data.getNode("aliases").delChild(context.data.getNode("aliases").index[alias]) context.data.getNode("aliases").delChild(context.data.getNode("aliases").index[alias])
res.append(Response("%s a bien été supprimé" % alias, res.append(Response("%s doesn't exist anymore." % alias,
channel=msg.channel)) channel=msg.channel))
else: else:
res.append(Response("%s n'est pas un alias" % alias, res.append(Response("%s is not an alias" % alias,
channel=msg.channel)) channel=msg.channel))
return res return res
@ -260,16 +266,16 @@ def treat_alias(msg):
@hook("ask_default") @hook("ask_default")
def parseask(msg): def parseask(msg):
if re.match(".*(set|cr[ée]{2}|nouvel(le)?) alias.*", msg.text) is not None: if re.match(".*(register|set|cr[ée]{2}|new|nouvel(le)?) alias.*", msg.text) is not None:
result = re.match(".*alias !?([^ ]+) ?(pour|=|:) ?(.+)$", msg.text) result = re.match(".*alias !?([^ ]+) ?(pour|for|=|:) ?(.+)$", msg.text)
if result.group(1) in context.data.getNode("aliases").index: if result.group(1) in context.data.getNode("aliases").index:
raise IRCException("cet alias est déjà défini.") raise IRCException("this alias is already defined.")
else: else:
create_alias(result.group(1), create_alias(result.group(1),
result.group(3), result.group(3),
channel=msg.channel, channel=msg.channel,
creator=msg.nick) creator=msg.nick)
res = Response("Nouvel alias %s défini avec succès." % res = Response("New alias %s successfully registered." %
result.group(1), channel=msg.channel) result.group(1), channel=msg.channel)
return res return res
return None return None

View file

@ -1,7 +1,7 @@
# coding=utf-8
"""People birthdays and ages""" """People birthdays and ages"""
# PYTHON STUFFS #######################################################
import re import re
import sys import sys
from datetime import date, datetime from datetime import date, datetime
@ -13,21 +13,16 @@ from nemubot.tools.countdown import countdown_format
from nemubot.tools.date import extractDate from nemubot.tools.date import extractDate
from nemubot.tools.xmlparser.node import ModuleState from nemubot.tools.xmlparser.node import ModuleState
nemubotversion = 3.4
from more import Response from more import Response
# LOADING #############################################################
def load(context): def load(context):
context.data.setIndex("name", "birthday") context.data.setIndex("name", "birthday")
def help_full(): # MODULE CORE #########################################################
return ("!anniv /who/: gives the remaining time before the anniversary of "
"/who/\n!age /who/: gives the age of /who/\nIf /who/ is not given,"
" gives the remaining time before your anniversary.\n\n To set you"
"r birthday, say it to nemubot :)")
def findName(msg): def findName(msg):
if (not len(msg.args) or msg.args[0].lower() == "moi" or if (not len(msg.args) or msg.args[0].lower() == "moi" or
@ -47,7 +42,16 @@ def findName(msg):
return (matches, name) return (matches, name)
@hook("cmd_hook", "anniv") # MODULE INTERFACE ####################################################
## Commands
@hook("cmd_hook", "anniv",
help="gives the remaining time before the anniversary of known people",
help_usage={
None: "Calculate the time remaining before your birthday",
"WHO": "Calculate the time remaining before WHO's birthday",
})
def cmd_anniv(msg): def cmd_anniv(msg):
(matches, name) = findName(msg) (matches, name) = findName(msg)
if len(matches) == 1: if len(matches) == 1:
@ -76,7 +80,12 @@ def cmd_anniv(msg):
msg.channel, msg.nick) msg.channel, msg.nick)
@hook("cmd_hook", "age") @hook("cmd_hook", "age",
help="Calculate age of known people",
help_usage={
None: "Calculate your age",
"WHO": "Calculate the age of WHO"
})
def cmd_age(msg): def cmd_age(msg):
(matches, name) = findName(msg) (matches, name) = findName(msg)
if len(matches) == 1: if len(matches) == 1:
@ -93,6 +102,8 @@ def cmd_age(msg):
return True return True
## Input parsing
@hook("ask_default") @hook("ask_default")
def parseask(msg): def parseask(msg):
res = re.match(r"^(\S+)\s*('s|suis|est|is|was|were)?\s+(birthday|geburtstag|née? |nee? le|born on).*$", msg.text, re.I) res = re.match(r"^(\S+)\s*('s|suis|est|is|was|were)?\s+(birthday|geburtstag|née? |nee? le|born on).*$", msg.text, re.I)

View file

@ -1,7 +1,7 @@
# coding=utf-8
"""Wishes Happy New Year when the time comes""" """Wishes Happy New Year when the time comes"""
# PYTHON STUFFS #######################################################
from datetime import datetime, timezone from datetime import datetime, timezone
from nemubot import context from nemubot import context
@ -9,14 +9,17 @@ from nemubot.event import ModuleEvent
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools.countdown import countdown_format from nemubot.tools.countdown import countdown_format
nemubotversion = 4.0
from more import Response from more import Response
# GLOBALS #############################################################
yr = datetime.now(timezone.utc).year yr = datetime.now(timezone.utc).year
yrn = datetime.now(timezone.utc).year + 1 yrn = datetime.now(timezone.utc).year + 1
# LOADING #############################################################
def load(context): def load(context):
if not context.config or not context.config.hasNode("sayon"): if not context.config or not context.config.hasNode("sayon"):
print("You can append in your configuration some balise to " print("You can append in your configuration some balise to "
@ -42,8 +45,12 @@ def load(context):
call=bonneannee)) call=bonneannee))
@hook("cmd_hook", "newyear") # MODULE INTERFACE ####################################################
@hook("cmd_hook", str(yrn))
@hook("cmd_hook", "newyear",
help="Display the remaining time before the next new year")
@hook("cmd_hook", str(yrn),
help="Display the remaining time before %d" % yrn)
def cmd_newyear(msg): def cmd_newyear(msg):
return Response(countdown_format(datetime(yrn, 1, 1, 0, 0, 1, 0, return Response(countdown_format(datetime(yrn, 1, 1, 0, 0, 1, 0,
timezone.utc), timezone.utc),
@ -52,7 +59,8 @@ def cmd_newyear(msg):
channel=msg.channel) channel=msg.channel)
@hook("cmd_rgxp", data=yrn, regexp="^[0-9]{4}$") @hook("cmd_rgxp", data=yrn, regexp="^[0-9]{4}$",
help="Calculate time remaining/passed before/since the requested year")
def cmd_timetoyear(msg, cur): def cmd_timetoyear(msg, cur):
yr = int(msg.cmd) yr = int(msg.cmd)

View file

@ -1,7 +1,7 @@
# coding=utf-8
"""Looking for books""" """Looking for books"""
# PYTHON STUFFS #######################################################
import urllib import urllib
from nemubot import context from nemubot import context
@ -9,11 +9,11 @@ from nemubot.exception import IRCException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
nemubotversion = 4.0
from more import Response from more import Response
# LOADING #############################################################
def load(context): def load(context):
if not context.config or not context.config.getAttribute("goodreadskey"): if not context.config or not context.config.getAttribute("goodreadskey"):
raise ImportError("You need a Goodreads API key in order to use this " raise ImportError("You need a Goodreads API key in order to use this "
@ -22,6 +22,8 @@ def load(context):
"Get one at https://www.goodreads.com/api/keys") "Get one at https://www.goodreads.com/api/keys")
# MODULE CORE #########################################################
def get_book(title): def get_book(title):
"""Retrieve a book from its title""" """Retrieve a book from its title"""
response = web.getXML("https://www.goodreads.com/book/title.xml?key=%s&title=%s" % response = web.getXML("https://www.goodreads.com/book/title.xml?key=%s&title=%s" %
@ -54,7 +56,13 @@ def search_author(name):
return None return None
@hook("cmd_hook", "book") # MODULE INTERFACE ####################################################
@hook("cmd_hook", "book",
help="Get information about a book from its title",
help_usage={
"TITLE": "Get information about a book titled TITLE"
})
def cmd_book(msg): def cmd_book(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("please give me a title to search") raise IRCException("please give me a title to search")
@ -69,7 +77,11 @@ def cmd_book(msg):
return res return res
@hook("cmd_hook", "search_books") @hook("cmd_hook", "search_books",
help="Search book's title",
help_usage={
"APPROX_TITLE": "Search for a book approximately titled APPROX_TITLE"
})
def cmd_books(msg): def cmd_books(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("please give me a title to search") raise IRCException("please give me a title to search")
@ -85,7 +97,11 @@ def cmd_books(msg):
return res return res
@hook("cmd_hook", "author_books") @hook("cmd_hook", "author_books",
help="Looking for books writen by a given author",
help_usage={
"AUTHOR": "Looking for books writen by AUTHOR"
})
def cmd_author(msg): def cmd_author(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("please give me an author to search") raise IRCException("please give me an author to search")

View file

@ -1,7 +1,7 @@
# coding=utf-8
"""Find french conjugaison""" """Find french conjugaison"""
# PYTHON STUFFS #######################################################
from collections import defaultdict from collections import defaultdict
import re import re
from urllib.parse import quote from urllib.parse import quote
@ -11,10 +11,11 @@ from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
from nemubot.tools.web import striphtml from nemubot.tools.web import striphtml
nemubotversion = 3.4
from more import Response from more import Response
# GLOBALS #############################################################
s = [('present', '0'), ('présent', '0'), ('pr', '0'), s = [('present', '0'), ('présent', '0'), ('pr', '0'),
('passé simple', '12'), ('passe simple', '12'), ('ps', '12'), ('passé simple', '12'), ('passe simple', '12'), ('ps', '12'),
('passé antérieur', '112'), ('passe anterieur', '112'), ('pa', '112'), ('passé antérieur', '112'), ('passe anterieur', '112'), ('pa', '112'),
@ -32,29 +33,7 @@ for k, v in s:
d[k].append(v) d[k].append(v)
def help_full(): # MODULE CORE #########################################################
return ("!conjugaison <tens> <verb>: give the conjugaison for <verb> in "
"<tens>.")
@hook("cmd_hook", "conjugaison")
def cmd_conjug(msg):
if len(msg.args) < 2:
raise IRCException("donne moi un temps et un verbe, et je te donnerai "
"sa conjugaison!")
tens = ' '.join(msg.args[:-1])
verb = msg.args[-1]
conjug = get_conjug(verb, tens)
if len(conjug) > 0:
return Response(conjug, channel=msg.channel,
title="Conjugaison de %s" % verb)
else:
raise IRCException("aucune conjugaison de '%s' n'a été trouvé" % verb)
def get_conjug(verb, stringTens): def get_conjug(verb, stringTens):
url = ("http://leconjugueur.lefigaro.fr/conjugaison/verbe/%s.html" % url = ("http://leconjugueur.lefigaro.fr/conjugaison/verbe/%s.html" %
@ -89,3 +68,27 @@ def compute_line(line, stringTens):
.replace("<b>", "\x02") .replace("<b>", "\x02")
.replace("</b>", "\x0F"))) .replace("</b>", "\x0F")))
return res return res
# MODULE INTERFACE ####################################################
@hook("cmd_hook", "conjugaison",
help_usage={
"TENS VERB": "give the conjugaison for VERB in TENS."
})
def cmd_conjug(msg):
if len(msg.args) < 2:
raise IRCException("donne moi un temps et un verbe, et je te donnerai "
"sa conjugaison!")
tens = ' '.join(msg.args[:-1])
verb = msg.args[-1]
conjug = get_conjug(verb, tens)
if len(conjug) > 0:
return Response(conjug, channel=msg.channel,
title="Conjugaison de %s" % verb)
else:
raise IRCException("aucune conjugaison de '%s' n'a été trouvé" % verb)

View file

@ -1,25 +1,34 @@
"""List upcoming CTFs"""
# PYTHON STUFFS #######################################################
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools.web import getURLContent from nemubot.tools.web import getURLContent, striphtml
from more import Response from more import Response
"""List upcoming CTFs"""
nemubotversion = 4.0 # GLOBALS #############################################################
@hook("cmd_hook", "ctfs") URL = 'https://ctftime.org/event/list/upcoming'
# MODULE INTERFACE ####################################################
@hook("cmd_hook", "ctfs",
help="Display the upcoming CTFs")
def get_info_yt(msg): def get_info_yt(msg):
soup = BeautifulSoup(getURLContent('https://ctftime.org/event/list/upcoming')) soup = BeautifulSoup(getURLContent(URL))
res = Response(channel=msg.channel, nomore="No more upcoming CTF")
for line in soup.body.find_all('tr'): res = Response(channel=msg.channel, nomore="No more upcoming CTF")
n = line.find_all('td')
if len(n) == 5: for line in soup.body.find_all('tr'):
try: n = line.find_all('td')
res.append_message("\x02%s:\x0F from %s type %s at %s. %s" % tuple([x.text.replace("\n", " ").strip() for x in n])) if len(n) == 5:
except: try:
import sys res.append_message("\x02%s:\x0F from %s type %s at %s. %s" %
import traceback tuple([striphtml(x.text) for x in n]))
exc_type, exc_value, _ = sys.exc_info() except:
sys.stderr.write(traceback.format_exception_only(exc_type, exc_value)[0]) pass
return res return res