Replace IRCException by IMException, as nemubot is not only built for IRC

This commit is contained in:
nemunaire 2015-10-30 21:57:45 +01:00
parent ac33ceb579
commit 8b4f08c5bd
40 changed files with 183 additions and 188 deletions

View file

@ -7,7 +7,7 @@ from datetime import datetime, timezone
import shlex import shlex
from nemubot import context from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.message import Command from nemubot.message import Command
from nemubot.tools.xmlparser.node import ModuleState from nemubot.tools.xmlparser.node import ModuleState
@ -183,7 +183,7 @@ def cmd_listvars(msg):
help_usage={"KEY VALUE": "Define the variable named KEY and fill it with VALUE as content"}) 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 take two args: the key and the value.") raise IMException("!set take two args: the key and the value.")
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 successfully defined." % msg.args[0], return Response("Variable $%s successfully defined." % msg.args[0],
channel=msg.channel) channel=msg.channel)
@ -209,7 +209,7 @@ def cmd_listalias(msg):
help="Display the replacement command for a given 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 takes as argument an alias to extend.") raise IMException("!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] == "!":
@ -225,7 +225,7 @@ def cmd_alias(msg):
help="Remove a previously created alias") 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("Which alias would you want to remove?") raise IMException("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:
@ -268,7 +268,7 @@ def parseask(msg):
if re.match(".*(register|set|cr[ée]{2}|new|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|for|=|:) ?(.+)$", 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("this alias is already defined.") raise IMException("this alias is already defined.")
else: else:
create_alias(result.group(1), create_alias(result.group(1),
result.group(3), result.group(3),

View file

@ -7,7 +7,7 @@ import sys
from datetime import date, datetime from datetime import date, datetime
from nemubot import context from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools.countdown import countdown_format from nemubot.tools.countdown import countdown_format
from nemubot.tools.date import extractDate from nemubot.tools.date import extractDate
@ -131,4 +131,4 @@ def parseask(msg):
msg.channel, msg.channel,
msg.nick) msg.nick)
except: except:
raise IRCException("la date de naissance ne paraît pas valide.") raise IMException("la date de naissance ne paraît pas valide.")

View file

@ -5,7 +5,7 @@
import urllib import urllib
from nemubot import context from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -65,11 +65,11 @@ def search_author(name):
}) })
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 IMException("please give me a title to search")
book = get_book(" ".join(msg.args)) book = get_book(" ".join(msg.args))
if book is None: if book is None:
raise IRCException("unable to find book named like this") raise IMException("unable to find book named like this")
res = Response(channel=msg.channel) res = Response(channel=msg.channel)
res.append_message("%s, written by %s: %s" % (book.getElementsByTagName("title")[0].firstChild.nodeValue, res.append_message("%s, written by %s: %s" % (book.getElementsByTagName("title")[0].firstChild.nodeValue,
book.getElementsByTagName("author")[0].getElementsByTagName("name")[0].firstChild.nodeValue, book.getElementsByTagName("author")[0].getElementsByTagName("name")[0].firstChild.nodeValue,
@ -84,7 +84,7 @@ def cmd_book(msg):
}) })
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 IMException("please give me a title to search")
title = " ".join(msg.args) title = " ".join(msg.args)
res = Response(channel=msg.channel, res = Response(channel=msg.channel,
@ -104,12 +104,12 @@ def cmd_books(msg):
}) })
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 IMException("please give me an author to search")
name = " ".join(msg.args) name = " ".join(msg.args)
ath = search_author(name) ath = search_author(name)
if ath is None: if ath is None:
raise IRCException("%s does not appear to be a published author." % name) raise IMException("%s does not appear to be a published author." % name)
return Response([b.getElementsByTagName("title")[0].firstChild.nodeValue for b in ath.getElementsByTagName("book")], return Response([b.getElementsByTagName("title")[0].firstChild.nodeValue for b in ath.getElementsByTagName("book")],
channel=msg.channel, channel=msg.channel,
title=ath.getElementsByTagName("name")[0].firstChild.nodeValue) title=ath.getElementsByTagName("name")[0].firstChild.nodeValue)

View file

@ -6,7 +6,7 @@ from collections import defaultdict
import re import re
from urllib.parse import quote from urllib.parse import quote
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook 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
@ -51,10 +51,10 @@ def compute_line(line, stringTens):
try: try:
idTemps = d[stringTens] idTemps = d[stringTens]
except: except:
raise IRCException("le temps demandé n'existe pas") raise IMException("le temps demandé n'existe pas")
if len(idTemps) == 0: if len(idTemps) == 0:
raise IRCException("le temps demandé n'existe pas") raise IMException("le temps demandé n'existe pas")
index = line.index('<div id="temps' + idTemps[0] + '\"') index = line.index('<div id="temps' + idTemps[0] + '\"')
endIndex = line[index:].index('<div class=\"conjugBloc\"') endIndex = line[index:].index('<div class=\"conjugBloc\"')
@ -78,7 +78,7 @@ def compute_line(line, stringTens):
}) })
def cmd_conjug(msg): def cmd_conjug(msg):
if len(msg.args) < 2: if len(msg.args) < 2:
raise IRCException("donne moi un temps et un verbe, et je te donnerai " raise IMException("donne moi un temps et un verbe, et je te donnerai "
"sa conjugaison!") "sa conjugaison!")
tens = ' '.join(msg.args[:-1]) tens = ' '.join(msg.args[:-1])
@ -91,4 +91,4 @@ def cmd_conjug(msg):
return Response(conjug, channel=msg.channel, return Response(conjug, channel=msg.channel,
title="Conjugaison de %s" % verb) title="Conjugaison de %s" % verb)
else: else:
raise IRCException("aucune conjugaison de '%s' n'a été trouvé" % verb) raise IMException("aucune conjugaison de '%s' n'a été trouvé" % verb)

View file

