Fill help in some modules

This commit is contained in:
nemunaire 2015-10-05 23:54:38 +02:00
parent e1310516fa
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
# 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 #############################################################
def load(context):
@ -161,38 +156,47 @@ def replace_variables(cnts, msg=None):
## 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):
if len(msg.args):
res = list()
for user in msg.args:
als = [v["alias"] for v in list_variables(user)]
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:
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)
elif len(context.data.getNode("variables").index):
return Response("Variables connues : %s." %
return Response("Known variables: %s." %
", ".join(list_variables()),
channel=msg.channel)
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):
if len(msg.args) < 2:
raise IRCException("!set prend au minimum deux arguments : "
"le nom de la variable et sa valeur.")
raise IRCException("!set take two args: the key and the value.")
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)
## 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):
aliases = [a for a in list_alias(None)] + [a for a in list_alias(msg.channel)]
if len(aliases):
@ -202,35 +206,37 @@ def cmd_listalias(msg):
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):
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()
for alias in msg.args:
if alias[0] == "!":
alias = alias[1:]
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:
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)
@hook("cmd_hook", "unalias")
@hook("cmd_hook", "unalias",
help="Remove a previously created alias")
def cmd_unalias(msg):
if not len(msg.args):
raise IRCException("Quel alias voulez-vous supprimer ?")
raise IRCException("Which alias would you want to remove?")
res = list()
for alias in msg.args:
if alias[0] == "!" and len(alias) > 1:
alias = alias[1:]
if alias in context.data.getNode("aliases").index:
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))
else:
res.append(Response("%s n'est pas un alias" % alias,
res.append(Response("%s is not an alias" % alias,
channel=msg.channel))
return res
@ -260,16 +266,16 @@ def treat_alias(msg):
@hook("ask_default")
def parseask(msg):
if re.match(".*(set|cr[ée]{2}|nouvel(le)?) alias.*", msg.text) is not None:
result = re.match(".*alias !?([^ ]+) ?(pour|=|:) ?(.+)$", msg.text)
if re.match(".*(register|set|cr[ée]{2}|new|nouvel(le)?) alias.*", msg.text) is not None:
result = re.match(".*alias !?([^ ]+) ?(pour|for|=|:) ?(.+)$", msg.text)
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:
create_alias(result.group(1),
result.group(3),
channel=msg.channel,
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)
return res
return None

View File

@ -1,7 +1,7 @@
# coding=utf-8
"""People birthdays and ages"""
# PYTHON STUFFS #######################################################
import re
import sys
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.xmlparser.node import ModuleState
nemubotversion = 3.4
from more import Response
# LOADING #############################################################
def load(context):
context.data.setIndex("name", "birthday")
def help_full():
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 :)")
# MODULE CORE #########################################################
def findName(msg):
if (not len(msg.args) or msg.args[0].lower() == "moi" or
@ -47,7 +42,16 @@ def findName(msg):
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):
(matches, name) = findName(msg)
if len(matches) == 1:
@ -76,7 +80,12 @@ def cmd_anniv(msg):
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):
(matches, name) = findName(msg)
if len(matches) == 1:
@ -93,6 +102,8 @@ def cmd_age(msg):
return True
## Input parsing
@hook("ask_default")
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)

View File

@ -1,7 +1,7 @@
# coding=utf-8
"""Wishes Happy New Year when the time comes"""
# PYTHON STUFFS #######################################################
from datetime import datetime, timezone
from nemubot import context
@ -9,14 +9,17 @@ from nemubot.event import ModuleEvent
from nemubot.hooks import hook
from nemubot.tools.countdown import countdown_format
nemubotversion = 4.0
from more import Response
# GLOBALS #############################################################
yr = datetime.now(timezone.utc).year
yrn = datetime.now(timezone.utc).year + 1
# LOADING #############################################################
def load(context):
if not context.config or not context.config.hasNode("sayon"):
print("You can append in your configuration some balise to "
@ -42,8 +45,12 @@ def load(context):
call=bonneannee))
@hook("cmd_hook", "newyear")
@hook("cmd_hook", str(yrn))
# MODULE INTERFACE ####################################################
@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):
return Response(countdown_format(datetime(yrn, 1, 1, 0, 0, 1, 0,
timezone.utc),
@ -52,7 +59,8 @@ def cmd_newyear(msg):
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):
yr = int(msg.cmd)

View File

@ -1,7 +1,7 @@
# coding=utf-8
"""Looking for books"""
# PYTHON STUFFS #######################################################
import urllib
from nemubot import context
@ -9,11 +9,11 @@ from nemubot.exception import IRCException
from nemubot.hooks import hook
from nemubot.tools import web
nemubotversion = 4.0
from more import Response
# LOADING #############################################################
def load(context):
if not context.config or not context.config.getAttribute("goodreadskey"):
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")
# MODULE CORE #########################################################
def get_book(title):
"""Retrieve a book from its title"""
response = web.getXML("https://www.goodreads.com/book/title.xml?key=%s&title=%s" %
@ -54,7 +56,13 @@ def search_author(name):
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):
if not len(msg.args):
raise IRCException("please give me a title to search")
@ -69,7 +77,11 @@ def cmd_book(msg):
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):
if not len(msg.args):
raise IRCException("please give me a title to search")
@ -85,7 +97,11 @@ def cmd_books(msg):
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):
if not len(msg.args):
raise IRCException("please give me an author to search")

View File

@ -1,7 +1,7 @@
# coding=utf-8
"""Find french conjugaison"""
# PYTHON STUFFS #######################################################
from collections import defaultdict
import re
from urllib.parse import quote
@ -11,10 +11,11 @@ from nemubot.hooks import hook
from nemubot.tools import web
from nemubot.tools.web import striphtml
nemubotversion = 3.4
from more import Response
# GLOBALS #############################################################
s = [('present', '0'), ('présent', '0'), ('pr', '0'),
('passé simple', '12'), ('passe simple', '12'), ('ps', '12'),
('passé antérieur', '112'), ('passe anterieur', '112'), ('pa', '112'),
@ -32,29 +33,7 @@ for k, v in s:
d[k].append(v)
def help_full():
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)
# MODULE CORE #########################################################
def get_conjug(verb, stringTens):
url = ("http://leconjugueur.lefigaro.fr/conjugaison/verbe/%s.html" %
@ -89,3 +68,27 @@ def compute_line(line, stringTens):
.replace("<b>", "\x02")
.replace("</b>", "\x0F")))
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 nemubot.hooks import hook
from nemubot.tools.web import getURLContent
from nemubot.tools.web import getURLContent, striphtml
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):
soup = BeautifulSoup(getURLContent('https://ctftime.org/event/list/upcoming'))
res = Response(channel=msg.channel, nomore="No more upcoming CTF")
for line in soup.body.find_all('tr'):
n = line.find_all('td')
if len(n) == 5:
try:
res.append_message("\x02%s:\x0F from %s type %s at %s. %s" % tuple([x.text.replace("\n", " ").strip() for x in n]))
except:
import sys
import traceback
exc_type, exc_value, _ = sys.exc_info()
sys.stderr.write(traceback.format_exception_only(exc_type, exc_value)[0])
return res
soup = BeautifulSoup(getURLContent(URL))
res = Response(channel=msg.channel, nomore="No more upcoming CTF")
for line in soup.body.find_all('tr'):
n = line.find_all('td')
if len(n) == 5:
try:
res.append_message("\x02%s:\x0F from %s type %s at %s. %s" %
tuple([striphtml(x.text) for x in n]))
except:
pass
return res