Пример #1
0
    def __init__(self, *args, **kwargs):
        self.__parent = super(DbiMemoDB, self)
        self.__parent.__init__(*args, **kwargs)

    def add(self, userid, text):
        assert isinstance(userid, int)
        return self.__parent.add(self.Record(at=now(), by=userid, text=text))

    def append(self, id, userid, text):
        memo = self.get(id)
        assert isinstance(userid, int)
        memo.appends.append([now(), userid, text])
        self.set(id, memo)


MemoDB = plugins.DB('Memo', {'flat': DbiMemoDB})


class Memo(callbacks.Privmsg):
    def __init__(self, irc):
        self.__parent = super(Memo, self)
        self.__parent.__init__(irc)
        self.db = MemoDB()

    def die(self):
        self.__parent.die()
        self.db.close()

    def add(self, irc, msg, args, user, text):
        """<text>
Пример #2
0
             "ORDER BY ts DESC LIMIT ?) AND uid = (SELECT uid FROM users WHERE nick = ?)",
             [nick, user[4], nick])
        else:  #something I've never seen before
            cursor.execute("DELETE FROM bgs WHERE uid IN (SELECT uid FROM users WHERE nick = ?) " \
             "AND ts < ?", [nick, dumbtime.time() - 86400 * 7]) #make it 7 days by default
        self.db.commit()

    def pruneall(self):
        cursor = self.db.cursor()
        cursor.execute("SELECT nick FROM users")
        users = cursor.fetchall()
        for user in users:
            self.pruneuser(user[0])


BGDB = plugins.DB('BGs', {'sqlite3': BGDB_SQLite, 'sqlite': BGDB_SQLite})


class BGs(callbacks.Plugin):
    def __init__(self, irc):
        self.__parent = super(BGs, self)
        self.__parent.__init__(irc)
        self.db = BGDB()

    def die(self):
        self.__parent.die()
        self.db.db.close()

    def bg(self, irc, msg, args, testlvl, tags):
        """<glucose test result> [<tag> ...]
		
Пример #3
0
        Record = UrlRecord

        def add(self, url, msg):
            record = self.Record(url=url,
                                 by=msg.nick,
                                 near=msg.args[1],
                                 at=msg.receivedAt)
            super(self.__class__, self).add(record)

        def urls(self, p):
            L = list(self.select(p))
            L.reverse()
            return L


URLDB = plugins.DB('URL', {'flat': DbiUrlDB})


class URL(callbacks.Plugin):
    """This plugin records how many URLs have been mentioned in
    a channel and what the last URL was."""
    def __init__(self, irc):
        self.__parent = super(URL, self)
        self.__parent.__init__(irc)
        self.db = URLDB()

    def doPrivmsg(self, irc, msg):
        if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
            return
        channel = msg.args[0]
        if irc.isChannel(channel):
