blacked
This commit is contained in:
parent
11c361153d
commit
3fd4b6eac4
8 changed files with 65 additions and 65 deletions
|
@ -226,7 +226,7 @@ bots:
|
||||||
- "Bref."
|
- "Bref."
|
||||||
- "D'accord ? Ok ? Voilà. Alors..."
|
- "D'accord ? Ok ? Voilà. Alors..."
|
||||||
min_time: 1 # in seconds
|
min_time: 1 # in seconds
|
||||||
|
|
||||||
rip_lorrabelle:
|
rip_lorrabelle:
|
||||||
on_ping:
|
on_ping:
|
||||||
- "Not under my watch."
|
- "Not under my watch."
|
||||||
|
@ -242,8 +242,4 @@ channels:
|
||||||
port: 6667
|
port: 6667
|
||||||
channel: "#centrale-supelec"
|
channel: "#centrale-supelec"
|
||||||
bots: [Souby, Chuck]
|
bots: [Souby, Chuck]
|
||||||
- server: irc.rezometz.org
|
|
||||||
port: 6667
|
|
||||||
channel: "#monit"
|
|
||||||
bots: [rip_lorrabelle]
|
|
||||||
|
|
||||||
|
|
|
@ -3,6 +3,7 @@ import random
|
||||||
import importlib
|
import importlib
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
|
|
||||||
class Bot:
|
class Bot:
|
||||||
def __init__(self, nickname):
|
def __init__(self, nickname):
|
||||||
"""Initialize a bot object
|
"""Initialize a bot object
|
||||||
|
@ -17,10 +18,10 @@ class Bot:
|
||||||
self.reactions = {}
|
self.reactions = {}
|
||||||
self.pings = []
|
self.pings = []
|
||||||
self.on_join = None
|
self.on_join = None
|
||||||
self.tg_user_match = re.compile('^<\x03..\x02\x02(?P<username>.+)\x03>')
|
self.tg_user_match = re.compile("^<\x03..\x02\x02(?P<username>.+)\x03>")
|
||||||
self.ping_match = re.compile('(<.+> )?\@?{name}'.format(name=nickname))
|
self.ping_match = re.compile("(<.+> )?\@?{name}".format(name=nickname))
|
||||||
self.min_time = 0
|
self.min_time = 0
|
||||||
self.last_time = datetime.datetime(1,1,1)
|
self.last_time = datetime.datetime(1, 1, 1)
|
||||||
|
|
||||||
def add_reaction(self, match, reaction):
|
def add_reaction(self, match, reaction):
|
||||||
"""Add a reaction to the bot.
|
"""Add a reaction to the bot.
|
||||||
|
@ -30,9 +31,9 @@ class Bot:
|
||||||
reaction: The string which will be sent.
|
reaction: The string which will be sent.
|
||||||
"""
|
"""
|
||||||
context = {
|
context = {
|
||||||
'server': self.server,
|
"server": self.server,
|
||||||
'channel': self.channel,
|
"channel": self.channel,
|
||||||
'name': self.nickname,
|
"name": self.nickname,
|
||||||
}
|
}
|
||||||
self.reactions[re.compile(match.format(**context))] = reaction
|
self.reactions[re.compile(match.format(**context))] = reaction
|
||||||
|
|
||||||
|
@ -55,8 +56,8 @@ class Bot:
|
||||||
|
|
||||||
def fetch_callback(self, path):
|
def fetch_callback(self, path):
|
||||||
"""Fetch a Python callable"""
|
"""Fetch a Python callable"""
|
||||||
s = path.split('.')
|
s = path.split(".")
|
||||||
module, callback = '.'.join(s[:-1]), s[-1]
|
module, callback = ".".join(s[:-1]), s[-1]
|
||||||
module = importlib.import_module(module)
|
module = importlib.import_module(module)
|
||||||
return getattr(module, callback)
|
return getattr(module, callback)
|
||||||
|
|
||||||
|
@ -73,17 +74,17 @@ class Bot:
|
||||||
"""
|
"""
|
||||||
if (datetime.datetime.now() - self.last_time).total_seconds() < self.min_time:
|
if (datetime.datetime.now() - self.last_time).total_seconds() < self.min_time:
|
||||||
return []
|
return []
|
||||||
username = user.split('!')[0]
|
username = user.split("!")[0]
|
||||||
tg_user_match = self.tg_user_match.match(message)
|
tg_user_match = self.tg_user_match.match(message)
|
||||||
if 'bot' in username.lower() and tg_user_match:
|
if "bot" in username.lower() and tg_user_match:
|
||||||
username = '@' + tg_user_match.groupdict()['username']
|
username = "@" + tg_user_match.groupdict()["username"]
|
||||||
|
|
||||||
context = {
|
context = {
|
||||||
'server': self.server,
|
"server": self.server,
|
||||||
'channel': channel,
|
"channel": channel,
|
||||||
'name': self.nickname,
|
"name": self.nickname,
|
||||||
'user': username,
|
"user": username,
|
||||||
'message': message
|
"message": message,
|
||||||
}
|
}
|
||||||
result = []
|
result = []
|
||||||
for m in self.reactions.keys():
|
for m in self.reactions.keys():
|
||||||
|
@ -102,10 +103,9 @@ class Bot:
|
||||||
r = r(self, username, channel, message)
|
r = r(self, username, channel, message)
|
||||||
else:
|
else:
|
||||||
r = r.format(**context)
|
r = r.format(**context)
|
||||||
result.append(' : '.join([username, r]))
|
result.append(" : ".join([username, r]))
|
||||||
|
|
||||||
if len(result) > 0:
|
if len(result) > 0:
|
||||||
self.last_time = datetime.datetime.now()
|
self.last_time = datetime.datetime.now()
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
|
@ -6,8 +6,9 @@ import json
|
||||||
|
|
||||||
|
|
||||||
def get_content():
|
def get_content():
|
||||||
r = requests.get('https://api.chucknorris.io/jokes/random')
|
r = requests.get("https://api.chucknorris.io/jokes/random")
|
||||||
return json.loads(r.content)['value']
|
return json.loads(r.content)["value"]
|
||||||
|
|
||||||
|
|
||||||
def on_ping(bot, user, channel, message):
|
def on_ping(bot, user, channel, message):
|
||||||
return get_content()
|
return get_content()
|
||||||
|
|
|
@ -6,34 +6,36 @@ from twisted.internet import reactor, protocol
|
||||||
from .bot import Bot
|
from .bot import Bot
|
||||||
from .settings import logger
|
from .settings import logger
|
||||||
|
|
||||||
|
|
||||||
class IRCBot(irc.IRCClient):
|
class IRCBot(irc.IRCClient):
|
||||||
"""An IRC bot"""
|
"""An IRC bot"""
|
||||||
|
|
||||||
def connectionMade(self):
|
def connectionMade(self):
|
||||||
super(IRCBot, self).connectionMade()
|
super(IRCBot, self).connectionMade()
|
||||||
logger.info('{name} is connected'.format(name=self.nickname))
|
logger.info("{name} is connected".format(name=self.nickname))
|
||||||
self.join(self.factory.channel)
|
self.join(self.factory.channel)
|
||||||
|
|
||||||
def connectionLost(self, reason):
|
def connectionLost(self, reason):
|
||||||
super(IRCBot, self).connectionLost(reason)
|
super(IRCBot, self).connectionLost(reason)
|
||||||
logger.info('{name} is disconnected : {reason}'.format(
|
logger.info(
|
||||||
name=self.nickname,
|
"{name} is disconnected : {reason}".format(
|
||||||
reason = reason
|
name=self.nickname, reason=reason
|
||||||
))
|
)
|
||||||
|
)
|
||||||
|
|
||||||
def signedOn(self):
|
def signedOn(self):
|
||||||
self.join(self.factory.channel)
|
self.join(self.factory.channel)
|
||||||
|
|
||||||
def joined(self, channel):
|
def joined(self, channel):
|
||||||
logger.info(self.nickname + ' joined ' + self.factory.channel)
|
logger.info(self.nickname + " joined " + self.factory.channel)
|
||||||
if self.factory.bot.on_join is not None:
|
if self.factory.bot.on_join is not None:
|
||||||
self.say(self.factory.channel, self.factory.bot.on_join)
|
self.say(self.factory.channel, self.factory.bot.on_join)
|
||||||
|
|
||||||
def privmsg(self, user, channel, msg):
|
def privmsg(self, user, channel, msg):
|
||||||
results = self.factory.bot.get_reaction(user, channel, msg)
|
results = self.factory.bot.get_reaction(user, channel, msg)
|
||||||
logger.debug(self.nickname + ' heard ' + msg)
|
logger.debug(self.nickname + " heard " + msg)
|
||||||
if results:
|
if results:
|
||||||
logger.info(self.nickname + ' reacting to ' + msg)
|
logger.info(self.nickname + " reacting to " + msg)
|
||||||
for r in results:
|
for r in results:
|
||||||
self.say(self.factory.channel, r)
|
self.say(self.factory.channel, r)
|
||||||
|
|
||||||
|
@ -49,7 +51,7 @@ class IRCBotFactory(protocol.ClientFactory):
|
||||||
connector.connect()
|
connector.connect()
|
||||||
|
|
||||||
def clientConnectionFailed(self, connector, reason):
|
def clientConnectionFailed(self, connector, reason):
|
||||||
logger.info("Connection failed : " + reason)
|
logger.info("Connection failed : " + str(reason))
|
||||||
reactor.stop()
|
reactor.stop()
|
||||||
|
|
||||||
def buildProtocol(self, addr):
|
def buildProtocol(self, addr):
|
||||||
|
@ -57,4 +59,3 @@ class IRCBotFactory(protocol.ClientFactory):
|
||||||
p.factory = self
|
p.factory = self
|
||||||
p.nickname = self.bot.nickname
|
p.nickname = self.bot.nickname
|
||||||
return p
|
return p
|
||||||
|
|
||||||
|
|
|
@ -6,39 +6,39 @@ from .settings import logger
|
||||||
|
|
||||||
class Loader:
|
class Loader:
|
||||||
def __init__(self, filename):
|
def __init__(self, filename):
|
||||||
logger.info('Loading configuration from ' + filename)
|
logger.info("Loading configuration from " + filename)
|
||||||
with open(filename) as f:
|
with open(filename) as f:
|
||||||
self.dict = yaml.load(f)
|
self.dict = yaml.load(f)
|
||||||
self.bots = []
|
self.bots = []
|
||||||
|
|
||||||
def load_bot_template(self, name, channel, serv, port):
|
def load_bot_template(self, name, channel, serv, port):
|
||||||
template = self.dict['bots'][name]
|
template = self.dict["bots"][name]
|
||||||
b = Bot(nickname=name)
|
b = Bot(nickname=name)
|
||||||
b.server = serv
|
b.server = serv
|
||||||
b.channel = channel
|
b.channel = channel
|
||||||
b.port = port
|
b.port = port
|
||||||
for ping in template.get('on_ping', []):
|
for ping in template.get("on_ping", []):
|
||||||
b.add_ping(ping)
|
b.add_ping(ping)
|
||||||
for ping in template.get('on_ping_python', []):
|
for ping in template.get("on_ping_python", []):
|
||||||
b.add_python_ping(ping)
|
b.add_python_ping(ping)
|
||||||
|
|
||||||
matches = template.get('on_match', [])
|
matches = template.get("on_match", [])
|
||||||
for match in matches:
|
for match in matches:
|
||||||
b.add_reaction(match, matches[match])
|
b.add_reaction(match, matches[match])
|
||||||
for match in template.get('on_match_python', []):
|
for match in template.get("on_match_python", []):
|
||||||
b.add_python_reaction(match, matches[match])
|
b.add_python_reaction(match, matches[match])
|
||||||
|
|
||||||
b.on_join = template.get('on_join', None)
|
b.on_join = template.get("on_join", None)
|
||||||
b.min_time = template.get('min_time', 20)
|
b.min_time = template.get("min_time", 20)
|
||||||
|
|
||||||
return b
|
return b
|
||||||
|
|
||||||
def load_bots(self):
|
def load_bots(self):
|
||||||
for channel in self.dict['channels']:
|
for channel in self.dict["channels"]:
|
||||||
name = channel['channel']
|
name = channel["channel"]
|
||||||
serv = channel['server']
|
serv = channel["server"]
|
||||||
port = channel.get('port', 6667)
|
port = channel.get("port", 6667)
|
||||||
bots_name = channel['bots']
|
bots_name = channel["bots"]
|
||||||
|
|
||||||
for nickname in bots_name:
|
for nickname in bots_name:
|
||||||
b = self.load_bot_template(nickname, name, serv, port)
|
b = self.load_bot_template(nickname, name, serv, port)
|
||||||
|
|
|
@ -4,6 +4,7 @@ from .loader import Loader
|
||||||
from .irc import IRCBotFactory
|
from .irc import IRCBotFactory
|
||||||
from .settings import logger, BOT_FILE
|
from .settings import logger, BOT_FILE
|
||||||
|
|
||||||
|
|
||||||
class Runner:
|
class Runner:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.loader = Loader(BOT_FILE)
|
self.loader = Loader(BOT_FILE)
|
||||||
|
@ -15,7 +16,8 @@ class Runner:
|
||||||
reactor.connectTCP(bot.server, bot.port, bot_factory)
|
reactor.connectTCP(bot.server, bot.port, bot_factory)
|
||||||
reactor.run()
|
reactor.run()
|
||||||
|
|
||||||
|
|
||||||
def run():
|
def run():
|
||||||
logger.info('Klafirc is running !')
|
logger.info("Klafirc is running !")
|
||||||
runner = Runner()
|
runner = Runner()
|
||||||
runner.run()
|
runner.run()
|
||||||
|
|
|
@ -1,14 +1,14 @@
|
||||||
import logging
|
import logging
|
||||||
from logging.handlers import RotatingFileHandler
|
from logging.handlers import RotatingFileHandler
|
||||||
|
|
||||||
DEBUG = False
|
DEBUG = True
|
||||||
|
|
||||||
if not DEBUG:
|
if not DEBUG:
|
||||||
BOT_FILE = '/etc/klafirc/bots.yaml'
|
BOT_FILE = "/etc/klafirc/bots.yaml"
|
||||||
LOG_FILE = '/var/log/klafirc/klafirc.log'
|
LOG_FILE = "/var/log/klafirc/klafirc.log"
|
||||||
else:
|
else:
|
||||||
BOT_FILE = './bots.yaml'
|
BOT_FILE = "./bots.yaml"
|
||||||
LOG_FILE = './klafirc.log'
|
LOG_FILE = "./klafirc.log"
|
||||||
|
|
||||||
logger = logging.getLogger()
|
logger = logging.getLogger()
|
||||||
|
|
||||||
|
@ -17,8 +17,8 @@ if DEBUG:
|
||||||
else:
|
else:
|
||||||
logger.setLevel(logging.INFO)
|
logger.setLevel(logging.INFO)
|
||||||
|
|
||||||
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')
|
formatter = logging.Formatter("%(asctime)s :: %(levelname)s :: %(message)s")
|
||||||
file_handler = RotatingFileHandler(LOG_FILE, 'a', 1000000, 1)
|
file_handler = RotatingFileHandler(LOG_FILE, "a", 1000000, 1)
|
||||||
file_handler.setLevel(logging.DEBUG)
|
file_handler.setLevel(logging.DEBUG)
|
||||||
file_handler.setFormatter(formatter)
|
file_handler.setFormatter(formatter)
|
||||||
logger.addHandler(file_handler)
|
logger.addHandler(file_handler)
|
||||||
|
|
18
setup.py
18
setup.py
|
@ -1,19 +1,19 @@
|
||||||
from setuptools import setup, find_packages
|
from setuptools import setup, find_packages
|
||||||
|
|
||||||
setup(
|
setup(
|
||||||
name='Klafirc',
|
name="Klafirc",
|
||||||
version="0.1",
|
version="0.1",
|
||||||
long_description=open('README.md').read(),
|
long_description=open("README.md").read(),
|
||||||
url='http://gitlab.rezometz.org/klafyvel/klafirc',
|
url="http://gitlab.rezometz.org/klafyvel/klafirc",
|
||||||
author='klafyvel',
|
author="klafyvel",
|
||||||
author_email="me@klafyvel.me",
|
author_email="me@klafyvel.me",
|
||||||
include_package_data=True,
|
include_package_data=True,
|
||||||
packages=find_packages(),
|
packages=find_packages(),
|
||||||
install_requires= open('requirements.txt').read().split('\n'),
|
install_requires=open("requirements.txt").read().split("\n"),
|
||||||
classifier=[
|
classifier=[
|
||||||
'Development Status :: 4 - Beta',
|
"Development Status :: 4 - Beta",
|
||||||
'Operating System :: POSIX :: Linux',
|
"Operating System :: POSIX :: Linux",
|
||||||
'Programming Language :: Python :: 3',
|
"Programming Language :: Python :: 3",
|
||||||
'Topic :: Utilities',
|
"Topic :: Utilities",
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
Loading…
Reference in a new issue