init: pristine aerc 0.20.0 source

This commit is contained in:
Mortdecai
2026-04-07 19:54:54 -04:00
commit 083402a548
502 changed files with 68722 additions and 0 deletions
+63
View File
@@ -0,0 +1,63 @@
###
# Copyright (c) 2005, Jeremiah Fincher
# Copyright (c) 2010-2021, Valentin Lorentz
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
"""
Plugin for keeping track of Karma for users and things in a channel.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
__version__ = ""
__author__ = supybot.authors.jemfinch
__maintainer__ = supybot.authors.limnoria_core
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
from . import config
from . import plugin
from importlib import reload
reload(plugin) # In case we're being reloaded.
# Add more reloads here if you add third-party modules and want them to be
# reloaded when this plugin is reloaded. Don't forget to import them as well!
if world.testing:
from . import test
Class = plugin.Class
configure = config.configure
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
+74
View File
@@ -0,0 +1,74 @@
###
# Copyright (c) 2005, Jeremiah Fincher
# Copyright (c) 2010-2021, Valentin Lorentz
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
import supybot.conf as conf
import supybot.registry as registry
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('Karma')
def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified themself as an advanced
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('Karma', True)
Karma = conf.registerPlugin('Karma')
conf.registerChannelValue(Karma, 'simpleOutput',
registry.Boolean(False, _("""Determines whether the bot will output shorter
versions of the karma output when requesting a single thing's karma.""")))
conf.registerChannelValue(Karma, 'incrementChars',
registry.SpaceSeparatedListOfStrings(['++'], _("""A space separated list of
characters to increase karma.""")))
conf.registerChannelValue(Karma, 'decrementChars',
registry.SpaceSeparatedListOfStrings(['--'], _("""A space separated list of
characters to decrease karma.""")))
conf.registerChannelValue(Karma, 'response',
registry.Boolean(False, _("""Determines whether the bot will reply with a
success message when something's karma is increased or decreased.""")))
conf.registerChannelValue(Karma, 'rankingDisplay',
registry.Integer(3, _("""Determines how many highest/lowest karma things
are shown when karma is called with no arguments.""")))
conf.registerChannelValue(Karma, 'mostDisplay',
registry.Integer(25, _("""Determines how many karma things are shown when
the most command is called.""")))
conf.registerChannelValue(Karma, 'allowSelfRating',
registry.Boolean(False, _("""Determines whether users can adjust the karma
of their nick.""")))
conf.registerChannelValue(Karma, 'allowUnaddressedKarma',
registry.Boolean(True, _("""Determines whether the bot will
increase/decrease karma without being addressed.""")))
conf.registerChannelValue(Karma, 'onlyNicks',
registry.Boolean(False, _("""Determines whether the bot will
only increase/decrease karma for nicks in the current channel.""")))
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
+469
View File
@@ -0,0 +1,469 @@
###
# Copyright (c) 2005, Jeremiah Fincher
# Copyright (c) 2010, James McCoy
# Copyright (c) 2010-2021, Valentin Lorentz
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
import os
import re
import sys
import csv
import time
import random
import supybot.conf as conf
import supybot.utils as utils
from supybot.commands import *
import supybot.utils.minisix as minisix
import supybot.plugins as plugins
import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
import supybot.schedule as schedule
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('Karma')
import sqlite3
def checkAllowShell(irc):
if not conf.supybot.commands.allowShell():
irc.error('This command is not available, because '
'supybot.commands.allowShell is False.', Raise=True)
class SqliteKarmaDB(object):
def __init__(self, filename):
self.dbs = ircutils.IrcDict()
self.filename = filename
def close(self):
for db in self.dbs.values():
db.close()
def _getDb(self, channel):
filename = plugins.makeChannelFilename(self.filename, channel)
if filename in self.dbs:
return self.dbs[filename]
if os.path.exists(filename):
db = sqlite3.connect(filename, check_same_thread=False)
if minisix.PY2:
db.text_factory = str
self.dbs[filename] = db
return db
db = sqlite3.connect(filename, check_same_thread=False)
if minisix.PY2:
db.text_factory = str
self.dbs[filename] = db
cursor = db.cursor()
cursor.execute("""CREATE TABLE karma (
id INTEGER PRIMARY KEY,
name TEXT,
normalized TEXT UNIQUE ON CONFLICT IGNORE,
added INTEGER,
subtracted INTEGER
)""")
db.commit()
def p(s1, s2):
return int(ircutils.nickEqual(s1, s2))
db.create_function('nickeq', 2, p)
return db
def get(self, channel, thing):
db = self._getDb(channel)
thing = thing.lower()
cursor = db.cursor()
cursor.execute("""SELECT added, subtracted FROM karma
WHERE normalized=?""", (thing,))
results = cursor.fetchall()
if len(results) == 0:
return None
else:
return list(map(int, results[0]))
def gets(self, channel, things):
db = self._getDb(channel)
cursor = db.cursor()
normalizedThings = dict(list(zip([s.lower() for s in things], things)))
criteria = ' OR '.join(['normalized=?'] * len(normalizedThings))
sql = """SELECT name, added-subtracted FROM karma
WHERE %s ORDER BY added-subtracted DESC""" % criteria
cursor.execute(sql, list(normalizedThings.keys()))
L = [(name, int(karma)) for (name, karma) in cursor.fetchall()]
for (name, _) in L:
del normalizedThings[name.lower()]
neutrals = list(normalizedThings.values())
neutrals.sort()
return (L, neutrals)
def top(self, channel, limit):
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute("""SELECT name, added-subtracted FROM karma
ORDER BY added-subtracted DESC LIMIT ?""", (limit,))
return [(t[0], int(t[1])) for t in cursor.fetchall()]
def bottom(self, channel, limit):
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute("""SELECT name, added-subtracted FROM karma
ORDER BY added-subtracted ASC LIMIT ?""", (limit,))
return [(t[0], int(t[1])) for t in cursor.fetchall()]
def rank(self, channel, thing):
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute("""SELECT added-subtracted FROM karma
WHERE name=?""", (thing,))
results = cursor.fetchall()
if len(results) == 0:
return None
karma = int(results[0][0])
cursor.execute("""SELECT COUNT(*) FROM karma
WHERE added-subtracted > ?""", (karma,))
rank = int(cursor.fetchone()[0])
return rank+1
def size(self, channel):
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute("""SELECT COUNT(*) FROM karma""")
return int(cursor.fetchone()[0])
def increment(self, channel, name):
db = self._getDb(channel)
cursor = db.cursor()
normalized = name.lower()
cursor.execute("""INSERT INTO karma VALUES (NULL, ?, ?, 0, 0)""",
(name, normalized,))
cursor.execute("""UPDATE karma SET added=added+1
WHERE normalized=?""", (normalized,))
db.commit()
def decrement(self, channel, name):
db = self._getDb(channel)
cursor = db.cursor()
normalized = name.lower()
cursor.execute("""INSERT INTO karma VALUES (NULL, ?, ?, 0, 0)""",
(name, normalized,))
cursor.execute("""UPDATE karma SET subtracted=subtracted+1
WHERE normalized=?""", (normalized,))
db.commit()
def most(self, channel, kind, limit):
if kind == 'increased':
orderby = 'added'
elif kind == 'decreased':
orderby = 'subtracted'
elif kind == 'active':
orderby = 'added+subtracted'
else:
raise ValueError('invalid kind')
sql = """SELECT name, %s FROM karma ORDER BY %s DESC LIMIT %s""" % \
(orderby, orderby, limit)
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute(sql)
return [(name, int(i)) for (name, i) in cursor.fetchall()]
def clear(self, channel, name=None):
db = self._getDb(channel)
cursor = db.cursor()
if name:
normalized = name.lower()
cursor.execute("""DELETE FROM karma
WHERE normalized=?""", (normalized,))
else:
cursor.execute("""DELETE FROM karma""")
db.commit()
def dump(self, channel, filename):
filename = conf.supybot.directories.data.dirize(filename)
fd = utils.file.AtomicFile(filename)
out = csv.writer(fd)
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute("""SELECT name, added, subtracted FROM karma""")
for (name, added, subtracted) in cursor.fetchall():
out.writerow([name, added, subtracted])
fd.close()
def load(self, channel, filename):
filename = conf.supybot.directories.data.dirize(filename)
fd = open(filename, encoding='utf8')
reader = csv.reader(fd)
db = self._getDb(channel)
cursor = db.cursor()
cursor.execute("""DELETE FROM karma""")
for (name, added, subtracted) in reader:
normalized = name.lower()
cursor.execute("""INSERT INTO karma
VALUES (NULL, ?, ?, ?, ?)""",
(name, normalized, added, subtracted,))
db.commit()
fd.close()
KarmaDB = plugins.DB('Karma',
{'sqlite3': SqliteKarmaDB})
class Karma(callbacks.Plugin):
"""
Provides a simple tracker for setting Karma (thing++, thing--).
If ``config plugins.karma.allowUnaddressedKarma`` is set to ``True``
(default since 2014.05.07), saying `boats++` will give 1 karma
to ``boats``, and ``ships--`` will subtract 1 karma from ``ships``.
However, if you use this in a sentence, like
``That deserves a ++. Kevin++``, 1 karma will be added to
``That deserves a ++. Kevin``, so you should only add or subtract karma
in a line that doesn't have anything else in it.
Alternatively, you can restrict karma tracking to nicks in the current
channel by setting `config plugins.Karma.onlyNicks` to ``True``.
If ``config plugins.karma.allowUnaddressedKarma` is set to `False``,
you must address the bot with nick or prefix to add or subtract karma.
"""
callBefore = ('Factoids', 'MoobotFactoids', 'Infobot')
def __init__(self, irc):
self.__parent = super(Karma, self)
self.__parent.__init__(irc)
self.db = KarmaDB()
def die(self):
self.__parent.die()
self.db.close()
def _normalizeThing(self, thing):
assert thing
if thing[0] == '(' and thing[-1] == ')':
thing = thing[1:-1]
return thing
def _respond(self, irc, channel, thing, karma):
if self.registryValue('response', channel, irc.network):
irc.reply(_('%(thing)s\'s karma is now %(karma)i') %
{'thing': thing, 'karma': karma})
else:
irc.noReply()
IRC_NICK = r'\w[\w\\`\[\]\{\}\^-]*'
TABLE_FLIP = re.compile(r'\s*[\(]╯...[\)]╯\s*︵\s*.*', re.U)
def _doKarma(self, irc, msg, channel, line):
match = self.TABLE_FLIP.match(line)
if match:
event_name = f'unflip {msg.nic}'
try:
schedule.removeEvent(event_name)
except KeyError:
pass
schedule.addEvent(
irc.reply,
time.time() + random.lognormvariate(0.5, 0.5),
name=event_name,
args=['┳━┳ノ(°_°ノ)'],
)
return
inc = self.registryValue('incrementChars', channel, irc.network)
dec = self.registryValue('decrementChars', channel, irc.network)
onlynicks = self.registryValue('onlyNicks', channel, irc.network)
karma = {}
for s in inc:
regex = re.compile(rf'\b({self.IRC_NICK})\b{re.escape(s)}')
for match in regex.finditer(line):
thing = match.group(1)
# Don't reply if the target isn't a nick
if onlynicks and thing.lower() not in map(ircutils.toLower,
irc.state.channels[channel].users):
return
if ircutils.strEqual(thing, msg.nick) and \
not self.registryValue('allowSelfRating',
channel, irc.network):
irc.error(_('You\'re not allowed to adjust your own karma.'))
return
self.db.increment(channel, self._normalizeThing(thing))
scores = self.db.get(channel, self._normalizeThing(thing))
if scores:
karma[thing] = scores[0] - scores[1]
for s in dec:
regex = re.compile(rf'\b({self.IRC_NICK})\b{re.escape(s)}')
for match in regex.finditer(line):
thing = match.group(1)
if onlynicks and thing.lower() not in map(ircutils.toLower,
irc.state.channels[channel].users):
return
if ircutils.strEqual(thing, msg.nick) and \
not self.registryValue('allowSelfRating',
channel, irc.network):
irc.error(_('You\'re not allowed to adjust your own karma.'))
return
self.db.decrement(channel, self._normalizeThing(thing))
scores = self.db.get(channel, self._normalizeThing(thing))
if scores:
karma[thing] = scores[0] - scores[1]
for thing, score in karma.items():
self._respond(irc, channel, thing, score)
def invalidCommand(self, irc, msg, tokens):
if msg.channel and tokens:
line = msg.args[1].rstrip()
self._doKarma(irc, msg, msg.channel, line)
def doPrivmsg(self, irc, msg):
# We don't handle this if we've been addressed because invalidCommand
# will handle it for us. This prevents us from accessing the db twice
# and therefore crashing.
if not (msg.addressed or msg.repliedTo):
if msg.channel and \
not ircmsgs.isCtcp(msg) and \
self.registryValue('allowUnaddressedKarma',
msg.channel, irc.network):
irc = callbacks.SimpleProxy(irc, msg)
line = msg.args[1].rstrip()
self._doKarma(irc, msg, msg.channel, line)
@internationalizeDocstring
def karma(self, irc, msg, args, channel, things):
"""[<channel>] [<thing> ...]
Returns the karma of <thing>. If <thing> is not given, returns the top
N karmas, where N is determined by the config variable
supybot.plugins.Karma.rankingDisplay. If one <thing> is given, returns
the details of its karma; if more than one <thing> is given, returns
the total karma of each of the things. <channel> is only necessary
if the message isn't sent on the channel itself.
"""
if len(things) == 1:
name = things[0]
t = self.db.get(channel, name)
if t is None:
irc.reply(format(_('%s has neutral karma.'), name))
else:
(added, subtracted) = t
total = added - subtracted
if self.registryValue('simpleOutput', channel, irc.network):
s = format('%s: %i', name, total)
else:
s = format(_('Karma for %q has been increased %n and '
'decreased %n for a total karma of %s.'),
name, (added, _('time')),
(subtracted, _('time')),
total)
irc.reply(s)
elif len(things) > 1:
(L, neutrals) = self.db.gets(channel, things)
if L:
s = format('%L', [format('%s: %i', *t) for t in L])
if neutrals:
neutral = format('. %L %h neutral karma',
neutrals, len(neutrals))
s += neutral
irc.reply(s + '.')
else:
irc.reply(_('I didn\'t know the karma for any of those '
'things.'))
else: # No name was given. Return the top/bottom N karmas.
limit = self.registryValue('rankingDisplay', channel, irc.network)
highest = [format('%q (%s)', s, t)
for (s, t) in self.db.top(channel, limit)]
lowest = [format('%q (%s)', s, t)
for (s, t) in self.db.bottom(channel, limit)]
if not (highest and lowest):
irc.error(_('I have no karma for this channel.'))
return
rank = self.db.rank(channel, msg.nick)
if rank is not None:
total = self.db.size(channel)
rankS = format(_(' You (%s) are ranked %i out of %i.'),
msg.nick, rank, total)
else:
rankS = ''
s = format(_('Highest karma: %L. Lowest karma: %L.%s'),
highest, lowest, rankS)
irc.reply(s)
karma = wrap(karma, ['channel', any('something')])
_mostAbbrev = utils.abbrev(['increased', 'decreased', 'active'])
@internationalizeDocstring
def most(self, irc, msg, args, channel, kind):
"""[<channel>] {increased,decreased,active}
Returns the most increased, the most decreased, or the most active
(the sum of increased and decreased) karma things. <channel> is only
necessary if the message isn't sent in the channel itself.
"""
L = self.db.most(channel, kind,
self.registryValue('mostDisplay',
channel, irc.network))
if L:
L = [format('%q: %i', name, i) for (name, i) in L]
irc.reply(format('%L', L))
else:
irc.error(_('I have no karma for this channel.'))
most = wrap(most, ['channel',
('literal', ['increased', 'decreased', 'active'])])
@internationalizeDocstring
def clear(self, irc, msg, args, channel, name):
"""[<channel>] [<name>]
Resets the karma of <name> to 0. If <name> is not given, resets
everything.
"""
self.db.clear(channel, name or None)
irc.replySuccess()
clear = wrap(clear, [('checkChannelCapability', 'op'), optional('text')])
@internationalizeDocstring
def dump(self, irc, msg, args, channel, filename):
"""[<channel>] <filename>
Dumps the Karma database for <channel> to <filename> in the bot's
data directory. <channel> is only necessary if the message isn't sent
in the channel itself.
"""
checkAllowShell(irc)
self.db.dump(channel, filename)
irc.replySuccess()
dump = wrap(dump, [('checkCapability', 'owner'), 'channeldb', 'filename'])
@internationalizeDocstring
def load(self, irc, msg, args, channel, filename):
"""[<channel>] <filename>
Loads the Karma database for <channel> from <filename> in the bot's
data directory. <channel> is only necessary if the message isn't sent
in the channel itself.
"""
checkAllowShell(irc)
self.db.load(channel, filename)
irc.replySuccess()
load = wrap(load, [('checkCapability', 'owner'), 'channeldb', 'filename'])
Class = Karma
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
+1
View File
@@ -0,0 +1 @@
Supybot plugin to receive Sourcehut webhooks
+21
View File
@@ -0,0 +1,21 @@
"""
Sourcehut: Supybot plugin to receive Sourcehut webhooks
"""
import sys
import supybot
__version__ = "0.1"
__author__ = supybot.authors.unknown
__contributors__ = {}
__url__ = ''
from . import config
from . import plugin
from importlib import reload
reload(config)
reload(plugin)
Class = plugin.Class
configure = config.configure
+14
View File
@@ -0,0 +1,14 @@
from supybot import conf, registry
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('Sourcehut')
except:
_ = lambda x: x
def configure(advanced):
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('Sourcehut', True)
Sourcehut = conf.registerPlugin('Sourcehut')
@@ -0,0 +1 @@
# Stub so local is a module, used for third-party modules
+141
View File
@@ -0,0 +1,141 @@
import email.header
import email.utils
import json
import mailbox
from urllib.parse import quote
from urllib.request import urlopen
import re
import traceback
from supybot import callbacks, httpserver, ircmsgs, world
from supybot.ircutils import bold, italic, mircColor, underline
class Sourcehut(callbacks.Plugin):
"""
Supybot plugin to receive Sourcehut webhooks
"""
def __init__(self, irc):
super().__init__(irc)
httpserver.hook("sourcehut", SourcehutServerCallback(self))
def die(self):
httpserver.unhook("sourcehut")
super().die()
def announce(self, channel, message):
libera = world.getIrc("libera")
if libera is None:
print("error: no irc libera")
return
if channel not in libera.state.channels:
print(f"error: not in {channel} channel")
return
libera.sendMsg(ircmsgs.notice(channel, message))
def decode_header(header: str) -> str:
if not header:
return ""
text = ""
for chunk, encoding in email.header.decode_header(header):
if isinstance(chunk, bytes):
chunk = chunk.decode(encoding or "us-ascii")
text += chunk
return text
class SourcehutServerCallback(httpserver.SupyHTTPServerCallback):
name = "Sourcehut"
defaultResponse = "Bad request\n"
def __init__(self, plugin: Sourcehut):
super().__init__()
self.plugin = plugin
SUBJECT = "[PATCH {prefix} v{version}] {subject}"
URL = "https://lists.sr.ht/{list[owner][canonicalName]}/{list[name]}"
CHANS = {
"#public-inbox": "##rjarry",
"#aerc-devel": "#aerc",
}
def announce_patch(self, patchset):
subject = self.SUBJECT.format(**patchset)
url = self.URL.format(**patchset)
if not url.startswith("https://lists.sr.ht/~rjarry/"):
raise ValueError("unknown list")
url += "/patches/{id}".format(**patchset)
channel = f"#{patchset['list']['name']}"
channel = self.CHANS.get(channel, channel)
try:
submitter = patchset["submitter"]["canonicalName"]
except KeyError:
try:
submitter = patchset["submitter"]["name"]
except KeyError:
submitter = patchset["submitter"]["address"]
msg = f"{mircColor('received', 'light gray')} {bold(subject)}"
msg += f" from {italic(submitter)}: {underline(url)}"
self.plugin.announce(channel, msg)
def announce_apply(self, mail):
channel = f"#{mail['list']['name']}"
channel = self.CHANS.get(channel, channel)
refs = []
for header in mail['references']:
refs += header.split()
for ref in refs:
url = self.URL.format(**mail) + quote(f"/{ref}")
print(f"GET {url}/raw")
with urlopen(f"{url}/raw") as u:
msg = mailbox.Message(u.read())
subject = re.sub(r"\s+", " ", decode_header(msg["subject"]))
if not subject.startswith("[PATCH"):
continue
for name, addr in email.utils.getaddresses([decode_header(msg["from"])]):
if name:
submitter = name
else:
submitter = addr
msg = f"{bold(mircColor('applied', 'green'))} {bold(subject)}"
msg += f" from {italic(submitter)}: {underline(url)}"
self.plugin.announce(channel, msg)
return
def doPost(self, handler, path, form=None):
if hasattr(form, "decode"):
form = form.decode("utf-8")
print(f"POST {path} {form}")
try:
body = json.loads(form)
hook = body["data"]["webhook"]
if hook["event"] == "PATCHSET_RECEIVED":
self.announce_patch(hook["patchset"])
handler.send_response(200)
handler.end_headers()
handler.wfile.write(b"")
return
if hook["event"] == "EMAIL_RECEIVED":
if hook["email"]["patchset_update"] == ["APPLIED"]:
self.announce_apply(hook["email"])
handler.send_response(200)
handler.end_headers()
handler.wfile.write(b"")
return
raise ValueError(f"unsupported webhook: {hook}")
except Exception as e:
traceback.print_exception(e)
handler.send_response(400)
handler.end_headers()
handler.wfile.write(b"Bad request\n")
def log_message(self, format, *args):
pass
Class = Sourcehut
+3
View File
@@ -0,0 +1,3 @@
from supybot.setup import plugin_setup
plugin_setup('Sourcehut')
+67
View File
@@ -0,0 +1,67 @@
#!/bin/sh
set -xe
list="${1:-https://lists.sr.ht/~rjarry/aerc-devel}"
url="${2:-https://bot.diabeteman.com/sourcehut/}"
hut lists webhook create "$list" --stdin -e patchset_received -u "$url" <<EOF
query {
webhook {
uuid
event
date
... on PatchsetEvent {
patchset {
id
subject
version
prefix
list {
name
owner {
... on User {
canonicalName
}
}
}
submitter {
... on User {
canonicalName
}
... on Mailbox {
name
address
}
}
}
}
}
}
EOF
hut lists webhook create "$list" --stdin -e email_received -u "$url" <<EOF
query {
webhook {
uuid
event
date
... on EmailEvent {
email {
id
subject
patchset_update: header(want: "X-Sourcehut-Patchset-Update")
references: header(want: "References")
list {
name
owner {
... on User {
canonicalName
}
}
}
}
}
}
}
EOF
+35
View File
@@ -0,0 +1,35 @@
limit_req_zone $binary_remote_addr zone=aercbot:1m rate=1r/s;
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name bot.diabeteman.com;
ssl_certificate /etc/dehydrated/certs/diabeteman.com/fullchain.pem;
ssl_certificate_key /etc/dehydrated/certs/diabeteman.com/privkey.pem;
client_max_body_size 150K;
limit_req zone=aercbot burst=10 nodelay;
location / {
allow 46.23.81.128/25;
allow 2a03:6000:1813::/48;
deny all;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_redirect off;
proxy_buffering off;
proxy_request_buffering off;
proxy_pass http://127.0.0.1:7777;
}
}
server {
listen 80;
listen [::]:80;
server_name bot.diabeteman.com;
return 301 https://$host$request_uri;
}
+40
View File
@@ -0,0 +1,40 @@
supybot.commands.allowShell = False
supybot.ident = aercbot
supybot.log.format = %(name)s: %(message)s
supybot.log.plugins.format = %(message)s
supybot.log.stdout.colorized = False
supybot.log.stdout.format = %(message)s
supybot.log.stdout.level = INFO
supybot.log.stdout.wrap = False
supybot.log.stdout = True
supybot.networks.libera.channels = #aerc
supybot.networks.libera.requireStarttls = False
supybot.networks.libera.sasl.password = ********************
supybot.networks.libera.sasl.required = True
supybot.networks.libera.sasl.username = aercbot
supybot.networks.libera.servers = irc.libera.chat:6697
supybot.networks.libera.ssl = True
supybot.networks = libera
supybot.nick.alternates = %s` %s_
supybot.nick = aercbot
supybot.plugins.Channel.partMsg = KTHXBYE
supybot.plugins.Karma.allowSelfRating = False
supybot.plugins.Karma.allowUnaddressedKarma = True
supybot.plugins.Karma.decrementChars = --
supybot.plugins.Karma.incrementChars = ++
supybot.plugins.Karma.mostDisplay = 25
supybot.plugins.Karma.onlyNicks = False
supybot.plugins.Karma.public = True
supybot.plugins.Karma.rankingDisplay = 3
supybot.plugins.Karma.response = True
supybot.plugins.Karma.simpleOutput = True
supybot.plugins.Karma = True
supybot.plugins.Sourcehut.public = False
supybot.plugins.Sourcehut = True
supybot.servers.http.hosts4 = 127.0.0.1
supybot.servers.http.hosts6 = ::1
supybot.servers.http.keepAlive = False
supybot.servers.http.port = 7777
supybot.servers.http.publicUrl = https://bot.diabeteman.com/
supybot.servers.http.singleStack = True
supybot.user = aerc's IRC bot
+19
View File
@@ -0,0 +1,19 @@
[Unit]
Description=IRC bot
After=network.target auditd.service
[Service]
ExecStart=/usr/bin/supybot /var/lib/supybot/supybot.conf
User=supybot
Group=supybot
WorkingDirectory=/var/lib/supybot
ProtectHome=true
ProtectSystem=strict
ReadWritePaths=/var/lib/supybot /tmp
PrivateTmp=true
SyslogIdentifier=supybot
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target