Exemplo n.º 1
0
    def oeis(self, event, query):
        query = re.sub(r"(,|\s)+", ",", query)
        f = urlopen("http://oeis.org/search?n=1&fmt=text&q=" + query)

        for i in range(3):
            f.next()  # the first lines are uninteresting
        results_m = re.search(r"Showing .* of (\d+)", f.next())
        if results_m:
            f.next()
            sequence = Sequence(f)
            event.addresponse(
                u"%(name)s - %(url)s - %(values)s",
                {"name": sequence.name, "url": sequence.url(), "values": sequence.values},
            )

            results = int(results_m.group(1))
            if results > 1:
                event.addresponse(
                    u"There %(was)s %(count)d more %(results)s. " u"See %(url)s%(query)s for more.",
                    {
                        "was": plural(results - 1, "was", "were"),
                        "count": results - 1,
                        "results": plural(results - 1, "result", "results"),
                        "url": "http://oeis.org/search?q=",
                        "query": query,
                    },
                )
        else:
            event.addresponse(u"I couldn't find that sequence.")
Exemplo n.º 2
0
    def oeis(self, event, query):
        query = re.sub(r'(,|\s)+', ',', query)
        f = urlopen('http://oeis.org/search?n=1&fmt=text&q=' + query)

        for i in range(3):
            f.next()  # the first lines are uninteresting
        results_m = re.search(r'Showing .* of (\d+)', f.next())
        if results_m:
            f.next()
            sequence = Sequence(f)
            event.addresponse(
                u'%(name)s - %(url)s - %(values)s', {
                    'name': sequence.name,
                    'url': sequence.url(),
                    'values': sequence.values
                })

            results = int(results_m.group(1))
            if results > 1:
                event.addresponse(
                    u'There %(was)s %(count)d more %(results)s. '
                    u'See %(url)s%(query)s for more.', {
                        'was': plural(results - 1, 'was', 'were'),
                        'count': results - 1,
                        'results': plural(results - 1, 'result', 'results'),
                        'url': 'http://oeis.org/search?q=',
                        'query': query
                    })
        else:
            event.addresponse(u"I couldn't find that sequence.")
Exemplo n.º 3
0
Arquivo: memo.py Projeto: shoosen/ibid
    def state(self, event):
        if event.state != 'online':
            return

        if event.identity in nomemos_cache:
            return

        memos = get_memos(event)

        if len(memos) > self.public_limit:
            event.addresponse(
                u'You have %s messages, too many for me to tell you in public,'
                u' so ask me in private.',
                len(memos), target=event.sender['connection'])
        elif len(memos) > 0:
            event.addresponse(
                plural(
                    len(memos),
                    u'You have %(memo_count)d message. '
                    u'Would you like to read it now?',
                    u'You have %(memo_count)d messages. '
                    u'Would you like to read them now?'),
                { 'memo_count' : len(memos) },
                target=event.sender['connection'])
        else:
            nomemos_cache.add(event.identity)
Exemplo n.º 4
0
    def state(self, event):
        if event.state != 'online':
            return

        if event.identity in nomemos_cache:
            return

        memos = get_memos(event)

        if len(memos) > self.public_limit:
            event.addresponse(
                u'You have %s messages, too many for me to tell you in public,'
                u' so ask me in private.',
                len(memos), target=event.sender['connection'], address=False)
        elif len(memos) > 0:
            event.addresponse(
                plural(
                    len(memos),
                    u'You have %(memo_count)d message. '
                    u'Would you like to read it now?',
                    u'You have %(memo_count)d messages. '
                    u'Would you like to read them now?'),
                { 'memo_count' : len(memos) },
                target=event.sender['connection'])
        else:
            nomemos_cache.add(event.identity)
