Skip to content

Commit

Permalink
Merge pull request #2 from embolalia/master
Browse files Browse the repository at this point in the history
Pull to my fork
  • Loading branch information
Nuvelle committed Apr 29, 2014
2 parents 578508a + 3ca1280 commit d5587f9
Show file tree
Hide file tree
Showing 48 changed files with 235 additions and 82 deletions.
3 changes: 2 additions & 1 deletion conftest.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
collect_ignore = ["setup.py", "willie.py"]
# This file lists files which should be ignored by pytest
collect_ignore = ["setup.py", "willie.py", "willie/modules/ipython.py"]
8 changes: 7 additions & 1 deletion willie/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ def is_shutdown(obj):
"""
if (callable(obj) and
hasattr(obj, "name")
hasattr(obj, "__name__")
and obj.__name__ == 'shutdown'):
return True
return False
Expand Down Expand Up @@ -566,6 +566,11 @@ def __init__(self, willie, origin):
self.bot = willie
self.origin = origin

def __dir__(self):
classattrs = [attr for attr in self.__dict__
if not attr.startswith('__')]
return list(self.__dict__)+classattrs+dir(self.bot)

def say(self, string, max_messages=1):
self.bot.msg(self.origin.sender, string, max_messages)

Expand Down Expand Up @@ -726,6 +731,7 @@ def call(self, func, origin, willie, trigger):

if not trigger.admin and \
not func.unblockable and \
func.rate > 0 and \
func in self.times[nick]:
timediff = time.time() - self.times[nick][func]
if timediff < func.rate:
Expand Down
18 changes: 17 additions & 1 deletion willie/coretasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ def retry_join(bot, trigger):

@willie.module.rule('(.*)')
@willie.module.event('353')
@willie.module.priority('high')
@willie.module.thread(False)
@willie.module.unblockable
def handle_names(bot, trigger):
Expand Down Expand Up @@ -163,6 +164,8 @@ def handle_names(bot, trigger):

@willie.module.rule('(.*)')
@willie.module.event('MODE')
@willie.module.priority('high')
@willie.module.thread(False)
@willie.module.unblockable
def track_modes(bot, trigger):
"""Track usermode changes and keep our lists of ops up to date."""
Expand Down Expand Up @@ -227,6 +230,8 @@ def handle_old_modes(nick, mode):

@willie.module.rule('.*')
@willie.module.event('NICK')
@willie.module.priority('high')
@willie.module.thread(False)
@willie.module.unblockable
def track_nicks(bot, trigger):
"""Track nickname changes and maintain our chanops list accordingly."""
Expand Down Expand Up @@ -273,17 +278,24 @@ def track_nicks(bot, trigger):

@willie.module.rule('(.*)')
@willie.module.event('PART')
@willie.module.priority('high')
@willie.module.thread(False)
@willie.module.unblockable
def track_part(bot, trigger):
if trigger.nick == bot.nick:
bot.channels.remove(trigger.sender)
del bot.privileges[trigger.sender]
else:
del bot.privileges[trigger.sender][trigger.nick]
try:
del bot.privileges[trigger.sender][trigger.nick]
except KeyError:
pass


@willie.module.rule('.*')
@willie.module.event('KICK')
@willie.module.priority('high')
@willie.module.thread(False)
@willie.module.unblockable
def track_kick(bot, trigger):
nick = Nick(trigger.args[1])
Expand All @@ -302,6 +314,8 @@ def track_kick(bot, trigger):

@willie.module.rule('.*')
@willie.module.event('JOIN')
@willie.module.priority('high')
@willie.module.thread(False)
@willie.module.unblockable
def track_join(bot, trigger):
if trigger.nick == bot.nick and trigger.sender not in bot.channels:
Expand All @@ -312,6 +326,8 @@ def track_join(bot, trigger):

@willie.module.rule('.*')
@willie.module.event('QUIT')
@willie.module.priority('high')
@willie.module.thread(False)
@willie.module.unblockable
def track_quit(bot, trigger):
for chanprivs in bot.privileges.values():
Expand Down
68 changes: 35 additions & 33 deletions willie/irc.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
import ssl
has_ssl = True
except ImportError:
#no SSL support
# no SSL support
has_ssl = False
if has_ssl:
if not hasattr(ssl, 'match_hostname'):
Expand All @@ -53,7 +53,7 @@ def __init__(self, bot, source, args, tags):
self.hostmask = source
self.tags = tags

#Split out the nick, user, and host from hostmask per the regex above.
# Split out the nick, user, and host from hostmask per the regex above.
match = Origin.source.match(source or '')
self.nick, self.user, self.host = match.groups()
self.nick = Nick(self.nick)
Expand All @@ -79,7 +79,7 @@ def __init__(self, config):
ca_certs = '/etc/pki/tls/cert.pem'

if config.log_raw is None:
#Default is to log raw data, can be disabled in config
# Default is to log raw data, can be disabled in config
config.log_raw = True
asynchat.async_chat.__init__(self)
self.set_terminator(b'\n')
Expand All @@ -104,9 +104,9 @@ def __init__(self, config):
self.writing_lock = threading.Lock()
self.raw = None

#Right now, only accounting for two op levels.
#This might be expanded later.
#These lists are filled in startup.py, as of right now.
# Right now, only accounting for two op levels.
# This might be expanded later.
# These lists are filled in startup.py, as of right now.
self.ops = dict()
"""
A dictionary mapping channels to a ``Nick`` list of their operators.
Expand All @@ -122,7 +122,7 @@ def __init__(self, config):
half-ops and ops.
"""

#We need this to prevent error loops in handle_error
# We need this to prevent error loops in handle_error
self.error_count = 0

self.connection_registered = False
Expand Down Expand Up @@ -155,7 +155,7 @@ def log_raw(self, line, prefix):

def safe(self, string):
"""Remove newlines from a string."""
if sys.version_info.major >=3 and isinstance(string, bytes):
if sys.version_info.major >= 3 and isinstance(string, bytes):
string = string.decode('utf8')
elif sys.version_info.major < 3:
if not isinstance(string, unicode):
Expand Down Expand Up @@ -189,17 +189,17 @@ def write(self, args, text=None):
self.writing_lock.acquire() # Blocking lock, can't send two things
# at a time

#From RFC2812 Internet Relay Chat: Client Protocol
#Section 2.3
# From RFC2812 Internet Relay Chat: Client Protocol
# Section 2.3
#
#https://tools.ietf.org/html/rfc2812.html
# https://tools.ietf.org/html/rfc2812.html
#
#IRC messages are always lines of characters terminated with a
#CR-LF (Carriage Return - Line Feed) pair, and these messages SHALL
#NOT exceed 512 characters in length, counting all characters
#including the trailing CR-LF. Thus, there are 510 characters
#maximum allowed for the command and its parameters. There is no
#provision for continuation of message lines.
# IRC messages are always lines of characters terminated with a
# CR-LF (Carriage Return - Line Feed) pair, and these messages SHALL
# NOT exceed 512 characters in length, counting all characters
# including the trailing CR-LF. Thus, there are 510 characters
# maximum allowed for the command and its parameters. There is no
# provision for continuation of message lines.

if text is not None:
temp = (' '.join(args) + ' :' + text)[:510] + '\r\n'
Expand All @@ -222,7 +222,7 @@ def initiate_connect(self, host, port):
source_address = ((self.config.core.bind_host, 0)
if self.config.core.bind_address else None)
self.set_socket(socket.create_connection((host, port),
source_address=source_address))
source_address=source_address))
if self.config.core.use_ssl and has_ssl:
self.send = self._ssl_send
self.recv = self._ssl_recv
Expand Down Expand Up @@ -474,14 +474,16 @@ def msg(self, recipient, text, max_messages=1):
if elapsed < wait:
time.sleep(wait - elapsed)

# Loop detection
messages = [m[1] for m in self.stack[-8:]]
if sys.version_info.major < 3 and isinstance(text, str):
text = text.decode('utf-8')
if messages.count(text) >= 5:
text = '...'
if messages.count('...') >= 3:
return
# Loop detection
messages = [m[1] for m in self.stack[-8:]]

# If what we about to send repeated at least 5 times in the
# last 5 minutes, replace with '...'
if messages.count(text) >= 5 and elapsed < 300:
text = '...'
if messages.count('...') >= 3:
# If we said '...' 3 times, discard message
return

self.write(('PRIVMSG', recipient), text)
self.stack.append((time.time(), self.safe(text)))
Expand Down Expand Up @@ -578,10 +580,10 @@ def handle_error(self):
if self.config.exit_on_error:
os._exit(1)

#Helper functions to maintain the oper list.
#They cast to Nick when adding to be quite sure there aren't any accidental
#string nicks. On deletion, you know you'll never need to worry about what
#the real superclass is, so we just cast and remove.
# Helper functions to maintain the oper list.
# They cast to Nick when adding to be quite sure there aren't any accidental
# string nicks. On deletion, you know you'll never need to worry about what
# the real superclass is, so we just cast and remove.
def add_op(self, channel, name):
if isinstance(name, Nick):
self.ops[channel].add(name)
Expand Down Expand Up @@ -615,9 +617,9 @@ def flush_ops(self, channel):
self.voices[channel] = set()

def init_ops_list(self, channel):
if not channel in self.halfplus:
if channel not in self.halfplus:
self.halfplus[channel] = set()
if not channel in self.ops:
if channel not in self.ops:
self.ops[channel] = set()
if not channel in self.voices:
if channel not in self.voices:
self.voices[channel] = set()
2 changes: 2 additions & 0 deletions willie/modules/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#coding: utf8
from __future__ import unicode_literals
3 changes: 2 additions & 1 deletion willie/modules/admin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# coding=utf-8
#coding: utf8
"""
admin.py - Willie Admin Module
Copyright 2010-2011, Sean B. Palmer (inamidst.com) and Michael Yanovich
Expand All @@ -10,6 +10,7 @@
http://willie.dftba.net
"""
from __future__ import unicode_literals

import willie.module

Expand Down
3 changes: 2 additions & 1 deletion willie/modules/adminchannel.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# coding=utf-8
#coding: utf8
"""
admin.py - Willie Admin Module
Copyright 2010-2011, Michael Yanovich, Alek Rollyson, and Edward Powell
Expand All @@ -8,6 +8,7 @@
http://willie.dftba.net/
"""
from __future__ import unicode_literals

import re
from willie.module import commands, priority, OP
Expand Down
4 changes: 3 additions & 1 deletion willie/modules/announce.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# -*- coding: utf8 -*-
#coding: utf8
"""
announce.py - Send a message to all channels
Copyright © 2013, Elad Alfassa, <[email protected]>
Licensed under the Eiffel Forum License 2.
"""
from __future__ import unicode_literals

from willie.module import commands, example


Expand Down
4 changes: 3 additions & 1 deletion willie/modules/bugzilla.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# coding=utf-8
#coding: utf8
"""
admin.py - Willie Bugzilla Module
Copyright © 2013, Edward Powell, embolalia.net
Licensed under the Eiffel Forum License 2.
http://willie.dftba.net/
"""
from __future__ import unicode_literals

from lxml import etree
import re
from willie import web, tools
Expand Down
2 changes: 1 addition & 1 deletion willie/modules/calc.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# coding=utf-8
#coding: utf8
"""
calc.py - Willie Calculator Module
Copyright 2008, Sean B. Palmer, inamidst.com
Expand Down
19 changes: 12 additions & 7 deletions willie/modules/chanlogs.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# coding=utf-8
#coding: utf8
"""
chanlogs.py - Willie Channel Logger module
Copyright 2014, David Baumgold <[email protected]>
Expand All @@ -11,6 +11,7 @@
import os
import os.path
import threading
import sys
from datetime import datetime
import willie.module
import willie.tools
Expand Down Expand Up @@ -63,12 +64,16 @@ def _format_template(tpl, bot, **kwargs):
if not bot.config.chanlogs.microseconds:
dt = dt.replace(microsecond=0)

return tpl.format(
formatted = tpl.format(
origin=bot.origin, datetime=dt.isoformat(),
date=dt.date().isoformat(), time=dt.time().isoformat(),
**kwargs
) + "\n"

if sys.version_info.major < 3 and isinstance(formatted, unicode):
formatted = formatted.encode('utf-8')
return formatted


def setup(bot):
if not getattr(bot.config, "chanlogs", None):
Expand Down Expand Up @@ -106,7 +111,7 @@ def log_message(bot, message):
fpath = get_fpath(bot)
with bot.memory['chanlog_locks'][fpath]:
with open(fpath, "a") as f:
f.write(logline.encode('utf-8'))
f.write(logline)


@willie.module.rule('.*')
Expand All @@ -118,7 +123,7 @@ def log_join(bot, trigger):
fpath = get_fpath(bot, channel=trigger)
with bot.memory['chanlog_locks'][fpath]:
with open(fpath, "a") as f:
f.write(logline.encode('utf-8'))
f.write(logline)


@willie.module.rule('.*')
Expand All @@ -130,7 +135,7 @@ def log_part(bot, trigger):
fpath = get_fpath(bot, channel=trigger)
with bot.memory['chanlog_locks'][fpath]:
with open(fpath, "a") as f:
f.write(logline.encode('utf-8'))
f.write(logline)


@willie.module.rule('.*')
Expand All @@ -149,7 +154,7 @@ def log_quit(bot, trigger):
fpath = get_fpath(bot, channel)
with bot.memory['chanlog_locks'][fpath]:
with open(fpath, "a") as f:
f.write(logline.encode('utf-8'))
f.write(logline)


@willie.module.rule('.*')
Expand All @@ -168,4 +173,4 @@ def log_nick_change(bot, trigger):
fpath = get_fpath(bot, channel)
with bot.memory['chanlog_locks'][fpath]:
with open(fpath, "a") as f:
f.write(logline.encode('utf-8'))
f.write(logline)
Loading

0 comments on commit d5587f9

Please sign in to comment.