Compare commits
113 commits
wip/smart_
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 27bd0c50c1 | |||
| 9d7c278d1a | |||
| 310f933091 | |||
| 26282cb81d | |||
| de2c37a54a | |||
| 622159f6b5 | |||
| 32ebe42f41 | |||
| ea0ec42a4b | |||
| 23f043673f | |||
| ac432fabcc | |||
| 38b5b1eabd | |||
| 84fef789b5 | |||
| 45a27b477d | |||
| a8472ecc29 | |||
| 861ca0afdd | |||
| 9f83e5b178 | |||
| 68c61f40d3 | |||
| 60a9ec92b7 | |||
| 8dd6b9d471 | |||
| 13c643fc19 | |||
| 5ec2f2997b | |||
| faa5759645 | |||
| 37a230e70e | |||
| 904ad72316 | |||
| f17f8b9dfa | |||
| d56c2396c0 | |||
| b369683914 | |||
| aee2da4122 | |||
| 1f2d297ea1 | |||
|
|
b72871a8c2 | ||
| 644a641b13 | |||
| 4499677d55 | |||
| 87b5ce842d | |||
| 144551a232 | |||
| 7854e8628f | |||
| 85c418bd06 | |||
| 20c19a72bc | |||
| 9417e2ba93 | |||
| 517bf21d25 | |||
| fa0f2e93ef | |||
| b349d22370 | |||
| 8605932702 | |||
| 10b8ce8940 | |||
| 445a66ea90 | |||
| 46541cb35e | |||
| 8224d11207 | |||
| 15064204d8 | |||
| 67dee382a6 | |||
| f1da640a5b | |||
| 2fd20d9002 | |||
| 31abcc97cf | |||
| 53fe00ed58 | |||
| 4a636b2b11 | |||
| 72bc8d3839 | |||
| 5578e8b86e | |||
| 3b99099b52 | |||
| cd6750154c | |||
| b8741bb1f7 | |||
| 125ae6ad0b | |||
| 015fb47d90 | |||
| 8a25ebb45b | |||
| 1887e481d2 | |||
| 342bb9acdc | |||
| 2af56e606a | |||
| 4275009dea | |||
| f520c67c89 | |||
| c3c7484792 | |||
| 4cd099e087 | |||
| d528746cb5 | |||
|
|
5cbad96492 | ||
| 226ee4e34e | |||
|
|
e0d7ef1314 | ||
|
|
99384ad6f7 | ||
|
|
ef4c119f1f | ||
|
|
a7f4ccc959 | ||
|
|
c23dc22ce2 | ||
| bb0e958118 | |||
| b15d18b3a5 | |||
| 5646850df1 | |||
| 30ec912162 | |||
| 28d4e507eb | |||
| 62cd92e1cb | |||
| 12ddf40ef4 | |||
| 7a4b27510c | |||
| 05d20ed6ee | |||
| f60de818f2 | |||
| 45fe5b2156 | |||
| e49312e63e | |||
| a11ccb2e39 | |||
| fde459c3ff | |||
| 694c54a6bc | |||
| 1dae3c713a | |||
| 89772ebce0 | |||
| aa81aa4e96 | |||
| 3c7ed176c0 | |||
| 6dda142188 | |||
| dcb44ca3f2 | |||
| 0a576410c7 | |||
| 128afb5914 | |||
| 39b7b1ae2f | |||
| 09462d0d90 | |||
| b8f4560780 | |||
| 281d81acc4 | |||
| 29817ba1c1 | |||
| b517cac4cf | |||
| f81349bbfd | |||
| ce012b7017 | |||
|
|
e3b6c3b85e | ||
| 39056cf358 | |||
| f16dedb320 | |||
| 171297b581 | |||
| 3267c3e2e1 | |||
| aad777058e |
99 changed files with 2711 additions and 1731 deletions
26
.drone.yml
Normal file
26
.drone.yml
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
---
|
||||||
|
kind: pipeline
|
||||||
|
type: docker
|
||||||
|
name: default-arm64
|
||||||
|
|
||||||
|
platform:
|
||||||
|
os: linux
|
||||||
|
arch: arm64
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: build
|
||||||
|
image: python:3.11-alpine
|
||||||
|
commands:
|
||||||
|
- pip install --no-cache-dir -r requirements.txt
|
||||||
|
- pip install .
|
||||||
|
|
||||||
|
- name: docker
|
||||||
|
image: plugins/docker
|
||||||
|
settings:
|
||||||
|
repo: nemunaire/nemubot
|
||||||
|
auto_tag: true
|
||||||
|
auto_tag_suffix: ${DRONE_STAGE_OS}-${DRONE_STAGE_ARCH}
|
||||||
|
username:
|
||||||
|
from_secret: docker_username
|
||||||
|
password:
|
||||||
|
from_secret: docker_password
|
||||||
|
|
@ -1,8 +1,9 @@
|
||||||
language: python
|
language: python
|
||||||
python:
|
python:
|
||||||
- 3.3
|
|
||||||
- 3.4
|
- 3.4
|
||||||
- 3.5
|
- 3.5
|
||||||
|
- 3.6
|
||||||
|
- 3.7
|
||||||
- nightly
|
- nightly
|
||||||
install:
|
install:
|
||||||
- pip install -r requirements.txt
|
- pip install -r requirements.txt
|
||||||
|
|
|
||||||
21
Dockerfile
Normal file
21
Dockerfile
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
FROM python:3.11-alpine
|
||||||
|
|
||||||
|
WORKDIR /usr/src/app
|
||||||
|
|
||||||
|
COPY requirements.txt /usr/src/app/
|
||||||
|
RUN apk add --no-cache bash build-base capstone-dev mandoc-doc man-db w3m youtube-dl aspell aspell-fr py3-matrix-nio && \
|
||||||
|
pip install --no-cache-dir --ignore-installed -r requirements.txt && \
|
||||||
|
pip install bs4 capstone dnspython openai && \
|
||||||
|
apk del build-base capstone-dev && \
|
||||||
|
ln -s /var/lib/nemubot/home /home/nemubot
|
||||||
|
|
||||||
|
VOLUME /var/lib/nemubot
|
||||||
|
|
||||||
|
COPY . /usr/src/app/
|
||||||
|
|
||||||
|
RUN ./setup.py install
|
||||||
|
|
||||||
|
WORKDIR /var/lib/nemubot
|
||||||
|
USER guest
|
||||||
|
ENTRYPOINT [ "python", "-m", "nemubot", "-d", "-P", "", "-M", "/usr/src/app/modules" ]
|
||||||
|
CMD [ "-D", "/var/lib/nemubot" ]
|
||||||
|
|
@ -9,10 +9,8 @@ Requirements
|
||||||
|
|
||||||
*nemubot* requires at least Python 3.3 to work.
|
*nemubot* requires at least Python 3.3 to work.
|
||||||
|
|
||||||
Connecting to SSL server requires [this patch](http://bugs.python.org/issue27629).
|
|
||||||
|
|
||||||
Some modules (like `cve`, `nextstop` or `laposte`) require the
|
Some modules (like `cve`, `nextstop` or `laposte`) require the
|
||||||
[BeautifulSoup module](http://www.crummy.com/software/BeautifulSoup/),
|
[BeautifulSoup module](https://www.crummy.com/software/BeautifulSoup/),
|
||||||
but the core and framework has no dependency.
|
but the core and framework has no dependency.
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ from nemubot.message import Command
|
||||||
from nemubot.tools.human import guess
|
from nemubot.tools.human import guess
|
||||||
from nemubot.tools.xmlparser.node import ModuleState
|
from nemubot.tools.xmlparser.node import ModuleState
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# LOADING #############################################################
|
# LOADING #############################################################
|
||||||
|
|
@ -185,7 +185,7 @@ def cmd_listvars(msg):
|
||||||
def cmd_set(msg):
|
def cmd_set(msg):
|
||||||
if len(msg.args) < 2:
|
if len(msg.args) < 2:
|
||||||
raise IMException("!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.frm)
|
||||||
return Response("Variable $%s successfully defined." % msg.args[0],
|
return Response("Variable $%s successfully defined." % msg.args[0],
|
||||||
channel=msg.channel)
|
channel=msg.channel)
|
||||||
|
|
||||||
|
|
@ -222,13 +222,13 @@ def cmd_alias(msg):
|
||||||
|
|
||||||
if alias.cmd in context.data.getNode("aliases").index:
|
if alias.cmd in context.data.getNode("aliases").index:
|
||||||
return Response("%s corresponds to %s" % (alias.cmd, context.data.getNode("aliases").index[alias.cmd]["origin"]),
|
return Response("%s corresponds to %s" % (alias.cmd, context.data.getNode("aliases").index[alias.cmd]["origin"]),
|
||||||
channel=msg.channel, nick=msg.nick)
|
channel=msg.channel, nick=msg.frm)
|
||||||
|
|
||||||
elif len(msg.args) > 1:
|
elif len(msg.args) > 1:
|
||||||
create_alias(alias.cmd,
|
create_alias(alias.cmd,
|
||||||
" ".join(msg.args[1:]),
|
" ".join(msg.args[1:]),
|
||||||
channel=msg.channel,
|
channel=msg.channel,
|
||||||
creator=msg.nick)
|
creator=msg.frm)
|
||||||
return Response("New alias %s successfully registered." % alias.cmd,
|
return Response("New alias %s successfully registered." % alias.cmd,
|
||||||
channel=msg.channel)
|
channel=msg.channel)
|
||||||
|
|
||||||
|
|
@ -272,7 +272,6 @@ def treat_alias(msg):
|
||||||
|
|
||||||
# Avoid infinite recursion
|
# Avoid infinite recursion
|
||||||
if not isinstance(rpl_msg, Command) or msg.cmd != rpl_msg.cmd:
|
if not isinstance(rpl_msg, Command) or msg.cmd != rpl_msg.cmd:
|
||||||
# Also return origin message, if it can be treated as well
|
return rpl_msg
|
||||||
return [msg, rpl_msg]
|
|
||||||
|
|
||||||
return msg
|
return msg
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ 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
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# LOADING #############################################################
|
# LOADING #############################################################
|
||||||
|
|
@ -27,7 +27,7 @@ def load(context):
|
||||||
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
|
||||||
msg.args[0].lower() == "me"):
|
msg.args[0].lower() == "me"):
|
||||||
name = msg.nick.lower()
|
name = msg.frm.lower()
|
||||||
else:
|
else:
|
||||||
name = msg.args[0].lower()
|
name = msg.args[0].lower()
|
||||||
|
|
||||||
|
|
@ -77,7 +77,7 @@ def cmd_anniv(msg):
|
||||||
else:
|
else:
|
||||||
return Response("désolé, je ne connais pas la date d'anniversaire"
|
return Response("désolé, je ne connais pas la date d'anniversaire"
|
||||||
" de %s. Quand est-il né ?" % name,
|
" de %s. Quand est-il né ?" % name,
|
||||||
msg.channel, msg.nick)
|
msg.channel, msg.frm)
|
||||||
|
|
||||||
|
|
||||||
@hook.command("age",
|
@hook.command("age",
|
||||||
|
|
@ -98,7 +98,7 @@ def cmd_age(msg):
|
||||||
msg.channel)
|
msg.channel)
|
||||||
else:
|
else:
|
||||||
return Response("désolé, je ne connais pas l'âge de %s."
|
return Response("désolé, je ne connais pas l'âge de %s."
|
||||||
" Quand est-il né ?" % name, msg.channel, msg.nick)
|
" Quand est-il né ?" % name, msg.channel, msg.frm)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -106,18 +106,18 @@ def cmd_age(msg):
|
||||||
|
|
||||||
@hook.ask()
|
@hook.ask()
|
||||||
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.message, re.I)
|
||||||
if res is not None:
|
if res is not None:
|
||||||
try:
|
try:
|
||||||
extDate = extractDate(msg.text)
|
extDate = extractDate(msg.message)
|
||||||
if extDate is None or extDate.year > datetime.now().year:
|
if extDate is None or extDate.year > datetime.now().year:
|
||||||
return Response("la date de naissance ne paraît pas valide...",
|
return Response("la date de naissance ne paraît pas valide...",
|
||||||
msg.channel,
|
msg.channel,
|
||||||
msg.nick)
|
msg.frm)
|
||||||
else:
|
else:
|
||||||
nick = res.group(1)
|
nick = res.group(1)
|
||||||
if nick == "my" or nick == "I" or nick == "i" or nick == "je" or nick == "mon" or nick == "ma":
|
if nick == "my" or nick == "I" or nick == "i" or nick == "je" or nick == "mon" or nick == "ma":
|
||||||
nick = msg.nick
|
nick = msg.frm
|
||||||
if nick.lower() in context.data.index:
|
if nick.lower() in context.data.index:
|
||||||
context.data.index[nick.lower()]["born"] = extDate
|
context.data.index[nick.lower()]["born"] = extDate
|
||||||
else:
|
else:
|
||||||
|
|
@ -129,6 +129,6 @@ def parseask(msg):
|
||||||
return Response("ok, c'est noté, %s est né le %s"
|
return Response("ok, c'est noté, %s est né le %s"
|
||||||
% (nick, extDate.strftime("%A %d %B %Y Ã %H:%M")),
|
% (nick, extDate.strftime("%A %d %B %Y Ã %H:%M")),
|
||||||
msg.channel,
|
msg.channel,
|
||||||
msg.nick)
|
msg.frm)
|
||||||
except:
|
except:
|
||||||
raise IMException("la date de naissance ne paraît pas valide.")
|
raise IMException("la date de naissance ne paraît pas valide.")
|
||||||
|
|
|
||||||
|
|
@ -4,12 +4,11 @@
|
||||||
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
from nemubot import context
|
|
||||||
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
|
from nemubot.tools.countdown import countdown_format
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# GLOBALS #############################################################
|
# GLOBALS #############################################################
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ 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 more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# LOADING #############################################################
|
# LOADING #############################################################
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ from nemubot.exception import IMException
|
||||||
from nemubot.hooks import hook
|
from nemubot.hooks import hook
|
||||||
from nemubot.message import Command, DirectAsk, Text
|
from nemubot.message import Command, DirectAsk, Text
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# MODULE CORE #########################################################
|
# MODULE CORE #########################################################
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ 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
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# GLOBALS #############################################################
|
# GLOBALS #############################################################
|
||||||
|
|
@ -36,7 +36,7 @@ for k, v in s:
|
||||||
# MODULE CORE #########################################################
|
# MODULE CORE #########################################################
|
||||||
|
|
||||||
def get_conjug(verb, stringTens):
|
def get_conjug(verb, stringTens):
|
||||||
url = ("http://leconjugueur.lefigaro.fr/conjugaison/verbe/%s.html" %
|
url = ("https://leconjugueur.lefigaro.fr/conjugaison/verbe/%s.html" %
|
||||||
quote(verb.encode("ISO-8859-1")))
|
quote(verb.encode("ISO-8859-1")))
|
||||||
page = web.getURLContent(url)
|
page = web.getURLContent(url)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ from bs4 import BeautifulSoup
|
||||||
|
|
||||||
from nemubot.hooks import hook
|
from nemubot.hooks import hook
|
||||||
from nemubot.tools.web import getURLContent, striphtml
|
from nemubot.tools.web import getURLContent, striphtml
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# GLOBALS #############################################################
|
# GLOBALS #############################################################
|
||||||
|
|
@ -25,10 +25,8 @@ def get_info_yt(msg):
|
||||||
|
|
||||||
for line in soup.body.find_all('tr'):
|
for line in soup.body.find_all('tr'):
|
||||||
n = line.find_all('td')
|
n = line.find_all('td')
|
||||||
if len(n) == 5:
|
if len(n) == 7:
|
||||||
try:
|
res.append_message("\x02%s:\x0F from %s type %s at %s. Weight: %s. %s%s" %
|
||||||
res.append_message("\x02%s:\x0F from %s type %s at %s. %s" %
|
tuple([striphtml(x.text).strip() for x in n]))
|
||||||
tuple([striphtml(x.text) for x in n]))
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
return res
|
return res
|
||||||
|
|
|
||||||
|
|
@ -5,41 +5,54 @@
|
||||||
from bs4 import BeautifulSoup
|
from bs4 import BeautifulSoup
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
from nemubot.exception import IMException
|
||||||
from nemubot.hooks import hook
|
from nemubot.hooks import hook
|
||||||
from nemubot.tools.web import getURLContent, striphtml
|
from nemubot.tools.web import getURLContent, striphtml
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
BASEURL_NIST = 'https://nvd.nist.gov/vuln/detail/'
|
BASEURL_NIST = 'https://nvd.nist.gov/vuln/detail/'
|
||||||
|
|
||||||
|
|
||||||
# MODULE CORE #########################################################
|
# MODULE CORE #########################################################
|
||||||
|
|
||||||
|
VULN_DATAS = {
|
||||||
|
"alert-title": "vuln-warning-status-name",
|
||||||
|
"alert-content": "vuln-warning-banner-content",
|
||||||
|
|
||||||
|
"description": "vuln-description",
|
||||||
|
"published": "vuln-published-on",
|
||||||
|
"last_modified": "vuln-last-modified-on",
|
||||||
|
|
||||||
|
"base_score": "vuln-cvssv3-base-score-link",
|
||||||
|
"severity": "vuln-cvssv3-base-score-severity",
|
||||||
|
"impact_score": "vuln-cvssv3-impact-score",
|
||||||
|
"exploitability_score": "vuln-cvssv3-exploitability-score",
|
||||||
|
|
||||||
|
"av": "vuln-cvssv3-av",
|
||||||
|
"ac": "vuln-cvssv3-ac",
|
||||||
|
"pr": "vuln-cvssv3-pr",
|
||||||
|
"ui": "vuln-cvssv3-ui",
|
||||||
|
"s": "vuln-cvssv3-s",
|
||||||
|
"c": "vuln-cvssv3-c",
|
||||||
|
"i": "vuln-cvssv3-i",
|
||||||
|
"a": "vuln-cvssv3-a",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def get_cve(cve_id):
|
def get_cve(cve_id):
|
||||||
search_url = BASEURL_NIST + quote(cve_id.upper())
|
search_url = BASEURL_NIST + quote(cve_id.upper())
|
||||||
|
|
||||||
soup = BeautifulSoup(getURLContent(search_url))
|
soup = BeautifulSoup(getURLContent(search_url))
|
||||||
|
|
||||||
return {
|
vuln = {}
|
||||||
"description": soup.body.find(attrs={"data-testid":"vuln-description"}).text.strip(),
|
|
||||||
"published": soup.body.find(attrs={"data-testid":"vuln-published-on"}).text.strip(),
|
|
||||||
"last_modified": soup.body.find(attrs={"data-testid":"vuln-last-modified-on"}).text.strip(),
|
|
||||||
"source": soup.body.find(attrs={"data-testid":"vuln-source"}).text.strip(),
|
|
||||||
|
|
||||||
"base_score": float(soup.body.find(attrs={"data-testid":"vuln-cvssv3-base-score-link"}).text.strip()),
|
for vd in VULN_DATAS:
|
||||||
"severity": soup.body.find(attrs={"data-testid":"vuln-cvssv3-base-score-severity"}).text.strip(),
|
r = soup.body.find(attrs={"data-testid": VULN_DATAS[vd]})
|
||||||
"impact_score": float(soup.body.find(attrs={"data-testid":"vuln-cvssv3-impact-score"}).text.strip()),
|
if r:
|
||||||
"exploitability_score": float(soup.body.find(attrs={"data-testid":"vuln-cvssv3-exploitability-score"}).text.strip()),
|
vuln[vd] = r.text.strip()
|
||||||
|
|
||||||
"av": soup.body.find(attrs={"data-testid":"vuln-cvssv3-av"}).text.strip(),
|
return vuln
|
||||||
"ac": soup.body.find(attrs={"data-testid":"vuln-cvssv3-ac"}).text.strip(),
|
|
||||||
"pr": soup.body.find(attrs={"data-testid":"vuln-cvssv3-pr"}).text.strip(),
|
|
||||||
"ui": soup.body.find(attrs={"data-testid":"vuln-cvssv3-ui"}).text.strip(),
|
|
||||||
"s": soup.body.find(attrs={"data-testid":"vuln-cvssv3-s"}).text.strip(),
|
|
||||||
"c": soup.body.find(attrs={"data-testid":"vuln-cvssv3-c"}).text.strip(),
|
|
||||||
"i": soup.body.find(attrs={"data-testid":"vuln-cvssv3-i"}).text.strip(),
|
|
||||||
"a": soup.body.find(attrs={"data-testid":"vuln-cvssv3-a"}).text.strip(),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def display_metrics(av, ac, pr, ui, s, c, i, a, **kwargs):
|
def display_metrics(av, ac, pr, ui, s, c, i, a, **kwargs):
|
||||||
|
|
@ -68,9 +81,19 @@ def get_cve_desc(msg):
|
||||||
cve_id = 'cve-' + cve_id
|
cve_id = 'cve-' + cve_id
|
||||||
|
|
||||||
cve = get_cve(cve_id)
|
cve = get_cve(cve_id)
|
||||||
metrics = display_metrics(**cve)
|
if not cve:
|
||||||
res.append_message("{cveid}: Base score: \x02{base_score} {severity}\x0F (impact: \x02{impact_score}\x0F, exploitability: \x02{exploitability_score}\x0F; {metrics}), from \x02{source}\x0F, last modified on \x02{last_modified}\x0F. {description}".format(cveid=cve_id, metrics=metrics, **cve))
|
raise IMException("CVE %s doesn't exists." % cve_id)
|
||||||
|
|
||||||
|
if "alert-title" in cve or "alert-content" in cve:
|
||||||
|
alert = "\x02%s:\x0F %s " % (cve["alert-title"] if "alert-title" in cve else "",
|
||||||
|
cve["alert-content"] if "alert-content" in cve else "")
|
||||||
|
else:
|
||||||
|
alert = ""
|
||||||
|
|
||||||
|
if "base_score" not in cve and "description" in cve:
|
||||||
|
res.append_message("{alert}Last modified on \x02{last_modified}\x0F. {description}".format(alert=alert, **cve), title=cve_id)
|
||||||
|
else:
|
||||||
|
metrics = display_metrics(**cve)
|
||||||
|
res.append_message("{alert}Base score: \x02{base_score} {severity}\x0F (impact: \x02{impact_score}\x0F, exploitability: \x02{exploitability_score}\x0F; {metrics}), last modified on \x02{last_modified}\x0F. {description}".format(alert=alert, metrics=metrics, **cve), title=cve_id)
|
||||||
|
|
||||||
return res
|
return res
|
||||||
|
|
||||||
print(get_cve("CVE-2017-11108"))
|
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ 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 more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
# MODULE CORE #########################################################
|
# MODULE CORE #########################################################
|
||||||
|
|
||||||
|
|
|
||||||
94
modules/dig.py
Normal file
94
modules/dig.py
Normal file
|
|
@ -0,0 +1,94 @@
|
||||||
|
"""DNS resolver"""
|
||||||
|
|
||||||
|
# PYTHON STUFFS #######################################################
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
|
import socket
|
||||||
|
|
||||||
|
import dns.exception
|
||||||
|
import dns.name
|
||||||
|
import dns.rdataclass
|
||||||
|
import dns.rdatatype
|
||||||
|
import dns.resolver
|
||||||
|
|
||||||
|
from nemubot.exception import IMException
|
||||||
|
from nemubot.hooks import hook
|
||||||
|
|
||||||
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
|
# MODULE INTERFACE ####################################################
|
||||||
|
|
||||||
|
@hook.command("dig",
|
||||||
|
help="Resolve domain name with a basic syntax similar to dig(1)")
|
||||||
|
def dig(msg):
|
||||||
|
lclass = "IN"
|
||||||
|
ltype = "A"
|
||||||
|
ledns = None
|
||||||
|
ltimeout = 6.0
|
||||||
|
ldomain = None
|
||||||
|
lnameservers = []
|
||||||
|
lsearchlist = []
|
||||||
|
loptions = []
|
||||||
|
for a in msg.args:
|
||||||
|
if a in dns.rdatatype._by_text:
|
||||||
|
ltype = a
|
||||||
|
elif a in dns.rdataclass._by_text:
|
||||||
|
lclass = a
|
||||||
|
elif a[0] == "@":
|
||||||
|
try:
|
||||||
|
lnameservers.append(str(ipaddress.ip_address(a[1:])))
|
||||||
|
except ValueError:
|
||||||
|
for r in socket.getaddrinfo(a[1:], 53, proto=socket.IPPROTO_UDP):
|
||||||
|
lnameservers.append(r[4][0])
|
||||||
|
|
||||||
|
elif a[0:8] == "+domain=":
|
||||||
|
lsearchlist.append(dns.name.from_unicode(a[8:]))
|
||||||
|
elif a[0:6] == "+edns=":
|
||||||
|
ledns = int(a[6:])
|
||||||
|
elif a[0:6] == "+time=":
|
||||||
|
ltimeout = float(a[6:])
|
||||||
|
elif a[0] == "+":
|
||||||
|
loptions.append(a[1:])
|
||||||
|
else:
|
||||||
|
ldomain = a
|
||||||
|
|
||||||
|
if not ldomain:
|
||||||
|
raise IMException("indicate a domain to resolve")
|
||||||
|
|
||||||
|
resolv = dns.resolver.Resolver()
|
||||||
|
if ledns:
|
||||||
|
resolv.edns = ledns
|
||||||
|
resolv.lifetime = ltimeout
|
||||||
|
resolv.timeout = ltimeout
|
||||||
|
resolv.flags = (
|
||||||
|
dns.flags.QR | dns.flags.RA |
|
||||||
|
dns.flags.AA if "aaonly" in loptions or "aaflag" in loptions else 0 |
|
||||||
|
dns.flags.AD if "adflag" in loptions else 0 |
|
||||||
|
dns.flags.CD if "cdflag" in loptions else 0 |
|
||||||
|
dns.flags.RD if "norecurse" not in loptions else 0
|
||||||
|
)
|
||||||
|
if lsearchlist:
|
||||||
|
resolv.search = lsearchlist
|
||||||
|
else:
|
||||||
|
resolv.search = [dns.name.from_text(".")]
|
||||||
|
|
||||||
|
if lnameservers:
|
||||||
|
resolv.nameservers = lnameservers
|
||||||
|
|
||||||
|
try:
|
||||||
|
answers = resolv.query(ldomain, ltype, lclass, tcp="tcp" in loptions)
|
||||||
|
except dns.exception.DNSException as e:
|
||||||
|
raise IMException(str(e))
|
||||||
|
|
||||||
|
res = Response(channel=msg.channel, count=" (%s others entries)")
|
||||||
|
for rdata in answers:
|
||||||
|
res.append_message("%s %s %s %s %s" % (
|
||||||
|
answers.qname.to_text(),
|
||||||
|
answers.ttl if not "nottlid" in loptions else "",
|
||||||
|
dns.rdataclass.to_text(answers.rdclass) if not "nocl" in loptions else "",
|
||||||
|
dns.rdatatype.to_text(answers.rdtype),
|
||||||
|
rdata.to_text())
|
||||||
|
)
|
||||||
|
|
||||||
|
return res
|
||||||
|
|
@ -7,7 +7,7 @@ import capstone
|
||||||
from nemubot.exception import IMException
|
from nemubot.exception import IMException
|
||||||
from nemubot.hooks import hook
|
from nemubot.hooks import hook
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# MODULE CORE #########################################################
|
# MODULE CORE #########################################################
|
||||||
|
|
@ -54,22 +54,26 @@ def cmd_disas(msg):
|
||||||
raise IMException("please give me some code")
|
raise IMException("please give me some code")
|
||||||
|
|
||||||
# Determine the architecture
|
# Determine the architecture
|
||||||
if "architecture" in msg.kwargs:
|
if "arch" in msg.kwargs:
|
||||||
if msg.kwargs["architecture"] not in ARCHITECTURES:
|
if msg.kwargs["arch"] not in ARCHITECTURES:
|
||||||
raise IMException("unknown architectures '%s'" % msg.kwargs["architecture"])
|
raise IMException("unknown architectures '%s'" % msg.kwargs["arch"])
|
||||||
architecture = ARCHITECTURES[msg.kwargs["architecture"]]
|
architecture = ARCHITECTURES[msg.kwargs["arch"]]
|
||||||
else:
|
else:
|
||||||
architecture = capstone.CS_ARCH_X86
|
architecture = capstone.CS_ARCH_X86
|
||||||
|
|
||||||
# Determine hardware modes
|
# Determine hardware modes
|
||||||
|
modes = 0
|
||||||
if "modes" in msg.kwargs:
|
if "modes" in msg.kwargs:
|
||||||
modes = 0
|
|
||||||
for mode in msg.kwargs["modes"].split(','):
|
for mode in msg.kwargs["modes"].split(','):
|
||||||
if mode not in MODES:
|
if mode not in MODES:
|
||||||
raise IMException("unknown mode '%s'" % mode)
|
raise IMException("unknown mode '%s'" % mode)
|
||||||
modes += MODES[mode]
|
modes += MODES[mode]
|
||||||
else:
|
elif architecture == capstone.CS_ARCH_X86 or architecture == capstone.CS_ARCH_PPC:
|
||||||
modes = capstone.CS_MODE_32
|
modes = capstone.CS_MODE_32
|
||||||
|
elif architecture == capstone.CS_ARCH_ARM or architecture == capstone.CS_ARCH_ARM64:
|
||||||
|
modes = capstone.CS_MODE_ARM
|
||||||
|
elif architecture == capstone.CS_ARCH_MIPS:
|
||||||
|
modes = capstone.CS_MODE_MIPS32
|
||||||
|
|
||||||
# Get the code
|
# Get the code
|
||||||
code = bytearray.fromhex(''.join([a.replace("0x", "") for a in msg.args]))
|
code = bytearray.fromhex(''.join([a.replace("0x", "") for a in msg.args]))
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
"""Create countdowns and reminders"""
|
"""Create countdowns and reminders"""
|
||||||
|
|
||||||
import re
|
import calendar
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from functools import partial
|
||||||
|
import re
|
||||||
|
|
||||||
from nemubot import context
|
from nemubot import context
|
||||||
from nemubot.exception import IMException
|
from nemubot.exception import IMException
|
||||||
|
|
@ -10,31 +12,84 @@ from nemubot.hooks import hook
|
||||||
from nemubot.message import Command
|
from nemubot.message import Command
|
||||||
from nemubot.tools.countdown import countdown_format, countdown
|
from nemubot.tools.countdown import countdown_format, countdown
|
||||||
from nemubot.tools.date import extractDate
|
from nemubot.tools.date import extractDate
|
||||||
from nemubot.tools.xmlparser.node import ModuleState
|
from nemubot.tools.xmlparser.basic import DictNode
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
|
class Event:
|
||||||
|
|
||||||
|
def __init__(self, server, channel, creator, start_time, end_time=None):
|
||||||
|
self._server = server
|
||||||
|
self._channel = channel
|
||||||
|
self._creator = creator
|
||||||
|
self._start = datetime.utcfromtimestamp(float(start_time)).replace(tzinfo=timezone.utc) if not isinstance(start_time, datetime) else start_time
|
||||||
|
self._end = datetime.utcfromtimestamp(float(end_time)).replace(tzinfo=timezone.utc) if end_time else None
|
||||||
|
self._evt = None
|
||||||
|
|
||||||
|
|
||||||
|
def __del__(self):
|
||||||
|
if self._evt is not None:
|
||||||
|
context.del_event(self._evt)
|
||||||
|
self._evt = None
|
||||||
|
|
||||||
|
|
||||||
|
def saveElement(self, store, tag="event"):
|
||||||
|
attrs = {
|
||||||
|
"server": str(self._server),
|
||||||
|
"channel": str(self._channel),
|
||||||
|
"creator": str(self._creator),
|
||||||
|
"start_time": str(calendar.timegm(self._start.timetuple())),
|
||||||
|
}
|
||||||
|
if self._end:
|
||||||
|
attrs["end_time"] = str(calendar.timegm(self._end.timetuple()))
|
||||||
|
store.startElement(tag, attrs)
|
||||||
|
store.endElement(tag)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def creator(self):
|
||||||
|
return self._creator
|
||||||
|
|
||||||
|
@property
|
||||||
|
def start(self):
|
||||||
|
return self._start
|
||||||
|
|
||||||
|
@property
|
||||||
|
def end(self):
|
||||||
|
return self._end
|
||||||
|
|
||||||
|
@end.setter
|
||||||
|
def end(self, c):
|
||||||
|
self._end = c
|
||||||
|
|
||||||
|
@end.deleter
|
||||||
|
def end(self):
|
||||||
|
self._end = None
|
||||||
|
|
||||||
|
|
||||||
def help_full ():
|
def help_full ():
|
||||||
return "This module store a lot of events: ny, we, " + (", ".join(context.datas.index.keys() if hasattr(context, "datas") else [])) + "\n!eventslist: gets list of timer\n!start /something/: launch a timer"
|
return "This module store a lot of events: ny, we, " + (", ".join(context.datas.keys()) if hasattr(context, "datas") else "") + "\n!eventslist: gets list of timer\n!start /something/: launch a timer"
|
||||||
|
|
||||||
|
|
||||||
def load(context):
|
def load(context):
|
||||||
#Define the index
|
context.set_knodes({
|
||||||
context.data.setIndex("name")
|
"dict": DictNode,
|
||||||
|
"event": Event,
|
||||||
|
})
|
||||||
|
|
||||||
for evt in context.data.index.keys():
|
if context.data is None:
|
||||||
if context.data.index[evt].hasAttribute("end"):
|
context.set_default(DictNode())
|
||||||
event = ModuleEvent(call=fini, call_data=dict(strend=context.data.index[evt]))
|
|
||||||
event._end = context.data.index[evt].getDate("end")
|
# Relaunch all timers
|
||||||
idt = context.add_event(event)
|
for kevt in context.data:
|
||||||
if idt is not None:
|
if context.data[kevt].end:
|
||||||
context.data.index[evt]["_id"] = idt
|
context.data[kevt]._evt = context.add_event(ModuleEvent(partial(fini, kevt, context.data[kevt]), offset=context.data[kevt].end - datetime.now(timezone.utc), interval=0))
|
||||||
|
|
||||||
|
|
||||||
def fini(d, strend):
|
def fini(name, evt):
|
||||||
context.send_response(strend["server"], Response("%s arrivé à échéance." % strend["name"], channel=strend["channel"], nick=strend["proprio"]))
|
context.send_response(evt._server, Response("%s arrivé à échéance." % name, channel=evt._channel, nick=evt.creator))
|
||||||
context.data.delChild(context.data.index[strend["name"]])
|
evt._evt = None
|
||||||
|
del context.data[name]
|
||||||
context.save()
|
context.save()
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -63,18 +118,10 @@ 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 IMException("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:
|
||||||
raise IMException("%s existe déjà ." % msg.args[0])
|
raise IMException("%s existe déjà ." % msg.args[0])
|
||||||
|
|
||||||
strnd = ModuleState("strend")
|
evt = Event(server=msg.server, channel=msg.channel, creator=msg.frm, start_time=msg.date)
|
||||||
strnd["server"] = msg.server
|
|
||||||
strnd["channel"] = msg.channel
|
|
||||||
strnd["proprio"] = msg.nick
|
|
||||||
strnd["start"] = msg.date
|
|
||||||
strnd["name"] = msg.args[0]
|
|
||||||
context.data.addChild(strnd)
|
|
||||||
|
|
||||||
evt = ModuleEvent(call=fini, call_data=dict(strend=strnd))
|
|
||||||
|
|
||||||
if len(msg.args) > 1:
|
if len(msg.args) > 1:
|
||||||
result1 = re.findall("([0-9]+)([smhdjwyaSMHDJWYA])?", msg.args[1])
|
result1 = re.findall("([0-9]+)([smhdjwyaSMHDJWYA])?", msg.args[1])
|
||||||
|
|
@ -92,50 +139,51 @@ def start_countdown(msg):
|
||||||
if result2 is None or result2.group(4) is None: yea = now.year
|
if result2 is None or result2.group(4) is None: yea = now.year
|
||||||
else: yea = int(result2.group(4))
|
else: yea = int(result2.group(4))
|
||||||
if result2 is not None and result3 is not None:
|
if result2 is not None and result3 is not None:
|
||||||
strnd["end"] = datetime(yea, int(result2.group(3)), int(result2.group(2)), hou, minu, sec, timezone.utc)
|
evt.end = datetime(yea, int(result2.group(3)), int(result2.group(2)), hou, minu, sec, timezone.utc)
|
||||||
elif result2 is not None:
|
elif result2 is not None:
|
||||||
strnd["end"] = datetime(int(result2.group(4)), int(result2.group(3)), int(result2.group(2)), 0, 0, 0, timezone.utc)
|
evt.end = datetime(int(result2.group(4)), int(result2.group(3)), int(result2.group(2)), 0, 0, 0, timezone.utc)
|
||||||
elif result3 is not None:
|
elif result3 is not None:
|
||||||
if hou * 3600 + minu * 60 + sec > now.hour * 3600 + now.minute * 60 + now.second:
|
if hou * 3600 + minu * 60 + sec > now.hour * 3600 + now.minute * 60 + now.second:
|
||||||
strnd["end"] = datetime(now.year, now.month, now.day, hou, minu, sec, timezone.utc)
|
evt.end = datetime(now.year, now.month, now.day, hou, minu, sec, timezone.utc)
|
||||||
else:
|
else:
|
||||||
strnd["end"] = datetime(now.year, now.month, now.day + 1, hou, minu, sec, timezone.utc)
|
evt.end = datetime(now.year, now.month, now.day + 1, hou, minu, sec, timezone.utc)
|
||||||
evt._end = strnd.getDate("end")
|
|
||||||
strnd["_id"] = context.add_event(evt)
|
|
||||||
except:
|
except:
|
||||||
context.data.delChild(strnd)
|
|
||||||
raise IMException("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
|
evt.end = msg.date
|
||||||
for (t, g) in result1:
|
for (t, g) in result1:
|
||||||
if g is None or g == "" or g == "m" or g == "M":
|
if g is None or g == "" or g == "m" or g == "M":
|
||||||
strnd["end"] += timedelta(minutes=int(t))
|
evt.end += timedelta(minutes=int(t))
|
||||||
elif g == "h" or g == "H":
|
elif g == "h" or g == "H":
|
||||||
strnd["end"] += timedelta(hours=int(t))
|
evt.end += timedelta(hours=int(t))
|
||||||
elif g == "d" or g == "D" or g == "j" or g == "J":
|
elif g == "d" or g == "D" or g == "j" or g == "J":
|
||||||
strnd["end"] += timedelta(days=int(t))
|
evt.end += timedelta(days=int(t))
|
||||||
elif g == "w" or g == "W":
|
elif g == "w" or g == "W":
|
||||||
strnd["end"] += timedelta(days=int(t)*7)
|
evt.end += timedelta(days=int(t)*7)
|
||||||
elif g == "y" or g == "Y" or g == "a" or g == "A":
|
elif g == "y" or g == "Y" or g == "a" or g == "A":
|
||||||
strnd["end"] += timedelta(days=int(t)*365)
|
evt.end += timedelta(days=int(t)*365)
|
||||||
else:
|
else:
|
||||||
strnd["end"] += timedelta(seconds=int(t))
|
evt.end += timedelta(seconds=int(t))
|
||||||
evt._end = strnd.getDate("end")
|
|
||||||
eid = context.add_event(evt)
|
|
||||||
if eid is not None:
|
|
||||||
strnd["_id"] = eid
|
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise IMException("Mauvais format de date pour l'événement %s. Il n'a pas été créé." % msg.args[0])
|
||||||
|
|
||||||
|
context.data[msg.args[0]] = evt
|
||||||
context.save()
|
context.save()
|
||||||
if "end" in strnd:
|
|
||||||
|
if evt.end is not None:
|
||||||
|
context.add_event(ModuleEvent(partial(fini, msg.args[0], evt),
|
||||||
|
offset=evt.end - datetime.now(timezone.utc),
|
||||||
|
interval=0))
|
||||||
return Response("%s commencé le %s et se terminera le %s." %
|
return Response("%s commencé le %s et se terminera le %s." %
|
||||||
(msg.args[0], msg.date.strftime("%A %d %B %Y Ã %H:%M:%S"),
|
(msg.args[0], msg.date.strftime("%A %d %B %Y Ã %H:%M:%S"),
|
||||||
strnd.getDate("end").strftime("%A %d %B %Y Ã %H:%M:%S")),
|
evt.end.strftime("%A %d %B %Y Ã %H:%M:%S")),
|
||||||
nick=msg.frm)
|
channel=msg.channel)
|
||||||
else:
|
else:
|
||||||
return Response("%s commencé le %s"% (msg.args[0],
|
return Response("%s commencé le %s"% (msg.args[0],
|
||||||
msg.date.strftime("%A %d %B %Y Ã %H:%M:%S")),
|
msg.date.strftime("%A %d %B %Y Ã %H:%M:%S")),
|
||||||
nick=msg.frm)
|
channel=msg.channel)
|
||||||
|
|
||||||
|
|
||||||
@hook.command("end")
|
@hook.command("end")
|
||||||
|
|
@ -144,67 +192,66 @@ def end_countdown(msg):
|
||||||
if len(msg.args) < 1:
|
if len(msg.args) < 1:
|
||||||
raise IMException("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:
|
||||||
if context.data.index[msg.args[0]]["proprio"] == msg.nick or (msg.cmd == "forceend" and msg.frm_owner):
|
if context.data[msg.args[0]].creator == msg.frm or (msg.cmd == "forceend" and msg.frm_owner):
|
||||||
duration = countdown(msg.date - context.data.index[msg.args[0]].getDate("start"))
|
duration = countdown(msg.date - context.data[msg.args[0]].start)
|
||||||
context.del_event(context.data.index[msg.args[0]]["_id"])
|
del context.data[msg.args[0]]
|
||||||
context.data.delChild(context.data.index[msg.args[0]])
|
|
||||||
context.save()
|
context.save()
|
||||||
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.frm)
|
||||||
else:
|
else:
|
||||||
raise IMException("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[msg.args[0]].creator))
|
||||||
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.frm)
|
||||||
|
|
||||||
|
|
||||||
@hook.command("eventslist")
|
@hook.command("eventslist")
|
||||||
def liste(msg):
|
def liste(msg):
|
||||||
"""!eventslist: gets list of timer"""
|
"""!eventslist: gets list of timer"""
|
||||||
if len(msg.args):
|
if len(msg.args):
|
||||||
res = list()
|
res = Response(channel=msg.channel)
|
||||||
for user in msg.args:
|
for user in msg.args:
|
||||||
cmptr = [x["name"] for x in context.data.index.values() if x["proprio"] == user]
|
cmptr = [k for k in context.data if context.data[k].creator == user]
|
||||||
if len(cmptr) > 0:
|
if len(cmptr) > 0:
|
||||||
res.append("Compteurs créés par %s : %s" % (user, ", ".join(cmptr)))
|
res.append_message(cmptr, title="Events created by %s" % user)
|
||||||
else:
|
else:
|
||||||
res.append("%s n'a pas créé de compteur" % user)
|
res.append_message("%s doesn't have any counting events" % user)
|
||||||
return Response(" ; ".join(res), channel=msg.channel)
|
return res
|
||||||
else:
|
else:
|
||||||
return Response("Compteurs connus : %s." % ", ".join(context.data.index.keys()), channel=msg.channel)
|
return Response(list(context.data.keys()), channel=msg.channel, title="Known events")
|
||||||
|
|
||||||
|
|
||||||
@hook.command(match=lambda msg: isinstance(msg, Command) and msg.cmd in context.data.index)
|
@hook.command(match=lambda msg: isinstance(msg, Command) and msg.cmd in context.data)
|
||||||
def parseanswer(msg):
|
def parseanswer(msg):
|
||||||
res = Response(channel=msg.channel)
|
res = Response(channel=msg.channel)
|
||||||
|
|
||||||
# Avoid message starting by ! which can be interpreted as command by other bots
|
# Avoid message starting by ! which can be interpreted as command by other bots
|
||||||
if msg.cmd[0] == "!":
|
if msg.cmd[0] == "!":
|
||||||
res.nick = msg.nick
|
res.nick = msg.frm
|
||||||
|
|
||||||
if context.data.index[msg.cmd].name == "strend":
|
if msg.cmd in context.data:
|
||||||
if context.data.index[msg.cmd].hasAttribute("end"):
|
if context.data[msg.cmd].end:
|
||||||
res.append_message("%s commencé il y a %s et se terminera dans %s." % (msg.cmd, countdown(msg.date - context.data.index[msg.cmd].getDate("start")), countdown(context.data.index[msg.cmd].getDate("end") - msg.date)))
|
res.append_message("%s commencé il y a %s et se terminera dans %s." % (msg.cmd, countdown(msg.date - context.data[msg.cmd].start), countdown(context.data[msg.cmd].end - msg.date)))
|
||||||
else:
|
else:
|
||||||
res.append_message("%s commencé il y a %s." % (msg.cmd, countdown(msg.date - context.data.index[msg.cmd].getDate("start"))))
|
res.append_message("%s commencé il y a %s." % (msg.cmd, countdown(msg.date - context.data[msg.cmd].start)))
|
||||||
else:
|
else:
|
||||||
res.append_message(countdown_format(context.data.index[msg.cmd].getDate("start"), context.data.index[msg.cmd]["msg_before"], context.data.index[msg.cmd]["msg_after"]))
|
res.append_message(countdown_format(context.data[msg.cmd].start, context.data[msg.cmd]["msg_before"], context.data[msg.cmd]["msg_after"]))
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
|
||||||
RGXP_ask = re.compile(r"^.*((create|new)\s+(a|an|a\s*new|an\s*other)?\s*(events?|commande?)|(nouvel(le)?|ajoute|cr[ée]{1,3})\s+(un)?\s*([eé]v[ée]nements?|commande?)).*$", re.I)
|
RGXP_ask = re.compile(r"^.*((create|new)\s+(a|an|a\s*new|an\s*other)?\s*(events?|commande?)|(nouvel(le)?|ajoute|cr[ée]{1,3})\s+(un)?\s*([eé]v[ée]nements?|commande?)).*$", re.I)
|
||||||
|
|
||||||
@hook.ask(match=lambda msg: RGXP_ask.match(msg.text))
|
@hook.ask(match=lambda msg: RGXP_ask.match(msg.message))
|
||||||
def parseask(msg):
|
def parseask(msg):
|
||||||
name = re.match("^.*!([^ \"'@!]+).*$", msg.text)
|
name = re.match("^.*!([^ \"'@!]+).*$", msg.message)
|
||||||
if name is None:
|
if name is None:
|
||||||
raise IMException("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:
|
||||||
raise IMException("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.message, 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.message)
|
||||||
if extDate is None or extDate == "":
|
if extDate is None or extDate == "":
|
||||||
raise IMException("la date de l'événement est invalide !")
|
raise IMException("la date de l'événement est invalide !")
|
||||||
|
|
||||||
|
|
@ -223,7 +270,7 @@ def parseask(msg):
|
||||||
evt = ModuleState("event")
|
evt = ModuleState("event")
|
||||||
evt["server"] = msg.server
|
evt["server"] = msg.server
|
||||||
evt["channel"] = msg.channel
|
evt["channel"] = msg.channel
|
||||||
evt["proprio"] = msg.nick
|
evt["proprio"] = msg.frm
|
||||||
evt["name"] = name.group(1)
|
evt["name"] = name.group(1)
|
||||||
evt["start"] = extDate
|
evt["start"] = extDate
|
||||||
evt["msg_after"] = msg_after
|
evt["msg_after"] = msg_after
|
||||||
|
|
@ -237,7 +284,7 @@ def parseask(msg):
|
||||||
evt = ModuleState("event")
|
evt = ModuleState("event")
|
||||||
evt["server"] = msg.server
|
evt["server"] = msg.server
|
||||||
evt["channel"] = msg.channel
|
evt["channel"] = msg.channel
|
||||||
evt["proprio"] = msg.nick
|
evt["proprio"] = msg.frm
|
||||||
evt["name"] = name.group(1)
|
evt["name"] = name.group(1)
|
||||||
evt["msg_before"] = texts.group (2)
|
evt["msg_before"] = texts.group (2)
|
||||||
context.data.addChild(evt)
|
context.data.addChild(evt)
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ 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 more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# MODULE CORE #########################################################
|
# MODULE CORE #########################################################
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ 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 more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# MODULE CORE #########################################################
|
# MODULE CORE #########################################################
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ from nemubot.exception import IMException
|
||||||
from nemubot.hooks import hook
|
from nemubot.hooks import hook
|
||||||
from nemubot.message import Command, Text
|
from nemubot.message import Command, Text
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# MODULE CORE #########################################################
|
# MODULE CORE #########################################################
|
||||||
|
|
@ -73,7 +73,7 @@ def cmd_grep(msg):
|
||||||
|
|
||||||
only = "only" in msg.kwargs
|
only = "only" in msg.kwargs
|
||||||
|
|
||||||
l = [m for m in grep(msg.args[0] if msg.args[0][0] == "^" else ".*?(" + msg.args[0] + ").*?",
|
l = [m for m in grep(msg.args[0] if len(msg.args[0]) and msg.args[0][0] == "^" else ".*?(" + msg.args[0] + ").*?",
|
||||||
" ".join(msg.args[1:]),
|
" ".join(msg.args[1:]),
|
||||||
msg,
|
msg,
|
||||||
icase="nocase" in msg.kwargs,
|
icase="nocase" in msg.kwargs,
|
||||||
|
|
|
||||||
|
|
@ -5,63 +5,56 @@
|
||||||
import re
|
import re
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
|
|
||||||
|
from bs4 import BeautifulSoup
|
||||||
|
|
||||||
from nemubot.exception import IMException
|
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 more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# MODULE CORE #########################################################
|
# MODULE CORE #########################################################
|
||||||
|
|
||||||
def get_movie(title=None, year=None, imdbid=None, fullplot=True, tomatoes=False):
|
def get_movie_by_id(imdbid):
|
||||||
"""Returns the information about the matching movie"""
|
"""Returns the information about the matching movie"""
|
||||||
|
|
||||||
# Built URL
|
url = "http://www.imdb.com/title/" + urllib.parse.quote(imdbid)
|
||||||
url = "http://www.omdbapi.com/?"
|
soup = BeautifulSoup(web.getURLContent(url))
|
||||||
if title is not None:
|
|
||||||
url += "t=%s&" % urllib.parse.quote(title)
|
|
||||||
if year is not None:
|
|
||||||
url += "y=%s&" % urllib.parse.quote(year)
|
|
||||||
if imdbid is not None:
|
|
||||||
url += "i=%s&" % urllib.parse.quote(imdbid)
|
|
||||||
if fullplot:
|
|
||||||
url += "plot=full&"
|
|
||||||
if tomatoes:
|
|
||||||
url += "tomatoes=true&"
|
|
||||||
|
|
||||||
# Make the request
|
return {
|
||||||
data = web.getJSON(url)
|
"imdbID": imdbid,
|
||||||
|
"Title": soup.body.find('h1').contents[0].strip(),
|
||||||
|
"Year": soup.body.find(id="titleYear").find("a").text.strip() if soup.body.find(id="titleYear") else ", ".join([y.text.strip() for y in soup.body.find(attrs={"class": "seasons-and-year-nav"}).find_all("a")[1:]]),
|
||||||
|
"Duration": soup.body.find(attrs={"class": "title_wrapper"}).find("time").text.strip() if soup.body.find(attrs={"class": "title_wrapper"}).find("time") else None,
|
||||||
|
"imdbRating": soup.body.find(attrs={"class": "ratingValue"}).find("strong").text.strip() if soup.body.find(attrs={"class": "ratingValue"}) else None,
|
||||||
|
"imdbVotes": soup.body.find(attrs={"class": "imdbRating"}).find("a").text.strip() if soup.body.find(attrs={"class": "imdbRating"}) else None,
|
||||||
|
"Plot": re.sub(r"\s+", " ", soup.body.find(attrs={"class": "summary_text"}).text).strip(),
|
||||||
|
|
||||||
# Return data
|
"Type": "TV Series" if soup.find(id="title-episode-widget") else "Movie",
|
||||||
if "Error" in data:
|
"Genre": ", ".join([x.text.strip() for x in soup.body.find(id="titleStoryLine").find_all("a") if x.get("href") is not None and x.get("href")[:21] == "/search/title?genres="]),
|
||||||
raise IMException(data["Error"])
|
"Country": ", ".join([x.text.strip() for x in soup.body.find(id="titleDetails").find_all("a") if x.get("href") is not None and x.get("href")[:32] == "/search/title?country_of_origin="]),
|
||||||
|
"Credits": " ; ".join([x.find("h4").text.strip() + " " + (", ".join([y.text.strip() for y in x.find_all("a") if y.get("href") is not None and y.get("href")[:6] == "/name/"])) for x in soup.body.find_all(attrs={"class": "credit_summary_item"})]),
|
||||||
elif "Response" in data and data["Response"] == "True":
|
}
|
||||||
return data
|
|
||||||
|
|
||||||
else:
|
|
||||||
raise IMException("An error occurs during movie search")
|
|
||||||
|
|
||||||
|
|
||||||
def find_movies(title):
|
def find_movies(title, year=None):
|
||||||
"""Find existing movies matching a approximate title"""
|
"""Find existing movies matching a approximate title"""
|
||||||
|
|
||||||
|
title = title.lower()
|
||||||
|
|
||||||
# Built URL
|
# Built URL
|
||||||
url = "http://www.omdbapi.com/?s=%s" % urllib.parse.quote(title)
|
url = "https://v2.sg.media-imdb.com/suggests/%s/%s.json" % (urllib.parse.quote(title[0]), urllib.parse.quote(title.replace(" ", "_")))
|
||||||
|
|
||||||
# Make the request
|
# Make the request
|
||||||
data = web.getJSON(url)
|
data = web.getJSON(url, remove_callback=True)
|
||||||
|
|
||||||
# Return data
|
|
||||||
if "Error" in data:
|
|
||||||
raise IMException(data["Error"])
|
|
||||||
|
|
||||||
elif "Search" in data:
|
|
||||||
return data
|
|
||||||
|
|
||||||
|
if "d" not in data:
|
||||||
|
return None
|
||||||
|
elif year is None:
|
||||||
|
return data["d"]
|
||||||
else:
|
else:
|
||||||
raise IMException("An error occurs during movie search")
|
return [d for d in data["d"] if "y" in d and str(d["y"]) == year]
|
||||||
|
|
||||||
|
|
||||||
# MODULE INTERFACE ####################################################
|
# MODULE INTERFACE ####################################################
|
||||||
|
|
@ -79,23 +72,28 @@ def cmd_imdb(msg):
|
||||||
title = ' '.join(msg.args)
|
title = ' '.join(msg.args)
|
||||||
|
|
||||||
if re.match("^tt[0-9]{7}$", title) is not None:
|
if re.match("^tt[0-9]{7}$", title) is not None:
|
||||||
data = get_movie(imdbid=title)
|
data = get_movie_by_id(imdbid=title)
|
||||||
else:
|
else:
|
||||||
rm = re.match(r"^(.+)\s\(([0-9]{4})\)$", title)
|
rm = re.match(r"^(.+)\s\(([0-9]{4})\)$", title)
|
||||||
if rm is not None:
|
if rm is not None:
|
||||||
data = get_movie(title=rm.group(1), year=rm.group(2))
|
data = find_movies(rm.group(1), year=rm.group(2))
|
||||||
else:
|
else:
|
||||||
data = get_movie(title=title)
|
data = find_movies(title)
|
||||||
|
|
||||||
|
if not data:
|
||||||
|
raise IMException("Movie/series not found")
|
||||||
|
|
||||||
|
data = get_movie_by_id(data[0]["id"])
|
||||||
|
|
||||||
res = Response(channel=msg.channel,
|
res = Response(channel=msg.channel,
|
||||||
title="%s (%s)" % (data['Title'], data['Year']),
|
title="%s (%s)" % (data['Title'], data['Year']),
|
||||||
nomore="No more information, more at http://www.imdb.com/title/%s" % data['imdbID'])
|
nomore="No more information, more at http://www.imdb.com/title/%s" % data['imdbID'])
|
||||||
|
|
||||||
res.append_message("\x02rating\x0F: %s (%s votes); \x02plot\x0F: %s" %
|
res.append_message("%s \x02genre:\x0F %s; \x02rating\x0F: %s (%s votes); \x02plot\x0F: %s" %
|
||||||
(data['imdbRating'], data['imdbVotes'], data['Plot']))
|
(data['Type'], data['Genre'], data['imdbRating'], data['imdbVotes'], data['Plot']))
|
||||||
|
res.append_message("%s \x02from\x0F %s; %s"
|
||||||
|
% (data['Type'], data['Country'], data['Credits']))
|
||||||
|
|
||||||
res.append_message("%s \x02from\x0F %s \x02released on\x0F %s; \x02genre:\x0F %s; \x02directed by:\x0F %s; \x02written by:\x0F %s; \x02main actors:\x0F %s"
|
|
||||||
% (data['Type'], data['Country'], data['Released'], data['Genre'], data['Director'], data['Writer'], data['Actors']))
|
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -111,7 +109,7 @@ def cmd_search(msg):
|
||||||
data = find_movies(' '.join(msg.args))
|
data = find_movies(' '.join(msg.args))
|
||||||
|
|
||||||
movies = list()
|
movies = list()
|
||||||
for m in data['Search']:
|
for m in data:
|
||||||
movies.append("\x02%s\x0F (%s of %s)" % (m['Title'], m['Type'], m['Year']))
|
movies.append("\x02%s\x0F%s with %s" % (m['l'], (" (" + str(m['y']) + ")") if "y" in m else "", m['s']))
|
||||||
|
|
||||||
return Response(movies, title="Titles found", channel=msg.channel)
|
return Response(movies, title="Titles found", channel=msg.channel)
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
from nemubot.hooks import hook
|
from nemubot.hooks import hook
|
||||||
from nemubot.exception import IMException
|
from nemubot.exception import IMException
|
||||||
from nemubot.tools import web
|
from nemubot.tools import web
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
import json
|
import json
|
||||||
|
|
||||||
nemubotversion = 3.4
|
nemubotversion = 3.4
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ import os
|
||||||
|
|
||||||
from nemubot.hooks import hook
|
from nemubot.hooks import hook
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# GLOBALS #############################################################
|
# GLOBALS #############################################################
|
||||||
|
|
|
||||||
|
|
@ -9,11 +9,11 @@ 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 more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
# GLOBALS #############################################################
|
# GLOBALS #############################################################
|
||||||
|
|
||||||
URL_API = "http://open.mapquestapi.com/geocoding/v1/address?key=%s&location=%%s"
|
URL_API = "https://open.mapquestapi.com/geocoding/v1/address?key=%s&location=%%s"
|
||||||
|
|
||||||
|
|
||||||
# LOADING #############################################################
|
# LOADING #############################################################
|
||||||
|
|
@ -23,7 +23,7 @@ def load(context):
|
||||||
raise ImportError("You need a MapQuest API key in order to use this "
|
raise ImportError("You need a MapQuest API key in order to use this "
|
||||||
"module. Add it to the module configuration file:\n"
|
"module. Add it to the module configuration file:\n"
|
||||||
"<module name=\"mapquest\" key=\"XXXXXXXXXXXXXXXX\" "
|
"<module name=\"mapquest\" key=\"XXXXXXXXXXXXXXXX\" "
|
||||||
"/>\nRegister at http://developer.mapquest.com/")
|
"/>\nRegister at https://developer.mapquest.com/")
|
||||||
global URL_API
|
global URL_API
|
||||||
URL_API = URL_API % context.config["apikey"].replace("%", "%%")
|
URL_API = URL_API % context.config["apikey"].replace("%", "%%")
|
||||||
|
|
||||||
|
|
@ -55,7 +55,7 @@ def cmd_geocode(msg):
|
||||||
if not len(msg.args):
|
if not len(msg.args):
|
||||||
raise IMException("indicate a name")
|
raise IMException("indicate a name")
|
||||||
|
|
||||||
res = Response(channel=msg.channel, nick=msg.nick,
|
res = Response(channel=msg.channel, nick=msg.frm,
|
||||||
nomore="No more geocode", count=" (%s more geocode)")
|
nomore="No more geocode", count=" (%s more geocode)")
|
||||||
|
|
||||||
for loc in geocode(' '.join(msg.args)):
|
for loc in geocode(' '.join(msg.args)):
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ from nemubot.tools import web
|
||||||
|
|
||||||
nemubotversion = 3.4
|
nemubotversion = 3.4
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# MEDIAWIKI REQUESTS ##################################################
|
# MEDIAWIKI REQUESTS ##################################################
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ import re
|
||||||
from nemubot.exception import IMException
|
from nemubot.exception import IMException
|
||||||
from nemubot.hooks import hook
|
from nemubot.hooks import hook
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
from . import isup
|
from . import isup
|
||||||
from . import page
|
from . import page
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ def isup(url):
|
||||||
|
|
||||||
o = urllib.parse.urlparse(getNormalizedURL(url), "http")
|
o = urllib.parse.urlparse(getNormalizedURL(url), "http")
|
||||||
if o.netloc != "":
|
if o.netloc != "":
|
||||||
isup = getJSON("http://isitup.org/%s.json" % o.netloc)
|
isup = getJSON("https://isitup.org/%s.json" % o.netloc)
|
||||||
if isup is not None and "status_code" in isup and isup["status_code"] == 1:
|
if isup is not None and "status_code" in isup and isup["status_code"] == 1:
|
||||||
return isup["response_time"]
|
return isup["response_time"]
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ def validator(url):
|
||||||
raise IMException("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("https://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 IMException("HTTP error occurs: %s %s" % (e.code, e.reason))
|
raise IMException("HTTP error occurs: %s %s" % (e.code, e.reason))
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
"""Alert on changes on websites"""
|
"""Alert on changes on websites"""
|
||||||
|
|
||||||
|
from functools import partial
|
||||||
import logging
|
import logging
|
||||||
from random import randint
|
from random import randint
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
|
|
@ -12,7 +13,7 @@ from nemubot.tools.xmlparser.node import ModuleState
|
||||||
|
|
||||||
logger = logging.getLogger("nemubot.module.networking.watchWebsite")
|
logger = logging.getLogger("nemubot.module.networking.watchWebsite")
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
from . import page
|
from . import page
|
||||||
|
|
||||||
|
|
@ -209,15 +210,14 @@ def start_watching(site, offset=0):
|
||||||
offset -- offset time to delay the launch of the first check
|
offset -- offset time to delay the launch of the first check
|
||||||
"""
|
"""
|
||||||
|
|
||||||
o = urlparse(getNormalizedURL(site["url"]), "http")
|
#o = urlparse(getNormalizedURL(site["url"]), "http")
|
||||||
#print_debug("Add %s event for site: %s" % (site["type"], o.netloc))
|
#print("Add %s event for site: %s" % (site["type"], o.netloc))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
evt = ModuleEvent(func=fwatch,
|
evt = ModuleEvent(func=partial(fwatch, url=site["url"]),
|
||||||
cmp_data=site["lastcontent"],
|
cmp=site["lastcontent"],
|
||||||
func_data=site["url"], offset=offset,
|
offset=offset, interval=site.getInt("time"),
|
||||||
interval=site.getInt("time"),
|
call=partial(alert_change, site=site))
|
||||||
call=alert_change, call_data=site)
|
|
||||||
site["_evt_id"] = add_event(evt)
|
site["_evt_id"] = add_event(evt)
|
||||||
except IMException:
|
except IMException:
|
||||||
logger.exception("Unable to watch %s", site["url"])
|
logger.exception("Unable to watch %s", site["url"])
|
||||||
|
|
|
||||||
|
|
@ -6,10 +6,10 @@ import urllib
|
||||||
from nemubot.exception import IMException
|
from nemubot.exception import IMException
|
||||||
from nemubot.tools.web import getJSON
|
from nemubot.tools.web import getJSON
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
URL_AVAIL = "https://www.whoisxmlapi.com/whoisserver/WhoisService?cmd=GET_DN_AVAILABILITY&domainName=%%s&outputFormat=json&username=%s&password=%s"
|
URL_AVAIL = "https://www.whoisxmlapi.com/whoisserver/WhoisService?cmd=GET_DN_AVAILABILITY&domainName=%%s&outputFormat=json&username=%s&password=%s"
|
||||||
URL_WHOIS = "http://www.whoisxmlapi.com/whoisserver/WhoisService?da=2&domainName=%%s&outputFormat=json&userName=%s&password=%s"
|
URL_WHOIS = "https://www.whoisxmlapi.com/whoisserver/WhoisService?da=2&domainName=%%s&outputFormat=json&userName=%s&password=%s"
|
||||||
|
|
||||||
|
|
||||||
# LOADING #############################################################
|
# LOADING #############################################################
|
||||||
|
|
@ -22,7 +22,7 @@ def load(CONF, add_hook):
|
||||||
"the !netwhois feature. Add it to the module "
|
"the !netwhois feature. Add it to the module "
|
||||||
"configuration file:\n<whoisxmlapi username=\"XX\" "
|
"configuration file:\n<whoisxmlapi username=\"XX\" "
|
||||||
"password=\"XXX\" />\nRegister at "
|
"password=\"XXX\" />\nRegister at "
|
||||||
"http://www.whoisxmlapi.com/newaccount.php")
|
"https://www.whoisxmlapi.com/newaccount.php")
|
||||||
|
|
||||||
URL_AVAIL = URL_AVAIL % (urllib.parse.quote(CONF.getNode("whoisxmlapi")["username"]), urllib.parse.quote(CONF.getNode("whoisxmlapi")["password"]))
|
URL_AVAIL = URL_AVAIL % (urllib.parse.quote(CONF.getNode("whoisxmlapi")["username"]), urllib.parse.quote(CONF.getNode("whoisxmlapi")["password"]))
|
||||||
URL_WHOIS = URL_WHOIS % (urllib.parse.quote(CONF.getNode("whoisxmlapi")["username"]), urllib.parse.quote(CONF.getNode("whoisxmlapi")["password"]))
|
URL_WHOIS = URL_WHOIS % (urllib.parse.quote(CONF.getNode("whoisxmlapi")["username"]), urllib.parse.quote(CONF.getNode("whoisxmlapi")["password"]))
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,8 @@ 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 more import Response
|
from nemubot.module.more import Response
|
||||||
|
from nemubot.module.urlreducer import reduce_inline
|
||||||
from nemubot.tools.feed import Feed, AtomEntry
|
from nemubot.tools.feed import Feed, AtomEntry
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -50,10 +51,11 @@ def cmd_news(msg):
|
||||||
links = [x for x in find_rss_links(url)]
|
links = [x for x in find_rss_links(url)]
|
||||||
if len(links) == 0: links = [ url ]
|
if len(links) == 0: links = [ url ]
|
||||||
|
|
||||||
res = Response(channel=msg.channel, nomore="No more news from %s" % url)
|
res = Response(channel=msg.channel, nomore="No more news from %s" % url, line_treat=reduce_inline)
|
||||||
for n in get_last_news(links[0]):
|
for n in get_last_news(links[0]):
|
||||||
res.append_message("%s published %s: %s %s" % (("\x02" + web.striphtml(n.title) + "\x0F") if n.title else "An article without title",
|
res.append_message("%s published %s: %s %s" % (("\x02" + web.striphtml(n.title) + "\x0F") if n.title else "An article without title",
|
||||||
(n.updated.strftime("on %A %d. %B %Y at %H:%M") if n.updated else "someday") if isinstance(n, AtomEntry) else n.pubDate,
|
(n.updated.strftime("on %A %d. %B %Y at %H:%M") if n.updated else "someday") if isinstance(n, AtomEntry) else n.pubDate,
|
||||||
web.striphtml(n.summary) if n.summary else "",
|
web.striphtml(n.summary) if n.summary else "",
|
||||||
n.link if n.link else ""))
|
n.link if n.link else ""))
|
||||||
|
|
||||||
return res
|
return res
|
||||||
|
|
|
||||||
229
modules/nntp.py
Normal file
229
modules/nntp.py
Normal file
|
|
@ -0,0 +1,229 @@
|
||||||
|
"""The NNTP module"""
|
||||||
|
|
||||||
|
# PYTHON STUFFS #######################################################
|
||||||
|
|
||||||
|
import email
|
||||||
|
import email.policy
|
||||||
|
from email.utils import mktime_tz, parseaddr, parsedate_tz
|
||||||
|
from functools import partial
|
||||||
|
from nntplib import NNTP, decode_header
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
from zlib import adler32
|
||||||
|
|
||||||
|
from nemubot import context
|
||||||
|
from nemubot.event import ModuleEvent
|
||||||
|
from nemubot.exception import IMException
|
||||||
|
from nemubot.hooks import hook
|
||||||
|
from nemubot.tools.xmlparser.node import ModuleState
|
||||||
|
|
||||||
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
|
# LOADING #############################################################
|
||||||
|
|
||||||
|
def load(context):
|
||||||
|
for wn in context.data.getNodes("watched_newsgroup"):
|
||||||
|
watch(**wn.attributes)
|
||||||
|
|
||||||
|
|
||||||
|
# MODULE CORE #########################################################
|
||||||
|
|
||||||
|
def list_groups(group_pattern="*", **server):
|
||||||
|
with NNTP(**server) as srv:
|
||||||
|
response, l = srv.list(group_pattern)
|
||||||
|
for i in l:
|
||||||
|
yield i.group, srv.description(i.group), i.flag
|
||||||
|
|
||||||
|
def read_group(group, **server):
|
||||||
|
with NNTP(**server) as srv:
|
||||||
|
response, count, first, last, name = srv.group(group)
|
||||||
|
resp, overviews = srv.over((first, last))
|
||||||
|
for art_num, over in reversed(overviews):
|
||||||
|
yield over
|
||||||
|
|
||||||
|
def read_article(msg_id, **server):
|
||||||
|
with NNTP(**server) as srv:
|
||||||
|
response, info = srv.article(msg_id)
|
||||||
|
return email.message_from_bytes(b"\r\n".join(info.lines), policy=email.policy.SMTPUTF8)
|
||||||
|
|
||||||
|
|
||||||
|
servers_lastcheck = dict()
|
||||||
|
servers_lastseen = dict()
|
||||||
|
|
||||||
|
def whatsnew(group="*", **server):
|
||||||
|
fill = dict()
|
||||||
|
if "user" in server: fill["user"] = server["user"]
|
||||||
|
if "password" in server: fill["password"] = server["password"]
|
||||||
|
if "host" in server: fill["host"] = server["host"]
|
||||||
|
if "port" in server: fill["port"] = server["port"]
|
||||||
|
|
||||||
|
idx = _indexServer(**server)
|
||||||
|
if idx in servers_lastcheck and servers_lastcheck[idx] is not None:
|
||||||
|
date_last_check = servers_lastcheck[idx]
|
||||||
|
else:
|
||||||
|
date_last_check = datetime.now()
|
||||||
|
|
||||||
|
if idx not in servers_lastseen:
|
||||||
|
servers_lastseen[idx] = []
|
||||||
|
|
||||||
|
with NNTP(**fill) as srv:
|
||||||
|
response, servers_lastcheck[idx] = srv.date()
|
||||||
|
|
||||||
|
response, groups = srv.newgroups(date_last_check)
|
||||||
|
for g in groups:
|
||||||
|
yield g
|
||||||
|
|
||||||
|
response, articles = srv.newnews(group, date_last_check)
|
||||||
|
for msg_id in articles:
|
||||||
|
if msg_id not in servers_lastseen[idx]:
|
||||||
|
servers_lastseen[idx].append(msg_id)
|
||||||
|
response, info = srv.article(msg_id)
|
||||||
|
yield email.message_from_bytes(b"\r\n".join(info.lines))
|
||||||
|
|
||||||
|
# Clean huge lists
|
||||||
|
if len(servers_lastseen[idx]) > 42:
|
||||||
|
servers_lastseen[idx] = servers_lastseen[idx][23:]
|
||||||
|
|
||||||
|
|
||||||
|
def format_article(art, **response_args):
|
||||||
|
art["X-FromName"], art["X-FromEmail"] = parseaddr(art["From"] if "From" in art else "")
|
||||||
|
if art["X-FromName"] == '': art["X-FromName"] = art["X-FromEmail"]
|
||||||
|
|
||||||
|
date = mktime_tz(parsedate_tz(art["Date"]))
|
||||||
|
if date < time.time() - 120:
|
||||||
|
title = "\x0314In \x0F\x03{0:02d}{Newsgroups}\x0F\x0314: on \x0F{Date}\x0314 by \x0F\x03{0:02d}{X-FromName}\x0F \x02{Subject}\x0F"
|
||||||
|
else:
|
||||||
|
title = "\x0314In \x0F\x03{0:02d}{Newsgroups}\x0F\x0314: by \x0F\x03{0:02d}{X-FromName}\x0F \x02{Subject}\x0F"
|
||||||
|
|
||||||
|
return Response(art.get_payload().replace('\n', ' '),
|
||||||
|
title=title.format(adler32(art["Newsgroups"].encode()) & 0xf, adler32(art["X-FromEmail"].encode()) & 0xf, **{h: decode_header(i) for h,i in art.items()}),
|
||||||
|
**response_args)
|
||||||
|
|
||||||
|
|
||||||
|
watches = dict()
|
||||||
|
|
||||||
|
def _indexServer(**kwargs):
|
||||||
|
if "user" not in kwargs: kwargs["user"] = ""
|
||||||
|
if "password" not in kwargs: kwargs["password"] = ""
|
||||||
|
if "host" not in kwargs: kwargs["host"] = ""
|
||||||
|
if "port" not in kwargs: kwargs["port"] = 119
|
||||||
|
return "{user}:{password}@{host}:{port}".format(**kwargs)
|
||||||
|
|
||||||
|
def _newevt(**args):
|
||||||
|
context.add_event(ModuleEvent(call=partial(_ticker, **args), interval=42))
|
||||||
|
|
||||||
|
def _ticker(to_server, to_channel, group, server):
|
||||||
|
_newevt(to_server=to_server, to_channel=to_channel, group=group, server=server)
|
||||||
|
n = 0
|
||||||
|
for art in whatsnew(group, **server):
|
||||||
|
n += 1
|
||||||
|
if n > 10:
|
||||||
|
continue
|
||||||
|
context.send_response(to_server, format_article(art, channel=to_channel))
|
||||||
|
if n > 10:
|
||||||
|
context.send_response(to_server, Response("... and %s others news" % (n - 10), channel=to_channel))
|
||||||
|
|
||||||
|
def watch(to_server, to_channel, group="*", **server):
|
||||||
|
_newevt(to_server=to_server, to_channel=to_channel, group=group, server=server)
|
||||||
|
|
||||||
|
|
||||||
|
# MODULE INTERFACE ####################################################
|
||||||
|
|
||||||
|
keywords_server = {
|
||||||
|
"host=HOST": "hostname or IP of the NNTP server",
|
||||||
|
"port=PORT": "port of the NNTP server",
|
||||||
|
"user=USERNAME": "username to use to connect to the server",
|
||||||
|
"password=PASSWORD": "password to use to connect to the server",
|
||||||
|
}
|
||||||
|
|
||||||
|
@hook.command("nntp_groups",
|
||||||
|
help="Show list of existing groups",
|
||||||
|
help_usage={
|
||||||
|
None: "Display all groups",
|
||||||
|
"PATTERN": "Filter on group matching the PATTERN"
|
||||||
|
},
|
||||||
|
keywords=keywords_server)
|
||||||
|
def cmd_groups(msg):
|
||||||
|
if "host" not in msg.kwargs:
|
||||||
|
raise IMException("please give a hostname in keywords")
|
||||||
|
|
||||||
|
return Response(["\x02\x03{0:02d}{1}\x0F: {2}".format(adler32(g[0].encode()) & 0xf, *g) for g in list_groups(msg.args[0] if len(msg.args) > 0 else "*", **msg.kwargs)],
|
||||||
|
channel=msg.channel,
|
||||||
|
title="Matching groups on %s" % msg.kwargs["host"])
|
||||||
|
|
||||||
|
|
||||||
|
@hook.command("nntp_overview",
|
||||||
|
help="Show an overview of articles in given group(s)",
|
||||||
|
help_usage={
|
||||||
|
"GROUP": "Filter on group matching the PATTERN"
|
||||||
|
},
|
||||||
|
keywords=keywords_server)
|
||||||
|
def cmd_overview(msg):
|
||||||
|
if "host" not in msg.kwargs:
|
||||||
|
raise IMException("please give a hostname in keywords")
|
||||||
|
|
||||||
|
if not len(msg.args):
|
||||||
|
raise IMException("which group would you overview?")
|
||||||
|
|
||||||
|
for g in msg.args:
|
||||||
|
arts = []
|
||||||
|
for grp in read_group(g, **msg.kwargs):
|
||||||
|
grp["X-FromName"], grp["X-FromEmail"] = parseaddr(grp["from"] if "from" in grp else "")
|
||||||
|
if grp["X-FromName"] == '': grp["X-FromName"] = grp["X-FromEmail"]
|
||||||
|
|
||||||
|
arts.append("On {date}, from \x03{0:02d}{X-FromName}\x0F \x02{subject}\x0F: \x0314{message-id}\x0F".format(adler32(grp["X-FromEmail"].encode()) & 0xf, **{h: decode_header(i) for h,i in grp.items()}))
|
||||||
|
|
||||||
|
if len(arts):
|
||||||
|
yield Response(arts,
|
||||||
|
channel=msg.channel,
|
||||||
|
title="In \x03{0:02d}{1}\x0F".format(adler32(g[0].encode()) & 0xf, g))
|
||||||
|
|
||||||
|
|
||||||
|
@hook.command("nntp_read",
|
||||||
|
help="Read an article from a server",
|
||||||
|
help_usage={
|
||||||
|
"MSG_ID": "Read the given message"
|
||||||
|
},
|
||||||
|
keywords=keywords_server)
|
||||||
|
def cmd_read(msg):
|
||||||
|
if "host" not in msg.kwargs:
|
||||||
|
raise IMException("please give a hostname in keywords")
|
||||||
|
|
||||||
|
for msgid in msg.args:
|
||||||
|
if not re.match("<.*>", msgid):
|
||||||
|
msgid = "<" + msgid + ">"
|
||||||
|
art = read_article(msgid, **msg.kwargs)
|
||||||
|
yield format_article(art, channel=msg.channel)
|
||||||
|
|
||||||
|
|
||||||
|
@hook.command("nntp_watch",
|
||||||
|
help="Launch an event looking for new groups and articles on a server",
|
||||||
|
help_usage={
|
||||||
|
None: "Watch all groups",
|
||||||
|
"PATTERN": "Limit the watch on group matching this PATTERN"
|
||||||
|
},
|
||||||
|
keywords=keywords_server)
|
||||||
|
def cmd_watch(msg):
|
||||||
|
if "host" not in msg.kwargs:
|
||||||
|
raise IMException("please give a hostname in keywords")
|
||||||
|
|
||||||
|
if not msg.frm_owner:
|
||||||
|
raise IMException("sorry, this command is currently limited to the owner")
|
||||||
|
|
||||||
|
wnnode = ModuleState("watched_newsgroup")
|
||||||
|
wnnode["id"] = _indexServer(**msg.kwargs)
|
||||||
|
wnnode["to_server"] = msg.server
|
||||||
|
wnnode["to_channel"] = msg.channel
|
||||||
|
wnnode["group"] = msg.args[0] if len(msg.args) > 0 else "*"
|
||||||
|
|
||||||
|
wnnode["user"] = msg.kwargs["user"] if "user" in msg.kwargs else ""
|
||||||
|
wnnode["password"] = msg.kwargs["password"] if "password" in msg.kwargs else ""
|
||||||
|
wnnode["host"] = msg.kwargs["host"] if "host" in msg.kwargs else ""
|
||||||
|
wnnode["port"] = msg.kwargs["port"] if "port" in msg.kwargs else 119
|
||||||
|
|
||||||
|
context.data.addChild(wnnode)
|
||||||
|
watch(**wnnode.attributes)
|
||||||
|
|
||||||
|
return Response("Ok ok, I watch this newsgroup!", channel=msg.channel)
|
||||||
87
modules/openai.py
Normal file
87
modules/openai.py
Normal file
|
|
@ -0,0 +1,87 @@
|
||||||
|
"""Perform requests to openai"""
|
||||||
|
|
||||||
|
# PYTHON STUFFS #######################################################
|
||||||
|
|
||||||
|
from openai import OpenAI
|
||||||
|
|
||||||
|
from nemubot import context
|
||||||
|
from nemubot.hooks import hook
|
||||||
|
from nemubot.tools import web
|
||||||
|
|
||||||
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
|
# LOADING #############################################################
|
||||||
|
|
||||||
|
CLIENT = None
|
||||||
|
MODEL = "gpt-4"
|
||||||
|
ENDPOINT = None
|
||||||
|
|
||||||
|
def load(context):
|
||||||
|
global CLIENT, ENDPOINT, MODEL
|
||||||
|
if not context.config or ("apikey" not in context.config and "endpoint" not in context.config):
|
||||||
|
raise ImportError ("You need a OpenAI API key in order to use "
|
||||||
|
"this module. Add it to the module configuration: "
|
||||||
|
"\n<module name=\"openai\" "
|
||||||
|
"apikey=\"XXXXXX-XXXXXXXXXX\" endpoint=\"https://...\" model=\"gpt-4\" />")
|
||||||
|
kwargs = {
|
||||||
|
"api_key": context.config["apikey"] or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
if "endpoint" in context.config:
|
||||||
|
ENDPOINT = context.config["endpoint"]
|
||||||
|
kwargs["base_url"] = ENDPOINT
|
||||||
|
|
||||||
|
CLIENT = OpenAI(**kwargs)
|
||||||
|
|
||||||
|
if "model" in context.config:
|
||||||
|
MODEL = context.config["model"]
|
||||||
|
|
||||||
|
|
||||||
|
# MODULE INTERFACE ####################################################
|
||||||
|
|
||||||
|
@hook.command("list_models",
|
||||||
|
help="list available LLM")
|
||||||
|
def cmd_listllm(msg):
|
||||||
|
llms = web.getJSON(ENDPOINT + "/models", timeout=6)
|
||||||
|
return Response(message=[m for m in map(lambda i: i["id"], llms["data"])], title="Here is the available models", channel=msg.channel)
|
||||||
|
|
||||||
|
|
||||||
|
@hook.command("set_model",
|
||||||
|
help="Set the model to use when talking to nemubot")
|
||||||
|
def cmd_setllm(msg):
|
||||||
|
if len(msg.args) != 1:
|
||||||
|
raise IMException("Indicate 1 model to use")
|
||||||
|
|
||||||
|
wanted_model = msg.args[0]
|
||||||
|
|
||||||
|
llms = web.getJSON(ENDPOINT + "/models", timeout=6)
|
||||||
|
for model in llms["data"]:
|
||||||
|
if wanted_model == model["id"]:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
raise IMException("Unable to set such model: unknown")
|
||||||
|
|
||||||
|
MODEL = wanted_model
|
||||||
|
return Response("New model in use: " + wanted_model, channel=msg.channel)
|
||||||
|
|
||||||
|
|
||||||
|
@hook.ask()
|
||||||
|
def parseask(msg):
|
||||||
|
chat_completion = CLIENT.chat.completions.create(
|
||||||
|
messages=[
|
||||||
|
{
|
||||||
|
"role": "system",
|
||||||
|
"content": "You are a kind multilingual assistant. Respond to the user request in 255 characters maximum. Be conscise, go directly to the point. Never add useless terms.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": msg.message,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
model=MODEL,
|
||||||
|
)
|
||||||
|
|
||||||
|
return Response(chat_completion.choices[0].message.content,
|
||||||
|
msg.channel,
|
||||||
|
msg.frm)
|
||||||
|
|
@ -9,7 +9,7 @@ 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 more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
# GLOBALS #############################################################
|
# GLOBALS #############################################################
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ from nemubot import context
|
||||||
from nemubot.exception import IMException
|
from nemubot.exception import IMException
|
||||||
from nemubot.hooks import hook
|
from nemubot.hooks import hook
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
DB = None
|
DB = None
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
|
|
||||||
from nemubot.exception import IMException
|
from nemubot.exception import IMException
|
||||||
from nemubot.hooks import hook
|
from nemubot.hooks import hook
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
from nextstop import ratp
|
from nextstop import ratp
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ from nemubot.tools import web
|
||||||
|
|
||||||
nemubotversion = 3.4
|
nemubotversion = 3.4
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
def help_full():
|
def help_full():
|
||||||
|
|
@ -40,7 +40,7 @@ def cmd_subreddit(msg):
|
||||||
else:
|
else:
|
||||||
where = "r"
|
where = "r"
|
||||||
|
|
||||||
sbr = web.getJSON("http://www.reddit.com/%s/%s/about.json" %
|
sbr = web.getJSON("https://www.reddit.com/%s/%s/about.json" %
|
||||||
(where, sub.group(2)))
|
(where, sub.group(2)))
|
||||||
|
|
||||||
if sbr is None:
|
if sbr is None:
|
||||||
|
|
@ -64,15 +64,22 @@ def cmd_subreddit(msg):
|
||||||
channel=msg.channel))
|
channel=msg.channel))
|
||||||
else:
|
else:
|
||||||
all_res.append(Response("%s is not a valid subreddit" % osub,
|
all_res.append(Response("%s is not a valid subreddit" % osub,
|
||||||
channel=msg.channel, nick=msg.nick))
|
channel=msg.channel, nick=msg.frm))
|
||||||
|
|
||||||
return all_res
|
return all_res
|
||||||
|
|
||||||
|
|
||||||
@hook.message()
|
@hook.message()
|
||||||
def parselisten(msg):
|
def parselisten(msg):
|
||||||
parseresponse(msg)
|
global LAST_SUBS
|
||||||
return None
|
|
||||||
|
if hasattr(msg, "message") and msg.message and type(msg.message) == str:
|
||||||
|
urls = re.findall("www.reddit.com(/\w/\w+/?)", msg.message)
|
||||||
|
for url in urls:
|
||||||
|
for recv in msg.to:
|
||||||
|
if recv not in LAST_SUBS:
|
||||||
|
LAST_SUBS[recv] = list()
|
||||||
|
LAST_SUBS[recv].append(url)
|
||||||
|
|
||||||
|
|
||||||
@hook.post()
|
@hook.post()
|
||||||
|
|
|
||||||
94
modules/repology.py
Normal file
94
modules/repology.py
Normal file
|
|
@ -0,0 +1,94 @@
|
||||||
|
# coding=utf-8
|
||||||
|
|
||||||
|
"""Repology.org module: the packaging hub"""
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
import re
|
||||||
|
|
||||||
|
from nemubot import context
|
||||||
|
from nemubot.exception import IMException
|
||||||
|
from nemubot.hooks import hook
|
||||||
|
from nemubot.tools import web
|
||||||
|
from nemubot.tools.xmlparser.node import ModuleState
|
||||||
|
|
||||||
|
nemubotversion = 4.0
|
||||||
|
|
||||||
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
URL_REPOAPI = "https://repology.org/api/v1/project/%s"
|
||||||
|
|
||||||
|
def get_json_project(project):
|
||||||
|
prj = web.getJSON(URL_REPOAPI % (project))
|
||||||
|
|
||||||
|
return prj
|
||||||
|
|
||||||
|
|
||||||
|
@hook.command("repology",
|
||||||
|
help="Display version information about a package",
|
||||||
|
help_usage={
|
||||||
|
"PACKAGE_NAME": "Retrieve informations about PACKAGE_NAME",
|
||||||
|
},
|
||||||
|
keywords={
|
||||||
|
"distro=DISTRO": "filter by disto",
|
||||||
|
"status=STATUS[,STATUS...]": "filter by status",
|
||||||
|
})
|
||||||
|
def cmd_repology(msg):
|
||||||
|
if len(msg.args) == 0:
|
||||||
|
raise IMException("Please provide at least a package name")
|
||||||
|
|
||||||
|
res = Response(channel=msg.channel, nomore="No more information on package")
|
||||||
|
|
||||||
|
for project in msg.args:
|
||||||
|
prj = get_json_project(project)
|
||||||
|
if len(prj) == 0:
|
||||||
|
raise IMException("Unable to find package " + project)
|
||||||
|
|
||||||
|
pkg_versions = {}
|
||||||
|
pkg_maintainers = {}
|
||||||
|
pkg_licenses = {}
|
||||||
|
summary = None
|
||||||
|
|
||||||
|
for repo in prj:
|
||||||
|
# Apply filters
|
||||||
|
if "distro" in msg.kwargs and repo["repo"].find(msg.kwargs["distro"]) < 0:
|
||||||
|
continue
|
||||||
|
if "status" in msg.kwargs and repo["status"] not in msg.kwargs["status"].split(","):
|
||||||
|
continue
|
||||||
|
|
||||||
|
name = repo["visiblename"] if "visiblename" in repo else repo["name"]
|
||||||
|
status = repo["status"] if "status" in repo else "unknown"
|
||||||
|
if name not in pkg_versions:
|
||||||
|
pkg_versions[name] = {}
|
||||||
|
if status not in pkg_versions[name]:
|
||||||
|
pkg_versions[name][status] = []
|
||||||
|
if repo["version"] not in pkg_versions[name][status]:
|
||||||
|
pkg_versions[name][status].append(repo["version"])
|
||||||
|
|
||||||
|
if "maintainers" in repo:
|
||||||
|
if name not in pkg_maintainers:
|
||||||
|
pkg_maintainers[name] = []
|
||||||
|
for maintainer in repo["maintainers"]:
|
||||||
|
if maintainer not in pkg_maintainers[name]:
|
||||||
|
pkg_maintainers[name].append(maintainer)
|
||||||
|
|
||||||
|
if "licenses" in repo:
|
||||||
|
if name not in pkg_licenses:
|
||||||
|
pkg_licenses[name] = []
|
||||||
|
for lic in repo["licenses"]:
|
||||||
|
if lic not in pkg_licenses[name]:
|
||||||
|
pkg_licenses[name].append(lic)
|
||||||
|
|
||||||
|
if "summary" in repo and summary is None:
|
||||||
|
summary = repo["summary"]
|
||||||
|
|
||||||
|
for pkgname in sorted(pkg_versions.keys()):
|
||||||
|
m = "Package " + pkgname + " (" + summary + ")"
|
||||||
|
if pkgname in pkg_licenses:
|
||||||
|
m += " under " + ", ".join(pkg_licenses[pkgname])
|
||||||
|
m += ": " + " - ".join([status + ": " + ", ".join(pkg_versions[pkgname][status]) for status in ["newest", "devel", "unique", "outdated", "legacy", "rolling", "noscheme", "untrusted", "ignored"] if status in pkg_versions[pkgname]])
|
||||||
|
if "distro" in msg.kwargs and pkgname in pkg_maintainers:
|
||||||
|
m += " - Maintained by " + ", ".join(pkg_maintainers[pkgname])
|
||||||
|
|
||||||
|
res.append_message(m)
|
||||||
|
|
||||||
|
return res
|
||||||
|
|
@ -9,7 +9,7 @@ from nemubot import context
|
||||||
from nemubot.exception import IMException
|
from nemubot.exception import IMException
|
||||||
from nemubot.hooks import hook
|
from nemubot.hooks import hook
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# MODULE INTERFACE ####################################################
|
# MODULE INTERFACE ####################################################
|
||||||
|
|
@ -21,7 +21,7 @@ def cmd_choice(msg):
|
||||||
|
|
||||||
return Response(random.choice(msg.args),
|
return Response(random.choice(msg.args),
|
||||||
channel=msg.channel,
|
channel=msg.channel,
|
||||||
nick=msg.nick)
|
nick=msg.frm)
|
||||||
|
|
||||||
|
|
||||||
@hook.command("choicecmd")
|
@hook.command("choicecmd")
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ from nemubot.tools import web
|
||||||
|
|
||||||
nemubotversion = 4.0
|
nemubotversion = 4.0
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
def help_full():
|
def help_full():
|
||||||
|
|
@ -25,7 +25,7 @@ def cmd_tcode(msg):
|
||||||
raise IMException("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 = ("https://www.tcodesearch.com/tcodes/search?q=%s" %
|
||||||
urllib.parse.quote(msg.args[0]))
|
urllib.parse.quote(msg.args[0]))
|
||||||
|
|
||||||
page = web.getURLContent(url)
|
page = web.getURLContent(url)
|
||||||
|
|
|
||||||
104
modules/shodan.py
Normal file
104
modules/shodan.py
Normal file
|
|
@ -0,0 +1,104 @@
|
||||||
|
"""Search engine for IoT"""
|
||||||
|
|
||||||
|
# PYTHON STUFFS #######################################################
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
import ipaddress
|
||||||
|
import urllib.parse
|
||||||
|
|
||||||
|
from nemubot import context
|
||||||
|
from nemubot.exception import IMException
|
||||||
|
from nemubot.hooks import hook
|
||||||
|
from nemubot.tools import web
|
||||||
|
|
||||||
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
|
# GLOBALS #############################################################
|
||||||
|
|
||||||
|
BASEURL = "https://api.shodan.io/shodan/"
|
||||||
|
|
||||||
|
|
||||||
|
# LOADING #############################################################
|
||||||
|
|
||||||
|
def load(context):
|
||||||
|
if not context.config or "apikey" not in context.config:
|
||||||
|
raise ImportError("You need a Shodan API key in order to use this "
|
||||||
|
"module. Add it to the module configuration file:\n"
|
||||||
|
"<module name=\"shodan\" apikey=\"XXXXXXXXXXXXXXXX\" "
|
||||||
|
"/>\nRegister at https://account.shodan.io/register")
|
||||||
|
|
||||||
|
|
||||||
|
# MODULE CORE #########################################################
|
||||||
|
|
||||||
|
def host_lookup(ip):
|
||||||
|
url = BASEURL + "host/" + urllib.parse.quote(ip) + "?" + urllib.parse.urlencode({'key': context.config["apikey"]})
|
||||||
|
return web.getJSON(url)
|
||||||
|
|
||||||
|
|
||||||
|
def search_hosts(query):
|
||||||
|
url = BASEURL + "host/search?" + urllib.parse.urlencode({'query': query, 'key': context.config["apikey"]})
|
||||||
|
return web.getJSON(url, max_size=4194304)
|
||||||
|
|
||||||
|
|
||||||
|
def print_ssl(ssl):
|
||||||
|
return (
|
||||||
|
"SSL: " +
|
||||||
|
" ".join([v for v in ssl["versions"] if v[0] != "-"]) +
|
||||||
|
"; cipher used: " + ssl["cipher"]["name"] +
|
||||||
|
("; certificate: " + ssl["cert"]["sig_alg"] +
|
||||||
|
" issued by: " + ssl["cert"]["issuer"]["CN"] +
|
||||||
|
" expires on: " + str(datetime.strptime(ssl["cert"]["expires"], "%Y%m%d%H%M%SZ")) if "cert" in ssl else "")
|
||||||
|
)
|
||||||
|
|
||||||
|
def print_service(svc):
|
||||||
|
ip = ipaddress.ip_address(svc["ip_str"])
|
||||||
|
return ((svc["ip_str"] if ip.version == 4 else "[%s]" % svc["ip_str"]) +
|
||||||
|
":{port}/{transport} ({module}):" +
|
||||||
|
(" {os}" if svc["os"] else "") +
|
||||||
|
(" {product}" if "product" in svc else "") +
|
||||||
|
(" {version}" if "version" in svc else "") +
|
||||||
|
(" {info}" if "info" in svc else "") +
|
||||||
|
(" Vulns: " + ", ".join(svc["opts"]["vulns"]) if "opts" in svc and "vulns" in svc["opts"] else "") +
|
||||||
|
(" " + print_ssl(svc["ssl"]) if "ssl" in svc else "") +
|
||||||
|
(" \x03\x1D" + svc["data"].replace("\r\n", "\n").split("\n")[0] + "\x03\x1D" if "data" in svc else "") +
|
||||||
|
(" " + svc["title"] if "title" in svc else "")
|
||||||
|
).format(module=svc["_shodan"]["module"], **svc)
|
||||||
|
|
||||||
|
|
||||||
|
# MODULE INTERFACE ####################################################
|
||||||
|
|
||||||
|
@hook.command("shodan",
|
||||||
|
help="Use shodan.io to get information on machines connected to Internet",
|
||||||
|
help_usage={
|
||||||
|
"IP": "retrieve information about the given IP (can be v4 or v6)",
|
||||||
|
"TERM": "retrieve all hosts matching TERM somewhere in their exposed stuff"
|
||||||
|
})
|
||||||
|
def shodan(msg):
|
||||||
|
if not msg.args:
|
||||||
|
raise IMException("indicate an IP or a term to search!")
|
||||||
|
|
||||||
|
terms = " ".join(msg.args)
|
||||||
|
|
||||||
|
try:
|
||||||
|
ip = ipaddress.ip_address(terms)
|
||||||
|
except ValueError:
|
||||||
|
ip = None
|
||||||
|
|
||||||
|
if ip:
|
||||||
|
h = host_lookup(terms)
|
||||||
|
res = Response(channel=msg.channel,
|
||||||
|
title="%s" % ((h["ip_str"] if ip.version == 4 else "[%s]" % h["ip_str"]) + (" (" + ", ".join(h["hostnames"]) + ")") if h["hostnames"] else ""))
|
||||||
|
res.append_message("{isp} ({asn}) -> {city} ({country_code}), running {os}. Vulns: {vulns_str}. Open ports: {open_ports}. Last update: {last_update}".format(
|
||||||
|
open_ports=", ".join(map(lambda a: str(a), h["ports"])), vulns_str=", ".join(h["vulns"]) if "vulns" in h else None, **h).strip())
|
||||||
|
for d in h["data"]:
|
||||||
|
res.append_message(print_service(d))
|
||||||
|
|
||||||
|
else:
|
||||||
|
q = search_hosts(terms)
|
||||||
|
res = Response(channel=msg.channel,
|
||||||
|
count=" (%%s/%s results)" % q["total"])
|
||||||
|
for r in q["matches"]:
|
||||||
|
res.append_message(print_service(r))
|
||||||
|
|
||||||
|
return res
|
||||||
|
|
@ -10,7 +10,7 @@ from nemubot.hooks import hook
|
||||||
|
|
||||||
nemubotversion = 3.4
|
nemubotversion = 3.4
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
def help_full():
|
def help_full():
|
||||||
|
|
|
||||||
116
modules/smmry.py
Normal file
116
modules/smmry.py
Normal file
|
|
@ -0,0 +1,116 @@
|
||||||
|
"""Summarize texts"""
|
||||||
|
|
||||||
|
# PYTHON STUFFS #######################################################
|
||||||
|
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
from nemubot import context
|
||||||
|
from nemubot.exception import IMException
|
||||||
|
from nemubot.hooks import hook
|
||||||
|
from nemubot.tools import web
|
||||||
|
|
||||||
|
from nemubot.module.more import Response
|
||||||
|
from nemubot.module.urlreducer import LAST_URLS
|
||||||
|
|
||||||
|
|
||||||
|
# GLOBALS #############################################################
|
||||||
|
|
||||||
|
URL_API = "https://api.smmry.com/?SM_API_KEY=%s"
|
||||||
|
|
||||||
|
|
||||||
|
# LOADING #############################################################
|
||||||
|
|
||||||
|
def load(context):
|
||||||
|
if not context.config or "apikey" not in context.config:
|
||||||
|
raise ImportError("You need a Smmry API key in order to use this "
|
||||||
|
"module. Add it to the module configuration file:\n"
|
||||||
|
"<module name=\"smmry\" apikey=\"XXXXXXXXXXXXXXXX\" "
|
||||||
|
"/>\nRegister at https://smmry.com/partner")
|
||||||
|
global URL_API
|
||||||
|
URL_API = URL_API % context.config["apikey"]
|
||||||
|
|
||||||
|
|
||||||
|
# MODULE INTERFACE ####################################################
|
||||||
|
|
||||||
|
@hook.command("smmry",
|
||||||
|
help="Summarize the following words/command return",
|
||||||
|
help_usage={
|
||||||
|
"WORDS/CMD": ""
|
||||||
|
},
|
||||||
|
keywords={
|
||||||
|
"keywords?=X": "Returns keywords instead of summary (count optional)",
|
||||||
|
"length=7": "The number of sentences returned, default 7",
|
||||||
|
"break": "inserts the string [BREAK] between sentences",
|
||||||
|
"ignore_length": "returns summary regardless of quality or length",
|
||||||
|
"quote_avoid": "sentences with quotations will be excluded",
|
||||||
|
"question_avoid": "sentences with question will be excluded",
|
||||||
|
"exclamation_avoid": "sentences with exclamation marks will be excluded",
|
||||||
|
})
|
||||||
|
def cmd_smmry(msg):
|
||||||
|
if not len(msg.args):
|
||||||
|
global LAST_URLS
|
||||||
|
if msg.channel in LAST_URLS and len(LAST_URLS[msg.channel]) > 0:
|
||||||
|
msg.args.append(LAST_URLS[msg.channel].pop())
|
||||||
|
else:
|
||||||
|
raise IMException("I have no more URL to sum up.")
|
||||||
|
|
||||||
|
URL = URL_API
|
||||||
|
if "length" in msg.kwargs:
|
||||||
|
if int(msg.kwargs["length"]) > 0 :
|
||||||
|
URL += "&SM_LENGTH=" + msg.kwargs["length"]
|
||||||
|
else:
|
||||||
|
msg.kwargs["ignore_length"] = True
|
||||||
|
if "break" in msg.kwargs: URL += "&SM_WITH_BREAK"
|
||||||
|
if "ignore_length" in msg.kwargs: URL += "&SM_IGNORE_LENGTH"
|
||||||
|
if "quote_avoid" in msg.kwargs: URL += "&SM_QUOTE_AVOID"
|
||||||
|
if "question_avoid" in msg.kwargs: URL += "&SM_QUESTION_AVOID"
|
||||||
|
if "exclamation_avoid" in msg.kwargs: URL += "&SM_EXCLAMATION_AVOID"
|
||||||
|
if "keywords" in msg.kwargs and msg.kwargs["keywords"] is not None and int(msg.kwargs["keywords"]) > 0: URL += "&SM_KEYWORD_COUNT=" + msg.kwargs["keywords"]
|
||||||
|
|
||||||
|
res = Response(channel=msg.channel)
|
||||||
|
|
||||||
|
if web.isURL(" ".join(msg.args)):
|
||||||
|
smmry = web.getJSON(URL + "&SM_URL=" + quote(" ".join(msg.args)), timeout=23)
|
||||||
|
else:
|
||||||
|
cnt = ""
|
||||||
|
for r in context.subtreat(context.subparse(msg, " ".join(msg.args))):
|
||||||
|
if isinstance(r, Response):
|
||||||
|
for i in range(len(r.messages) - 1, -1, -1):
|
||||||
|
if isinstance(r.messages[i], list):
|
||||||
|
for j in range(len(r.messages[i]) - 1, -1, -1):
|
||||||
|
cnt += r.messages[i][j] + "\n"
|
||||||
|
elif isinstance(r.messages[i], str):
|
||||||
|
cnt += r.messages[i] + "\n"
|
||||||
|
else:
|
||||||
|
cnt += str(r.messages) + "\n"
|
||||||
|
|
||||||
|
elif isinstance(r, Text):
|
||||||
|
cnt += r.message + "\n"
|
||||||
|
|
||||||
|
else:
|
||||||
|
cnt += str(r) + "\n"
|
||||||
|
|
||||||
|
smmry = web.getJSON(URL, body="sm_api_input=" + quote(cnt), timeout=23)
|
||||||
|
|
||||||
|
if "sm_api_error" in smmry:
|
||||||
|
if smmry["sm_api_error"] == 0:
|
||||||
|
title = "Internal server problem (not your fault)"
|
||||||
|
elif smmry["sm_api_error"] == 1:
|
||||||
|
title = "Incorrect submission variables"
|
||||||
|
elif smmry["sm_api_error"] == 2:
|
||||||
|
title = "Intentional restriction (low credits?)"
|
||||||
|
elif smmry["sm_api_error"] == 3:
|
||||||
|
title = "Summarization error"
|
||||||
|
else:
|
||||||
|
title = "Unknown error"
|
||||||
|
raise IMException(title + ": " + smmry['sm_api_message'].lower())
|
||||||
|
|
||||||
|
if "keywords" in msg.kwargs:
|
||||||
|
smmry["sm_api_content"] = ", ".join(smmry["sm_api_keyword_array"])
|
||||||
|
|
||||||
|
if "sm_api_title" in smmry and smmry["sm_api_title"] != "":
|
||||||
|
res.append_message(smmry["sm_api_content"], title=smmry["sm_api_title"])
|
||||||
|
else:
|
||||||
|
res.append_message(smmry["sm_api_content"])
|
||||||
|
|
||||||
|
return res
|
||||||
110
modules/sms.py
110
modules/sms.py
|
|
@ -16,7 +16,7 @@ from nemubot.tools.xmlparser.node import ModuleState
|
||||||
|
|
||||||
nemubotversion = 3.4
|
nemubotversion = 3.4
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
def load(context):
|
def load(context):
|
||||||
context.data.setIndex("name", "phone")
|
context.data.setIndex("name", "phone")
|
||||||
|
|
@ -46,47 +46,89 @@ def send_sms(frm, api_usr, api_key, content):
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def check_sms_dests(dests, cur_epoch):
|
||||||
|
"""Raise exception if one of the dest is not known or has already receive a SMS recently
|
||||||
|
"""
|
||||||
|
for u in dests:
|
||||||
|
if u not in context.data.index:
|
||||||
|
raise IMException("Désolé, je sais pas comment envoyer de SMS à %s." % u)
|
||||||
|
elif cur_epoch - float(context.data.index[u]["lastuse"]) < 42:
|
||||||
|
raise IMException("Un peu de calme, %s a déjà reçu un SMS il n'y a pas si longtemps." % u)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def send_sms_to_list(msg, frm, dests, content, cur_epoch):
|
||||||
|
fails = list()
|
||||||
|
for u in dests:
|
||||||
|
context.data.index[u]["lastuse"] = cur_epoch
|
||||||
|
test = send_sms(frm, context.data.index[u]["user"], context.data.index[u]["key"], content)
|
||||||
|
if test is not None:
|
||||||
|
fails.append( "%s: %s" % (u, test) )
|
||||||
|
|
||||||
|
if len(fails) > 0:
|
||||||
|
return Response("quelque chose ne s'est pas bien passé durant l'envoi du SMS : " + ", ".join(fails), msg.channel, msg.frm)
|
||||||
|
else:
|
||||||
|
return Response("le SMS a bien été envoyé", msg.channel, msg.frm)
|
||||||
|
|
||||||
|
|
||||||
@hook.command("sms")
|
@hook.command("sms")
|
||||||
def cmd_sms(msg):
|
def cmd_sms(msg):
|
||||||
if not len(msg.args):
|
if not len(msg.args):
|
||||||
raise IMException("À qui veux-tu envoyer ce SMS ?")
|
raise IMException("À qui veux-tu envoyer ce SMS ?")
|
||||||
|
|
||||||
# Check dests
|
cur_epoch = time.mktime(time.localtime())
|
||||||
cur_epoch = time.mktime(time.localtime());
|
dests = msg.args[0].split(",")
|
||||||
for u in msg.args[0].split(","):
|
frm = msg.frm if msg.to_response[0] == msg.frm else msg.frm + "@" + msg.to[0]
|
||||||
if u not in context.data.index:
|
content = " ".join(msg.args[1:])
|
||||||
raise IMException("Désolé, je sais pas comment envoyer de SMS à %s." % u)
|
|
||||||
elif cur_epoch - float(context.data.index[u]["lastuse"]) < 42:
|
|
||||||
raise IMException("Un peu de calme, %s a déjà reçu un SMS il n'y a pas si longtemps." % u)
|
|
||||||
|
|
||||||
# Go!
|
check_sms_dests(dests, cur_epoch)
|
||||||
fails = list()
|
return send_sms_to_list(msg, frm, dests, content, cur_epoch)
|
||||||
for u in msg.args[0].split(","):
|
|
||||||
context.data.index[u]["lastuse"] = cur_epoch
|
|
||||||
if msg.to_response[0] == msg.frm:
|
@hook.command("smscmd")
|
||||||
frm = msg.frm
|
def cmd_smscmd(msg):
|
||||||
else:
|
if not len(msg.args):
|
||||||
frm = msg.frm + "@" + msg.to[0]
|
raise IMException("À qui veux-tu envoyer ce SMS ?")
|
||||||
test = send_sms(frm, context.data.index[u]["user"], context.data.index[u]["key"], " ".join(msg.args[1:]))
|
|
||||||
if test is not None:
|
cur_epoch = time.mktime(time.localtime())
|
||||||
fails.append( "%s: %s" % (u, test) )
|
dests = msg.args[0].split(",")
|
||||||
|
frm = msg.frm if msg.to_response[0] == msg.frm else msg.frm + "@" + msg.to[0]
|
||||||
|
cmd = " ".join(msg.args[1:])
|
||||||
|
|
||||||
|
content = None
|
||||||
|
for r in context.subtreat(context.subparse(msg, cmd)):
|
||||||
|
if isinstance(r, Response):
|
||||||
|
for m in r.messages:
|
||||||
|
if isinstance(m, list):
|
||||||
|
for n in m:
|
||||||
|
content = n
|
||||||
|
break
|
||||||
|
if content is not None:
|
||||||
|
break
|
||||||
|
elif isinstance(m, str):
|
||||||
|
content = m
|
||||||
|
break
|
||||||
|
|
||||||
|
elif isinstance(r, Text):
|
||||||
|
content = r.message
|
||||||
|
|
||||||
|
if content is None:
|
||||||
|
raise IMException("Aucun SMS envoyé : le résultat de la commande n'a pas retourné de contenu.")
|
||||||
|
|
||||||
|
check_sms_dests(dests, cur_epoch)
|
||||||
|
return send_sms_to_list(msg, frm, dests, content, cur_epoch)
|
||||||
|
|
||||||
if len(fails) > 0:
|
|
||||||
return Response("quelque chose ne s'est pas bien passé durant l'envoi du SMS : " + ", ".join(fails), msg.channel, msg.nick)
|
|
||||||
else:
|
|
||||||
return Response("le SMS a bien été envoyé", msg.channel, msg.nick)
|
|
||||||
|
|
||||||
apiuser_ask = re.compile(r"(utilisateur|user|numéro|numero|compte|abonne|abone|abonné|account)\s+(est|is)\s+(?P<user>[0-9]{7,})", re.IGNORECASE)
|
apiuser_ask = re.compile(r"(utilisateur|user|numéro|numero|compte|abonne|abone|abonné|account)\s+(est|is)\s+(?P<user>[0-9]{7,})", re.IGNORECASE)
|
||||||
apikey_ask = re.compile(r"(clef|key|password|mot de passe?)\s+(?:est|is)?\s+(?P<key>[a-zA-Z0-9]{10,})", re.IGNORECASE)
|
apikey_ask = re.compile(r"(clef|key|password|mot de passe?)\s+(?:est|is)?\s+(?P<key>[a-zA-Z0-9]{10,})", re.IGNORECASE)
|
||||||
|
|
||||||
@hook.ask()
|
@hook.ask()
|
||||||
def parseask(msg):
|
def parseask(msg):
|
||||||
if msg.text.find("Free") >= 0 and (
|
if msg.message.find("Free") >= 0 and (
|
||||||
msg.text.find("API") >= 0 or msg.text.find("api") >= 0) and (
|
msg.message.find("API") >= 0 or msg.message.find("api") >= 0) and (
|
||||||
msg.text.find("SMS") >= 0 or msg.text.find("sms") >= 0):
|
msg.message.find("SMS") >= 0 or msg.message.find("sms") >= 0):
|
||||||
resuser = apiuser_ask.search(msg.text)
|
resuser = apiuser_ask.search(msg.message)
|
||||||
reskey = apikey_ask.search(msg.text)
|
reskey = apikey_ask.search(msg.message)
|
||||||
if resuser is not None and reskey is not None:
|
if resuser is not None and reskey is not None:
|
||||||
apiuser = resuser.group("user")
|
apiuser = resuser.group("user")
|
||||||
apikey = reskey.group("key")
|
apikey = reskey.group("key")
|
||||||
|
|
@ -94,18 +136,18 @@ def parseask(msg):
|
||||||
test = send_sms("nemubot", apiuser, apikey,
|
test = send_sms("nemubot", apiuser, apikey,
|
||||||
"Vous avez enregistré vos codes d'authentification dans nemubot, félicitation !")
|
"Vous avez enregistré vos codes d'authentification dans nemubot, félicitation !")
|
||||||
if test is not None:
|
if test is not None:
|
||||||
return Response("je n'ai pas pu enregistrer tes identifiants : %s" % test, msg.channel, msg.nick)
|
return Response("je n'ai pas pu enregistrer tes identifiants : %s" % test, msg.channel, msg.frm)
|
||||||
|
|
||||||
if msg.nick in context.data.index:
|
if msg.frm in context.data.index:
|
||||||
context.data.index[msg.nick]["user"] = apiuser
|
context.data.index[msg.frm]["user"] = apiuser
|
||||||
context.data.index[msg.nick]["key"] = apikey
|
context.data.index[msg.frm]["key"] = apikey
|
||||||
else:
|
else:
|
||||||
ms = ModuleState("phone")
|
ms = ModuleState("phone")
|
||||||
ms.setAttribute("name", msg.nick)
|
ms.setAttribute("name", msg.frm)
|
||||||
ms.setAttribute("user", apiuser)
|
ms.setAttribute("user", apiuser)
|
||||||
ms.setAttribute("key", apikey)
|
ms.setAttribute("key", apikey)
|
||||||
ms.setAttribute("lastuse", 0)
|
ms.setAttribute("lastuse", 0)
|
||||||
context.data.addChild(ms)
|
context.data.addChild(ms)
|
||||||
context.save()
|
context.save()
|
||||||
return Response("ok, c'est noté. Je t'ai envoyé un SMS pour tester ;)",
|
return Response("ok, c'est noté. Je t'ai envoyé un SMS pour tester ;)",
|
||||||
msg.channel, msg.nick)
|
msg.channel, msg.frm)
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ from nemubot.tools.xmlparser.node import ModuleState
|
||||||
from .pyaspell import Aspell
|
from .pyaspell import Aspell
|
||||||
from .pyaspell import AspellError
|
from .pyaspell import AspellError
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# LOADING #############################################################
|
# LOADING #############################################################
|
||||||
|
|
@ -64,15 +64,15 @@ def cmd_spell(msg):
|
||||||
raise IMException("Je n'ai pas le dictionnaire `%s' :(" % lang)
|
raise IMException("Je n'ai pas le dictionnaire `%s' :(" % lang)
|
||||||
|
|
||||||
if r == True:
|
if r == True:
|
||||||
add_score(msg.nick, "correct")
|
add_score(msg.frm, "correct")
|
||||||
res.append_message("l'orthographe de `%s' est correcte" % word)
|
res.append_message("l'orthographe de `%s' est correcte" % word)
|
||||||
|
|
||||||
elif len(r) > 0:
|
elif len(r) > 0:
|
||||||
add_score(msg.nick, "bad")
|
add_score(msg.frm, "bad")
|
||||||
res.append_message(r, title="suggestions pour `%s'" % word)
|
res.append_message(r, title="suggestions pour `%s'" % word)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
add_score(msg.nick, "bad")
|
add_score(msg.frm, "bad")
|
||||||
res.append_message("aucune suggestion pour `%s'" % word)
|
res.append_message("aucune suggestion pour `%s'" % word)
|
||||||
|
|
||||||
return res
|
return res
|
||||||
|
|
|
||||||
|
|
@ -9,15 +9,15 @@ import re
|
||||||
|
|
||||||
from nemubot.hooks import hook
|
from nemubot.hooks import hook
|
||||||
from nemubot.exception import IMException
|
from nemubot.exception import IMException
|
||||||
from nemubot.tools.web import getURLContent, getJSON
|
from nemubot.tools.web import getURLContent, getURLHeaders, getJSON
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# POSTAGE SERVICE PARSERS ############################################
|
# POSTAGE SERVICE PARSERS ############################################
|
||||||
|
|
||||||
def get_tnt_info(track_id):
|
def get_tnt_info(track_id):
|
||||||
values = []
|
values = []
|
||||||
data = getURLContent('www.tnt.fr/public/suivi_colis/recherche/visubontransport.do?bonTransport=%s' % track_id)
|
data = getURLContent('https://www.tnt.fr/public/suivi_colis/recherche/visubontransport.do?bonTransport=%s' % track_id)
|
||||||
soup = BeautifulSoup(data)
|
soup = BeautifulSoup(data)
|
||||||
status_list = soup.find('div', class_='result__content')
|
status_list = soup.find('div', class_='result__content')
|
||||||
if not status_list:
|
if not status_list:
|
||||||
|
|
@ -31,21 +31,22 @@ def get_tnt_info(track_id):
|
||||||
|
|
||||||
|
|
||||||
def get_colissimo_info(colissimo_id):
|
def get_colissimo_info(colissimo_id):
|
||||||
colissimo_data = getURLContent("http://www.colissimo.fr/portail_colissimo/suivre.do?colispart=%s" % colissimo_id)
|
colissimo_data = getURLContent("https://www.laposte.fr/particulier/outils/suivre-vos-envois?code=%s" % colissimo_id)
|
||||||
soup = BeautifulSoup(colissimo_data)
|
soup = BeautifulSoup(colissimo_data)
|
||||||
|
|
||||||
dataArray = soup.find(class_='dataArray')
|
dataArray = soup.find(class_='results-suivi')
|
||||||
if dataArray and dataArray.tbody and dataArray.tbody.tr:
|
if dataArray and dataArray.table and dataArray.table.tbody and dataArray.table.tbody.tr:
|
||||||
date = dataArray.tbody.tr.find(headers="Date").get_text()
|
td = dataArray.table.tbody.tr.find_all('td')
|
||||||
libelle = re.sub(r'[\n\t\r]', '',
|
if len(td) > 2:
|
||||||
dataArray.tbody.tr.find(headers="Libelle").get_text())
|
date = td[0].get_text()
|
||||||
site = dataArray.tbody.tr.find(headers="site").get_text().strip()
|
libelle = re.sub(r'[\n\t\r]', '', td[1].get_text())
|
||||||
return (date, libelle, site.strip())
|
site = td[2].get_text().strip()
|
||||||
|
return (date, libelle, site.strip())
|
||||||
|
|
||||||
|
|
||||||
def get_chronopost_info(track_id):
|
def get_chronopost_info(track_id):
|
||||||
data = urllib.parse.urlencode({'listeNumeros': track_id})
|
data = urllib.parse.urlencode({'listeNumeros': track_id})
|
||||||
track_baseurl = "http://www.chronopost.fr/expedier/inputLTNumbersNoJahia.do?lang=fr_FR"
|
track_baseurl = "https://www.chronopost.fr/expedier/inputLTNumbersNoJahia.do?lang=fr_FR"
|
||||||
track_data = getURLContent(track_baseurl, data.encode('utf-8'))
|
track_data = getURLContent(track_baseurl, data.encode('utf-8'))
|
||||||
soup = BeautifulSoup(track_data)
|
soup = BeautifulSoup(track_data)
|
||||||
|
|
||||||
|
|
@ -74,33 +75,29 @@ def get_colisprive_info(track_id):
|
||||||
return status
|
return status
|
||||||
|
|
||||||
|
|
||||||
|
def get_ups_info(track_id):
|
||||||
|
data = json.dumps({'Locale': "en_US", 'TrackingNumber': [track_id]})
|
||||||
|
track_baseurl = "https://www.ups.com/track/api/Track/GetStatus?loc=en_US"
|
||||||
|
track_data = getJSON(track_baseurl, data.encode('utf-8'), header={"Content-Type": "application/json"})
|
||||||
|
return (track_data["trackDetails"][0]["trackingNumber"],
|
||||||
|
track_data["trackDetails"][0]["packageStatus"],
|
||||||
|
track_data["trackDetails"][0]["shipmentProgressActivities"][0]["date"] + " " + track_data["trackDetails"][0]["shipmentProgressActivities"][0]["time"],
|
||||||
|
track_data["trackDetails"][0]["shipmentProgressActivities"][0]["location"],
|
||||||
|
track_data["trackDetails"][0]["shipmentProgressActivities"][0]["activityScan"])
|
||||||
|
|
||||||
|
|
||||||
def get_laposte_info(laposte_id):
|
def get_laposte_info(laposte_id):
|
||||||
data = urllib.parse.urlencode({'id': laposte_id})
|
status, laposte_headers = getURLHeaders("https://www.laposte.fr/outils/suivre-vos-envois?" + urllib.parse.urlencode({'code': laposte_id}))
|
||||||
laposte_baseurl = "http://www.part.csuivi.courrier.laposte.fr/suivi/index"
|
|
||||||
|
|
||||||
laposte_data = getURLContent(laposte_baseurl, data.encode('utf-8'))
|
laposte_cookie = None
|
||||||
soup = BeautifulSoup(laposte_data)
|
for k,v in laposte_headers:
|
||||||
search_res = soup.find(class_='resultat_rech_simple_table').tbody.tr
|
if k.lower() == "set-cookie" and v.find("access_token") >= 0:
|
||||||
if (soup.find(class_='resultat_rech_simple_table').thead
|
laposte_cookie = v.split(";")[0]
|
||||||
and soup.find(class_='resultat_rech_simple_table').thead.tr
|
|
||||||
and len(search_res.find_all('td')) > 3):
|
|
||||||
field = search_res.find('td')
|
|
||||||
poste_id = field.get_text()
|
|
||||||
|
|
||||||
field = field.find_next('td')
|
laposte_data = getJSON("https://api.laposte.fr/ssu/v1/suivi-unifie/idship/%s?lang=fr_FR" % urllib.parse.quote(laposte_id), header={"Accept": "application/json", "Cookie": laposte_cookie})
|
||||||
poste_type = field.get_text()
|
|
||||||
|
|
||||||
field = field.find_next('td')
|
shipment = laposte_data["shipment"]
|
||||||
poste_date = field.get_text()
|
return (shipment["product"], shipment["idShip"], shipment["event"][0]["label"], shipment["event"][0]["date"])
|
||||||
|
|
||||||
field = field.find_next('td')
|
|
||||||
poste_location = field.get_text()
|
|
||||||
|
|
||||||
field = field.find_next('td')
|
|
||||||
poste_status = field.get_text()
|
|
||||||
|
|
||||||
return (poste_type.lower(), poste_id.strip(), poste_status.lower(),
|
|
||||||
poste_location, poste_date)
|
|
||||||
|
|
||||||
|
|
||||||
def get_postnl_info(postnl_id):
|
def get_postnl_info(postnl_id):
|
||||||
|
|
@ -131,7 +128,7 @@ def get_usps_info(usps_id):
|
||||||
|
|
||||||
usps_data = getURLContent(usps_parcelurl)
|
usps_data = getURLContent(usps_parcelurl)
|
||||||
soup = BeautifulSoup(usps_data)
|
soup = BeautifulSoup(usps_data)
|
||||||
if (soup.find(class_="tracking_history")
|
if (soup.find(id="trackingHistory_1")
|
||||||
and soup.find(class_="tracking_history").find(class_="row_notification")
|
and soup.find(class_="tracking_history").find(class_="row_notification")
|
||||||
and soup.find(class_="tracking_history").find(class_="row_top").find_all("td")):
|
and soup.find(class_="tracking_history").find(class_="row_top").find_all("td")):
|
||||||
notification = soup.find(class_="tracking_history").find(class_="row_notification").text.strip()
|
notification = soup.find(class_="tracking_history").find(class_="row_notification").text.strip()
|
||||||
|
|
@ -175,7 +172,8 @@ def get_fedex_info(fedex_id, lang="en_US"):
|
||||||
if ("TrackPackagesResponse" in fedex_data and
|
if ("TrackPackagesResponse" in fedex_data and
|
||||||
"packageList" in fedex_data["TrackPackagesResponse"] and
|
"packageList" in fedex_data["TrackPackagesResponse"] and
|
||||||
len(fedex_data["TrackPackagesResponse"]["packageList"]) and
|
len(fedex_data["TrackPackagesResponse"]["packageList"]) and
|
||||||
not fedex_data["TrackPackagesResponse"]["errorList"][0]["code"] and
|
(not fedex_data["TrackPackagesResponse"]["errorList"][0]["code"] or
|
||||||
|
fedex_data["TrackPackagesResponse"]["errorList"][0]["code"] == '0') and
|
||||||
not fedex_data["TrackPackagesResponse"]["packageList"][0]["errorList"][0]["code"]
|
not fedex_data["TrackPackagesResponse"]["packageList"][0]["errorList"][0]["code"]
|
||||||
):
|
):
|
||||||
return fedex_data["TrackPackagesResponse"]["packageList"][0]
|
return fedex_data["TrackPackagesResponse"]["packageList"][0]
|
||||||
|
|
@ -208,11 +206,10 @@ def handle_tnt(tracknum):
|
||||||
def handle_laposte(tracknum):
|
def handle_laposte(tracknum):
|
||||||
info = get_laposte_info(tracknum)
|
info = get_laposte_info(tracknum)
|
||||||
if info:
|
if info:
|
||||||
poste_type, poste_id, poste_status, poste_location, poste_date = info
|
poste_type, poste_id, poste_status, poste_date = info
|
||||||
return ("Le courrier de type \x02%s\x0F : \x02%s\x0F est actuellement "
|
return ("\x02%s\x0F : \x02%s\x0F est actuellement "
|
||||||
"\x02%s\x0F dans la zone \x02%s\x0F (Mis à jour le \x02%s\x0F"
|
"\x02%s\x0F (Mis à jour le \x02%s\x0F"
|
||||||
")." % (poste_type, poste_id, poste_status,
|
")." % (poste_type, poste_id, poste_status, poste_date))
|
||||||
poste_location, poste_date))
|
|
||||||
|
|
||||||
|
|
||||||
def handle_postnl(tracknum):
|
def handle_postnl(tracknum):
|
||||||
|
|
@ -228,7 +225,14 @@ def handle_usps(tracknum):
|
||||||
info = get_usps_info(tracknum)
|
info = get_usps_info(tracknum)
|
||||||
if info:
|
if info:
|
||||||
notif, last_date, last_status, last_location = info
|
notif, last_date, last_status, last_location = info
|
||||||
return ("USPS \x02{tracknum}\x0F is {last_status} in \x02{last_location}\x0F as of {last_date}: {notif}".format(tracknum=tracknum, notif=notif, last_date=last_date, last_status=last_status.lower(), last_location=last_location))
|
return ("USPS \x02{tracknum}\x0F: {last_status} in \x02{last_location}\x0F as of {last_date}: {notif}".format(tracknum=tracknum, notif=notif, last_date=last_date, last_status=last_status.lower(), last_location=last_location))
|
||||||
|
|
||||||
|
|
||||||
|
def handle_ups(tracknum):
|
||||||
|
info = get_ups_info(tracknum)
|
||||||
|
if info:
|
||||||
|
tracknum, status, last_date, last_location, last_status = info
|
||||||
|
return ("UPS \x02{tracknum}\x0F: {status}: in \x02{last_location}\x0F as of {last_date}: {last_status}".format(tracknum=tracknum, status=status, last_date=last_date, last_status=last_status.lower(), last_location=last_location))
|
||||||
|
|
||||||
|
|
||||||
def handle_colissimo(tracknum):
|
def handle_colissimo(tracknum):
|
||||||
|
|
@ -281,6 +285,7 @@ TRACKING_HANDLERS = {
|
||||||
'fedex': handle_fedex,
|
'fedex': handle_fedex,
|
||||||
'dhl': handle_dhl,
|
'dhl': handle_dhl,
|
||||||
'usps': handle_usps,
|
'usps': handle_usps,
|
||||||
|
'ups': handle_ups,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ 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 more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# LOADING #############################################################
|
# LOADING #############################################################
|
||||||
|
|
@ -29,7 +29,7 @@ def load(context):
|
||||||
# MODULE CORE #########################################################
|
# MODULE CORE #########################################################
|
||||||
|
|
||||||
def get_french_synos(word):
|
def get_french_synos(word):
|
||||||
url = "http://www.crisco.unicaen.fr/des/synonymes/" + quote(word)
|
url = "https://crisco.unicaen.fr/des/synonymes/" + quote(word)
|
||||||
page = web.getURLContent(url)
|
page = web.getURLContent(url)
|
||||||
|
|
||||||
best = list(); synos = list(); anton = list()
|
best = list(); synos = list(); anton = list()
|
||||||
|
|
@ -53,7 +53,7 @@ def get_french_synos(word):
|
||||||
|
|
||||||
|
|
||||||
def get_english_synos(key, word):
|
def get_english_synos(key, word):
|
||||||
cnt = web.getJSON("http://words.bighugelabs.com/api/2/%s/%s/json" %
|
cnt = web.getJSON("https://words.bighugelabs.com/api/2/%s/%s/json" %
|
||||||
(quote(key), quote(word.encode("ISO-8859-1"))))
|
(quote(key), quote(word.encode("ISO-8859-1"))))
|
||||||
|
|
||||||
best = list(); synos = list(); anton = list()
|
best = list(); synos = list(); anton = list()
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ from nemubot.tools.web import getJSON
|
||||||
|
|
||||||
nemubotversion = 4.0
|
nemubotversion = 4.0
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
URL_TPBAPI = None
|
URL_TPBAPI = None
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ 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 more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# GLOBALS #############################################################
|
# GLOBALS #############################################################
|
||||||
|
|
|
||||||
|
|
@ -8,13 +8,13 @@ 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 more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
# MODULE CORE #########################################################
|
# MODULE CORE #########################################################
|
||||||
|
|
||||||
def search(terms):
|
def search(terms):
|
||||||
return web.getJSON(
|
return web.getJSON(
|
||||||
"http://api.urbandictionary.com/v0/define?term=%s"
|
"https://api.urbandictionary.com/v0/define?term=%s"
|
||||||
% quote(' '.join(terms)))
|
% quote(' '.join(terms)))
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ def default_reducer(url, data):
|
||||||
|
|
||||||
|
|
||||||
def ycc_reducer(url, data):
|
def ycc_reducer(url, data):
|
||||||
return "http://ycc.fr/%s" % default_reducer(url, data)
|
return "https://ycc.fr/%s" % default_reducer(url, data)
|
||||||
|
|
||||||
def lstu_reducer(url, data):
|
def lstu_reducer(url, data):
|
||||||
json_data = json.loads(web.getURLContent(url, "lsturl=" + quote(data),
|
json_data = json.loads(web.getURLContent(url, "lsturl=" + quote(data),
|
||||||
|
|
@ -36,8 +36,8 @@ def lstu_reducer(url, data):
|
||||||
# MODULE VARIABLES ####################################################
|
# MODULE VARIABLES ####################################################
|
||||||
|
|
||||||
PROVIDERS = {
|
PROVIDERS = {
|
||||||
"tinyurl": (default_reducer, "http://tinyurl.com/api-create.php?url="),
|
"tinyurl": (default_reducer, "https://tinyurl.com/api-create.php?url="),
|
||||||
"ycc": (ycc_reducer, "http://ycc.fr/redirection/create/"),
|
"ycc": (ycc_reducer, "https://ycc.fr/redirection/create/"),
|
||||||
"framalink": (lstu_reducer, "https://frama.link/a?format=json"),
|
"framalink": (lstu_reducer, "https://frama.link/a?format=json"),
|
||||||
"huitre": (lstu_reducer, "https://huit.re/a?format=json"),
|
"huitre": (lstu_reducer, "https://huit.re/a?format=json"),
|
||||||
"lstu": (lstu_reducer, "https://lstu.fr/a?format=json"),
|
"lstu": (lstu_reducer, "https://lstu.fr/a?format=json"),
|
||||||
|
|
@ -60,12 +60,20 @@ def load(context):
|
||||||
|
|
||||||
# MODULE CORE #########################################################
|
# MODULE CORE #########################################################
|
||||||
|
|
||||||
def reduce(url, provider=DEFAULT_PROVIDER):
|
def reduce_inline(txt, provider=None):
|
||||||
|
for url in re.findall("([a-zA-Z0-9+.-]+:(?://)?(?:[^ :/]+:[0-9]+)?[^ :]+)", txt):
|
||||||
|
txt = txt.replace(url, reduce(url, provider))
|
||||||
|
return txt
|
||||||
|
|
||||||
|
|
||||||
|
def reduce(url, provider=None):
|
||||||
"""Ask the url shortner website to reduce given URL
|
"""Ask the url shortner website to reduce given URL
|
||||||
|
|
||||||
Argument:
|
Argument:
|
||||||
url -- the URL to reduce
|
url -- the URL to reduce
|
||||||
"""
|
"""
|
||||||
|
if provider is None:
|
||||||
|
provider = DEFAULT_PROVIDER
|
||||||
return PROVIDERS[provider][0](PROVIDERS[provider][1], url)
|
return PROVIDERS[provider][0](PROVIDERS[provider][1], url)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -84,8 +92,22 @@ LAST_URLS = dict()
|
||||||
|
|
||||||
@hook.message()
|
@hook.message()
|
||||||
def parselisten(msg):
|
def parselisten(msg):
|
||||||
parseresponse(msg)
|
global LAST_URLS
|
||||||
return None
|
if hasattr(msg, "message") and isinstance(msg.message, str):
|
||||||
|
urls = re.findall("([a-zA-Z0-9+.-]+:(?://)?(?:[^ :/]+:[0-9]+)?[^ :]+)",
|
||||||
|
msg.message)
|
||||||
|
for url in urls:
|
||||||
|
o = urlparse(web._getNormalizedURL(url), "http")
|
||||||
|
|
||||||
|
# Skip short URLs
|
||||||
|
if (o.netloc == "" or o.netloc in PROVIDERS or
|
||||||
|
len(o.netloc) + len(o.path) < 17):
|
||||||
|
continue
|
||||||
|
|
||||||
|
for recv in msg.to:
|
||||||
|
if recv not in LAST_URLS:
|
||||||
|
LAST_URLS[recv] = list()
|
||||||
|
LAST_URLS[recv].append(url)
|
||||||
|
|
||||||
|
|
||||||
@hook.post()
|
@hook.post()
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ 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 more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# LOADING #############################################################
|
# LOADING #############################################################
|
||||||
|
|
|
||||||
|
|
@ -10,12 +10,12 @@ 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 more import Response
|
from nemubot.module.more import Response
|
||||||
import mapquest
|
from nemubot.module import mapquest
|
||||||
|
|
||||||
# GLOBALS #############################################################
|
# GLOBALS #############################################################
|
||||||
|
|
||||||
URL_API = "http://public-api.adsbexchange.com/VirtualRadar/AircraftList.json?fcallC=%s"
|
URL_API = "https://public-api.adsbexchange.com/VirtualRadar/AircraftList.json?fcallC=%s"
|
||||||
|
|
||||||
SPEED_TYPES = {
|
SPEED_TYPES = {
|
||||||
0: 'Ground speed',
|
0: 'Ground speed',
|
||||||
|
|
@ -80,7 +80,7 @@ def cmd_flight(msg):
|
||||||
if not len(msg.args):
|
if not len(msg.args):
|
||||||
raise IMException("please indicate a flight")
|
raise IMException("please indicate a flight")
|
||||||
|
|
||||||
res = Response(channel=msg.channel, nick=msg.nick,
|
res = Response(channel=msg.channel, nick=msg.frm,
|
||||||
nomore="No more flights", count=" (%s more flights)")
|
nomore="No more flights", count=" (%s more flights)")
|
||||||
|
|
||||||
for param in msg.args:
|
for param in msg.args:
|
||||||
|
|
|
||||||
|
|
@ -11,33 +11,71 @@ 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
|
||||||
|
|
||||||
import mapquest
|
from nemubot.module import mapquest
|
||||||
|
|
||||||
nemubotversion = 4.0
|
nemubotversion = 4.0
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
URL_DSAPI = "https://api.darksky.net/forecast/%s/%%s,%%s?lang=%%s&units=%%s"
|
URL_DSAPI = "https://api.darksky.net/forecast/%s/%%s,%%s?lang=%%s&units=%%s"
|
||||||
|
|
||||||
|
UNITS = {
|
||||||
|
"ca": {
|
||||||
|
"temperature": "°C",
|
||||||
|
"distance": "km",
|
||||||
|
"precipIntensity": "mm/h",
|
||||||
|
"precip": "cm",
|
||||||
|
"speed": "km/h",
|
||||||
|
"pressure": "hPa",
|
||||||
|
},
|
||||||
|
"uk2": {
|
||||||
|
"temperature": "°C",
|
||||||
|
"distance": "mi",
|
||||||
|
"precipIntensity": "mm/h",
|
||||||
|
"precip": "cm",
|
||||||
|
"speed": "mi/h",
|
||||||
|
"pressure": "hPa",
|
||||||
|
},
|
||||||
|
"us": {
|
||||||
|
"temperature": "°F",
|
||||||
|
"distance": "mi",
|
||||||
|
"precipIntensity": "in/h",
|
||||||
|
"precip": "in",
|
||||||
|
"speed": "mi/h",
|
||||||
|
"pressure": "mbar",
|
||||||
|
},
|
||||||
|
"si": {
|
||||||
|
"temperature": "°C",
|
||||||
|
"distance": "km",
|
||||||
|
"precipIntensity": "mm/h",
|
||||||
|
"precip": "cm",
|
||||||
|
"speed": "m/s",
|
||||||
|
"pressure": "hPa",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
def load(context):
|
def load(context):
|
||||||
if not context.config or "darkskyapikey" not in context.config:
|
if not context.config or "darkskyapikey" not in context.config:
|
||||||
raise ImportError("You need a Dark-Sky API key in order to use this "
|
raise ImportError("You need a Dark-Sky API key in order to use this "
|
||||||
"module. Add it to the module configuration file:\n"
|
"module. Add it to the module configuration file:\n"
|
||||||
"<module name=\"weather\" darkskyapikey=\"XXX\" />\n"
|
"<module name=\"weather\" darkskyapikey=\"XXX\" />\n"
|
||||||
"Register at http://developer.forecast.io/")
|
"Register at https://developer.forecast.io/")
|
||||||
context.data.setIndex("name", "city")
|
context.data.setIndex("name", "city")
|
||||||
global URL_DSAPI
|
global URL_DSAPI
|
||||||
URL_DSAPI = URL_DSAPI % context.config["darkskyapikey"]
|
URL_DSAPI = URL_DSAPI % context.config["darkskyapikey"]
|
||||||
|
|
||||||
|
|
||||||
def format_wth(wth):
|
def format_wth(wth, flags):
|
||||||
return ("{temperature} °C {summary}; precipitation ({precipProbability:.0%} chance) intensity: {precipIntensity} mm/h; relative humidity: {humidity:.0%}; wind speed: {windSpeed} km/s {windBearing}°; cloud coverage: {cloudCover:.0%}; pressure: {pressure} hPa; ozone: {ozone} DU"
|
units = UNITS[flags["units"] if "units" in flags and flags["units"] in UNITS else "si"]
|
||||||
.format(**wth)
|
return ("{temperature} {units[temperature]} {summary}; precipitation ({precipProbability:.0%} chance) intensity: {precipIntensity} {units[precipIntensity]}; relative humidity: {humidity:.0%}; wind speed: {windSpeed} {units[speed]} {windBearing}°; cloud coverage: {cloudCover:.0%}; pressure: {pressure} {units[pressure]}; ozone: {ozone} DU"
|
||||||
|
.format(units=units, **wth)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def format_forecast_daily(wth):
|
def format_forecast_daily(wth, flags):
|
||||||
return ("{summary}; between {temperatureMin}-{temperatureMax} °C; precipitation ({precipProbability:.0%} chance) intensity: maximum {precipIntensity} mm/h; relative humidity: {humidity:.0%}; wind speed: {windSpeed} km/h {windBearing}°; cloud coverage: {cloudCover:.0%}; pressure: {pressure} hPa; ozone: {ozone} DU".format(**wth))
|
units = UNITS[flags["units"] if "units" in flags and flags["units"] in UNITS else "si"]
|
||||||
|
print(units)
|
||||||
|
return ("{summary}; between {temperatureMin}-{temperatureMax} {units[temperature]}; precipitation ({precipProbability:.0%} chance) intensity: maximum {precipIntensity} {units[precipIntensity]}; relative humidity: {humidity:.0%}; wind speed: {windSpeed} {units[speed]} {windBearing}°; cloud coverage: {cloudCover:.0%}; pressure: {pressure} {units[pressure]}; ozone: {ozone} DU".format(units=units, **wth))
|
||||||
|
|
||||||
|
|
||||||
def format_timestamp(timestamp, tzname, tzoffset, format="%c"):
|
def format_timestamp(timestamp, tzname, tzoffset, format="%c"):
|
||||||
|
|
@ -88,7 +126,7 @@ def treat_coord(msg):
|
||||||
raise IMException("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, lang="en", units="auto"):
|
def get_json_weather(coords, lang="en", units="ca"):
|
||||||
wth = web.getJSON(URL_DSAPI % (float(coords[0]), float(coords[1]), lang, units))
|
wth = web.getJSON(URL_DSAPI % (float(coords[0]), float(coords[1]), lang, units))
|
||||||
|
|
||||||
# First read flags
|
# First read flags
|
||||||
|
|
@ -114,13 +152,13 @@ def cmd_coordinates(msg):
|
||||||
@hook.command("alert",
|
@hook.command("alert",
|
||||||
keywords={
|
keywords={
|
||||||
"lang=LANG": "change the output language of weather sumarry; default: en",
|
"lang=LANG": "change the output language of weather sumarry; default: en",
|
||||||
"units=UNITS": "return weather conditions in the requested units; default: auto",
|
"units=UNITS": "return weather conditions in the requested units; default: ca",
|
||||||
})
|
})
|
||||||
def cmd_alert(msg):
|
def cmd_alert(msg):
|
||||||
loc, coords, specific = treat_coord(msg)
|
loc, coords, specific = treat_coord(msg)
|
||||||
wth = get_json_weather(coords,
|
wth = get_json_weather(coords,
|
||||||
lang=msg.kwargs["lang"] if "lang" in msg.kwargs else "en",
|
lang=msg.kwargs["lang"] if "lang" in msg.kwargs else "en",
|
||||||
units=msg.kwargs["units"] if "units" in msg.kwargs else "auto")
|
units=msg.kwargs["units"] if "units" in msg.kwargs else "ca")
|
||||||
|
|
||||||
res = Response(channel=msg.channel, nomore="No more weather alert", count=" (%d more alerts)")
|
res = Response(channel=msg.channel, nomore="No more weather alert", count=" (%d more alerts)")
|
||||||
|
|
||||||
|
|
@ -141,13 +179,13 @@ def cmd_alert(msg):
|
||||||
},
|
},
|
||||||
keywords={
|
keywords={
|
||||||
"lang=LANG": "change the output language of weather sumarry; default: en",
|
"lang=LANG": "change the output language of weather sumarry; default: en",
|
||||||
"units=UNITS": "return weather conditions in the requested units; default: auto",
|
"units=UNITS": "return weather conditions in the requested units; default: ca",
|
||||||
})
|
})
|
||||||
def cmd_weather(msg):
|
def cmd_weather(msg):
|
||||||
loc, coords, specific = treat_coord(msg)
|
loc, coords, specific = treat_coord(msg)
|
||||||
wth = get_json_weather(coords,
|
wth = get_json_weather(coords,
|
||||||
lang=msg.kwargs["lang"] if "lang" in msg.kwargs else "en",
|
lang=msg.kwargs["lang"] if "lang" in msg.kwargs else "en",
|
||||||
units=msg.kwargs["units"] if "units" in msg.kwargs else "auto")
|
units=msg.kwargs["units"] if "units" in msg.kwargs else "ca")
|
||||||
|
|
||||||
res = Response(channel=msg.channel, nomore="No more weather information")
|
res = Response(channel=msg.channel, nomore="No more weather information")
|
||||||
|
|
||||||
|
|
@ -169,17 +207,17 @@ def cmd_weather(msg):
|
||||||
|
|
||||||
if gr.group(2).lower() == "h" and gr1 < len(wth["hourly"]["data"]):
|
if gr.group(2).lower() == "h" and gr1 < len(wth["hourly"]["data"]):
|
||||||
hour = wth["hourly"]["data"][gr1]
|
hour = wth["hourly"]["data"][gr1]
|
||||||
res.append_message("\x03\x02At %sh:\x03\x02 %s" % (format_timestamp(int(hour["time"]), wth["timezone"], wth["offset"], '%H'), format_wth(hour)))
|
res.append_message("\x03\x02At %sh:\x03\x02 %s" % (format_timestamp(int(hour["time"]), wth["timezone"], wth["offset"], '%H'), format_wth(hour, wth["flags"])))
|
||||||
|
|
||||||
elif gr.group(2).lower() == "d" and gr1 < len(wth["daily"]["data"]):
|
elif gr.group(2).lower() == "d" and gr1 < len(wth["daily"]["data"]):
|
||||||
day = wth["daily"]["data"][gr1]
|
day = wth["daily"]["data"][gr1]
|
||||||
res.append_message("\x03\x02On %s:\x03\x02 %s" % (format_timestamp(int(day["time"]), wth["timezone"], wth["offset"], '%A'), format_forecast_daily(day)))
|
res.append_message("\x03\x02On %s:\x03\x02 %s" % (format_timestamp(int(day["time"]), wth["timezone"], wth["offset"], '%A'), format_forecast_daily(day, wth["flags"])))
|
||||||
|
|
||||||
else:
|
else:
|
||||||
res.append_message("I don't understand %s or information is not available" % specific)
|
res.append_message("I don't understand %s or information is not available" % specific)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
res.append_message("\x03\x02Currently:\x03\x02 " + format_wth(wth["currently"]))
|
res.append_message("\x03\x02Currently:\x03\x02 " + format_wth(wth["currently"], wth["flags"]))
|
||||||
|
|
||||||
nextres = "\x03\x02Today:\x03\x02 %s " % wth["daily"]["data"][0]["summary"]
|
nextres = "\x03\x02Today:\x03\x02 %s " % wth["daily"]["data"][0]["summary"]
|
||||||
if "minutely" in wth:
|
if "minutely" in wth:
|
||||||
|
|
@ -189,11 +227,11 @@ def cmd_weather(msg):
|
||||||
|
|
||||||
for hour in wth["hourly"]["data"][1:4]:
|
for hour in wth["hourly"]["data"][1:4]:
|
||||||
res.append_message("\x03\x02At %sh:\x03\x02 %s" % (format_timestamp(int(hour["time"]), wth["timezone"], wth["offset"], '%H'),
|
res.append_message("\x03\x02At %sh:\x03\x02 %s" % (format_timestamp(int(hour["time"]), wth["timezone"], wth["offset"], '%H'),
|
||||||
format_wth(hour)))
|
format_wth(hour, wth["flags"])))
|
||||||
|
|
||||||
for day in wth["daily"]["data"][1:]:
|
for day in wth["daily"]["data"][1:]:
|
||||||
res.append_message("\x03\x02On %s:\x03\x02 %s" % (format_timestamp(int(day["time"]), wth["timezone"], wth["offset"], '%A'),
|
res.append_message("\x03\x02On %s:\x03\x02 %s" % (format_timestamp(int(day["time"]), wth["timezone"], wth["offset"], '%A'),
|
||||||
format_forecast_daily(day)))
|
format_forecast_daily(day, wth["flags"])))
|
||||||
|
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
|
@ -203,7 +241,7 @@ gps_ask = re.compile(r"^\s*(?P<city>.*\w)\s*(?:(?:se|est)\s+(?:trouve|situ[ée]*
|
||||||
|
|
||||||
@hook.ask()
|
@hook.ask()
|
||||||
def parseask(msg):
|
def parseask(msg):
|
||||||
res = gps_ask.match(msg.text)
|
res = gps_ask.match(msg.message)
|
||||||
if res is not None:
|
if res is not None:
|
||||||
city_name = res.group("city").lower()
|
city_name = res.group("city").lower()
|
||||||
gps_lat = res.group("lat").replace(",", ".")
|
gps_lat = res.group("lat").replace(",", ".")
|
||||||
|
|
@ -220,4 +258,4 @@ def parseask(msg):
|
||||||
context.data.addChild(ms)
|
context.data.addChild(ms)
|
||||||
context.save()
|
context.save()
|
||||||
return Response("ok, j'ai bien noté les coordonnées de %s" % res.group("city"),
|
return Response("ok, j'ai bien noté les coordonnées de %s" % res.group("city"),
|
||||||
msg.channel, msg.nick)
|
msg.channel, msg.frm)
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
# coding=utf-8
|
# coding=utf-8
|
||||||
|
|
||||||
|
import json
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from nemubot import context
|
from nemubot import context
|
||||||
|
|
@ -9,47 +10,70 @@ from nemubot.tools.xmlparser.node import ModuleState
|
||||||
|
|
||||||
nemubotversion = 3.4
|
nemubotversion = 3.4
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
from networking.page import headers
|
from nemubot.module.networking.page import headers
|
||||||
|
|
||||||
PASSWD_FILE = None
|
PASSWD_FILE = None
|
||||||
|
# You can get one with: curl -b "sessionid=YOURSESSIONID" 'https://accounts.cri.epita.net/api/users/?limit=10000' > users.json
|
||||||
|
APIEXTRACT_FILE = None
|
||||||
|
|
||||||
def load(context):
|
def load(context):
|
||||||
global PASSWD_FILE
|
global PASSWD_FILE
|
||||||
if not context.config or "passwd" not in context.config:
|
if not context.config or "passwd" not in context.config:
|
||||||
print("No passwd file given")
|
print("No passwd file given")
|
||||||
|
else:
|
||||||
|
PASSWD_FILE = context.config["passwd"]
|
||||||
|
print("passwd file loaded:", PASSWD_FILE)
|
||||||
|
|
||||||
|
global APIEXTRACT_FILE
|
||||||
|
if not context.config or "apiextract" not in context.config:
|
||||||
|
print("No passwd file given")
|
||||||
|
else:
|
||||||
|
APIEXTRACT_FILE = context.config["apiextract"]
|
||||||
|
print("JSON users file loaded:", APIEXTRACT_FILE)
|
||||||
|
|
||||||
|
if PASSWD_FILE is None and APIEXTRACT_FILE is None:
|
||||||
return None
|
return None
|
||||||
PASSWD_FILE = context.config["passwd"]
|
|
||||||
|
|
||||||
if not context.data.hasNode("aliases"):
|
if not context.data.hasNode("aliases"):
|
||||||
context.data.addChild(ModuleState("aliases"))
|
context.data.addChild(ModuleState("aliases"))
|
||||||
context.data.getNode("aliases").setIndex("from", "alias")
|
context.data.getNode("aliases").setIndex("from", "alias")
|
||||||
|
|
||||||
if not context.data.hasNode("pics"):
|
|
||||||
context.data.addChild(ModuleState("pics"))
|
|
||||||
context.data.getNode("pics").setIndex("login", "pict")
|
|
||||||
|
|
||||||
import nemubot.hooks
|
import nemubot.hooks
|
||||||
context.add_hook(nemubot.hooks.Command(cmd_whois, "whois", keywords={"lookup": "Perform a lookup of the begining of the login instead of an exact search."}),
|
context.add_hook(nemubot.hooks.Command(cmd_whois, "whois", keywords={"lookup": "Perform a lookup of the begining of the login instead of an exact search."}),
|
||||||
"in","Command")
|
"in","Command")
|
||||||
|
|
||||||
class Login:
|
class Login:
|
||||||
|
|
||||||
def __init__(self, line):
|
def __init__(self, line=None, login=None, uidNumber=None, firstname=None, lastname=None, promo=None, **kwargs):
|
||||||
s = line.split(":")
|
if line is not None:
|
||||||
self.login = s[0]
|
s = line.split(":")
|
||||||
self.uid = s[2]
|
self.login = s[0]
|
||||||
self.gid = s[3]
|
self.uid = s[2]
|
||||||
self.cn = s[4]
|
self.gid = s[3]
|
||||||
self.home = s[5]
|
self.cn = s[4]
|
||||||
|
self.home = s[5]
|
||||||
|
else:
|
||||||
|
self.login = login
|
||||||
|
self.uid = uidNumber
|
||||||
|
self.promo = promo
|
||||||
|
self.cn = firstname + " " + lastname
|
||||||
|
try:
|
||||||
|
self.gid = "epita" + str(int(promo))
|
||||||
|
except:
|
||||||
|
self.gid = promo
|
||||||
|
|
||||||
def get_promo(self):
|
def get_promo(self):
|
||||||
return self.home.split("/")[2].replace("_", " ")
|
if hasattr(self, "promo"):
|
||||||
|
return self.promo
|
||||||
|
if hasattr(self, "home"):
|
||||||
|
try:
|
||||||
|
return self.home.split("/")[2].replace("_", " ")
|
||||||
|
except:
|
||||||
|
return self.gid
|
||||||
|
|
||||||
def get_photo(self):
|
def get_photo(self):
|
||||||
if self.login in context.data.getNode("pics").index:
|
for url in [ "https://photos.cri.epita.fr/%s", "https://intra-bocal.epitech.eu/trombi/%s.jpg" ]:
|
||||||
return context.data.getNode("pics").index[self.login]["url"]
|
|
||||||
for url in [ "https://photos.cri.epita.net/%s", "https://static.acu.epita.fr/photos/%s", "https://static.acu.epita.fr/photos/%s/%%s" % self.gid, "https://intra-bocal.epitech.eu/trombi/%s.jpg", "http://whois.23.tf/p/%s/%%s.jpg" % self.gid ]:
|
|
||||||
url = url % self.login
|
url = url % self.login
|
||||||
try:
|
try:
|
||||||
_, status, _, _ = headers(url)
|
_, status, _, _ = headers(url)
|
||||||
|
|
@ -60,17 +84,25 @@ class Login:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def found_login(login, search=False):
|
def login_lookup(login, search=False):
|
||||||
if login in context.data.getNode("aliases").index:
|
if login in context.data.getNode("aliases").index:
|
||||||
login = context.data.getNode("aliases").index[login]["to"]
|
login = context.data.getNode("aliases").index[login]["to"]
|
||||||
|
|
||||||
|
if APIEXTRACT_FILE:
|
||||||
|
with open(APIEXTRACT_FILE, encoding="utf-8") as f:
|
||||||
|
api = json.load(f)
|
||||||
|
for l in api["results"]:
|
||||||
|
if (not search and l["login"] == login) or (search and (("login" in l and l["login"].find(login) != -1) or ("cn" in l and l["cn"].find(login) != -1) or ("uid" in l and str(l["uid"]) == login))):
|
||||||
|
yield Login(**l)
|
||||||
|
|
||||||
login_ = login + (":" if not search else "")
|
login_ = login + (":" if not search else "")
|
||||||
lsize = len(login_)
|
lsize = len(login_)
|
||||||
|
|
||||||
with open(PASSWD_FILE, encoding="iso-8859-15") as f:
|
if PASSWD_FILE:
|
||||||
for l in f.readlines():
|
with open(PASSWD_FILE, encoding="iso-8859-15") as f:
|
||||||
if l[:lsize] == login_:
|
for l in f.readlines():
|
||||||
yield Login(l.strip())
|
if l[:lsize] == login_:
|
||||||
|
yield Login(l.strip())
|
||||||
|
|
||||||
def cmd_whois(msg):
|
def cmd_whois(msg):
|
||||||
if len(msg.args) < 1:
|
if len(msg.args) < 1:
|
||||||
|
|
@ -87,7 +119,7 @@ def cmd_whois(msg):
|
||||||
res = Response(channel=msg.channel, count=" (%d more logins)", line_treat=format_response)
|
res = Response(channel=msg.channel, count=" (%d more logins)", line_treat=format_response)
|
||||||
for srch in msg.args:
|
for srch in msg.args:
|
||||||
found = False
|
found = False
|
||||||
for l in found_login(srch, "lookup" in msg.kwargs):
|
for l in login_lookup(srch, "lookup" in msg.kwargs):
|
||||||
found = True
|
found = True
|
||||||
res.append_message((srch, l))
|
res.append_message((srch, l))
|
||||||
if not found:
|
if not found:
|
||||||
|
|
@ -98,7 +130,7 @@ def cmd_whois(msg):
|
||||||
def cmd_nicks(msg):
|
def cmd_nicks(msg):
|
||||||
if len(msg.args) < 1:
|
if len(msg.args) < 1:
|
||||||
raise IMException("Provide a login")
|
raise IMException("Provide a login")
|
||||||
nick = found_login(msg.args[0])
|
nick = login_lookup(msg.args[0])
|
||||||
if nick is None:
|
if nick is None:
|
||||||
nick = msg.args[0]
|
nick = msg.args[0]
|
||||||
else:
|
else:
|
||||||
|
|
@ -115,12 +147,12 @@ def cmd_nicks(msg):
|
||||||
|
|
||||||
@hook.ask()
|
@hook.ask()
|
||||||
def parseask(msg):
|
def parseask(msg):
|
||||||
res = re.match(r"^(\S+)\s*('s|suis|est|is|was|were)\s+([a-zA-Z0-9_-]{3,8})$", msg.text, re.I)
|
res = re.match(r"^(\S+)\s*('s|suis|est|is|was|were)\s+([a-zA-Z0-9_-]{3,8})$", msg.message, re.I)
|
||||||
if res is not None:
|
if res is not None:
|
||||||
nick = res.group(1)
|
nick = res.group(1)
|
||||||
login = res.group(3)
|
login = res.group(3)
|
||||||
if nick == "my" or nick == "I" or nick == "i" or nick == "je" or nick == "mon" or nick == "ma":
|
if nick == "my" or nick == "I" or nick == "i" or nick == "je" or nick == "mon" or nick == "ma":
|
||||||
nick = msg.nick
|
nick = msg.frm
|
||||||
if nick in context.data.getNode("aliases").index:
|
if nick in context.data.getNode("aliases").index:
|
||||||
context.data.getNode("aliases").index[nick]["to"] = login
|
context.data.getNode("aliases").index[nick]["to"] = login
|
||||||
else:
|
else:
|
||||||
|
|
@ -132,4 +164,4 @@ def parseask(msg):
|
||||||
return Response("ok, c'est noté, %s est %s"
|
return Response("ok, c'est noté, %s est %s"
|
||||||
% (nick, login),
|
% (nick, login),
|
||||||
channel=msg.channel,
|
channel=msg.channel,
|
||||||
nick=msg.nick)
|
nick=msg.frm)
|
||||||
|
|
|
||||||
|
|
@ -10,12 +10,12 @@ 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 more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
|
|
||||||
# LOADING #############################################################
|
# LOADING #############################################################
|
||||||
|
|
||||||
URL_API = "http://api.wolframalpha.com/v2/query?input=%%s&format=plaintext&appid=%s"
|
URL_API = "https://api.wolframalpha.com/v2/query?input=%%s&format=plaintext&appid=%s"
|
||||||
|
|
||||||
def load(context):
|
def load(context):
|
||||||
global URL_API
|
global URL_API
|
||||||
|
|
@ -24,7 +24,7 @@ def load(context):
|
||||||
"this module. Add it to the module configuration: "
|
"this module. Add it to the module configuration: "
|
||||||
"\n<module name=\"wolframalpha\" "
|
"\n<module name=\"wolframalpha\" "
|
||||||
"apikey=\"XXXXXX-XXXXXXXXXX\" />\n"
|
"apikey=\"XXXXXX-XXXXXXXXXX\" />\n"
|
||||||
"Register at http://products.wolframalpha.com/api/")
|
"Register at https://products.wolframalpha.com/api/")
|
||||||
URL_API = URL_API % quote(context.config["apikey"]).replace("%", "%%")
|
URL_API = URL_API % quote(context.config["apikey"]).replace("%", "%%")
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,27 +1,28 @@
|
||||||
# coding=utf-8
|
# coding=utf-8
|
||||||
|
|
||||||
"""The 2014 football worldcup module"""
|
"""The 2014,2018 football worldcup module"""
|
||||||
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
from functools import partial
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
from urllib.parse import quote
|
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.event import ModuleEvent
|
||||||
from nemubot.exception import IMException
|
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
|
||||||
|
|
||||||
nemubotversion = 3.4
|
nemubotversion = 3.4
|
||||||
|
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
|
|
||||||
API_URL="http://worldcup.sfg.io/%s"
|
API_URL="http://worldcup.sfg.io/%s"
|
||||||
|
|
||||||
def load(context):
|
def load(context):
|
||||||
from nemubot.event import ModuleEvent
|
context.add_event(ModuleEvent(func=partial(lambda url: urlopen(url, timeout=10).read().decode(), API_URL % "matches/current?by_date=DESC"), call=current_match_new_action, interval=30))
|
||||||
context.add_event(ModuleEvent(func=lambda url: urlopen(url, timeout=10).read().decode(), func_data=API_URL % "matches/current?by_date=DESC", call=current_match_new_action, interval=30))
|
|
||||||
|
|
||||||
|
|
||||||
def help_full ():
|
def help_full ():
|
||||||
|
|
@ -32,7 +33,7 @@ def start_watch(msg):
|
||||||
w = ModuleState("watch")
|
w = ModuleState("watch")
|
||||||
w["server"] = msg.server
|
w["server"] = msg.server
|
||||||
w["channel"] = msg.channel
|
w["channel"] = msg.channel
|
||||||
w["proprio"] = msg.nick
|
w["proprio"] = msg.frm
|
||||||
w["start"] = datetime.now(timezone.utc)
|
w["start"] = datetime.now(timezone.utc)
|
||||||
context.data.addChild(w)
|
context.data.addChild(w)
|
||||||
context.save()
|
context.save()
|
||||||
|
|
@ -65,10 +66,10 @@ def cmd_watch(msg):
|
||||||
context.save()
|
context.save()
|
||||||
raise IMException("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(matches):
|
||||||
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))
|
def cmp(om, nm):
|
||||||
|
return len(nm) and (len(om) == 0 or len(nm[0]["home_team_events"]) != len(om[0]["home_team_events"]) or len(nm[0]["away_team_events"]) != len(om[0]["away_team_events"]))
|
||||||
matches = json.loads(match_str)
|
context.add_event(ModuleEvent(func=partial(lambda url: json.loads(urlopen(url).read().decode()), API_URL % "matches/current?by_date=DESC"), cmp=partial(cmp, matches), call=current_match_new_action, interval=30))
|
||||||
|
|
||||||
for match in matches:
|
for match in matches:
|
||||||
if is_valid(match):
|
if is_valid(match):
|
||||||
|
|
@ -120,20 +121,19 @@ def detail_event(evt):
|
||||||
return evt + " par"
|
return evt + " par"
|
||||||
|
|
||||||
def txt_event(e):
|
def txt_event(e):
|
||||||
return "%se minutes : %s %s (%s)" % (e["time"], detail_event(e["type_of_event"]), e["player"], e["team"]["code"])
|
return "%s minute : %s %s (%s)" % (e["time"], detail_event(e["type_of_event"]), e["player"], e["team"]["code"])
|
||||||
|
|
||||||
def prettify(match):
|
def prettify(match):
|
||||||
matchdate_local = datetime.strptime(match["datetime"].replace(':', ''), "%Y-%m-%dT%H%M%S.%f%z")
|
matchdate = datetime.strptime(match["datetime"].replace(':', ''), "%Y-%m-%dT%H%M%SZ").replace(tzinfo=timezone.utc)
|
||||||
matchdate = matchdate_local - (matchdate_local.utcoffset() - datetime.timedelta(hours=2))
|
|
||||||
if match["status"] == "future":
|
if match["status"] == "future":
|
||||||
return ["Match à venir (%s) le %s : %s vs. %s" % (match["match_number"], matchdate.strftime("%A %d à %H:%M"), match["home_team"]["country"], match["away_team"]["country"])]
|
return ["Match à venir (%s) le %s : %s vs. %s" % (match["fifa_id"], matchdate.strftime("%A %d à %H:%M"), match["home_team"]["country"], match["away_team"]["country"])]
|
||||||
else:
|
else:
|
||||||
msgs = list()
|
msgs = list()
|
||||||
msg = ""
|
msg = ""
|
||||||
if match["status"] == "completed":
|
if match["status"] == "completed":
|
||||||
msg += "Match (%s) du %s terminé : " % (match["match_number"], matchdate.strftime("%A %d à %H:%M"))
|
msg += "Match (%s) du %s terminé : " % (match["fifa_id"], matchdate.strftime("%A %d à %H:%M"))
|
||||||
else:
|
else:
|
||||||
msg += "Match en cours (%s) depuis %d minutes : " % (match["match_number"], (datetime.now(matchdate.tzinfo) - matchdate_local).total_seconds() / 60)
|
msg += "Match en cours (%s) depuis %d minutes : " % (match["fifa_id"], (datetime.now(tz=timezone.utc) - matchdate).total_seconds() / 60)
|
||||||
|
|
||||||
msg += "%s %d - %d %s" % (match["home_team"]["country"], match["home_team"]["goals"], match["away_team"]["goals"], match["away_team"]["country"])
|
msg += "%s %d - %d %s" % (match["home_team"]["country"], match["home_team"]["goals"], match["away_team"]["goals"], match["away_team"]["country"])
|
||||||
|
|
||||||
|
|
@ -163,7 +163,7 @@ def is_valid(match):
|
||||||
def get_match(url, matchid):
|
def get_match(url, matchid):
|
||||||
allm = get_matches(url)
|
allm = get_matches(url)
|
||||||
for m in allm:
|
for m in allm:
|
||||||
if int(m["match_number"]) == matchid:
|
if int(m["fifa_id"]) == matchid:
|
||||||
return [ m ]
|
return [ m ]
|
||||||
|
|
||||||
def get_matches(url):
|
def get_matches(url):
|
||||||
|
|
@ -192,7 +192,7 @@ def cmd_worldcup(msg):
|
||||||
elif len(msg.args[0]) == 3:
|
elif len(msg.args[0]) == 3:
|
||||||
url = "matches/country?fifa_code=%s&by_date=DESC" % msg.args[0]
|
url = "matches/country?fifa_code=%s&by_date=DESC" % msg.args[0]
|
||||||
elif is_int(msg.args[0]):
|
elif is_int(msg.args[0]):
|
||||||
url = int(msg.arg[0])
|
url = int(msg.args[0])
|
||||||
else:
|
else:
|
||||||
raise IMException("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")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import re, json, subprocess
|
||||||
from nemubot.exception import IMException
|
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 nemubot.module.more import Response
|
||||||
|
|
||||||
"""Get information of youtube videos"""
|
"""Get information of youtube videos"""
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -39,10 +39,14 @@ def requires_version(min=None, max=None):
|
||||||
"but this is nemubot v%s." % (str(max), __version__))
|
"but this is nemubot v%s." % (str(max), __version__))
|
||||||
|
|
||||||
|
|
||||||
def attach(pid, socketfile):
|
def attach(pidfile, socketfile):
|
||||||
import socket
|
import socket
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
|
# Read PID from pidfile
|
||||||
|
with open(pidfile, "r") as f:
|
||||||
|
pid = int(f.readline())
|
||||||
|
|
||||||
print("nemubot is launched with PID %d. Attaching to Unix socket at: %s" % (pid, socketfile))
|
print("nemubot is launched with PID %d. Attaching to Unix socket at: %s" % (pid, socketfile))
|
||||||
|
|
||||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||||
|
|
@ -106,28 +110,13 @@ def attach(pid, socketfile):
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def daemonize(socketfile=None, autoattach=True):
|
def daemonize(socketfile=None):
|
||||||
"""Detach the running process to run as a daemon
|
"""Detach the running process to run as a daemon
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
if socketfile is not None:
|
|
||||||
try:
|
|
||||||
pid = os.fork()
|
|
||||||
if pid > 0:
|
|
||||||
if autoattach:
|
|
||||||
import time
|
|
||||||
os.waitpid(pid, 0)
|
|
||||||
time.sleep(1)
|
|
||||||
sys.exit(attach(pid, socketfile))
|
|
||||||
else:
|
|
||||||
sys.exit(0)
|
|
||||||
except OSError as err:
|
|
||||||
sys.stderr.write("Unable to fork: %s\n" % err)
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
pid = os.fork()
|
pid = os.fork()
|
||||||
if pid > 0:
|
if pid > 0:
|
||||||
|
|
|
||||||
|
|
@ -71,12 +71,26 @@ def main():
|
||||||
|
|
||||||
# Resolve relatives paths
|
# Resolve relatives paths
|
||||||
args.data_path = os.path.abspath(os.path.expanduser(args.data_path))
|
args.data_path = os.path.abspath(os.path.expanduser(args.data_path))
|
||||||
args.pidfile = os.path.abspath(os.path.expanduser(args.pidfile))
|
args.pidfile = os.path.abspath(os.path.expanduser(args.pidfile)) if args.pidfile is not None and args.pidfile != "" else None
|
||||||
args.socketfile = os.path.abspath(os.path.expanduser(args.socketfile))
|
args.socketfile = os.path.abspath(os.path.expanduser(args.socketfile)) if args.socketfile is not None and args.socketfile != "" else None
|
||||||
args.logfile = os.path.abspath(os.path.expanduser(args.logfile))
|
args.logfile = os.path.abspath(os.path.expanduser(args.logfile))
|
||||||
args.files = [x for x in map(os.path.abspath, args.files)]
|
args.files = [x for x in map(os.path.abspath, args.files)]
|
||||||
args.modules_path = [x for x in map(os.path.abspath, args.modules_path)]
|
args.modules_path = [x for x in map(os.path.abspath, args.modules_path)]
|
||||||
|
|
||||||
|
# Prepare the attached client, before setting other stuff
|
||||||
|
if not args.debug and not args.no_attach and args.socketfile is not None and args.pidfile is not None:
|
||||||
|
try:
|
||||||
|
pid = os.fork()
|
||||||
|
if pid > 0:
|
||||||
|
import time
|
||||||
|
os.waitpid(pid, 0)
|
||||||
|
time.sleep(1)
|
||||||
|
from nemubot import attach
|
||||||
|
sys.exit(attach(args.pidfile, args.socketfile))
|
||||||
|
except OSError as err:
|
||||||
|
sys.stderr.write("Unable to fork: %s\n" % err)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
# Setup logging interface
|
# Setup logging interface
|
||||||
import logging
|
import logging
|
||||||
logger = logging.getLogger("nemubot")
|
logger = logging.getLogger("nemubot")
|
||||||
|
|
@ -106,7 +120,7 @@ def main():
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
from nemubot import attach
|
from nemubot import attach
|
||||||
sys.exit(attach(pid, args.socketfile))
|
sys.exit(attach(args.pidfile, args.socketfile))
|
||||||
|
|
||||||
# Add modules dir paths
|
# Add modules dir paths
|
||||||
modules_paths = list()
|
modules_paths = list()
|
||||||
|
|
@ -118,10 +132,10 @@ def main():
|
||||||
|
|
||||||
# Create bot context
|
# Create bot context
|
||||||
from nemubot import datastore
|
from nemubot import datastore
|
||||||
from nemubot.bot import Bot, sync_act
|
from nemubot.bot import Bot
|
||||||
context = Bot(modules_paths=modules_paths,
|
context = Bot(modules_paths=modules_paths,
|
||||||
data_store=datastore.XML(args.data_path),
|
data_store=datastore.XML(args.data_path),
|
||||||
verbosity=args.verbose)
|
debug=args.verbose > 0)
|
||||||
|
|
||||||
if args.no_connect:
|
if args.no_connect:
|
||||||
context.noautoconnect = True
|
context.noautoconnect = True
|
||||||
|
|
@ -133,14 +147,44 @@ def main():
|
||||||
|
|
||||||
# Load requested configuration files
|
# Load requested configuration files
|
||||||
for path in args.files:
|
for path in args.files:
|
||||||
if os.path.isfile(path):
|
if not os.path.isfile(path):
|
||||||
sync_act("loadconf", path)
|
|
||||||
else:
|
|
||||||
logger.error("%s is not a readable file", path)
|
logger.error("%s is not a readable file", path)
|
||||||
|
continue
|
||||||
|
|
||||||
|
config = load_config(path)
|
||||||
|
|
||||||
|
# Preset each server in this file
|
||||||
|
for server in config.servers:
|
||||||
|
# Add the server in the context
|
||||||
|
for i in [0,1,2,3]:
|
||||||
|
srv = server.server(config, trynb=i)
|
||||||
|
try:
|
||||||
|
if context.add_server(srv):
|
||||||
|
logger.info("Server '%s' successfully added.", srv.name)
|
||||||
|
else:
|
||||||
|
logger.error("Can't add server '%s'.", srv.name)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Unable to connect to '%s': %s", srv.name, e)
|
||||||
|
continue
|
||||||
|
break
|
||||||
|
|
||||||
|
# Load module and their configuration
|
||||||
|
for mod in config.modules:
|
||||||
|
context.modules_configuration[mod.name] = mod
|
||||||
|
if mod.autoload:
|
||||||
|
try:
|
||||||
|
__import__("nemubot.module." + mod.name)
|
||||||
|
except:
|
||||||
|
logger.exception("Exception occurs when loading module"
|
||||||
|
" '%s'", mod.name)
|
||||||
|
|
||||||
|
# Load files asked by the configuration file
|
||||||
|
args.files += config.includes
|
||||||
|
|
||||||
|
|
||||||
if args.module:
|
if args.module:
|
||||||
for module in args.module:
|
for module in args.module:
|
||||||
__import__(module)
|
__import__("nemubot.module." + module)
|
||||||
|
|
||||||
if args.socketfile:
|
if args.socketfile:
|
||||||
from nemubot.server.socket import UnixSocketListener
|
from nemubot.server.socket import UnixSocketListener
|
||||||
|
|
@ -151,7 +195,7 @@ def main():
|
||||||
# Daemonize
|
# Daemonize
|
||||||
if not args.debug:
|
if not args.debug:
|
||||||
from nemubot import daemonize
|
from nemubot import daemonize
|
||||||
daemonize(args.socketfile, not args.no_attach)
|
daemonize(args.socketfile)
|
||||||
|
|
||||||
# Signals handling
|
# Signals handling
|
||||||
def sigtermhandler(signum, frame):
|
def sigtermhandler(signum, frame):
|
||||||
|
|
@ -205,5 +249,31 @@ def main():
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
|
|
||||||
|
def load_config(filename):
|
||||||
|
"""Load a configuration file
|
||||||
|
|
||||||
|
Arguments:
|
||||||
|
filename -- the path to the file to load
|
||||||
|
"""
|
||||||
|
|
||||||
|
from nemubot.channel import Channel
|
||||||
|
from nemubot import config
|
||||||
|
from nemubot.tools.xmlparser import XMLParser
|
||||||
|
|
||||||
|
try:
|
||||||
|
p = XMLParser({
|
||||||
|
"nemubotconfig": config.Nemubot,
|
||||||
|
"server": config.Server,
|
||||||
|
"channel": Channel,
|
||||||
|
"module": config.Module,
|
||||||
|
"include": config.Include,
|
||||||
|
})
|
||||||
|
return p.parse_file(filename)
|
||||||
|
except:
|
||||||
|
logger.exception("Can't load `%s'; this is not a valid nemubot "
|
||||||
|
"configuration file.", filename)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|
|
||||||
156
nemubot/bot.py
156
nemubot/bot.py
|
|
@ -40,14 +40,14 @@ class Bot(threading.Thread):
|
||||||
"""Class containing the bot context and ensuring key goals"""
|
"""Class containing the bot context and ensuring key goals"""
|
||||||
|
|
||||||
def __init__(self, ip="127.0.0.1", modules_paths=list(),
|
def __init__(self, ip="127.0.0.1", modules_paths=list(),
|
||||||
data_store=datastore.Abstract(), verbosity=0):
|
data_store=datastore.Abstract(), debug=False):
|
||||||
"""Initialize the bot context
|
"""Initialize the bot context
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
ip -- The external IP of the bot (default: 127.0.0.1)
|
ip -- The external IP of the bot (default: 127.0.0.1)
|
||||||
modules_paths -- Paths to all directories where looking for modules
|
modules_paths -- Paths to all directories where looking for modules
|
||||||
data_store -- An instance of the nemubot datastore for bot's modules
|
data_store -- An instance of the nemubot datastore for bot's modules
|
||||||
verbosity -- verbosity level
|
debug -- enable debug
|
||||||
"""
|
"""
|
||||||
|
|
||||||
super().__init__(name="Nemubot main")
|
super().__init__(name="Nemubot main")
|
||||||
|
|
@ -56,8 +56,8 @@ class Bot(threading.Thread):
|
||||||
__version__,
|
__version__,
|
||||||
sys.version_info.major, sys.version_info.minor, sys.version_info.micro)
|
sys.version_info.major, sys.version_info.minor, sys.version_info.micro)
|
||||||
|
|
||||||
self.verbosity = verbosity
|
self.debug = debug
|
||||||
self.stop = None
|
self.stop = True
|
||||||
|
|
||||||
# External IP for accessing this bot
|
# External IP for accessing this bot
|
||||||
import ipaddress
|
import ipaddress
|
||||||
|
|
@ -92,23 +92,24 @@ class Bot(threading.Thread):
|
||||||
|
|
||||||
def in_echo(msg):
|
def in_echo(msg):
|
||||||
from nemubot.message import Text
|
from nemubot.message import Text
|
||||||
return Text(msg.nick + ": " + " ".join(msg.args), to=msg.to_response)
|
return Text(msg.frm + ": " + " ".join(msg.args), to=msg.to_response)
|
||||||
self.treater.hm.add_hook(nemubot.hooks.Command(in_echo, "echo"), "in", "Command")
|
self.treater.hm.add_hook(nemubot.hooks.Command(in_echo, "echo"), "in", "Command")
|
||||||
|
|
||||||
def _help_msg(msg):
|
def _help_msg(msg):
|
||||||
"""Parse and response to help messages"""
|
"""Parse and response to help messages"""
|
||||||
from more import Response
|
from nemubot.module.more import Response
|
||||||
res = Response(channel=msg.to_response)
|
res = Response(channel=msg.to_response)
|
||||||
if len(msg.args) >= 1:
|
if len(msg.args) >= 1:
|
||||||
if msg.args[0] in self.modules and self.modules[msg.args[0]]() is not None:
|
if "nemubot.module." + msg.args[0] in self.modules and self.modules["nemubot.module." + msg.args[0]]() is not None:
|
||||||
if hasattr(self.modules[msg.args[0]](), "help_full"):
|
mname = "nemubot.module." + msg.args[0]
|
||||||
hlp = self.modules[msg.args[0]]().help_full()
|
if hasattr(self.modules[mname](), "help_full"):
|
||||||
|
hlp = self.modules[mname]().help_full()
|
||||||
if isinstance(hlp, Response):
|
if isinstance(hlp, Response):
|
||||||
return hlp
|
return hlp
|
||||||
else:
|
else:
|
||||||
res.append_message(hlp)
|
res.append_message(hlp)
|
||||||
else:
|
else:
|
||||||
res.append_message([str(h) for s,h in self.modules[msg.args[0]]().__nemubot_context__.hooks], title="Available commands for module " + msg.args[0])
|
res.append_message([str(h) for s,h in self.modules[mname]().__nemubot_context__.hooks], title="Available commands for module " + msg.args[0])
|
||||||
elif msg.args[0][0] == "!":
|
elif msg.args[0][0] == "!":
|
||||||
from nemubot.message.command import Command
|
from nemubot.message.command import Command
|
||||||
for h in self.treater._in_hooks(Command(msg.args[0][1:])):
|
for h in self.treater._in_hooks(Command(msg.args[0][1:])):
|
||||||
|
|
@ -134,7 +135,7 @@ class Bot(threading.Thread):
|
||||||
"Vous pouvez le consulter, le dupliquer, "
|
"Vous pouvez le consulter, le dupliquer, "
|
||||||
"envoyer des rapports de bogues ou bien "
|
"envoyer des rapports de bogues ou bien "
|
||||||
"contribuer au projet sur GitHub : "
|
"contribuer au projet sur GitHub : "
|
||||||
"http://github.com/nemunaire/nemubot/")
|
"https://github.com/nemunaire/nemubot/")
|
||||||
res.append_message(title="Pour plus de détails sur un module, "
|
res.append_message(title="Pour plus de détails sur un module, "
|
||||||
"envoyez \"!help nomdumodule\". Voici la liste"
|
"envoyez \"!help nomdumodule\". Voici la liste"
|
||||||
" de tous les modules disponibles localement",
|
" de tous les modules disponibles localement",
|
||||||
|
|
@ -142,11 +143,20 @@ class Bot(threading.Thread):
|
||||||
return res
|
return res
|
||||||
self.treater.hm.add_hook(nemubot.hooks.Command(_help_msg, "help"), "in", "Command")
|
self.treater.hm.add_hook(nemubot.hooks.Command(_help_msg, "help"), "in", "Command")
|
||||||
|
|
||||||
|
import os
|
||||||
from queue import Queue
|
from queue import Queue
|
||||||
# Messages to be treated
|
# Messages to be treated — shared across all server connections.
|
||||||
self.cnsr_queue = Queue()
|
# cnsr_active tracks consumers currently inside stm.run() (not idle),
|
||||||
self.cnsr_thrd = list()
|
# which lets us spawn a new thread the moment all existing ones are busy.
|
||||||
self.cnsr_thrd_size = -1
|
self.cnsr_queue = Queue()
|
||||||
|
self.cnsr_thrd = list()
|
||||||
|
self.cnsr_lock = threading.Lock()
|
||||||
|
self.cnsr_active = 0 # consumers currently executing a task
|
||||||
|
self.cnsr_max = os.cpu_count() or 4 # upper bound on concurrent consumer threads
|
||||||
|
|
||||||
|
|
||||||
|
def __del__(self):
|
||||||
|
self.datastore.close()
|
||||||
|
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
|
|
@ -159,8 +169,13 @@ class Bot(threading.Thread):
|
||||||
|
|
||||||
self._poll.register(sync_queue._reader, select.POLLIN | select.POLLPRI)
|
self._poll.register(sync_queue._reader, select.POLLIN | select.POLLPRI)
|
||||||
|
|
||||||
logger.info("Starting main loop")
|
|
||||||
self.stop = False
|
self.stop = False
|
||||||
|
|
||||||
|
# Relaunch events
|
||||||
|
self._update_event_timer()
|
||||||
|
|
||||||
|
logger.info("Starting main loop")
|
||||||
while not self.stop:
|
while not self.stop:
|
||||||
for fd, flag in self._poll.poll():
|
for fd, flag in self._poll.poll():
|
||||||
# Handle internal socket passing orders
|
# Handle internal socket passing orders
|
||||||
|
|
@ -208,7 +223,10 @@ class Bot(threading.Thread):
|
||||||
elif args[0] == "register":
|
elif args[0] == "register":
|
||||||
self._poll.register(int(args[1]), select.POLLIN | select.POLLPRI)
|
self._poll.register(int(args[1]), select.POLLIN | select.POLLPRI)
|
||||||
elif args[0] == "unregister":
|
elif args[0] == "unregister":
|
||||||
self._poll.unregister(int(args[1]))
|
try:
|
||||||
|
self._poll.unregister(int(args[1]))
|
||||||
|
except KeyError:
|
||||||
|
pass
|
||||||
except:
|
except:
|
||||||
logger.exception("Unhandled excpetion during action:")
|
logger.exception("Unhandled excpetion during action:")
|
||||||
|
|
||||||
|
|
@ -218,86 +236,23 @@ class Bot(threading.Thread):
|
||||||
elif action == "launch_consumer":
|
elif action == "launch_consumer":
|
||||||
pass # This is treated after the loop
|
pass # This is treated after the loop
|
||||||
|
|
||||||
elif action == "loadconf":
|
|
||||||
for path in args:
|
|
||||||
logger.debug("Load configuration from %s", path)
|
|
||||||
self.load_file(path)
|
|
||||||
logger.info("Configurations successfully loaded")
|
|
||||||
|
|
||||||
sync_queue.task_done()
|
sync_queue.task_done()
|
||||||
|
|
||||||
|
|
||||||
# Launch new consumer threads if necessary
|
# Spawn a new consumer whenever the queue has work and every
|
||||||
while self.cnsr_queue.qsize() > self.cnsr_thrd_size:
|
# existing consumer is already busy executing a task.
|
||||||
# Next launch if two more items in queue
|
with self.cnsr_lock:
|
||||||
self.cnsr_thrd_size += 2
|
while (not self.cnsr_queue.empty()
|
||||||
|
and self.cnsr_active >= len(self.cnsr_thrd)
|
||||||
c = Consumer(self)
|
and len(self.cnsr_thrd) < self.cnsr_max):
|
||||||
self.cnsr_thrd.append(c)
|
c = Consumer(self)
|
||||||
c.start()
|
self.cnsr_thrd.append(c)
|
||||||
|
c.start()
|
||||||
sync_queue = None
|
sync_queue = None
|
||||||
logger.info("Ending main loop")
|
logger.info("Ending main loop")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Config methods
|
|
||||||
|
|
||||||
def load_file(self, filename):
|
|
||||||
"""Load a configuration file
|
|
||||||
|
|
||||||
Arguments:
|
|
||||||
filename -- the path to the file to load
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
|
|
||||||
# Unexisting file, assume a name was passed, import the module!
|
|
||||||
if not os.path.isfile(filename):
|
|
||||||
return self.import_module(filename)
|
|
||||||
|
|
||||||
from nemubot.channel import Channel
|
|
||||||
from nemubot import config
|
|
||||||
from nemubot.tools.xmlparser import XMLParser
|
|
||||||
|
|
||||||
try:
|
|
||||||
p = XMLParser({
|
|
||||||
"nemubotconfig": config.Nemubot,
|
|
||||||
"server": config.Server,
|
|
||||||
"channel": Channel,
|
|
||||||
"module": config.Module,
|
|
||||||
"include": config.Include,
|
|
||||||
})
|
|
||||||
config = p.parse_file(filename)
|
|
||||||
except:
|
|
||||||
logger.exception("Can't load `%s'; this is not a valid nemubot "
|
|
||||||
"configuration file." % filename)
|
|
||||||
return False
|
|
||||||
|
|
||||||
# Preset each server in this file
|
|
||||||
for server in config.servers:
|
|
||||||
srv = server.server(config)
|
|
||||||
# Add the server in the context
|
|
||||||
if self.add_server(srv, server.autoconnect):
|
|
||||||
logger.info("Server '%s' successfully added." % srv.name)
|
|
||||||
else:
|
|
||||||
logger.error("Can't add server '%s'." % srv.name)
|
|
||||||
|
|
||||||
# Load module and their configuration
|
|
||||||
for mod in config.modules:
|
|
||||||
self.modules_configuration[mod.name] = mod
|
|
||||||
if mod.autoload:
|
|
||||||
try:
|
|
||||||
__import__(mod.name)
|
|
||||||
except:
|
|
||||||
logger.exception("Exception occurs when loading module"
|
|
||||||
" '%s'", mod.name)
|
|
||||||
|
|
||||||
|
|
||||||
# Load files asked by the configuration file
|
|
||||||
for load in config.includes:
|
|
||||||
self.load_file(load.path)
|
|
||||||
|
|
||||||
|
|
||||||
# Events methods
|
# Events methods
|
||||||
|
|
||||||
def add_event(self, evt, eid=None, module_src=None):
|
def add_event(self, evt, eid=None, module_src=None):
|
||||||
|
|
@ -315,10 +270,6 @@ class Bot(threading.Thread):
|
||||||
module_src -- The module to which the event is attached to
|
module_src -- The module to which the event is attached to
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if hasattr(self, "stop") and self.stop:
|
|
||||||
logger.warn("The bot is stopped, can't register new events")
|
|
||||||
return
|
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
# Generate the event id if no given
|
# Generate the event id if no given
|
||||||
|
|
@ -345,7 +296,7 @@ class Bot(threading.Thread):
|
||||||
break
|
break
|
||||||
self.events.insert(i, evt)
|
self.events.insert(i, evt)
|
||||||
|
|
||||||
if i == 0:
|
if i == 0 and not self.stop:
|
||||||
# First event changed, reset timer
|
# First event changed, reset timer
|
||||||
self._update_event_timer()
|
self._update_event_timer()
|
||||||
if len(self.events) <= 0 or self.events[i] != evt:
|
if len(self.events) <= 0 or self.events[i] != evt:
|
||||||
|
|
@ -354,7 +305,7 @@ class Bot(threading.Thread):
|
||||||
|
|
||||||
# Register the event in the source module
|
# Register the event in the source module
|
||||||
if module_src is not None:
|
if module_src is not None:
|
||||||
module_src.__nemubot_context__.events.append(evt.id)
|
module_src.__nemubot_context__.events.append((evt, evt.id))
|
||||||
evt.module_src = module_src
|
evt.module_src = module_src
|
||||||
|
|
||||||
logger.info("New event registered in %d position: %s", i, t)
|
logger.info("New event registered in %d position: %s", i, t)
|
||||||
|
|
@ -384,10 +335,10 @@ class Bot(threading.Thread):
|
||||||
id = evt
|
id = evt
|
||||||
|
|
||||||
if len(self.events) > 0 and id == self.events[0].id:
|
if len(self.events) > 0 and id == self.events[0].id:
|
||||||
|
if module_src is not None:
|
||||||
|
module_src.__nemubot_context__.events.remove((self.events[0], id))
|
||||||
self.events.remove(self.events[0])
|
self.events.remove(self.events[0])
|
||||||
self._update_event_timer()
|
self._update_event_timer()
|
||||||
if module_src is not None:
|
|
||||||
module_src.__nemubot_context__.events.remove(id)
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
for evt in self.events:
|
for evt in self.events:
|
||||||
|
|
@ -395,7 +346,7 @@ class Bot(threading.Thread):
|
||||||
self.events.remove(evt)
|
self.events.remove(evt)
|
||||||
|
|
||||||
if module_src is not None:
|
if module_src is not None:
|
||||||
module_src.__nemubot_context__.events.remove(evt.id)
|
module_src.__nemubot_context__.events.remove((evt, evt.id))
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
@ -476,10 +427,6 @@ class Bot(threading.Thread):
|
||||||
old one before"""
|
old one before"""
|
||||||
module_name = module.__spec__.name if hasattr(module, "__spec__") else module.__name__
|
module_name = module.__spec__.name if hasattr(module, "__spec__") else module.__name__
|
||||||
|
|
||||||
if hasattr(self, "stop") and self.stop:
|
|
||||||
logger.warn("The bot is stopped, can't register new modules")
|
|
||||||
return
|
|
||||||
|
|
||||||
# Check if the module already exists
|
# Check if the module already exists
|
||||||
if module_name in self.modules:
|
if module_name in self.modules:
|
||||||
self.unload_module(module_name)
|
self.unload_module(module_name)
|
||||||
|
|
@ -577,12 +524,11 @@ class Bot(threading.Thread):
|
||||||
srv.close()
|
srv.close()
|
||||||
|
|
||||||
logger.info("Stop consumers")
|
logger.info("Stop consumers")
|
||||||
k = self.cnsr_thrd
|
with self.cnsr_lock:
|
||||||
|
k = list(self.cnsr_thrd)
|
||||||
for cnsr in k:
|
for cnsr in k:
|
||||||
cnsr.stop = True
|
cnsr.stop = True
|
||||||
|
|
||||||
self.datastore.close()
|
|
||||||
|
|
||||||
if self.stop is False or sync_queue is not None:
|
if self.stop is False or sync_queue is not None:
|
||||||
self.stop = True
|
self.stop = True
|
||||||
sync_act("end")
|
sync_act("end")
|
||||||
|
|
|
||||||
|
|
@ -52,11 +52,11 @@ class Channel:
|
||||||
elif cmd == "MODE":
|
elif cmd == "MODE":
|
||||||
self.mode(msg)
|
self.mode(msg)
|
||||||
elif cmd == "JOIN":
|
elif cmd == "JOIN":
|
||||||
self.join(msg.nick)
|
self.join(msg.frm)
|
||||||
elif cmd == "NICK":
|
elif cmd == "NICK":
|
||||||
self.nick(msg.nick, msg.text)
|
self.nick(msg.frm, msg.text)
|
||||||
elif cmd == "PART" or cmd == "QUIT":
|
elif cmd == "PART" or cmd == "QUIT":
|
||||||
self.part(msg.nick)
|
self.part(msg.frm)
|
||||||
elif cmd == "TOPIC":
|
elif cmd == "TOPIC":
|
||||||
self.topic = self.text
|
self.topic = self.text
|
||||||
|
|
||||||
|
|
@ -120,17 +120,17 @@ class Channel:
|
||||||
else:
|
else:
|
||||||
self.password = msg.text[1]
|
self.password = msg.text[1]
|
||||||
elif msg.text[0] == "+o":
|
elif msg.text[0] == "+o":
|
||||||
self.people[msg.nick] |= 4
|
self.people[msg.frm] |= 4
|
||||||
elif msg.text[0] == "-o":
|
elif msg.text[0] == "-o":
|
||||||
self.people[msg.nick] &= ~4
|
self.people[msg.frm] &= ~4
|
||||||
elif msg.text[0] == "+h":
|
elif msg.text[0] == "+h":
|
||||||
self.people[msg.nick] |= 2
|
self.people[msg.frm] |= 2
|
||||||
elif msg.text[0] == "-h":
|
elif msg.text[0] == "-h":
|
||||||
self.people[msg.nick] &= ~2
|
self.people[msg.frm] &= ~2
|
||||||
elif msg.text[0] == "+v":
|
elif msg.text[0] == "+v":
|
||||||
self.people[msg.nick] |= 1
|
self.people[msg.frm] |= 1
|
||||||
elif msg.text[0] == "-v":
|
elif msg.text[0] == "-v":
|
||||||
self.people[msg.nick] &= ~1
|
self.people[msg.frm] &= ~1
|
||||||
|
|
||||||
def parse332(self, msg):
|
def parse332(self, msg):
|
||||||
"""Parse RPL_TOPIC message
|
"""Parse RPL_TOPIC message
|
||||||
|
|
|
||||||
|
|
@ -33,7 +33,7 @@ class Server:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def server(self, parent):
|
def server(self, parent, trynb=0):
|
||||||
from nemubot.server import factory
|
from nemubot.server import factory
|
||||||
|
|
||||||
for a in ["nick", "owner", "realname", "encoding"]:
|
for a in ["nick", "owner", "realname", "encoding"]:
|
||||||
|
|
@ -42,4 +42,4 @@ class Server:
|
||||||
|
|
||||||
self.caps += parent.caps
|
self.caps += parent.caps
|
||||||
|
|
||||||
return factory(self.uri, caps=self.caps, channels=self.channels, **self.args)
|
return factory(self.uri, caps=self.caps, channels=self.channels, trynb=trynb, **self.args)
|
||||||
|
|
|
||||||
|
|
@ -94,7 +94,7 @@ class EventConsumer:
|
||||||
# Or remove reference of this event
|
# Or remove reference of this event
|
||||||
elif (hasattr(self.evt, "module_src") and
|
elif (hasattr(self.evt, "module_src") and
|
||||||
self.evt.module_src is not None):
|
self.evt.module_src is not None):
|
||||||
self.evt.module_src.__nemubot_context__.events.remove(self.evt.id)
|
self.evt.module_src.__nemubot_context__.events.remove((self.evt, self.evt.id))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -105,18 +105,25 @@ class Consumer(threading.Thread):
|
||||||
def __init__(self, context):
|
def __init__(self, context):
|
||||||
self.context = context
|
self.context = context
|
||||||
self.stop = False
|
self.stop = False
|
||||||
super().__init__(name="Nemubot consumer")
|
super().__init__(name="Nemubot consumer", daemon=True)
|
||||||
|
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
try:
|
try:
|
||||||
while not self.stop:
|
while not self.stop:
|
||||||
stm = self.context.cnsr_queue.get(True, 1)
|
try:
|
||||||
stm.run(self.context)
|
stm = self.context.cnsr_queue.get(True, 1)
|
||||||
self.context.cnsr_queue.task_done()
|
except queue.Empty:
|
||||||
|
break
|
||||||
|
|
||||||
except queue.Empty:
|
with self.context.cnsr_lock:
|
||||||
pass
|
self.context.cnsr_active += 1
|
||||||
|
try:
|
||||||
|
stm.run(self.context)
|
||||||
|
finally:
|
||||||
|
self.context.cnsr_queue.task_done()
|
||||||
|
with self.context.cnsr_lock:
|
||||||
|
self.context.cnsr_active -= 1
|
||||||
finally:
|
finally:
|
||||||
self.context.cnsr_thrd_size -= 2
|
with self.context.cnsr_lock:
|
||||||
self.context.cnsr_thrd.remove(self)
|
self.context.cnsr_thrd.remove(self)
|
||||||
|
|
|
||||||
|
|
@ -32,16 +32,20 @@ class Abstract:
|
||||||
def close(self):
|
def close(self):
|
||||||
return
|
return
|
||||||
|
|
||||||
def load(self, module):
|
def load(self, module, knodes):
|
||||||
"""Load data for the given module
|
"""Load data for the given module
|
||||||
|
|
||||||
Argument:
|
Argument:
|
||||||
module -- the module name of data to load
|
module -- the module name of data to load
|
||||||
|
knodes -- the schema to use to load the datas
|
||||||
|
|
||||||
Return:
|
Return:
|
||||||
The loaded data
|
The loaded data
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
if knodes is not None:
|
||||||
|
return None
|
||||||
|
|
||||||
return self.new()
|
return self.new()
|
||||||
|
|
||||||
def save(self, module, data):
|
def save(self, module, data):
|
||||||
|
|
|
||||||
|
|
@ -83,27 +83,38 @@ class XML(Abstract):
|
||||||
|
|
||||||
return os.path.join(self.basedir, module + ".xml")
|
return os.path.join(self.basedir, module + ".xml")
|
||||||
|
|
||||||
def load(self, module):
|
def load(self, module, knodes):
|
||||||
"""Load data for the given module
|
"""Load data for the given module
|
||||||
|
|
||||||
Argument:
|
Argument:
|
||||||
module -- the module name of data to load
|
module -- the module name of data to load
|
||||||
|
knodes -- the schema to use to load the datas
|
||||||
"""
|
"""
|
||||||
|
|
||||||
data_file = self._get_data_file_path(module)
|
data_file = self._get_data_file_path(module)
|
||||||
|
|
||||||
|
if knodes is None:
|
||||||
|
from nemubot.tools.xmlparser import parse_file
|
||||||
|
def _true_load(path):
|
||||||
|
return parse_file(path)
|
||||||
|
|
||||||
|
else:
|
||||||
|
from nemubot.tools.xmlparser import XMLParser
|
||||||
|
p = XMLParser(knodes)
|
||||||
|
def _true_load(path):
|
||||||
|
return p.parse_file(path)
|
||||||
|
|
||||||
# Try to load original file
|
# Try to load original file
|
||||||
if os.path.isfile(data_file):
|
if os.path.isfile(data_file):
|
||||||
from nemubot.tools.xmlparser import parse_file
|
|
||||||
try:
|
try:
|
||||||
return parse_file(data_file)
|
return _true_load(data_file)
|
||||||
except xml.parsers.expat.ExpatError:
|
except xml.parsers.expat.ExpatError:
|
||||||
# Try to load from backup
|
# Try to load from backup
|
||||||
for i in range(10):
|
for i in range(10):
|
||||||
path = data_file + "." + str(i)
|
path = data_file + "." + str(i)
|
||||||
if os.path.isfile(path):
|
if os.path.isfile(path):
|
||||||
try:
|
try:
|
||||||
cnt = parse_file(path)
|
cnt = _true_load(path)
|
||||||
|
|
||||||
logger.warn("Restoring from backup: %s", path)
|
logger.warn("Restoring from backup: %s", path)
|
||||||
|
|
||||||
|
|
@ -112,7 +123,7 @@ class XML(Abstract):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Default case: initialize a new empty datastore
|
# Default case: initialize a new empty datastore
|
||||||
return Abstract.load(self, module)
|
return super().load(module, knodes)
|
||||||
|
|
||||||
def _rotate(self, path):
|
def _rotate(self, path):
|
||||||
"""Backup given path
|
"""Backup given path
|
||||||
|
|
@ -143,6 +154,9 @@ class XML(Abstract):
|
||||||
if self.rotate:
|
if self.rotate:
|
||||||
self._rotate(path)
|
self._rotate(path)
|
||||||
|
|
||||||
|
if data is None:
|
||||||
|
return
|
||||||
|
|
||||||
import tempfile
|
import tempfile
|
||||||
_, tmpath = tempfile.mkstemp()
|
_, tmpath = tempfile.mkstemp()
|
||||||
with open(tmpath, "w") as f:
|
with open(tmpath, "w") as f:
|
||||||
|
|
|
||||||
|
|
@ -21,18 +21,14 @@ class ModuleEvent:
|
||||||
|
|
||||||
"""Representation of a event initiated by a bot module"""
|
"""Representation of a event initiated by a bot module"""
|
||||||
|
|
||||||
def __init__(self, call=None, call_data=None, func=None, func_data=None,
|
def __init__(self, call=None, func=None, cmp=None, interval=60, offset=0, times=1):
|
||||||
cmp=None, cmp_data=None, interval=60, offset=0, times=1):
|
|
||||||
|
|
||||||
"""Initialize the event
|
"""Initialize the event
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
call -- Function to call when the event is realized
|
call -- Function to call when the event is realized
|
||||||
call_data -- Argument(s) (single or dict) to pass as argument
|
|
||||||
func -- Function called to check
|
func -- Function called to check
|
||||||
func_data -- Argument(s) (single or dict) to pass as argument OR if no func, initial data to watch
|
cmp -- Boolean function called to check changes or value to compare with
|
||||||
cmp -- Boolean function called to check changes
|
|
||||||
cmp_data -- Argument(s) (single or dict) to pass as argument OR if no cmp, data compared to previous
|
|
||||||
interval -- Time in seconds between each check (default: 60)
|
interval -- Time in seconds between each check (default: 60)
|
||||||
offset -- Time in seconds added to interval before the first check (default: 0)
|
offset -- Time in seconds added to interval before the first check (default: 0)
|
||||||
times -- Number of times the event has to be realized before being removed; -1 for no limit (default: 1)
|
times -- Number of times the event has to be realized before being removed; -1 for no limit (default: 1)
|
||||||
|
|
@ -40,31 +36,22 @@ class ModuleEvent:
|
||||||
|
|
||||||
# What have we to check?
|
# What have we to check?
|
||||||
self.func = func
|
self.func = func
|
||||||
self.func_data = func_data
|
|
||||||
|
|
||||||
# How detect a change?
|
# How detect a change?
|
||||||
self.cmp = cmp
|
self.cmp = cmp
|
||||||
self.cmp_data = None
|
|
||||||
if cmp_data is not None:
|
|
||||||
self.cmp_data = cmp_data
|
|
||||||
elif self.func is not None:
|
|
||||||
if self.func_data is None:
|
|
||||||
self.cmp_data = self.func()
|
|
||||||
elif isinstance(self.func_data, dict):
|
|
||||||
self. | |||||||