/usr/share/pyshared/fedmsg/consumers/ircbot.py is in python-fedmsg 0.7.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | # This file is part of fedmsg.
# Copyright (C) 2012 Red Hat, Inc.
#
# fedmsg is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# fedmsg is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with fedmsg; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Authors: Ralph Bean <rbean@redhat.com>
#
# -*- coding; utf-8 -*-
# Author: Ryan Brown
# Author: Ralph Bean
# Description: A bot that takes a config and puts messages matching given
# regexes in specified IRC channels
import fedmsg
import fedmsg.encoding
import fedmsg.meta
from fedmsg.meta import _
import copy
import re
import time
import pygments
import pygments.lexers
import pygments.formatters
from fedmsg.consumers import FedmsgConsumer
from twisted.words.protocols import irc
from twisted.internet import protocol
from twisted.internet import reactor
from twisted.internet import defer
import logging
log = logging.getLogger(__name__)
mirc_colors = {
"white": 0,
"black": 1,
"blue": 2,
"green": 3,
"red": 4,
"brown": 5,
"purple": 6,
"orange": 7,
"yellow": 8,
"light green": 9,
"teal": 10,
"light cyan": 11,
"light blue": 12,
"pink": 13,
"grey": 14,
"light grey": 15,
}
def ircprettify(title, subtitle, link="", config=None):
def markup(s, color):
return "\x03%i%s\x03" % (mirc_colors[color], s)
config = config or {}
if link:
link = markup(link, "teal")
color_lookup = config.get('irc_color_lookup', {})
title_color = color_lookup.get(title.split('.')[0], "light grey")
title = markup(title, title_color)
fmt = u"{title} -- {subtitle} {link}"
return fmt.format(title=title, subtitle=subtitle, link=link)
class FedMsngr(irc.IRCClient):
# The 0.6 seconds here is empircally guessed so we don't get dropped by
# freenode. FIXME - this should be pulled from the config.
lineRate = 0.6
sourceURL = "http://github.com/fedora-infra/fedmsg"
def __init__(self, *args, **kw):
super(FedMsgnr, self).__init__(*args, **kw)
def _get_nickname(self):
return self.factory.nickname
nickname = property(_get_nickname)
def __init__(self, *args, **kwargs):
self._modecallback = {}
def signedOn(self):
self.join(self.factory.channel)
log.info("Signed on as %s." % (self.nickname,))
def joined(self, channel):
log.info("Joined %s." % (channel,))
self.factory.parent_consumer.add_irc_client(self)
def got_modes(modelist):
modes = ''.join(modelist)
if 'c' in modes:
log.info("%s has +c is on. No prettiness" % channel)
self.factory.pretty = False
self.modes(channel).addCallback(got_modes)
def modes(self, channel):
channel = channel.lower()
d = defer.Deferred()
if channel not in self._modecallback:
self._modecallback[channel] = ([], [])
self._modecallback[channel][0].append(d)
self.sendLine("MODE %s" % channel)
return d
def irc_RPL_CHANNELMODEIS(self, prefix, params):
""" Handy reference for IRC mnemonics
www.irchelp.org/irchelp/rfc/chapter4.html#c4_2_3 """
channel = params[1].lower()
modes = params[2]
if channel not in self._modecallback:
return
n = self._modecallback[channel][1]
n.append(modes)
callbacks, modelist = self._modecallback[channel]
for cb in callbacks:
cb.callback(modelist)
del self._modecallback[channel]
class FedMsngrFactory(protocol.ClientFactory):
protocol = FedMsngr
def __init__(self, channel, nickname, filters,
pretty, terse, parent_consumer):
self.channel = channel
self.nickname = nickname
self.filters = filters
self.pretty = pretty
self.terse = terse
self.parent_consumer = parent_consumer
self.log = logging.getLogger("moksha.hub")
def clientConnectionLost(self, connector, reason):
self.log.warning("Lost connection (%s), reconnecting." % (reason,))
self.parent_consumer.del_irc_clients(factory=self)
connector.connect()
def clientConnectionFailed(self, connector, reason):
self.log.error("Could not connect: %s" % (reason,))
class IRCBotConsumer(FedmsgConsumer):
validate_signatures = False
config_key = 'fedmsg.consumers.ircbot.enabled'
def __init__(self, hub):
self.hub = hub
self.DBSession = None
self.irc_clients = []
# The consumer should pick up *all* messages.
self.topic = self.hub.config.get('topic_prefix', 'org.fedoraproject')
if not self.topic.endswith('*'):
self.topic += '*'
super(IRCBotConsumer, self).__init__(hub)
fedmsg.meta.make_processors(**hub.config)
if not getattr(self, '_initialized', False):
return
irc_settings = hub.config.get('irc')
for settings in irc_settings:
network = settings.get('network', 'irc.freenode.net')
port = settings.get('port', 6667)
channel = settings.get('channel', None)
if not channel:
self.log.error("No channel specified. Ignoring entry.")
continue
if not channel.startswith("#"):
channel = "#" + channel
nickname = settings.get('nickname', "fedmsg-bot")
pretty = settings.get('make_pretty', False)
terse = settings.get('make_terse', False)
timeout = settings.get('timeout', 120)
filters = self.compile_filters(settings.get('filters', None))
factory = FedMsngrFactory(channel, nickname, filters,
pretty, terse, self)
reactor.connectTCP(network, port, factory, timeout=timeout)
def add_irc_client(self, client):
self.irc_clients.append(client)
def del_irc_clients(self, client=None, factory=None):
if factory:
self.irc_clients = [
c for c in self.irc_clients
if c.factory != factory
]
if client and client in self.irc_clients:
self.irc_clients.remove(client)
def compile_filters(self, filters):
compiled_filters = dict(topic=[], body=[])
for tag, flist in filters.items():
for f in flist:
compiled_filters[tag].append(re.compile(f))
return compiled_filters
def apply_filters(self, filters, topic, msg):
for f in filters.get('topic', []):
if f and re.search(f, topic):
return False
for f in filters.get('body', []):
type(msg)
if f and re.search(f, str(msg)):
return False
return True
def prettify(self, topic, msg, pretty=False, terse=False):
if terse:
if pretty:
title = fedmsg.meta.msg2title(msg, **self.hub.config)
if 'signature' not in msg:
title += " " + _("(unsigned)")
elif self.hub.config.get('validate_signatures'):
if not fedmsg.crypto.validate(msg, **self.hub.config):
title += " " + _("(invalid signature!)")
return ircprettify(
title=title,
subtitle=fedmsg.meta.msg2subtitle(msg, **self.hub.config),
link=fedmsg.meta.msg2link(msg, **self.hub.config),
config=self.hub.config,
)
else:
return fedmsg.meta.msg2repr(msg, **self.hub.config)
msg = copy.deepcopy(msg)
if msg.get('topic', None):
msg.pop('topic')
if msg.get('timestamp', None):
msg['timestamp'] = time.ctime(msg['timestamp'])
if pretty:
msg = pygments.highlight(
fedmsg.encoding.pretty_dumps(msg),
pygments.lexers.JavascriptLexer(),
pygments.formatters.TerminalFormatter()
).strip().encode('UTF-8')
return "{0:<30} {1}".format(topic, msg)
def consume(self, msg):
""" Forward on messages from the bus to all IRC connections. """
log.debug("Got message %r" % msg)
topic, body = msg.get('topic'), msg.get('body')
for client in self.irc_clients:
if not client.factory.filters or (
client.factory.filters and
self.apply_filters(client.factory.filters, topic, body)
):
raw_msg = self.prettify(
topic=topic,
msg=body,
pretty=client.factory.pretty,
terse=client.factory.terse,
)
raw_msg = raw_msg.encode('utf-8')
getattr(client, self.hub.config['irc_method'], 'notice')(
client.factory.channel,
raw_msg,
)
|