Пример #4
0
        fd = file(filename)
        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, %s, %s, %s, %s)""", name,
                normalized, added, subtracted)
        db.commit()
        fd.close()


KarmaDB = plugins.DB('Karma', {'sqlite': SqliteKarmaDB})


class Karma(callbacks.Plugin):
    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):
Пример #5
0
                return self.__parent.get(id)
            else:
                L = [R for R in self if R.expires >= now or R.expires == 0]
                if not L:
                    raise dbi.NoRecordError
                return L

        def change(self, id, f):
            news = self.get(id)
            s = '%s: %s' % (news.subject, news.text)
            s = f(s)
            (news.subject, news.text) = s.split(': ', 1)
            self.set(id, news)


NewsDB = plugins.DB('News', {'flat': DbiNewsDB})


class News(callbacks.Plugin):
    """This plugin provides a means of maintaining News for a channel."""
    def __init__(self, irc):
        self.__parent = super(News, self)
        self.__parent.__init__(irc)
        self.db = NewsDB()

    def die(self):
        self.__parent.die()
        self.db.close()

    @internationalizeDocstring
    def add(self, irc, msg, args, channel, user, at, expires, news):
Пример #6
0
 def __init__(self, irc):
     self.__parent = super(LoveHate, self)
     self.__parent.__init__(irc)
     self.db = plugins.DB(self.name(), {'flat': self.DB})()
Пример #7
0
            return None

    def set_user(self, channel, nick, user):
        db = self._getDb(channel)
        cursor = db.cursor()
        cursor.execute(
            """DELETE FROM lastfm
                          WHERE nick=?""", (nick, ))
        cursor.execute("""INSERT INTO lastfm VALUES (NULL, ?, ?)""", (
            nick,
            user,
        ))
        db.commit()


LastFMDB = plugins.DB('LastFM', {'sqlite3': SqliteLastFMDB})


class LastFM(callbacks.Plugin):
    """Last.fm client"""
    def __init__(self, irc):
        self.__parent = super(LastFM, self)
        self.__parent.__init__(irc)
        self.db = LastFMDB()
        self.network = None
        self.prepend = "0,5last.fm"

    def die(self):
        self.__parent.die()
        self.db.close()
            db.commit()
            db.close()

    def buildReply(self, channel, word):
        if (word != None):
            phrase = (word, )
        else:
            phrase = ()
        current = self.nextWord(channel, word)
        while (current != None):
            phrase += (current, )
            current = self.nextWord(channel, current)
        return ' '.join(phrase)


MarkovDB = plugins.DB('ArtificialIntelligence', {'sqlite': SQLiteMarkovDB})


class ArtificialIntelligence(callbacks.Plugin):
    """Add the help for "@plugin help ArtificialIntelligence" here
    This should describe *how* to use this plugin."""
    threaded = False

    def __init__(self, irc):
        self.__parent = super(ArtificialIntelligence, self)
        super(ArtificialIntelligence, self).__init__(irc)
        self.db = MarkovDB()
        self.lastSpoke = time.time()

    def die(self):
        self.__parent.die()
Пример #9
0
 def __init__(self, irc):
     self.__parent = super(AudioScrobbler, self)
     self.__parent.__init__(irc)
     self.db = plugins.DB(self.name(), {'flat': self.DB})()
Пример #10
0
        def __repr__(self):
            return '<HostGreeterEntry channel={!r} hostmask={!r} greeting={!r}'.format(
                self.channel, self.hostmask, self.greeting)

    def __init__(self, filename):
        self.__parent = super(self.__class__, self)
        self.__parent.__init__(filename)

    def add(self, channel, hostmask, greeting):
        return self.__parent.add(
            self.Record(channel=channel.lower(),
                        hostmask=hostmask,
                        greeting=greeting))


HostGreeterDB = plugins.DB('HostGreeter', {'flat': DbiHostGreeterDB})


class HostGreeter(callbacks.Plugin):
    """Greet users based on hostmask"""
    def __init__(self, irc):
        self.__parent = super(HostGreeter, self)
        self.__parent.__init__(irc)
        self.db = HostGreeterDB()

    def die(self):
        self.db.close()
        self.__parent.die()

    def list(self, irc, msg, args, channel):
        """<channel>"""
Пример #11
0
    def get(self, service, twitt):
        return self.dbs[service][twitt]

    def set(self, service, twitt, twittID):
        self.dbs[service][twitt] = twittID

    def close(self):
        for service in self.dbs:
            self.dbs[service].close()

    def flush(self):
        for service in self.dbs:
            self.dbs[service].flush()


TwitterDB = plugins.DB('Twitter', {'cdb': CdbTwitterDB})


class Twitter(callbacks.Plugin):
    """This plugin is for accessing a Twitter account"""
    threaded = False

    def __init__(self, irc):
        self.__parent = super(Twitter, self)
        self.__parent.__init__(irc)
        self.lastRequest = ""
        self.db = TwitterDB()

    def die(self):
        self.db.close()
Пример #12
0

atRe = re.compile(r'@(\d+)')


def findBiggestAt(alias):
    ats = atRe.findall(alias)
    ats = map(int, ats)
    ats.sort()
    if ats:
        return ats[-1]
    else:
        return 0


AkaDB = plugins.DB('Aka', {'sqlalchemy': SqlAlchemyAkaDB})


class Aka(callbacks.Plugin):
    """Add the help for "@plugin help Aka" here
    This should describe *how* to use this plugin."""
    def __init__(self, irc):
        self.__parent = super(Aka, self)
        self.__parent.__init__(irc)
        self._db = AkaDB()

    def isCommandMethod(self, name):
        if sys.version_info[0] < 3 and isinstance(name, str):
            name = name.decode('utf8')
        channel = dynamic.channel or 'global'
        return self._db.has_aka(channel, name) or \
Пример #13
0
 def __init__(self, irc):
     self.__parent = super(Cast, self)
     self.__parent.__init__(irc)
     self.db = plugins.DB('NotMe', {'flat': self.DB})()
Пример #14
0
            for i in range(1, size + 1):
                u = self.get(i)
                if u.nick == nick:
                    self.remove(i)
                    return True
            return False

        def getusername(self, nick):
            size = self.size()
            for i in range(1, size + 1):
                u = self.get(i)
                if u.nick == nick: return u.username
            return nick


LASTFMNICKDB = plugins.DB('LastFM', {'flat': DbiLastFMNickDB})

apikey = 'Not set'
url = 'http://ws.audioscrobbler.com/2.0/?'


class LastFM(callbacks.Plugin):
    """Simply returns current playing track for a LastFM user. If no track is
    currently playing the last played track will be displayed."""
    threaded = True

    def __init__(self, irc):
        self.__parent = super(LastFM, self)
        self.__parent.__init__(irc)
        self.db = LASTFMNICKDB()
Пример #15
0
        pairs = [k for k in db.keys() if b'\n' not in k]
        return len(pairs)

    def follows(self, channel):
        db = self._getDb(channel)
        # dbm sucks in that we're not guaranteed to have .iteritems()
        # *cough*gdbm*cough*, so this has to be done the stupid way
        follows = [
            len([f for f in db[k].split() if f != b'\n']) for k in db.keys()
            if b'\n' not in k
        ]
        return sum(follows)


MarkovDB = plugins.DB('Markov', {
    'dbm': DbmMarkovDB,
    'sqlalchemy': SqlAlchemyMarkovDB
})


class MarkovWorkQueue(threading.Thread):
    def __init__(self, *args, **kwargs):
        name = 'Thread #%s (MarkovWorkQueue)' % world.threadsSpawned
        world.threadsSpawned += 1
        threading.Thread.__init__(self, name=name)
        self.db = MarkovDB(*args, **kwargs)
        self.q = Queue.Queue()
        self.killed = False
        self.setDaemon(True)
        self.start()

    def die(self):
Пример #16
0
 def __init__(self, irc):
     self.__parent = super(Helpers, self)
     self.__parent.__init__(irc)
     # The Greeter plugin relies on this database name. If for some reason
     # you change it here, change it there too.
     self.db = plugins.DB(self.name(), {'flat': self.DB})()
Пример #17
0
        VALUES (?, ?, ?)""", (
                text,
                nick,
                ts,
            ))
        db.commit()
        return cur.lastrowid

    def delQuoteById(self, channel, qid):
        db = self._getDb(channel)
        cur = db.cursor()
        cur.execute("""DELETE FROM quotes WHERE rowid = ?""", (qid, ))
        db.commit()


