This commit is contained in:
Hugo LEVY-FALK 2019-04-21 23:14:28 +02:00
parent 11c361153d
commit 3fd4b6eac4
8 changed files with 65 additions and 65 deletions

View file

@ -242,8 +242,4 @@ channels:
port: 6667
channel: "#centrale-supelec"
bots: [Souby, Chuck]
- server: irc.rezometz.org
port: 6667
channel: "#monit"
bots: [rip_lorrabelle]

View file

@ -3,6 +3,7 @@ import random
import importlib
import datetime
class Bot:
def __init__(self, nickname):
"""Initialize a bot object
@ -17,8 +18,8 @@ class Bot:
self.reactions = {}
self.pings = []
self.on_join = None
self.tg_user_match = re.compile('^<\x03..\x02\x02(?P<username>.+)\x03>')
self.ping_match = re.compile('(<.+> )?\@?{name}'.format(name=nickname))
self.tg_user_match = re.compile("^<\x03..\x02\x02(?P<username>.+)\x03>")
self.ping_match = re.compile("(<.+> )?\@?{name}".format(name=nickname))
self.min_time = 0
self.last_time = datetime.datetime(1, 1, 1)
@ -30,9 +31,9 @@ class Bot:
reaction: The string which will be sent.
"""
context = {
'server': self.server,
'channel': self.channel,
'name': self.nickname,
"server": self.server,
"channel": self.channel,
"name": self.nickname,
}
self.reactions[re.compile(match.format(**context))] = reaction
@ -55,8 +56,8 @@ class Bot:
def fetch_callback(self, path):
"""Fetch a Python callable"""
s = path.split('.')
module, callback = '.'.join(s[:-1]), s[-1]
s = path.split(".")
module, callback = ".".join(s[:-1]), s[-1]
module = importlib.import_module(module)
return getattr(module, callback)
@ -73,17 +74,17 @@ class Bot:
"""
if (datetime.datetime.now() - self.last_time).total_seconds() < self.min_time:
return []
username = user.split('!')[0]
username = user.split("!")[0]
tg_user_match = self.tg_user_match.match(message)
if 'bot' in username.lower() and tg_user_match:
username = '@' + tg_user_match.groupdict()['username']
if "bot" in username.lower() and tg_user_match:
username = "@" + tg_user_match.groupdict()["username"]
context = {
'server': self.server,
'channel': channel,
'name': self.nickname,
'user': username,
'message': message
"server": self.server,
"channel": channel,
"name": self.nickname,
"user": username,
"message": message,
}
result = []
for m in self.reactions.keys():
@ -102,10 +103,9 @@ class Bot:
r = r(self, username, channel, message)
else:
r = r.format(**context)
result.append(' : '.join([username, r]))
result.append(" : ".join([username, r]))
if len(result) > 0:
self.last_time = datetime.datetime.now()
return result

View file

@ -6,8 +6,9 @@ import json
def get_content():
r = requests.get('https://api.chucknorris.io/jokes/random')
return json.loads(r.content)['value']
r = requests.get("https://api.chucknorris.io/jokes/random")
return json.loads(r.content)["value"]
def on_ping(bot, user, channel, message):
return get_content()

View file

@ -6,34 +6,36 @@ from twisted.internet import reactor, protocol
from .bot import Bot
from .settings import logger
class IRCBot(irc.IRCClient):
"""An IRC bot"""
def connectionMade(self):
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)
def connectionLost(self, reason):
super(IRCBot, self).connectionLost(reason)
logger.info('{name} is disconnected : {reason}'.format(
name=self.nickname,
reason = reason
))
logger.info(
"{name} is disconnected : {reason}".format(
name=self.nickname, reason=reason
)
)
def signedOn(self):
self.join(self.factory.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:
self.say(self.factory.channel, self.factory.bot.on_join)
def privmsg(self, 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:
logger.info(self.nickname + ' reacting to ' + msg)
logger.info(self.nickname + " reacting to " + msg)
for r in results:
self.say(self.factory.channel, r)
@ -49,7 +51,7 @@ class IRCBotFactory(protocol.ClientFactory):
connector.connect()
def clientConnectionFailed(self, connector, reason):
logger.info("Connection failed : " + reason)
logger.info("Connection failed : " + str(reason))
reactor.stop()
def buildProtocol(self, addr):
@ -57,4 +59,3 @@ class IRCBotFactory(protocol.ClientFactory):
p.factory = self
p.nickname = self.bot.nickname
return p

View file

@ -6,39 +6,39 @@ from .settings import logger
class Loader:
def __init__(self, filename):
logger.info('Loading configuration from ' + filename)
logger.info("Loading configuration from " + filename)
with open(filename) as f:
self.dict = yaml.load(f)
self.bots = []
def load_bot_template(self, name, channel, serv, port):
template = self.dict['bots'][name]
template = self.dict["bots"][name]
b = Bot(nickname=name)
b.server = serv
b.channel = channel
b.port = port
for ping in template.get('on_ping', []):
for ping in template.get("on_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)
matches = template.get('on_match', [])
matches = template.get("on_match", [])
for match in matches:
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.on_join = template.get('on_join', None)
b.min_time = template.get('min_time', 20)
b.on_join = template.get("on_join", None)
b.min_time = template.get("min_time", 20)
return b
def load_bots(self):
for channel in self.dict['channels']:
name = channel['channel']
serv = channel['server']
port = channel.get('port', 6667)
bots_name = channel['bots']
for channel in self.dict["channels"]:
name = channel["channel"]
serv = channel["server"]
port = channel.get("port", 6667)
bots_name = channel["bots"]
for nickname in bots_name:
b = self.load_bot_template(nickname, name, serv, port)

View file

@ -4,6 +4,7 @@ from .loader import Loader
from .irc import IRCBotFactory
from .settings import logger, BOT_FILE
class Runner:
def __init__(self):
self.loader = Loader(BOT_FILE)
@ -15,7 +16,8 @@ class Runner:
reactor.connectTCP(bot.server, bot.port, bot_factory)
reactor.run()
def run():
logger.info('Klafirc is running !')
logger.info("Klafirc is running !")
runner = Runner()
runner.run()

View file

@ -1,14 +1,14 @@
import logging
from logging.handlers import RotatingFileHandler
DEBUG = False
DEBUG = True
if not DEBUG:
BOT_FILE = '/etc/klafirc/bots.yaml'
LOG_FILE = '/var/log/klafirc/klafirc.log'
BOT_FILE = "/etc/klafirc/bots.yaml"
LOG_FILE = "/var/log/klafirc/klafirc.log"
else:
BOT_FILE = './bots.yaml'
LOG_FILE = './klafirc.log'
BOT_FILE = "./bots.yaml"
LOG_FILE = "./klafirc.log"
logger = logging.getLogger()
@ -17,8 +17,8 @@ if DEBUG:
else:
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')
file_handler = RotatingFileHandler(LOG_FILE, 'a', 1000000, 1)
formatter = logging.Formatter("%(asctime)s :: %(levelname)s :: %(message)s")
file_handler = RotatingFileHandler(LOG_FILE, "a", 1000000, 1)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

View file

@ -1,19 +1,19 @@
from setuptools import setup, find_packages
setup(
name='Klafirc',
name="Klafirc",
version="0.1",
long_description=open('README.md').read(),
url='http://gitlab.rezometz.org/klafyvel/klafirc',
author='klafyvel',
long_description=open("README.md").read(),
url="http://gitlab.rezometz.org/klafyvel/klafirc",
author="klafyvel",
author_email="me@klafyvel.me",
include_package_data=True,
packages=find_packages(),
install_requires= open('requirements.txt').read().split('\n'),
install_requires=open("requirements.txt").read().split("\n"),
classifier=[
'Development Status :: 4 - Beta',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3',
'Topic :: Utilities',
"Development Status :: 4 - Beta",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3",
"Topic :: Utilities",
],
)