def set_weboob(self, weboob): self.weboob = weboob self.storage = ApplicationStorage('boobot', weboob.storage) self.storage.load({})
class Boobot(SingleServerIRCBot): def __init__(self, channels, nickname, server, port=6667): SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname) # self.connection.add_global_handler('pubmsg', self.on_pubmsg) self.connection.add_global_handler('join', self.on_join) self.connection.add_global_handler('welcome', self.on_welcome) self.mainchannel = channels[0] self.joined = dict() for channel in channels: self.joined[channel] = Event() self.weboob = None self.storage = None def set_weboob(self, weboob): self.weboob = weboob self.storage = ApplicationStorage('boobot', weboob.storage) self.storage.load({}) def on_welcome(self, c, event): for channel in self.joined.keys(): c.join(channel) def on_join(self, c, event): # irclib 5.0 compatibility if callable(event.target): channel = event.target() else: channel = event.target self.joined[channel].set() def send_message(self, msg, channel=None): for m in msg.splitlines(): self.connection.privmsg(to_unicode(channel or self.mainchannel), to_unicode(m)[:450]) def on_pubmsg(self, c, event): # irclib 5.0 compatibility if callable(event.arguments): text = ' '.join(event.arguments()) channel = event.target() nick = event.source() else: text = ' '.join(event.arguments) channel = event.target nick = event.source for ignore in IRC_IGNORE: if ignore.search(nick): return for m in re.findall('([\w\d_\-]+@\w+)', text): for msg in self.on_boobid(m): self.send_message(msg, channel) for m in re.findall(u'(https?://[^\s\xa0+]+)', text): for msg in self.on_url(m): self.send_message(msg, channel) m = re.match('^%(?P<cmd>\w+)(?P<args>.*)$', text) if m and hasattr(self, 'cmd_%s' % m.groupdict()['cmd']): getattr(self, 'cmd_%s' % m.groupdict()['cmd'])(nick, channel, m.groupdict()['args'].strip()) def cmd_addquote(self, nick, channel, text): quotes = self.storage.get(channel, 'quotes', default=[]) quotes.append({'author': nick, 'timestamp': datetime.now(), 'text': text}) self.storage.set(channel, 'quotes', quotes) self.storage.save() self.send_message('Quote #%s added' % (len(quotes) - 1), channel) def cmd_delquote(self, nick, channel, text): quotes = self.storage.get(channel, 'quotes', default=[]) try: n = int(text) except ValueError: self.send_message("Quote #%s not found gros" % text, channel) return quotes.pop(n) self.storage.set(channel, 'quotes', quotes) self.storage.save() self.send_message('Quote #%s removed' % n, channel) def cmd_searchquote(self, nick, channel, text): try: pattern = re.compile(to_unicode(text), re.IGNORECASE|re.UNICODE) except Exception as e: self.send_message(str(e), channel) return quotes = [] for quote in self.storage.get(channel, 'quotes', default=[]): if pattern.search(to_unicode(quote['text'])): quotes.append(quote) try: quote = choice(quotes) except IndexError: self.send_message('No match', channel) else: self.send_message('%s' % quote['text'], channel) def cmd_getquote(self, nick, channel, text): quotes = self.storage.get(channel, 'quotes', default=[]) if len(quotes) == 0: return try: n = int(text) except ValueError: n = randint(0, len(quotes)-1) try: quote = quotes[n] except IndexError: self.send_message('Unable to find quote #%s' % n, channel) else: self.send_message('[%s] %s' % (n, quote['text']), channel) def on_boobid(self, boobid): _id, backend_name = boobid.split('@', 1) if backend_name in self.weboob.backend_instances: backend = self.weboob.backend_instances[backend_name] for cap in backend.iter_caps(): func = 'obj_info_%s' % cap.__name__[3:].lower() if hasattr(self, func): try: for msg in getattr(self, func)(backend, _id): yield msg except Exception as e: print(get_backtrace()) yield u'Oops: [%s] %s' % (type(e).__name__, e) break def on_url(self, url): url = fixurl(url) try: content_type, hsize, title = BoobotBrowser().urlinfo(url) if title: yield u'URL: %s' % title elif hsize: yield u'URL (file): %s, %s' % (content_type, hsize) else: yield u'URL (file): %s' % content_type except BrowserUnavailable as e: yield u'URL (error): %s' % e except Exception as e: print(get_backtrace()) yield u'Oops: [%s] %s' % (type(e).__name__, e) def obj_info_video(self, backend, id): v = backend.get_video(id) if v: yield u'Video: %s (%s)' % (v.title, v.duration) def obj_info_housing(self, backend, id): h = backend.get_housing(id) if h: yield u'Housing: %s (%sm² / %s%s)' % (h.title, h.area, h.cost, h.currency)
class Boobot(SingleServerIRCBot): def __init__(self, channels, nickname, server, port=6667): SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname) # self.connection.add_global_handler('pubmsg', self.on_pubmsg) self.connection.add_global_handler('join', self.on_join) self.connection.add_global_handler('welcome', self.on_welcome) self.connection.buffer_class.errors = 'replace' self.mainchannel = channels[0] self.joined = dict() for channel in channels: self.joined[channel] = Event() self.weboob = None self.storage = None self.tasks_queue = [] def set_weboob(self, weboob): self.weboob = weboob self.storage = ApplicationStorage('boobot', weboob.storage) self.storage.load({}) def on_welcome(self, c, event): for channel in self.joined.keys(): c.join(channel) def on_join(self, c, event): # irclib 5.0 compatibility if callable(event.target): channel = event.target() else: channel = event.target self.joined[channel].set() def send_message(self, msg, channel=None): for m in msg.splitlines(): msg = to_unicode(m).encode('utf-8')[:450].decode('utf-8') self.connection.privmsg(to_unicode(channel or self.mainchannel), msg) def on_pubmsg(self, c, event): # irclib 5.0 compatibility if callable(event.arguments): text = ' '.join(event.arguments()) channel = event.target() nick = event.source() else: text = ' '.join(event.arguments) channel = event.target nick = event.source for ignore in IRC_IGNORE: if ignore.search(nick): return for m in re.findall('([\w\d_\-]+@\w+)', text): for msg in self.on_boobid(m): self.send_message(msg, channel) for m in re.findall(u'(https?://[^\s\xa0+]+)', text): for msg in self.on_url(m): self.send_message(msg, channel) m = re.match('^%(?P<cmd>\w+)(?P<args>.*)$', text) if m and hasattr(self, 'cmd_%s' % m.groupdict()['cmd']): getattr(self, 'cmd_%s' % m.groupdict()['cmd'])(nick, channel, m.groupdict()['args'].strip()) def cmd_at(self, nick, channel, text): try: datetime, message = text.split(' ', 1) except ValueError: self.send_message('Syntax: %at [YYYY-MM-DDT]HH:MM[:SS] message', channel) return try: datetime = parse_date(datetime) except ValueError: self.send_message('Unable to read date %r' % datetime) return self.tasks_queue.append(Task(datetime, message, channel)) def cmd_addquote(self, nick, channel, text): quotes = self.storage.get(channel, 'quotes', default=[]) quotes.append({'author': nick, 'timestamp': datetime.now(), 'text': text}) self.storage.set(channel, 'quotes', quotes) self.storage.save() self.send_message('Quote #%s added' % (len(quotes) - 1), channel) def cmd_delquote(self, nick, channel, text): quotes = self.storage.get(channel, 'quotes', default=[]) try: n = int(text) except ValueError: self.send_message("Quote #%s not found gros" % text, channel) return quotes.pop(n) self.storage.set(channel, 'quotes', quotes) self.storage.save() self.send_message('Quote #%s removed' % n, channel) def cmd_searchquote(self, nick, channel, text): try: pattern = re.compile(to_unicode(text), re.IGNORECASE|re.UNICODE) except Exception as e: self.send_message(str(e), channel) return quotes = [] for quote in self.storage.get(channel, 'quotes', default=[]): if pattern.search(to_unicode(quote['text'])): quotes.append(quote) try: quote = choice(quotes) except IndexError: self.send_message('No match', channel) else: self.send_message('%s' % quote['text'], channel) def cmd_getquote(self, nick, channel, text): quotes = self.storage.get(channel, 'quotes', default=[]) if len(quotes) == 0: return try: n = int(text) except ValueError: n = randint(0, len(quotes)-1) try: quote = quotes[n] except IndexError: self.send_message('Unable to find quote #%s' % n, channel) else: self.send_message('[%s] %s' % (n, quote['text']), channel) def on_boobid(self, boobid): _id, backend_name = boobid.split('@', 1) if backend_name in self.weboob.backend_instances: backend = self.weboob.backend_instances[backend_name] for cap in backend.iter_caps(): func = 'obj_info_%s' % cap.__name__[3:].lower() if hasattr(self, func): try: for msg in getattr(self, func)(backend, _id): yield msg except Exception as e: print(get_backtrace()) yield u'Oops: [%s] %s' % (type(e).__name__, e) break def on_url(self, url): url = fixurl(url) try: content_type, hsize, title = BoobotBrowser().urlinfo(url) if title: yield u'URL: %s' % title elif hsize: yield u'URL (file): %s, %s' % (content_type, hsize) else: yield u'URL (file): %s' % content_type except BrowserUnavailable as e: yield u'URL (error): %s' % e except Exception as e: print(get_backtrace()) yield u'Oops: [%s] %s' % (type(e).__name__, e) def obj_info_video(self, backend, id): v = backend.get_video(id) if v: yield u'Video: %s (%s)' % (v.title, v.duration) def obj_info_housing(self, backend, id): h = backend.get_housing(id) if h: yield u'Housing: %s (%sm² / %s%s)' % (h.title, h.area, h.cost, h.currency)