QuotesDB = plugins.DB('Quotes', {'sqlite3': SqliteQuotesDB})


class Quotes(callbacks.Plugin):
    """Simple quote system"""
    def __init__(self, irc):
        self.__parent = super(Quotes, self)
        self.__parent.__init__(irc)
        self.db = QuotesDB()

    def die(self):
        self.__parent.die()
        self.db.close()

    def addquote(self, irc, msg, args, optlist, text):
        """[--channel <#channel>] <text>
Пример #18
0
            return 0

    def pairs(self, channel):
        db = self._getDb(channel)
        pairs = [k for k in db.keys() if '\n' not in k]
        return len(pairs)

    def follows(self, channel):
        db = self._getDb(channel)
        # anydbm sucks in that we're not guaranteed to have .iteritems()
        # *cough*gdbm*cough*, so this has to be done the stupid way
        follows = [len(db[k].split()) for k in db.keys() if '\n' not in k]
        return sum(follows)


MarkovDB = plugins.DB('Markov', {'anydbm': DbmMarkovDB})


class MarkovWorkQueue(threading.Thread):
    def __init__(self, *args, **kwargs):
        name = 'Thread #%s (MarkovWorkQueue)' % world.threadsSpawned
        world.threadsSpawned += 1
        threading.Thread.__init__(self, name=name)
        self.db = MarkovDB(*args, **kwargs)
        self.q = Queue.Queue()
        self.killed = False
        self.setDaemon(True)
        self.start()

    def die(self):
        self.killed = True
Пример #19
0

atRe = re.compile(r'@(\d+)')


def findBiggestAt(alias):
    ats = atRe.findall(alias)
    ats = list(map(int, ats))
    ats.sort()
    if ats:
        return ats[-1]
    else:
        return 0


AkaDB = plugins.DB('Aka', available_db)


class Aka(callbacks.Plugin):
    """Aka is the improved version of the Alias plugin. It stores akas outside
    of the bot.conf, which doesn't have risk of corrupting the bot.conf file
    (this often happens when there are Unicode issues). Aka also
    introduces multi-worded akas."""
    def __init__(self, irc):
        self.__parent = super(Aka, self)
        self.__parent.__init__(irc)
        self._db = AkaDB()

    def isCommandMethod(self, name):
        args = name.split(' ')
        if '|' in args:
Пример #20
0
    def send(self, frm, to, public, text):
        n = self.Record(frm=frm, to=to, text=text,
                        at=time.time(), public=public)
        id = self.add(n)
        self._addCache(n)
        return id

    def unsend(self, id):
        self.remove(id)
        for cache in self.unRead, self.unNotified:
            for (to, ids) in cache.items():
                while id in ids:
                    ids.remove(id)

NoteDB = plugins.DB('Note', {'flat': DbiNoteDB})

class Note(callbacks.Plugin):
    def __init__(self, irc):
        self.__parent= super(Note, self)
        self.__parent.__init__(irc)
        self.db = NoteDB()

    def die(self):
        self.__parent.die()
        self.db.close()

    def doPrivmsg(self, irc, msg):
        if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
            return
        self._notify(irc, msg)
Пример #21
0
        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()


KatelloKarmaDB = plugins.DB('KatelloKarma', {'sqlite3': SqliteKatelloKarmaDB})


class KatelloKarma(callbacks.Plugin):
    callBefore = ('Factoids', 'MoobotFactoids', 'Infobot')

    def __init__(self, irc):
        self.__parent = super(KatelloKarma, self)
        self.__parent.__init__(irc)
        self.db = KatelloKarmaDB()

    def die(self):
        self.__parent.die()
        self.db.close()

    def _normalizeThing(self, thing):
Пример #22
0
                          ORDER BY key""", (glob, ))
        results = cursor.fetchall()
        return results

    def getKeysByValueGlob(self, channel, glob):
        db = self._getDb(channel)
        cursor = db.cursor()
        glob = '%%%s%%' % glob
        cursor.execute(
            """SELECT key FROM factoids WHERE fact LIKE ?
                          ORDER BY key""", (glob, ))
        results = cursor.fetchall()
        return results