Exemplo n.º 5
0
    def end_poll(self, event):
        if not event.public:
            event.addresponse(u'Sorry, must be done in public')
            return

        if (event.source, event.channel) not in self.polls:
            event.addresponse(u'Sorry, no poll in progress.')
            return

        poll = self.polls.pop((event.source, event.channel))
        if poll.delayed_call.active():
            poll.delayed_call.cancel()

        votes = [[poll.options[i], 0]
                for i in range(len(poll.options))]
        for vote in poll.votes.itervalues():
            votes[vote][1] += 1
        votes.sort(reverse=True, key=lambda x: x[1])
        event.addresponse(u'The polls are closed. Totals:', address=False)

        position = (1, votes[0][1])
        for o, v in votes:
            if v < position[1]:
                position = (position[0] + 1, v)
            event.addresponse(
                    u'%(position)i: %(option)s - %(votes)i %(word)s', {
                        'position': position[0],
                        'option': o,
                        'votes': v,
                        'word': plural(v, u'vote', u'votes'),
                }, address=False)
Exemplo n.º 6
0
    def end_poll(self, event):
        if not event.public:
            event.addresponse(u'Sorry, must be done in public')
            return

        if (event.source, event.channel) not in self.polls:
            event.addresponse(u'Sorry, no poll in progress.')
            return

        poll = self.polls.pop((event.source, event.channel))
        if poll.delayed_call.active():
            poll.delayed_call.cancel()

        votes = [[poll.options[i], 0] for i in range(len(poll.options))]
        for vote in poll.votes.itervalues():
            votes[vote][1] += 1
        votes.sort(reverse=True, key=lambda x: x[1])
        event.addresponse(u'The polls are closed. Totals:', address=False)

        position = (1, votes[0][1])
        for o, v in votes:
            if v < position[1]:
                position = (position[0] + 1, v)
            event.addresponse(u'%(position)i: %(option)s - %(votes)i %(word)s',
                              {
                                  'position': position[0],
                                  'option': o,
                                  'votes': v,
                                  'word': plural(v, u'vote', u'votes'),
                              },
                              address=False)
Exemplo n.º 7
0
Arquivo: karma.py Projeto: vhata/ibid
    def set(self, event, subject, adjust, reason=None):
        if reason is None:
            reason = event["message"]["clean"]

        if self.public and not event.public:
            event.addresponse(u"Karma must be done in public")
            return

        if subject.lower() in self.ignore:
            return

        karma = event.session.query(Karma).filter_by(subject=subject).first()
        if not karma:
            karma = Karma(subject)

        if self.match_operators(self.increase_reg, adjust.lower()):
            if subject.lower() == event.sender["nick"].lower():
                event.addresponse(u"You can't karma yourself!")
                return
            karma.changes += 1
            karma.value += 1
            change = u"Increased"
        elif self.match_operators(self.decrease_reg, adjust.lower()):
            karma.changes += 1
            karma.value -= 1
            change = u"Decreased"
        else:
            karma.changes += 2
            change = u"Increased and decreased"

        if karma.value == 0 and karma.changes <= self.importance:
            change = u"Forgotten (unimportant)"

            event.session.delete(karma)
        else:
            event.session.save_or_update(karma)
        event.session.commit()

        log.info(
            u"%s karma for '%s' by %s/%s (%s) because: %s",
            change,
            subject,
            event.account,
            event.identity,
            event.sender["connection"],
            reason,
        )

        if self.reply:
            event.addresponse(
                u"%(subject)s now has %(value)s %(points)s of karma",
                {"subject": subject, "value": karma.value, "points": plural(karma.value, "point", "points")},
            )
        else:
            event.processed = True