@ -4,7 +4,7 @@
from urllib.parse import quote from urllib.parse import quote
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -29,7 +29,7 @@ class DDGResult:
def __init__(self, terms, res): def __init__(self, terms, res):
if res is None: if res is None:
raise IRCException("An error occurs during search") raise IMException("An error occurs during search")
self.terms = terms self.terms = terms
self.ddgres = res self.ddgres = res
@ -106,19 +106,19 @@ class DDGResult:
@hook("cmd_hook", "define") @hook("cmd_hook", "define")
def define(msg): def define(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Indicate a term to define") raise IMException("Indicate a term to define")
s = do_search(msg.args) s = do_search(msg.args)
if not s.definition: if not s.definition:
raise IRCException("no definition found for '%s'." % " ".join(msg.args)) raise IMException("no definition found for '%s'." % " ".join(msg.args))
return Response(s.definition, channel=msg.channel) return Response(s.definition, channel=msg.channel)
@hook("cmd_hook", "search") @hook("cmd_hook", "search")
def search(msg): def search(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Indicate a term to search") raise IMException("Indicate a term to search")
s = do_search(msg.args) s = do_search(msg.args)

View file

@ -2,16 +2,11 @@
"""Create countdowns and reminders""" """Create countdowns and reminders"""
import imp
import re import re
import sys
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
import time
import threading
import traceback
from nemubot import context from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.event import ModuleEvent from nemubot.event import ModuleEvent
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools.countdown import countdown_format, countdown from nemubot.tools.countdown import countdown_format, countdown
@ -65,9 +60,9 @@ def cmd_we(msg):
def start_countdown(msg): def start_countdown(msg):
"""!start /something/: launch a timer""" """!start /something/: launch a timer"""
if len(msg.args) < 1: if len(msg.args) < 1:
raise IRCException("indique le nom d'un événement à chronométrer") raise IMException("indique le nom d'un événement à chronométrer")
if msg.args[0] in context.data.index: if msg.args[0] in context.data.index:
raise IRCException("%s existe déjà." % msg.args[0]) raise IMException("%s existe déjà." % msg.args[0])
strnd = ModuleState("strend") strnd = ModuleState("strend")
strnd["server"] = msg.server strnd["server"] = msg.server
@ -107,7 +102,7 @@ def start_countdown(msg):
strnd["_id"] = context.add_event(evt) strnd["_id"] = context.add_event(evt)
except: except:
context.data.delChild(strnd) context.data.delChild(strnd)
raise IRCException("Mauvais format de date pour l'événement %s. Il n'a pas été créé." % msg.args[0]) raise IMException("Mauvais format de date pour l'événement %s. Il n'a pas été créé." % msg.args[0])
elif result1 is not None and len(result1) > 0: elif result1 is not None and len(result1) > 0:
strnd["end"] = msg.date strnd["end"] = msg.date
@ -144,7 +139,7 @@ def start_countdown(msg):
@hook("cmd_hook", "forceend") @hook("cmd_hook", "forceend")
def end_countdown(msg): def end_countdown(msg):
if len(msg.args) < 1: if len(msg.args) < 1:
raise IRCException("quel événement terminer ?") raise IMException("quel événement terminer ?")
if msg.args[0] in context.data.index: if msg.args[0] in context.data.index:
if context.data.index[msg.args[0]]["proprio"] == msg.nick or (msg.cmd == "forceend" and msg.frm_owner): if context.data.index[msg.args[0]]["proprio"] == msg.nick or (msg.cmd == "forceend" and msg.frm_owner):
@ -155,7 +150,7 @@ def end_countdown(msg):
return Response("%s a duré %s." % (msg.args[0], duration), return Response("%s a duré %s." % (msg.args[0], duration),
channel=msg.channel, nick=msg.nick) channel=msg.channel, nick=msg.nick)
else: else:
raise IRCException("Vous ne pouvez pas terminer le compteur %s, créé par %s." % (msg.args[0], context.data.index[msg.args[0]]["proprio"])) raise IMException("Vous ne pouvez pas terminer le compteur %s, créé par %s." % (msg.args[0], context.data.index[msg.args[0]]["proprio"]))
else: else:
return Response("%s n'est pas un compteur connu."% (msg.args[0]), channel=msg.channel, nick=msg.nick) return Response("%s n'est pas un compteur connu."% (msg.args[0]), channel=msg.channel, nick=msg.nick)
@ -199,15 +194,15 @@ def parseask(msg):
if RGXP_ask.match(msg.text) is not None: if RGXP_ask.match(msg.text) is not None:
name = re.match("^.*!([^ \"'@!]+).*$", msg.text) name = re.match("^.*!([^ \"'@!]+).*$", msg.text)
if name is None: if name is None:
raise IRCException("il faut que tu attribues une commande à l'événement.") raise IMException("il faut que tu attribues une commande à l'événement.")
if name.group(1) in context.data.index: if name.group(1) in context.data.index:
raise IRCException("un événement portant ce nom existe déjà.") raise IMException("un événement portant ce nom existe déjà.")
texts = re.match("^[^\"]*(avant|après|apres|before|after)?[^\"]*\"([^\"]+)\"[^\"]*((avant|après|apres|before|after)?.*\"([^\"]+)\".*)?$", msg.text, re.I) texts = re.match("^[^\"]*(avant|après|apres|before|after)?[^\"]*\"([^\"]+)\"[^\"]*((avant|après|apres|before|after)?.*\"([^\"]+)\".*)?$", msg.text, re.I)
if texts is not None and texts.group(3) is not None: if texts is not None and texts.group(3) is not None:
extDate = extractDate(msg.text) extDate = extractDate(msg.text)
if extDate is None or extDate == "": if extDate is None or extDate == "":
raise IRCException("la date de l'événement est invalide !") raise IMException("la date de l'événement est invalide !")
if texts.group(1) is not None and (texts.group(1) == "après" or texts.group(1) == "apres" or texts.group(1) == "after"): if texts.group(1) is not None and (texts.group(1) == "après" or texts.group(1) == "apres" or texts.group(1) == "after"):
msg_after = texts.group (2) msg_after = texts.group (2)
@ -217,7 +212,7 @@ def parseask(msg):
msg_after = texts.group (5) msg_after = texts.group (5)
if msg_before.find("%s") == -1 or msg_after.find("%s") == -1: if msg_before.find("%s") == -1 or msg_after.find("%s") == -1:
raise IRCException("Pour que l'événement soit valide, ajouter %s à" raise IMException("Pour que l'événement soit valide, ajouter %s à"
" l'endroit où vous voulez que soit ajouté le" " l'endroit où vous voulez que soit ajouté le"
" compte à rebours.") " compte à rebours.")
@ -247,4 +242,4 @@ def parseask(msg):
channel=msg.channel) channel=msg.channel)
else: else:
raise IRCException("Veuillez indiquez les messages d'attente et d'après événement entre guillemets.") raise IMException("Veuillez indiquez les messages d'attente et d'après événement entre guillemets.")

View file

@ -7,7 +7,7 @@ import json
from urllib.parse import urlparse from urllib.parse import urlparse
from urllib.parse import quote from urllib.parse import quote
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.message import Text from nemubot.message import Text
from nemubot.tools import web from nemubot.tools import web
@ -29,9 +29,9 @@ def framalink_reducer(url, data):
if 'short' in json_data: if 'short' in json_data:
return json_data['short'] return json_data['short']
elif 'msg' in json_data: elif 'msg' in json_data:
raise IRCException("Error: %s" % json_data['msg']) raise IMException("Error: %s" % json_data['msg'])
else: else:
IRCException("An error occured while shortening %s." % data) IMException("An error occured while shortening %s." % data)
# MODULE VARIABLES #################################################### # MODULE VARIABLES ####################################################
@ -69,7 +69,7 @@ def reduce(url, provider=DEFAULT_PROVIDER):
def gen_response(res, msg, srv): def gen_response(res, msg, srv):
if res is None: if res is None:
raise IRCException("bad URL : %s" % srv) raise IMException("bad URL : %s" % srv)
else: else:
return Text("URL for %s: %s" % (srv, res), server=None, return Text("URL for %s: %s" % (srv, res), server=None,
to=msg.to_response) to=msg.to_response)
@ -121,10 +121,10 @@ def cmd_reduceurl(msg):
if msg.channel in LAST_URLS and len(LAST_URLS[msg.channel]) > 0: if msg.channel in LAST_URLS and len(LAST_URLS[msg.channel]) > 0:
minify.append(LAST_URLS[msg.channel].pop()) minify.append(LAST_URLS[msg.channel].pop())
else: else:
raise IRCException("I have no more URL to reduce.") raise IMException("I have no more URL to reduce.")
if len(msg.args) > 4: if len(msg.args) > 4:
raise IRCException("I cannot reduce that maby URLs at once.") raise IMException("I cannot reduce that maby URLs at once.")
else: else:
minify += msg.args minify += msg.args

View file