MoobotDB = plugins.DB('MoobotFactoids', {'sqlite3': SqliteMoobotDB})


class MoobotFactoids(callbacks.Plugin):
    """Add the help for "@help MoobotFactoids" here (assuming you don't implement a MoobotFactoids
    command).  This should describe *how* to use this plugin."""
    callBefore = ['Dunno']

    def __init__(self, irc):
        self.db = MoobotDB()
        self.__parent = super(MoobotFactoids, self)
        self.__parent.__init__(irc)

    def die(self):
        self.__parent.die()
        self.db.close()
Пример #23
0
 def __init__(self, irc):
     super(Github.secret, self).__init__(irc)
     self.db = plugins.DB(("github-secret"), {'flat': self.DB})()
     globals.secretDB = self.db
Пример #24
0
        cursor = db.cursor()
        text = '%' + text + '%'
        cursor.execute(
            """SELECT id, nick, quote FROM quotegrabs
                          WHERE quote LIKE ?
                          ORDER BY id DESC""", (text, ))
        results = cursor.fetchall()
        if len(results) == 0:
            raise dbi.NoRecordError
        return [
            QuoteGrabsRecord(id, text=quote, by=nick)
            for (id, nick, quote) in results
        ]


QuoteGrabsDB = plugins.DB('QuoteGrabs', {'sqlite3': SqliteQuoteGrabsDB})