Exemplo n.º 8
0
    def set(self, event, subject, adjust, reason=None):
        if reason is None:
            reason = event['message']['clean']

        if self.public and not event.public:
            event.addresponse(u'Karma must be done in public')
            return

        if subject.lower() in self.ignore:
            return

        karma = event.session.query(Karma).filter_by(subject=subject).first()
        if not karma:
            karma = Karma(subject)

        if self.match_operators(self.increase_reg, adjust.lower()):
            if subject.lower() == event.sender['nick'].lower():
                event.addresponse(u"You can't karma yourself!")
                return
            karma.changes += 1
            karma.value += 1
            change = u'Increased'
        elif self.match_operators(self.decrease_reg, adjust.lower()):
            karma.changes += 1
            karma.value -= 1
            change = u'Decreased'
        else:
            karma.changes += 2
            change = u'Increased and decreased'

        if karma.value == 0 and karma.changes <= self.importance:
            change = u'Forgotten (unimportant)'

            event.session.delete(karma)
        else:
            event.session.save_or_update(karma)
        event.session.commit()

        log.info(u"%s karma for '%s' by %s/%s (%s) because: %s", change,
                 subject, event.account, event.identity,
                 event.sender['connection'], reason)

        if self.reply:
            event.addresponse(
                u'%(subject)s now has %(value)s %(points)s of karma', {
                    'subject': subject,
                    'value': karma.value,
                    'points': plural(karma.value, "point", "points"),
                })
        else:
            event.processed = True
Exemplo n.º 9
0
    def search(self, event, package, search):
        package = package.lower()
        if search is not None:
            search = search.lower()
        result = json_webservice(
            u'http://dde.debian.net/dde/q/bts/bypackage/%s' % package,
            {'t': 'json'})
        bugs = result['r']
        if not bugs:
            event.addresponse(u"Sorry, I couldn't find any open bugs on %s",
                              package)
            return

        severities = {
            'critical': 4,
            'grave': 3,
            'serious': 2,
            'important': 1,
            'normal': 0,
            'minor': -1,
            'wishlist': -2,
        }

        buglist = []
        for b in bugs.itervalues():
            if search and search not in b['subject'].lower():
                continue

            tags = b['tags']
            if b['pending'] != 'pending':
                tags.append(b['pending'])
            if tags:
                tags = ', ' + ', '.join(b['tags'])
            else:
                tags = ''

            body = '%s [%s%s]' % (b['subject'], b['severity'], tags)
            sev = 0 - severities.get(b['severity'], 0)
            buglist.append((b['bug_num'], sev, body))
        buglist.sort()
        if not buglist:
            event.addresponse(u"Sorry, I couldn't find any open bugs matching "
                              u"your query")
            return
        event.addresponse(
            u'Found %(count)i matching %(plural)s: %(bugs)s', {
                'count': len(buglist),
                'plural': plural(len(buglist), u'bug', u'bugs'),
                'bugs': ', '.join('%i: %s' % (b[0], b[2]) for b in buglist)
            })
Exemplo n.º 10
0
    def night(self, event):
        """Start of night.

        Tell seer and werewolf to act.

        This state lasts for the whole night. The next state is dawn.
        """
        self.state = self.night
        event.addresponse(
            u'Night falls... most villagers are sleeping, '
            u'but outside, something stirs.\n' +
            plural(len(self.wolves), u'Werewolf, you may kill somebody.',
                   u'Werewolves, you may kill somebody.') + '\n' +
            plural(len(
                self.seers), u"Seer, you may discover somebody's true form.",
                   u"Seers, you may discover somebody's true form."),
            conflate=False)
        self.say_survivors(event)

        self.wolf_targets = {}
        self.seer_targets = {}

        self.timed_goto(event, self.day_length, self.dawn)
Exemplo n.º 11
0
    def search(self, event, package, search):
        package = package.lower()
        if search is not None:
            search = search.lower()
        result = json_webservice(
            u'http://dde.debian.net/dde/q/bts/bypackage/%s' % package,
            {'t': 'json'})
        bugs = result['r']
        if not bugs:
            event.addresponse(u"Sorry, I couldn't find any open bugs on %s",
                    package)
            return

        severities = {
            'critical': 4,
            'grave': 3,
            'serious': 2,
            'important': 1,
            'normal': 0,
            'minor': -1,
            'wishlist': -2,
        }

        buglist = []
        for b in bugs.itervalues():
            if search and search not in b['subject'].lower():
                continue

            tags = b['tags']
            if b['pending'] != 'pending':
                tags.append(b['pending'])
            if tags:
                tags = ', ' + ', '.join(b['tags'])
            else:
                tags = ''

            body = '%s [%s%s]' % (b['subject'], b['severity'], tags)
            sev = 0 - severities.get(b['severity'], 0)
            buglist.append((b['bug_num'], sev, body))
        buglist.sort()
        if not buglist:
            event.addresponse(u"Sorry, I couldn't find any open bugs matching "
                              u"your query")
            return
        event.addresponse(u'Found %(count)i matching %(plural)s: %(bugs)s', {
            'count': len(buglist),
            'plural': plural(len(buglist), u'bug', u'bugs'),
            'bugs': ', '.join('%i: %s' % (b[0], b[2]) for b in buglist)
        })