@ -5,7 +5,7 @@
import re import re
from urllib.parse import quote from urllib.parse import quote
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -68,7 +68,7 @@ def info_commit(repo, commit=None):
@hook("cmd_hook", "github") @hook("cmd_hook", "github")
def cmd_github(msg): def cmd_github(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("indicate a repository name to search") raise IMException("indicate a repository name to search")
repos = info_repos(" ".join(msg.args)) repos = info_repos(" ".join(msg.args))
@ -96,7 +96,7 @@ def cmd_github(msg):
@hook("cmd_hook", "github_user") @hook("cmd_hook", "github_user")
def cmd_github_user(msg): def cmd_github_user(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("indicate a user name to search") raise IMException("indicate a user name to search")
res = Response(channel=msg.channel, nomore="No more user") res = Response(channel=msg.channel, nomore="No more user")
@ -121,7 +121,7 @@ def cmd_github_user(msg):
user["html_url"], user["html_url"],
kf)) kf))
else: else:
raise IRCException("User not found") raise IMException("User not found")
return res return res
@ -129,7 +129,7 @@ def cmd_github_user(msg):
@hook("cmd_hook", "github_issue") @hook("cmd_hook", "github_issue")
def cmd_github_issue(msg): def cmd_github_issue(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("indicate a repository to view its issues") raise IMException("indicate a repository to view its issues")
issue = None issue = None
@ -150,7 +150,7 @@ def cmd_github_issue(msg):
issues = info_issue(repo, issue) issues = info_issue(repo, issue)
if issues is None: if issues is None:
raise IRCException("Repository not found") raise IMException("Repository not found")
for issue in issues: for issue in issues:
res.append_message("%s%s issue #%d: \x03\x02%s\x03\x02 opened by %s on %s: %s" % res.append_message("%s%s issue #%d: \x03\x02%s\x03\x02 opened by %s on %s: %s" %
@ -167,7 +167,7 @@ def cmd_github_issue(msg):
@hook("cmd_hook", "github_commit") @hook("cmd_hook", "github_commit")
def cmd_github_commit(msg): def cmd_github_commit(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("indicate a repository to view its commits") raise IMException("indicate a repository to view its commits")
commit = None commit = None
if re.match("^[a-fA-F0-9]+$", msg.args[0]): if re.match("^[a-fA-F0-9]+$", msg.args[0]):
@ -185,7 +185,7 @@ def cmd_github_commit(msg):
commits = info_commit(repo, commit) commits = info_commit(repo, commit)
if commits is None: if commits is None:
raise IRCException("Repository not found") raise IMException("Repository not found")
for commit in commits: for commit in commits:
res.append_message("Commit %s by %s on %s: %s" % res.append_message("Commit %s by %s on %s: %s" %

View file

@ -5,7 +5,7 @@
import re import re
import urllib.parse import urllib.parse
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -39,13 +39,13 @@ def get_movie(title=None, year=None, imdbid=None, fullplot=True, tomatoes=False)
# Return data # Return data
if "Error" in data: if "Error" in data:
raise IRCException(data["Error"]) raise IMException(data["Error"])
elif "Response" in data and data["Response"] == "True": elif "Response" in data and data["Response"] == "True":
return data return data
else: else:
raise IRCException("An error occurs during movie search") raise IMException("An error occurs during movie search")
def find_movies(title): def find_movies(title):
@ -59,20 +59,20 @@ def find_movies(title):
# Return data # Return data
if "Error" in data: if "Error" in data:
raise IRCException(data["Error"]) raise IMException(data["Error"])
elif "Search" in data: elif "Search" in data:
return data return data
else: else:
raise IRCException("An error occurs during movie search") raise IMException("An error occurs during movie search")
@hook("cmd_hook", "imdb") @hook("cmd_hook", "imdb")
def cmd_imdb(msg): def cmd_imdb(msg):
"""View movie details with !imdb <title>""" """View movie details with !imdb <title>"""
if not len(msg.args): if not len(msg.args):
raise IRCException("precise a movie/serie title!") raise IMException("precise a movie/serie title!")
title = ' '.join(msg.args) title = ' '.join(msg.args)
@ -101,7 +101,7 @@ def cmd_imdb(msg):
def cmd_search(msg): def cmd_search(msg):
"""!imdbs <approximative title> to search a movie title""" """!imdbs <approximative title> to search a movie title"""
if not len(msg.args): if not len(msg.args):
raise IRCException("precise a movie/serie title!") raise IMException("precise a movie/serie title!")
data = find_movies(' '.join(msg.args)) data = find_movies(' '.join(msg.args))

View file

@ -1,5 +1,5 @@
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.tools import web from nemubot.tools import web
from more import Response from more import Response
import json import json
@ -42,15 +42,15 @@ def getJsonKeys(data):
@hook("cmd_hook", "json") @hook("cmd_hook", "json")
def get_json_info(msg): def get_json_info(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Please specify a url and a list of JSON keys.") raise IMException("Please specify a url and a list of JSON keys.")
request_data = web.getURLContent(msg.args[0].replace(' ', "%20")) request_data = web.getURLContent(msg.args[0].replace(' ', "%20"))
if not request_data: if not request_data:
raise IRCException("Please specify a valid url.") raise IMException("Please specify a valid url.")
json_data = json.loads(request_data) json_data = json.loads(request_data)
if len(msg.args) == 1: if len(msg.args) == 1:
raise IRCException("Please specify the keys to return (%s)" % ", ".join(getJsonKeys(json_data))) raise IMException("Please specify the keys to return (%s)" % ", ".join(getJsonKeys(json_data)))
tags = ','.join(msg.args[1:]).split(',') tags = ','.join(msg.args[1:]).split(',')
response = getRequestedTags(tags, json_data) response = getRequestedTags(tags, json_data)

View file

@ -5,7 +5,7 @@
import re import re
from urllib.parse import quote from urllib.parse import quote
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -46,7 +46,7 @@ def where(loc):
@hook("cmd_hook", "geocode") @hook("cmd_hook", "geocode")
def cmd_geocode(msg): def cmd_geocode(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("indicate a name") raise IMException("indicate a name")
res = Response(channel=msg.channel, nick=msg.nick, res = Response(channel=msg.channel, nick=msg.nick,
nomore="No more geocode", count=" (%s more geocode)") nomore="No more geocode", count=" (%s more geocode)")

View file

@ -5,7 +5,7 @@
import re import re
import urllib.parse import urllib.parse
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -42,7 +42,7 @@ def get_raw_page(site, term, ssl=False):
try: try:
return data["query"]["pages"][k]["revisions"][0]["*"] return data["query"]["pages"][k]["revisions"][0]["*"]
except: except:
raise IRCException("article not found") raise IMException("article not found")
def get_unwikitextified(site, wikitext, ssl=False): def get_unwikitextified(site, wikitext, ssl=False):
@ -179,7 +179,7 @@ def mediawiki_response(site, term, receivers):
def cmd_mediawiki(msg): def cmd_mediawiki(msg):
"""Read an article on a MediaWiki""" """Read an article on a MediaWiki"""
if len(msg.args) < 2: if len(msg.args) < 2:
raise IRCException("indicate a domain and a term to search") raise IMException("indicate a domain and a term to search")
return mediawiki_response(msg.args[0], return mediawiki_response(msg.args[0],
" ".join(msg.args[1:]), " ".join(msg.args[1:]),
@ -190,7 +190,7 @@ def cmd_mediawiki(msg):
def cmd_srchmediawiki(msg): def cmd_srchmediawiki(msg):
"""Search an article on a MediaWiki""" """Search an article on a MediaWiki"""
if len(msg.args) < 2: if len(msg.args) < 2:
raise IRCException("indicate a domain and a term to search") raise IMException("indicate a domain and a term to search")
res = Response(channel=msg.receivers, nomore="No more results", count=" (%d more results)") res = Response(channel=msg.receivers, nomore="No more results", count=" (%d more results)")
@ -203,7 +203,7 @@ def cmd_srchmediawiki(msg):
@hook("cmd_hook", "wikipedia") @hook("cmd_hook", "wikipedia")
def cmd_wikipedia(msg): def cmd_wikipedia(msg):
if len(msg.args) < 2: if len(msg.args) < 2:
raise IRCException("indicate a lang and a term to search") raise IMException("indicate a lang and a term to search")
return mediawiki_response(msg.args[0] + ".wikipedia.org", return mediawiki_response(msg.args[0] + ".wikipedia.org",
" ".join(msg.args[1:]), " ".join(msg.args[1:]),

View file

@ -5,7 +5,7 @@
import logging import logging
import re import re
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from more import Response from more import Response
@ -43,13 +43,13 @@ def load(context):
help_usage={"URL": "Display the title of the given URL"}) help_usage={"URL": "Display the title of the given URL"})
def cmd_title(msg): def cmd_title(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Indicate the URL to visit.") raise IMException("Indicate the URL to visit.")
url = " ".join(msg.args) url = " ".join(msg.args)
res = re.search("<title>(.*?)</title>", page.fetch(" ".join(msg.args)), re.DOTALL) res = re.search("<title>(.*?)</title>", page.fetch(" ".join(msg.args)), re.DOTALL)
if res is None: if res is None:
raise IRCException("The page %s has no title" % url) raise IMException("The page %s has no title" % url)
else: else:
return Response("%s: %s" % (url, res.group(1).replace("\n", " ")), channel=msg.channel) return Response("%s: %s" % (url, res.group(1).replace("\n", " ")), channel=msg.channel)
@ -59,7 +59,7 @@ def cmd_title(msg):
help_usage={"URL": "Display HTTP headers of the given URL"}) help_usage={"URL": "Display HTTP headers of the given URL"})
def cmd_curly(msg): def cmd_curly(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Indicate the URL to visit.") raise IMException("Indicate the URL to visit.")
url = " ".join(msg.args) url = " ".join(msg.args)
version, status, reason, headers = page.headers(url) version, status, reason, headers = page.headers(url)
@ -72,7 +72,7 @@ def cmd_curly(msg):
help_usage={"URL": "Display raw HTTP body of the given URL"}) help_usage={"URL": "Display raw HTTP body of the given URL"})
def cmd_curl(msg): def cmd_curl(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Indicate the URL to visit.") raise IMException("Indicate the URL to visit.")
res = Response(channel=msg.channel) res = Response(channel=msg.channel)
for m in page.fetch(" ".join(msg.args)).split("\n"): for m in page.fetch(" ".join(msg.args)).split("\n"):
@ -85,7 +85,7 @@ def cmd_curl(msg):
help_usage={"URL": "Display and format HTTP content of the given URL"}) help_usage={"URL": "Display and format HTTP content of the given URL"})
def cmd_w3m(msg): def cmd_w3m(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Indicate the URL to visit.") raise IMException("Indicate the URL to visit.")
res = Response(channel=msg.channel) res = Response(channel=msg.channel)
for line in page.render(" ".join(msg.args)).split("\n"): for line in page.render(" ".join(msg.args)).split("\n"):
res.append_message(line) res.append_message(line)
@ -97,7 +97,7 @@ def cmd_w3m(msg):
help_usage={"URL": "Display redirections steps for the given URL"}) help_usage={"URL": "Display redirections steps for the given URL"})
def cmd_traceurl(msg): def cmd_traceurl(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Indicate an URL to trace!") raise IMException("Indicate an URL to trace!")
res = list() res = list()
for url in msg.args[:4]: for url in msg.args[:4]:
@ -114,7 +114,7 @@ def cmd_traceurl(msg):
help_usage={"DOMAIN": "Check if a DOMAIN is up"}) help_usage={"DOMAIN": "Check if a DOMAIN is up"})
def cmd_isup(msg): def cmd_isup(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Indicate an domain name to check!") raise IMException("Indicate an domain name to check!")
res = list() res = list()
for url in msg.args[:4]: for url in msg.args[:4]:
@ -131,7 +131,7 @@ def cmd_isup(msg):
help_usage={"URL": "Do W3C HTML validation on the given URL"}) help_usage={"URL": "Do W3C HTML validation on the given URL"})
def cmd_w3c(msg): def cmd_w3c(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Indicate an URL to validate!") raise IMException("Indicate an URL to validate!")
headers, validator = w3c.validator(msg.args[0]) headers, validator = w3c.validator(msg.args[0])
@ -157,7 +157,7 @@ def cmd_w3c(msg):
help_usage={"URL": "Watch the given domain and alert when it availability status changes"}) help_usage={"URL": "Watch the given domain and alert when it availability status changes"})
def cmd_watch(msg, diffType="diff"): def cmd_watch(msg, diffType="diff"):
if not len(msg.args): if not len(msg.args):
raise IRCException("indicate an URL to watch!") raise IMException("indicate an URL to watch!")
return watchWebsite.add_site(msg.args[0], msg.frm, msg.channel, msg.server, diffType) return watchWebsite.add_site(msg.args[0], msg.frm, msg.channel, msg.server, diffType)
@ -178,7 +178,7 @@ def cmd_listwatch(msg):
help_usage={"URL": "Unwatch the given URL"}) help_usage={"URL": "Unwatch the given URL"})
def cmd_unwatch(msg): def cmd_unwatch(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("which URL should I stop watching?") raise IMException("which URL should I stop watching?")
for arg in msg.args: for arg in msg.args:
return watchWebsite.del_site(arg, msg.frm, msg.channel, msg.frm_owner) return watchWebsite.del_site(arg, msg.frm, msg.channel, msg.frm_owner)

View file

@ -5,7 +5,7 @@ import tempfile
import urllib import urllib
from nemubot import __version__ from nemubot import __version__
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.tools import web from nemubot.tools import web
@ -23,7 +23,7 @@ def headers(url):
o = urllib.parse.urlparse(web.getNormalizedURL(url), "http") o = urllib.parse.urlparse(web.getNormalizedURL(url), "http")
if o.netloc == "": if o.netloc == "":
raise IRCException("invalid URL") raise IMException("invalid URL")
if o.scheme == "http": if o.scheme == "http":
conn = http.client.HTTPConnection(o.hostname, port=o.port, timeout=5) conn = http.client.HTTPConnection(o.hostname, port=o.port, timeout=5)
else: else:
@ -32,18 +32,18 @@ def headers(url):
conn.request("HEAD", o.path, None, {"User-agent": conn.request("HEAD", o.path, None, {"User-agent":
"Nemubot v%s" % __version__}) "Nemubot v%s" % __version__})
except ConnectionError as e: except ConnectionError as e:
raise IRCException(e.strerror) raise IMException(e.strerror)
except socket.timeout: except socket.timeout:
raise IRCException("request timeout") raise IMException("request timeout")
except socket.gaierror: except socket.gaierror:
print ("<tools.web> Unable to receive page %s from %s on %d." print ("<tools.web> Unable to receive page %s from %s on %d."
% (o.path, o.hostname, o.port if o.port is not None else 0)) % (o.path, o.hostname, o.port if o.port is not None else 0))
raise IRCException("an unexpected error occurs") raise IMException("an unexpected error occurs")
try: try:
res = conn.getresponse() res = conn.getresponse()
except http.client.BadStatusLine: except http.client.BadStatusLine:
raise IRCException("An error occurs") raise IMException("An error occurs")
finally: finally:
conn.close() conn.close()
@ -51,7 +51,7 @@ def headers(url):
def _onNoneDefault(): def _onNoneDefault():
raise IRCException("An error occurs when trying to access the page") raise IMException("An error occurs when trying to access the page")
def fetch(url, onNone=_onNoneDefault): def fetch(url, onNone=_onNoneDefault):
@ -71,11 +71,11 @@ def fetch(url, onNone=_onNoneDefault):
else: else:
return None return None
except ConnectionError as e: except ConnectionError as e:
raise IRCException(e.strerror) raise IMException(e.strerror)
except socket.timeout: except socket.timeout:
raise IRCException("The request timeout when trying to access the page") raise IMException("The request timeout when trying to access the page")
except socket.error as e: except socket.error as e:
raise IRCException(e.strerror) raise IMException(e.strerror)
def _render(cnt): def _render(cnt):

View file

@ -2,7 +2,7 @@ import json
import urllib import urllib
from nemubot import __version__ from nemubot import __version__
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.tools.web import getNormalizedURL from nemubot.tools.web import getNormalizedURL
def validator(url): def validator(url):
@ -14,19 +14,19 @@ def validator(url):
o = urllib.parse.urlparse(getNormalizedURL(url), "http") o = urllib.parse.urlparse(getNormalizedURL(url), "http")
if o.netloc == "": if o.netloc == "":
raise IRCException("Indicate a valid URL!") raise IMException("Indicate a valid URL!")
try: try:
req = urllib.request.Request("http://validator.w3.org/check?uri=%s&output=json" % (urllib.parse.quote(o.geturl())), headers={ 'User-Agent' : "Nemubot v%s" % __version__}) req = urllib.request.Request("http://validator.w3.org/check?uri=%s&output=json" % (urllib.parse.quote(o.geturl())), headers={ 'User-Agent' : "Nemubot v%s" % __version__})
raw = urllib.request.urlopen(req, timeout=10) raw = urllib.request.urlopen(req, timeout=10)
except urllib.error.HTTPError as e: except urllib.error.HTTPError as e:
raise IRCException("HTTP error occurs: %s %s" % (e.code, e.reason)) raise IMException("HTTP error occurs: %s %s" % (e.code, e.reason))
headers = dict() headers = dict()
for Hname, Hval in raw.getheaders(): for Hname, Hval in raw.getheaders():
headers[Hname] = Hval headers[Hname] = Hval
if "X-W3C-Validator-Status" not in headers or (headers["X-W3C-Validator-Status"] != "Valid" and headers["X-W3C-Validator-Status"] != "Invalid"): if "X-W3C-Validator-Status" not in headers or (headers["X-W3C-Validator-Status"] != "Valid" and headers["X-W3C-Validator-Status"] != "Invalid"):
raise IRCException("Unexpected error on W3C servers" + (" (" + headers["X-W3C-Validator-Status"] + ")" if "X-W3C-Validator-Status" in headers else "")) raise IMException("Unexpected error on W3C servers" + (" (" + headers["X-W3C-Validator-Status"] + ")" if "X-W3C-Validator-Status" in headers else ""))
return headers, json.loads(raw.read().decode()) return headers, json.loads(raw.read().decode())

View file

@ -6,7 +6,7 @@ import urllib.parse
from urllib.parse import urlparse from urllib.parse import urlparse
from nemubot.event import ModuleEvent from nemubot.event import ModuleEvent
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.tools.web import getNormalizedURL from nemubot.tools.web import getNormalizedURL
from nemubot.tools.xmlparser.node import ModuleState from nemubot.tools.xmlparser.node import ModuleState
@ -61,7 +61,7 @@ def del_site(url, nick, channel, frm_owner):
for a in site.getNodes("alert"): for a in site.getNodes("alert"):
if a["channel"] == channel: if a["channel"] == channel:
# if not (nick == a["nick"] or frm_owner): # if not (nick == a["nick"] or frm_owner):
# raise IRCException("you cannot unwatch this URL.") # raise IMException("you cannot unwatch this URL.")
site.delChild(a) site.delChild(a)
if not site.hasNode("alert"): if not site.hasNode("alert"):
del_event(site["_evt_id"]) del_event(site["_evt_id"])
@ -69,7 +69,7 @@ def del_site(url, nick, channel, frm_owner):
save() save()
return Response("I don't watch this URL anymore.", return Response("I don't watch this URL anymore.",
channel=channel, nick=nick) channel=channel, nick=nick)
raise IRCException("I didn't watch this URL!") raise IMException("I didn't watch this URL!")
def add_site(url, nick, channel, server, diffType="diff"): def add_site(url, nick, channel, server, diffType="diff"):
@ -81,7 +81,7 @@ def add_site(url, nick, channel, server, diffType="diff"):
o = urlparse(getNormalizedURL(url), "http") o = urlparse(getNormalizedURL(url), "http")
if o.netloc == "": if o.netloc == "":
raise IRCException("sorry, I can't watch this URL :(") raise IMException("sorry, I can't watch this URL :(")
alert = ModuleState("alert") alert = ModuleState("alert")
alert["nick"] = nick alert["nick"] = nick
@ -219,5 +219,5 @@ def start_watching(site, offset=0):
interval=site.getInt("time"), interval=site.getInt("time"),
call=alert_change, call_data=site) call=alert_change, call_data=site)
site["_evt_id"] = add_event(evt) site["_evt_id"] = add_event(evt)
except IRCException: except IMException:
logger.exception("Unable to watch %s", site["url"]) logger.exception("Unable to watch %s", site["url"])

