Commits

Benoit C committed a735756

run asyncmodul's threads.
moves decorators to autiste/

Comments (0)

Files changed (7)

 import yaml
 
 #autist
-from decorators import module_call
+from autiste.decorators import module_call
+from autiste.modules.base import AsyncModule
 
 class LogBot(irc.IRCClient):
     """A logging IRC bot."""
                 ret = __import__("autiste.modules.%s" % modname, globals(), locals(), ['Module'])
                 mod = getattr(ret, "Module")
                 # ret = imp.find_module(modname+".py", "autiste/modules/")
-                self.modules[modname] = mod(modconf, self)
+                instance = mod(modconf, self)
+                if isinstance(instance, AsyncModule):
+                    instance.start()
+                self.modules[modname] = instance
             except ImportError, e:
                 print "Can't import module %s (%s)" % (modname, e)
             except Exception, e:
     @module_call
     def connectionLost(self, reason):
         irc.IRCClient.connectionLost(self, reason)
-        for mod in self.modules.keys():
-            self.modules[mod].connectionLost(reason)
 
     # callbacks for events
     def userJoined(self, user, channel):

autiste/decorators.py

+# -*- coding: latin-1 -*-
+"""
+
+
+
+"""
+import traceback
+
+def module_call(func, **kwargs):
+    """tries to call the same function on all loaded module
+without try/except
+    """
+    def decorate(*args, **kwargs):
+        instance = args[0]
+        modlist = instance.modules
+        for module in modlist.keys():
+            strfunc = func.__name__
+            if strfunc in dir(instance.modules[module]):
+                funccall = getattr(instance.modules[module], strfunc)
+                if callable(funccall):
+                    newargs = args[1:]
+                    try:
+                        funccall(*newargs, **kwargs)
+                    except Exception, e:
+                        traceback.print_exc()
+
+        return func(*args, **kwargs)
+    return decorate

autiste/modules/link.py

-from base import AsyncModule
-import lxml.html
+from base import IrcModule
 class Module(AsyncModule):
     """
 

autiste/modules/links.py

 import urllib
 import BeautifulSoup
 
-from base import AsyncModule
+from base import IrcModule
 import unicodedata
 
 
 url_re = re.compile(url, re.VERBOSE | re.MULTILINE)
 
 def strip_accents(s):
-   return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn'))
+   return unicodedata.normalize('NFKD', s).encode('ascii','ignore')
 
 def grabUrls(text):
     """Given a text string, returns all the urls we can find in it."""
     return url_re.findall(text)
 
-class Module(AsyncModule):
+class Module(IrcModule):
     """
 
     """
     def __init__(self, conf, irc):
-        AsyncModule.__init__(self, conf, irc)
+        IrcModule.__init__(self, conf, irc)
 
     def name(self):
         return 'Title links grabber'

autiste/modules/logger.py

 import time
 import os
 
-from base import AsyncModule
+from base import IrcModule
 
 class ChannelLogger(object):
     def __init__(self, conf, channel):
         return self.chan[channel].get_random()
 
 
-class Module(AsyncModule):
+class Module(IrcModule):
     """
 
     """
     def __init__(self, conf, irc):
-        AsyncModule.__init__(self, conf, irc)
+        IrcModule.__init__(self, conf, irc)
         self.logger = None
         print conf
 

autiste/modules/twitter.py

 import sys
 import pprint
 import twitter
+import pycurl
+import simplejson as json
 
 from base import AsyncModule
 
+STREAM_URL="http://stream.twitter.com/1/statuses/filter.json"
+
+import unicodedata
+
+def asciize(s):
+    return str(unicodedata.normalize('NFKD', s).encode('ascii','ignore'))
+
+
 class Module(AsyncModule):
     """
 
     """
     def __init__(self, conf, irc):
         AsyncModule.__init__(self, conf, irc)
+        self.buffer = ""
+        self.pyc = None
+
+    def run(self):
+        self.pyc = pycurl.Curl()
+        self.pyc.setopt(pycurl.USERPWD, "%s:%s" % (self.conf.get("user"), self.conf.get("pass")))
+        self.pyc.setopt(pycurl.URL, STREAM_URL)
+        self.pyc.setopt(pycurl.WRITEFUNCTION, self.on_receive)
+        self.pyc.setopt(pycurl.POSTFIELDS, "follow=24299195,116523453,15687408,38331159")
+        self.pyc.setopt(pycurl.POST, 1)
+        self.pyc.setopt(pycurl.VERBOSE, 1)
+        self.pyc.perform()
+
+
+    def on_receive(self, data):
+        print "on_receive", data
+        self.buffer += data
+        if data.endswith("\r\n") and self.buffer.strip():
+            content = json.loads(self.buffer)
+            self.buffer = ""
+            if "text" in content:
+                self.irc.say("#dzen", asciize(u"{0[user][name]}: {0[text]}".format(content)))
+                print "{0[user][name]}: {0[text]}".format(content)
 
     def name(self):
         return 'TwitterFeed'

decorators.py

-# -*- coding: latin-1 -*-
-"""
-
-
-
-"""
-import traceback
-
-def module_call(func, **kwargs):
-    """tries to call the same function on all loaded module
-without try/except
-    """
-    def decorate(*args, **kwargs):
-        instance = args[0]
-        modlist = instance.modules
-        for module in modlist.keys():
-            strfunc = func.__name__
-            print strfunc
-            if strfunc in dir(instance.modules[module]):
-                funccall = getattr(instance.modules[module], strfunc)
-                if callable(funccall):
-                    newargs = args[1:]
-                    try:
-                        funccall(*newargs, **kwargs)
-                    except Exception, e:
-                        traceback.print_exc()
-
-        return func(*args, **kwargs)
-    return decorate