Exemplo n.º 12
0
    def set(self, event, subject, adjust, reason=None):
        if reason is None:
            reason = event['message']['clean']

        if self.public and not event.public:
            event.addresponse(u'Karma must be done in public')
            return

        if subject.lower() in self.ignore:
            return

        karma = event.session.query(Karma).filter_by(subject=subject).first()
        if not karma:
            karma = Karma(subject)

        if self.match_operators(self.increase_reg, adjust.lower()):
            if subject.lower() == event.sender['nick'].lower():
                event.addresponse(u"You can't karma yourself!")
                return
            karma.changes += 1
            karma.value += 1
            change = u'Increased'
        elif self.match_operators(self.decrease_reg, adjust.lower()):
            karma.changes += 1
            karma.value -= 1
            change = u'Decreased'
        else:
            karma.changes += 2
            change = u'Increased and decreased'

        if karma.value == 0 and karma.changes <= self.importance:
            change = u'Forgotten (unimportant)'

            event.session.delete(karma)
        else:
            event.session.add(karma)
        event.session.commit()

        log.info(u"%s karma for '%s' by %s/%s (%s) because: %s",
                change, subject, event.account, event.identity, event.sender['connection'], reason)

        if self.reply:
            event.addresponse(u'%(subject)s now has %(value)s %(points)s of karma', {
                'subject': subject,
                'value': karma.value,
                'points': plural(karma.value, "point", "points"),
            })
        else:
            event.processed = True
Exemplo n.º 13
0
    def night(self, event):
        """Start of night.

        Tell seer and werewolf to act.

        This state lasts for the whole night. The next state is dawn.
        """
        self.state = self.night
        event.addresponse(
                u'Night falls... most villagers are sleeping, '
                u'but outside, something stirs.\n'
                + plural(len(self.wolves),
                         u'Werewolf, you may kill somebody.',
                         u'Werewolves, you may kill somebody.') + '\n'
                + plural(len(self.seers),
                         u"Seer, you may discover somebody's true form.",
                         u"Seers, you may discover somebody's true form."),
                conflate=False)
        self.say_survivors(event)

        self.wolf_targets = {}
        self.seer_targets = {}

        self.timed_goto(event, self.day_length, self.dawn)
Exemplo n.º 14
0
    def query_giver(self, event, determiner, object):
        if determiner is None:
            determiner = ''

        who = event.sender['nick']
        if determiner.lower() == 'our':
            if who[-1] in 'sS':
                determiner = who + "'"
            else:
                determiner = who + "'s"
            yours = True
        elif determiner.lower() == 'my':
            determiner = who + "'s"
            yours = True
        else:
            yours = False

        kind, items = self.find_items(event.session, determiner, object)

        if items:
            explanation = u''
            if kind == 'unowned':
                explanation = plural(len(items),
                                     u". I didn't realise it was ",
                                     u". I didn't realise they were ")
                if yours:
                    explanation += u"yours"
                else:
                    explanation += determiner
                explanation += u"."
                yours = False

            event.addresponse(u'I got ' +
                human_join(u'%(item)s from %(giver)s' %
                                {'item':
                                    [item, u'your ' + item.description][yours],
                                'giver': identity_name(event, item.giver)}
                            for item in items)
                        + explanation)
            return
        else:
            if yours:
                object = u'your ' + object
            elif determiner:
                object = determiner + u' ' + object
            event.addresponse(choice((
                u"There's nothing like that in my bucket.",
                u"I don't have %s" % object)))