View file

@ -1,7 +1,7 @@
import datetime import datetime
import urllib import urllib
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.tools.web import getJSON from nemubot.tools.web import getJSON
from more import Response from more import Response
@ -80,14 +80,14 @@ def whois_entityformat(entity):
def cmd_whois(msg): def cmd_whois(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Indiquer un domaine ou une IP à whois !") raise IMException("Indiquer un domaine ou une IP à whois !")
dom = msg.args[0] dom = msg.args[0]
js = getJSON(URL_WHOIS % urllib.parse.quote(dom)) js = getJSON(URL_WHOIS % urllib.parse.quote(dom))
if "ErrorMessage" in js: if "ErrorMessage" in js:
raise IRCException(js["ErrorMessage"]["msg"]) raise IMException(js["ErrorMessage"]["msg"])
whois = js["WhoisRecord"] whois = js["WhoisRecord"]

View file

@ -8,7 +8,7 @@ from urllib.parse import urljoin
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -44,7 +44,7 @@ def get_last_news(url):
@hook("cmd_hook", "news") @hook("cmd_hook", "news")
def cmd_news(msg): def cmd_news(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Indicate the URL to visit.") raise IMException("Indicate the URL to visit.")
url = " ".join(msg.args) url = " ".join(msg.args)
links = [x for x in find_rss_links(url)] links = [x for x in find_rss_links(url)]

View file

@ -2,7 +2,7 @@
"""Informe les usagers des prochains passages des transports en communs de la RATP""" """Informe les usagers des prochains passages des transports en communs de la RATP"""
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from more import Response from more import Response
@ -27,7 +27,7 @@ def ask_ratp(msg):
times = ratp.getNextStopsAtStation(transport, line, station) times = ratp.getNextStopsAtStation(transport, line, station)
if len(times) == 0: if len(times) == 0:
raise IRCException("la station %s n'existe pas sur le %s ligne %s." % (station, transport, line)) raise IMException("la station %s n'existe pas sur le %s ligne %s." % (station, transport, line))
(time, direction, stationname) = times[0] (time, direction, stationname) = times[0]
return Response(message=["\x03\x02%s\x03\x02 direction %s" % (time, direction) for time, direction, stationname in times], return Response(message=["\x03\x02%s\x03\x02 direction %s" % (time, direction) for time, direction, stationname in times],
@ -38,11 +38,11 @@ def ask_ratp(msg):
stations = ratp.getAllStations(msg.args[0], msg.args[1]) stations = ratp.getAllStations(msg.args[0], msg.args[1])
if len(stations) == 0: if len(stations) == 0:
raise IRCException("aucune station trouvée.") raise IMException("aucune station trouvée.")
return Response([s for s in stations], title="Stations", channel=msg.channel) return Response([s for s in stations], title="Stations", channel=msg.channel)
else: else:
raise IRCException("Mauvais usage, merci de spécifier un type de transport et une ligne, ou de consulter l'aide du module.") raise IMException("Mauvais usage, merci de spécifier un type de transport et une ligne, ou de consulter l'aide du module.")
@hook("cmd_hook", "ratp_alert") @hook("cmd_hook", "ratp_alert")
def ratp_alert(msg): def ratp_alert(msg):
@ -52,4 +52,4 @@ def ratp_alert(msg):
incidents = ratp.getDisturbance(cause, transport) incidents = ratp.getDisturbance(cause, transport)
return Response(incidents, channel=msg.channel, nomore="No more incidents", count=" (%d more incidents)") return Response(incidents, channel=msg.channel, nomore="No more incidents", count=" (%d more incidents)")
else: else:
raise IRCException("Mauvais usage, merci de spécifier un type de transport et un type d'alerte (alerte, manif, travaux), ou de consulter l'aide du module.") raise IMException("Mauvais usage, merci de spécifier un type de transport et un type d'alerte (alerte, manif, travaux), ou de consulter l'aide du module.")

View file

@ -4,7 +4,7 @@
import re import re
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -26,7 +26,7 @@ def cmd_subreddit(msg):
if msg.channel in LAST_SUBS and len(LAST_SUBS[msg.channel]) > 0: if msg.channel in LAST_SUBS and len(LAST_SUBS[msg.channel]) > 0:
subs = [LAST_SUBS[msg.channel].pop()] subs = [LAST_SUBS[msg.channel].pop()]
else: else:
raise IRCException("Which subreddit? Need inspiration? " raise IMException("Which subreddit? Need inspiration? "
"type !horny or !bored") "type !horny or !bored")
else: else:
subs = msg.args subs = msg.args
@ -44,7 +44,7 @@ def cmd_subreddit(msg):
(where, sub.group(2))) (where, sub.group(2)))
if sbr is None: if sbr is None:
raise IRCException("subreddit not found") raise IMException("subreddit not found")
if "title" in sbr["data"]: if "title" in sbr["data"]:
res = Response(channel=msg.channel, res = Response(channel=msg.channel,

View file

@ -6,7 +6,7 @@ import random
import shlex import shlex
from nemubot import context from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.message import Command from nemubot.message import Command
@ -18,7 +18,7 @@ from more import Response
@hook("cmd_hook", "choice") @hook("cmd_hook", "choice")
def cmd_choice(msg): def cmd_choice(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("indicate some terms to pick!") raise IMException("indicate some terms to pick!")
return Response(random.choice(msg.args), return Response(random.choice(msg.args),
channel=msg.channel, channel=msg.channel,
@ -28,7 +28,7 @@ def cmd_choice(msg):
@hook("cmd_hook", "choicecmd") @hook("cmd_hook", "choicecmd")
def cmd_choicecmd(msg): def cmd_choicecmd(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("indicate some command to pick!") raise IMException("indicate some command to pick!")
choice = shlex.split(random.choice(msg.args)) choice = shlex.split(random.choice(msg.args))

View file

@ -6,7 +6,7 @@ import urllib.parse
import urllib.request import urllib.request
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -22,7 +22,7 @@ def help_full():
@hook("cmd_hook", "tcode") @hook("cmd_hook", "tcode")
def cmd_tcode(msg): def cmd_tcode(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("indicate a transaction code or " raise IMException("indicate a transaction code or "
"a keyword to search!") "a keyword to search!")
url = ("http://www.tcodesearch.com/tcodes/search?q=%s" % url = ("http://www.tcodesearch.com/tcodes/search?q=%s" %

View file

@ -10,7 +10,7 @@ import urllib.request
import urllib.parse import urllib.parse
from nemubot import context from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools.xmlparser.node import ModuleState from nemubot.tools.xmlparser.node import ModuleState
@ -50,15 +50,15 @@ def send_sms(frm, api_usr, api_key, content):
@hook("cmd_hook", "sms") @hook("cmd_hook", "sms")
def cmd_sms(msg): def cmd_sms(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("À qui veux-tu envoyer ce SMS ?") raise IMException("À qui veux-tu envoyer ce SMS ?")
# Check dests # Check dests
cur_epoch = time.mktime(time.localtime()); cur_epoch = time.mktime(time.localtime());
for u in msg.args[0].split(","): for u in msg.args[0].split(","):
if u not in context.data.index: if u not in context.data.index:
raise IRCException("Désolé, je sais pas comment envoyer de SMS à %s." % u) raise IMException("Désolé, je sais pas comment envoyer de SMS à %s." % u)
elif cur_epoch - float(context.data.index[u]["lastuse"]) < 42: elif cur_epoch - float(context.data.index[u]["lastuse"]) < 42:
raise IRCException("Un peu de calme, %s a déjà reçu un SMS il n'y a pas si longtemps." % u) raise IMException("Un peu de calme, %s a déjà reçu un SMS il n'y a pas si longtemps." % u)
# Go! # Go!
fails = list() fails = list()

View file

@ -6,7 +6,7 @@ import re
from urllib.parse import quote from urllib.parse import quote
from nemubot import context from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools.xmlparser.node import ModuleState from nemubot.tools.xmlparser.node import ModuleState
@ -26,7 +26,7 @@ def load(context):
@hook("cmd_hook", "spell") @hook("cmd_hook", "spell")
def cmd_spell(msg): def cmd_spell(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("indique une orthographe approximative du mot dont tu veux vérifier l'orthographe.") raise IMException("indique une orthographe approximative du mot dont tu veux vérifier l'orthographe.")
lang = "fr" lang = "fr"
strRes = list() strRes = list()
@ -66,7 +66,7 @@ def cmd_score(msg):
res = list() res = list()
unknown = list() unknown = list()
if not len(msg.args): if not len(msg.args):
raise IRCException("De qui veux-tu voir les scores ?") raise IMException("De qui veux-tu voir les scores ?")
for cmd in msg.args: for cmd in msg.args:
if cmd in context.data.index: if cmd in context.data.index:
res.append(Response("%s: %s" % (cmd, " ; ".join(["%s: %d" % (a, context.data.index[cmd].getInt(a)) for a in context.data.index[cmd].attributes.keys() if a != "name"])), channel=msg.channel)) res.append(Response("%s: %s" % (cmd, " ; ".join(["%s: %d" % (a, context.data.index[cmd].getInt(a)) for a in context.data.index[cmd].attributes.keys() if a != "name"])), channel=msg.channel))

View file

@ -4,7 +4,7 @@ from bs4 import BeautifulSoup
import re import re
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.tools.web import getURLContent from nemubot.tools.web import getURLContent
from more import Response from more import Response
@ -160,7 +160,7 @@ TRACKING_HANDLERS = {
"or all of them."}) "or all of them."})
def get_tracking_info(msg): def get_tracking_info(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Renseignez un identifiant d'envoi.") raise IMException("Renseignez un identifiant d'envoi.")
res = Response(channel=msg.channel, count=" (%d suivis supplémentaires)") res = Response(channel=msg.channel, count=" (%d suivis supplémentaires)")
@ -170,7 +170,7 @@ def get_tracking_info(msg):
msg.kwargs['tracker']: TRACKING_HANDLERS[msg.kwargs['tracker']] msg.kwargs['tracker']: TRACKING_HANDLERS[msg.kwargs['tracker']]
} }
else: else:
raise IRCException("No tracker named \x02{tracker}\x0F, please use" raise IMException("No tracker named \x02{tracker}\x0F, please use"
" one of the following: \x02{trackers}\x0F" " one of the following: \x02{trackers}\x0F"
.format(tracker=msg.kwargs['tracker'], .format(tracker=msg.kwargs['tracker'],
trackers=', ' trackers=', '

View file

@ -5,7 +5,7 @@
import re import re
from urllib.parse import quote from urllib.parse import quote
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -76,7 +76,7 @@ lang_binding = { 'fr': get_french_synos }
@hook("cmd_hook", "antonymes", data="antonymes") @hook("cmd_hook", "antonymes", data="antonymes")
def go(msg, what): def go(msg, what):
if not len(msg.args): if not len(msg.args):
raise IRCException("de quel mot veux-tu connaître la liste des synonymes ?") raise IMException("de quel mot veux-tu connaître la liste des synonymes ?")
# Detect lang # Detect lang
if msg.args[0] in lang_binding: if msg.args[0] in lang_binding:
@ -86,7 +86,7 @@ def go(msg, what):
func = lang_binding["fr"] func = lang_binding["fr"]
word = ' '.join(msg.args) word = ' '.join(msg.args)
# TODO: depreciate usage without lang # TODO: depreciate usage without lang
#raise IRCException("language %s is not handled yet." % msg.args[0]) #raise IMException("language %s is not handled yet." % msg.args[0])
try: try:
best, synos, anton = func(word) best, synos, anton = func(word)
@ -100,7 +100,7 @@ def go(msg, what):
if len(synos) > 0: res.append_message(synos) if len(synos) > 0: res.append_message(synos)
return res return res
else: else:
raise IRCException("Aucun synonyme de %s n'a été trouvé" % word) raise IMException("Aucun synonyme de %s n'a été trouvé" % word)
elif what == "antonymes": elif what == "antonymes":
if len(anton) > 0: if len(anton) > 0:
@ -108,7 +108,7 @@ def go(msg, what):
title="Antonymes de %s" % word) title="Antonymes de %s" % word)
return res return res
else: else:
raise IRCException("Aucun antonyme de %s n'a été trouvé" % word) raise IMException("Aucun antonyme de %s n'a été trouvé" % word)
else: else:
raise IRCException("WHAT?!") raise IMException("WHAT?!")

View file

@ -1,7 +1,7 @@
from datetime import datetime from datetime import datetime
import urllib import urllib
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import human from nemubot.tools import human
from nemubot.tools.web import getJSON from nemubot.tools.web import getJSON
@ -25,7 +25,7 @@ def load(context):
@hook("cmd_hook", "tpb") @hook("cmd_hook", "tpb")
def cmd_tpb(msg): def cmd_tpb(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("indicate an item to search!") raise IMException("indicate an item to search!")
torrents = getJSON(URL_TPBAPI + urllib.parse.quote(" ".join(msg.args))) torrents = getJSON(URL_TPBAPI + urllib.parse.quote(" ".join(msg.args)))

View file

@ -5,7 +5,7 @@
import re import re
from urllib.parse import quote from urllib.parse import quote
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -36,11 +36,11 @@ def help_full():
@hook("cmd_hook", "translate") @hook("cmd_hook", "translate")
def cmd_translate(msg): def cmd_translate(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("which word would you translate?") raise IMException("which word would you translate?")
if len(msg.args) > 2 and msg.args[0] in LANG and msg.args[1] in LANG: if len(msg.args) > 2 and msg.args[0] in LANG and msg.args[1] in LANG:
if msg.args[0] != "en" and msg.args[1] != "en": if msg.args[0] != "en" and msg.args[1] != "en":
raise IRCException("sorry, I can only translate to or from english") raise IMException("sorry, I can only translate to or from english")
langFrom = msg.args[0] langFrom = msg.args[0]
langTo = msg.args[1] langTo = msg.args[1]
term = ' '.join(msg.args[2:]) term = ' '.join(msg.args[2:])
@ -59,7 +59,7 @@ def cmd_translate(msg):
wres = web.getJSON(URL % (langFrom, langTo, quote(term))) wres = web.getJSON(URL % (langFrom, langTo, quote(term)))
if "Error" in wres: if "Error" in wres:
raise IRCException(wres["Note"]) raise IMException(wres["Note"])
else: else:
res = Response(channel=msg.channel, res = Response(channel=msg.channel,

View file

@ -4,7 +4,7 @@
from urllib.parse import quote from urllib.parse import quote
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -23,7 +23,7 @@ def search(terms):
@hook("cmd_hook", "urbandictionnary") @hook("cmd_hook", "urbandictionnary")
def udsearch(msg): def udsearch(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Indicate a term to search") raise IMException("Indicate a term to search")
s = search(msg.args) s = search(msg.args)

View file

@ -5,7 +5,7 @@
import re import re
from nemubot import context from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -61,7 +61,7 @@ def print_station_status(msg, station):
return Response("À la station %s : %d vélib et %d points d'attache" return Response("À la station %s : %d vélib et %d points d'attache"
" disponibles." % (station, available, free), " disponibles." % (station, available, free),
channel=msg.channel) channel=msg.channel)
raise IRCException("station %s inconnue." % station) raise IMException("station %s inconnue." % station)
# MODULE INTERFACE #################################################### # MODULE INTERFACE ####################################################
@ -73,9 +73,9 @@ def print_station_status(msg, station):
}) })
def ask_stations(msg): def ask_stations(msg):
if len(msg.args) > 4: if len(msg.args) > 4:
raise IRCException("demande-moi moins de stations à la fois.") raise IMException("demande-moi moins de stations à la fois.")
elif not len(msg.args): elif not len(msg.args):
raise IRCException("pour quelle station ?") raise IMException("pour quelle station ?")
for station in msg.args: for station in msg.args:
if re.match("^[0-9]{4,5}$", station): if re.match("^[0-9]{4,5}$", station):
@ -84,4 +84,4 @@ def ask_stations(msg):
return print_station_status(msg, return print_station_status(msg,
context.data.index[station]["number"]) context.data.index[station]["number"])
else: else:
raise IRCException("numéro de station invalide.") raise IMException("numéro de station invalide.")

View file

@ -6,7 +6,7 @@ import datetime
import re import re
from nemubot import context from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
from nemubot.tools.xmlparser.node import ModuleState from nemubot.tools.xmlparser.node import ModuleState
@ -120,10 +120,10 @@ def treat_coord(msg):
coords.append(geocode[0]["latLng"]["lng"]) coords.append(geocode[0]["latLng"]["lng"])
return mapquest.where(geocode[0]), coords, specific return mapquest.where(geocode[0]), coords, specific
raise IRCException("Je ne sais pas où se trouve %s." % city) raise IMException("Je ne sais pas où se trouve %s." % city)
else: else:
raise IRCException("indique-moi un nom de ville ou des coordonnées.") raise IMException("indique-moi un nom de ville ou des coordonnées.")
def get_json_weather(coords): def get_json_weather(coords):
@ -131,7 +131,7 @@ def get_json_weather(coords):
# First read flags # First read flags
if wth is None or "darksky-unavailable" in wth["flags"]: if wth is None or "darksky-unavailable" in wth["flags"]:
raise IRCException("The given location is supported but a temporary error (such as a radar station being down for maintenace) made data unavailable.") raise IMException("The given location is supported but a temporary error (such as a radar station being down for maintenace) made data unavailable.")
return wth return wth
@ -139,11 +139,11 @@ def get_json_weather(coords):
@hook("cmd_hook", "coordinates") @hook("cmd_hook", "coordinates")
def cmd_coordinates(msg): def cmd_coordinates(msg):
if len(msg.args) < 1: if len(msg.args) < 1:
raise IRCException("indique-moi un nom de ville.") raise IMException("indique-moi un nom de ville.")
j = msg.args[0].lower() j = msg.args[0].lower()
if j not in context.data.index: if j not in context.data.index:
raise IRCException("%s n'est pas une ville connue" % msg.args[0]) raise IMException("%s n'est pas une ville connue" % msg.args[0])
coords = context.data.index[j] coords = context.data.index[j]
return Response("Les coordonnées de %s sont %s,%s" % (msg.args[0], coords["lat"], coords["long"]), channel=msg.channel) return Response("Les coordonnées de %s sont %s,%s" % (msg.args[0], coords["lat"], coords["long"]), channel=msg.channel)

View file

@ -3,7 +3,7 @@
import re import re
from nemubot import context from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools.xmlparser.node import ModuleState from nemubot.tools.xmlparser.node import ModuleState
@ -75,7 +75,7 @@ def found_login(login):
def cmd_whois(msg): def cmd_whois(msg):
if len(msg.args) < 1: if len(msg.args) < 1:
raise IRCException("Provide a name") raise IMException("Provide a name")
res = Response(channel=msg.channel, count=" (%d more logins)") res = Response(channel=msg.channel, count=" (%d more logins)")
for srch in msg.args: for srch in msg.args:
@ -90,7 +90,7 @@ def cmd_whois(msg):
@hook("cmd_hook", "nicks") @hook("cmd_hook", "nicks")
def cmd_nicks(msg): def cmd_nicks(msg):
if len(msg.args) < 1: if len(msg.args) < 1:
raise IRCException("Provide a login") raise IMException("Provide a login")
nick = found_login(msg.args[0]) nick = found_login(msg.args[0])
if nick is None: if nick is None:
nick = msg.args[0] nick = msg.args[0]

View file

@ -6,7 +6,7 @@ from urllib.parse import quote
import re import re
from nemubot import context from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools import web from nemubot.tools import web
@ -100,12 +100,12 @@ class WFAResults:
}) })
def calculate(msg): def calculate(msg):
if not len(msg.args): if not len(msg.args):
raise IRCException("Indicate a calcul to compute") raise IMException("Indicate a calcul to compute")
s = WFAResults(' '.join(msg.args)) s = WFAResults(' '.join(msg.args))
if not s.success: if not s.success:
raise IRCException(s.error) raise IMException(s.error)
res = Response(channel=msg.channel, nomore="No more results") res = Response(channel=msg.channel, nomore="No more results")

View file

@ -9,7 +9,7 @@ from urllib.parse import quote
from urllib.request import urlopen from urllib.request import urlopen
from nemubot import context from nemubot import context
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools.xmlparser.node import ModuleState from nemubot.tools.xmlparser.node import ModuleState
@ -36,7 +36,7 @@ def start_watch(msg):
w["start"] = datetime.now(timezone.utc) w["start"] = datetime.now(timezone.utc)
context.data.addChild(w) context.data.addChild(w)
context.save() context.save()
raise IRCException("This channel is now watching world cup events!") raise IMException("This channel is now watching world cup events!")
@hook("cmd_hook", "watch_worldcup") @hook("cmd_hook", "watch_worldcup")
def cmd_watch(msg): def cmd_watch(msg):
@ -52,18 +52,18 @@ def cmd_watch(msg):
if msg.args[0] == "stop" and node is not None: if msg.args[0] == "stop" and node is not None:
context.data.delChild(node) context.data.delChild(node)
context.save() context.save()
raise IRCException("This channel will not anymore receives world cup events.") raise IMException("This channel will not anymore receives world cup events.")
elif msg.args[0] == "start" and node is None: elif msg.args[0] == "start" and node is None:
start_watch(msg) start_watch(msg)
else: else:
raise IRCException("Use only start or stop as first argument") raise IMException("Use only start or stop as first argument")
else: else:
if node is None: if node is None:
start_watch(msg) start_watch(msg)
else: else:
context.data.delChild(node) context.data.delChild(node)
context.save() context.save()
raise IRCException("This channel will not anymore receives world cup events.") raise IMException("This channel will not anymore receives world cup events.")
def current_match_new_action(match_str, osef): def current_match_new_action(match_str, osef):
context.add_event(ModuleEvent(func=lambda url: urlopen(url).read().decode(), func_data=API_URL % "matches/current?by_date=DESC", call=current_match_new_action, interval=30)) context.add_event(ModuleEvent(func=lambda url: urlopen(url).read().decode(), func_data=API_URL % "matches/current?by_date=DESC", call=current_match_new_action, interval=30))
@ -170,7 +170,7 @@ def get_matches(url):
try: try:
raw = urlopen(url) raw = urlopen(url)
except: except:
raise IRCException("requête invalide") raise IMException("requête invalide")
matches = json.loads(raw.read().decode()) matches = json.loads(raw.read().decode())
for match in matches: for match in matches:
@ -194,7 +194,7 @@ def cmd_worldcup(msg):
elif is_int(msg.args[0]): elif is_int(msg.args[0]):
url = int(msg.arg[0]) url = int(msg.arg[0])
else: else:
raise IRCException("unrecognized request; choose between 'today', 'tomorrow', a FIFA country code or a match identifier") raise IMException("unrecognized request; choose between 'today', 'tomorrow', a FIFA country code or a match identifier")
if url is None: if url is None:
url = "matches/current?by_date=ASC" url = "matches/current?by_date=ASC"

View file

@ -1,7 +1,7 @@
from urllib.parse import urlparse from urllib.parse import urlparse
import re, json, subprocess import re, json, subprocess
from nemubot.exception import IRCException from nemubot.exception import IMException
from nemubot.hooks import hook from nemubot.hooks import hook
from nemubot.tools.web import _getNormalizedURL, getURLContent from nemubot.tools.web import _getNormalizedURL, getURLContent
from more import Response from more import Response
@ -19,7 +19,7 @@ def _get_ytdl(links):
res = [] res = []
with subprocess.Popen(cmd, stdout=subprocess.PIPE) as p: with subprocess.Popen(cmd, stdout=subprocess.PIPE) as p:
if p.wait() > 0: if p.wait() > 0:
raise IRCException("Error while retrieving video information.") raise IMException("Error while retrieving video information.")
for line in p.stdout.read().split(b"\n"): for line in p.stdout.read().split(b"\n"):
localres = '' localres = ''
if not line: if not line:
@ -46,7 +46,7 @@ def _get_ytdl(links):
localres += ' | ' + info['webpage_url'] localres += ' | ' + info['webpage_url']
res.append(localres) res.append(localres)
if not res: if not res:
raise IRCException("No video information to retrieve about this. Sorry!") raise IMException("No video information to retrieve about this. Sorry!")
return res return res
LAST_URLS = dict() LAST_URLS = dict()
@ -61,7 +61,7 @@ def get_info_yt(msg):
if msg.channel in LAST_URLS and len(LAST_URLS[msg.channel]) > 0: if msg.channel in LAST_URLS and len(LAST_URLS[msg.channel]) > 0:
links.append(LAST_URLS[msg.channel].pop()) links.append(LAST_URLS[msg.channel].pop())
else: else:
raise IRCException("I don't have any youtube URL for now, please provide me one to get information!") raise IMException("I don't have any youtube URL for now, please provide me one to get information!")
else: else:
for url in msg.args: for url in msg.args:
links.append(url) links.append(url)

View file

@ -1,5 +1,3 @@
# coding=utf-8
# Nemubot is a smart and modulable IM bot. # Nemubot is a smart and modulable IM bot.
# Copyright (C) 2012-2015 Mercier Pierre-Olivier # Copyright (C) 2012-2015 Mercier Pierre-Olivier
# #
@ -16,20 +14,21 @@
# You should have received a copy of the GNU Affero General Public License # You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
class IRCException(Exception): class IMException(Exception):
def __init__(self, message, personnal=True): def __init__(self, message, personnal=True):
super(IRCException, self).__init__(message) super(IMException, self).__init__(message)
self.message = message
self.personnal = personnal self.personnal = personnal
def fill_response(self, msg): def fill_response(self, msg):
if self.personnal: if self.personnal:
from nemubot.message import DirectAsk from nemubot.message import DirectAsk
return DirectAsk(msg.frm, self.message, return DirectAsk(msg.frm, *self.args,
server=msg.server, to=msg.to_response) server=msg.server, to=msg.to_response)
else: else:
from nemubot.message import Text from nemubot.message import Text
return Text(self.message, return Text(*self.args,
server=msg.server, to=msg.to_response) server=msg.server, to=msg.to_response)

View file

@ -57,12 +57,12 @@ class Abstract:
def run(self, data1, *args): def run(self, data1, *args):
"""Run the hook""" """Run the hook"""
from nemubot.exception import IRCException from nemubot.exception import IMException
self.times -= 1 self.times -= 1
try: try:
ret = call_game(self.call, data1, self.data, *args) ret = call_game(self.call, data1, self.data, *args)
except IRCException as e: except IMException as e:
ret = e.fill_response(data1) ret = e.fill_response(data1)
finally: finally:
if self.times == 0: if self.times == 0:

View file

@ -110,8 +110,8 @@ class Feed:
elif self.feed.tagName == "feed": elif self.feed.tagName == "feed":
self._parse_atom_feed() self._parse_atom_feed()
else: else:
from nemubot.exception import IRCException from nemubot.exception import IMException
raise IRCException("This is not a valid Atom or RSS feed") raise IMException("This is not a valid Atom or RSS feed")
def _parse_atom_feed(self): def _parse_atom_feed(self):

View file

@ -16,7 +16,7 @@
from urllib.parse import urlparse, urlsplit, urlunsplit from urllib.parse import urlparse, urlsplit, urlunsplit
from nemubot.exception import IRCException from nemubot.exception import IMException
def isURL(url): def isURL(url):
@ -100,7 +100,7 @@ def getURLContent(url, body=None, timeout=7, header=None):
elif o.scheme is None or o.scheme == "": elif o.scheme is None or o.scheme == "":
conn = http.client.HTTPConnection(**kwargs) conn = http.client.HTTPConnection(**kwargs)
else: else:
raise IRCException("Invalid URL") raise IMException("Invalid URL")
from nemubot import __version__ from nemubot import __version__
if header is None: if header is None:
@ -121,7 +121,7 @@ def getURLContent(url, body=None, timeout=7, header=None):
body, body,
header) header)
except OSError as e: except OSError as e:
raise IRCException(e.strerror) raise IMException(e.strerror)
try: try:
res = conn.getresponse() res = conn.getresponse()
@ -129,7 +129,7 @@ def getURLContent(url, body=None, timeout=7, header=None):
cntype = res.getheader("Content-Type") cntype = res.getheader("Content-Type")
if size > 524288 or (cntype is not None and cntype[:4] != "text" and cntype[:4] != "appl"): if size > 524288 or (cntype is not None and cntype[:4] != "text" and cntype[:4] != "appl"):
raise IRCException("Content too large to be retrieved") raise IMException("Content too large to be retrieved")
data = res.read(size) data = res.read(size)
@ -147,7 +147,7 @@ def getURLContent(url, body=None, timeout=7, header=None):
else: else:
charset = cha[0] charset = cha[0]
except http.client.BadStatusLine: except http.client.BadStatusLine:
raise IRCException("Invalid HTTP response") raise IMException("Invalid HTTP response")
finally: finally:
conn.close() conn.close()
@ -158,7 +158,7 @@ def getURLContent(url, body=None, timeout=7, header=None):
res.getheader("Location") != url): res.getheader("Location") != url):
return getURLContent(res.getheader("Location"), timeout=timeout) return getURLContent(res.getheader("Location"), timeout=timeout)
else: else:
raise IRCException("A HTTP error occurs: %d - %s" % raise IMException("A HTTP error occurs: %d - %s" %
(res.status, http.client.responses[res.status])) (res.status, http.client.responses[res.status]))

View file

@ -63,6 +63,7 @@ setup(
'nemubot', 'nemubot',
'nemubot.datastore', 'nemubot.datastore',
'nemubot.event', 'nemubot.event',
'nemubot.exception',
'nemubot.hooks', 'nemubot.hooks',
'nemubot.message', 'nemubot.message',
'nemubot.message.printer', 'nemubot.message.printer',