class QuoteGrabs(callbacks.Plugin):
    """Stores and displays quotes from channels. Quotes are stored randomly
    and/or on user request."""
    def __init__(self, irc):
        self.__parent = super(QuoteGrabs, self)
        self.__parent.__init__(irc)
        self.db = QuoteGrabsDB()

    def doPrivmsg(self, irc, msg):
        if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
            return
        irc = callbacks.SimpleProxy(irc, msg)
        if msg.channel:
Пример #25
0
    def select(self, channel):
        db = self._getDb(channel)
        cursor = db.cursor()
        cursor.execute("""SELECT id, started_by, question
                          FROM polls
                          WHERE open=1""")
        if cursor.rowcount:
            return [
                PollRecord(id, question=q, by=by, status=1)
                for (id, by, q) in cursor.fetchall()
            ]
        else:
            raise dbi.NoRecordError


PollDB = plugins.DB('Poll', {'sqlite': SqlitePollDB})


class Poll(callbacks.Plugin):
    def __init__(self, irc):
        self.__parent = super(Poll, self)
        self.__parent.__init__(irc)
        self.db = PollDB()

    def die(self):
        self.__parent.die()
        self.db.close()

    def poll(self, irc, msg, args, channel, id):
        """[<channel>] <id>
Пример #26
0
    def get(self, service, url):
        return self.dbs[service][url]

    def set(self, service, url, shrunkurl):
        self.dbs[service][url] = shrunkurl

    def close(self):
        for service in self.dbs:
            self.dbs[service].close()

    def flush(self):
        for service in self.dbs:
            self.dbs[service].flush()


ShrunkenUrlDB = plugins.DB('ShrinkUrl', {'cdb': CdbShrunkenUrlDB})


class ShrinkError(Exception):
    pass


class ShrinkUrl(callbacks.PluginRegexp):
    regexps = ['shrinkSnarfer']

    def __init__(self, irc):
        self.__parent = super(ShrinkUrl, self)
        self.__parent.__init__(irc)
        self.db = ShrunkenUrlDB()

    def die(self):
Пример #27
0
            return self.responses[filename]
        except KeyError:
            return 0

    def getNumFacts(self, channel):
        (db, _) = self._getDb(channel)
        cursor = db.cursor()
        cursor.execute("""SELECT COUNT(*) FROM areFacts""")
        areFacts = int(cursor.fetchone()[0])
        cursor.execute("""SELECT COUNT(*) FROM isFacts""")
        isFacts = int(cursor.fetchone()[0])
        return areFacts + isFacts


InfobotDB = plugins.DB('Infobot', {
    'sqlite': SqliteInfobotDB,
    'pickle': PickleInfobotDB
})


class Dunno(Exception):
    pass


class Infobot(callbacks.PluginRegexp):
    addressedRegexps = [
        'doForce', 'doForget', 'doChange', 'doFactoid', 'doUnknown'
    ]
    unaddressedRegexps = ['doForce', 'doForget', 'doFactoid', 'doUnknown']

    def __init__(self, irc):
        self.__parent = super(Infobot, self)