From 4dfd9d6853d4a6a452c9c9903bb80ba58ea51366 Mon Sep 17 00:00:00 2001 From: Sridhar Ratna Date: Tue, 1 Jan 2008 16:23:45 +0000 Subject: [PATCH] neat hack: probability_of_one_by --- plugins.py | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/plugins.py b/plugins.py index d9b35de..0582c1f 100644 --- a/plugins.py +++ b/plugins.py @@ -1,9 +1,14 @@ +from __future__ import with_statement + import twisted from twisted.python import log from datetime import datetime import random, time, re, urllib +from contextlib import contextmanager + + PREFIX = ',' SOURCE = 'http://repo.or.cz/w/lusty.git' @@ -29,6 +34,11 @@ def prefixMatch(string, prefixes): else: return None +@contextmanager +def probability_of_one_by(n): + random.seed(time.time()) + yield 0 == random.choice(range(n)) + def soupify(url): from BeautifulSoup import BeautifulSoup import urllib2 @@ -235,8 +245,9 @@ class Filters(BotActions): def respondWisely(self, msg, for_words, with_responses, one_for_every=1): random.seed(time.time()) if self.grep(msg, for_words): - if random.choice(range(one_for_every)) == 0: - self.toChannel(random.choice(with_responses)) + with probability_of_one_by(one_for_every) as do: + if do: + self.toChannel(random.choice(with_responses)) def filter_obscene(self, msg): words = ['fuck', 'f**k', 'bitch', 'cunt', 'tits'] @@ -289,11 +300,19 @@ class Filters(BotActions): def filter_random(self, msg): random.seed(time.time()) - if random.choice(range(100)) == 0: - self.doAction( - random.choice([ - 'looks around nervously', - ])) + with probability_of_one_by(100) as do: + if do: + with probability_of_one_by(2) as do2: + if do2: + self.doAction( + random.choice([ + 'looks around nervously', + ])) + else: + self.toChannel( + random.choice([ + 'Let\'s fight a land war in space.' + ])) _filter_links_url = re.compile('.*(https?://[^ ]*).*') def filter_links(self, msg): -- 2.11.4.GIT