Пример #1
0
    def __init__(self, **kwargs):
        self.irc_nick = kwargs.pop('irc_nick', DEFAULT_IRC_NICK)
        self.irc_host = kwargs.pop('irc_host', DEFAULT_IRC_HOST)
        self.irc_port = kwargs.pop('irc_port', DEFAULT_IRC_PORT)
        self.irc_channels = [x.strip('#') for x in
                             kwargs.pop('irc_channels', DEFAULT_IRC_CHANNELS)]
        # TODO: validate channel formatting?
        self.irc_client = IRCClient(self.irc_host,
                                    self.irc_nick,
                                    self.irc_port,
                                    reconnect=True)
        self.irc_client.add_handler(ping_handler, 'PING')
        self.irc_client.add_handler(self.on_irc_connect, _JOIN_CODE)
        self.irc_client.add_handler(self._on_irc)
        self.irc_client.add_handler(self.on_message, 'PRIVMSG')

        self.ws_port = kwargs.pop('ws_port', DEFAULT_WS_PORT)
        self.ws_server = WebSocketServer(('', self.ws_port),
                                         Resource({'/': WebSocketApplication}))
        defer_start = kwargs.pop('defer_start', False)
        if not defer_start:
            self.start()
Пример #2
0
def create_client(host, nickname, password=None, **kwargs):
    """ Create quite simple default client"""
    cl = Client(host, nickname, **kwargs)
    cl.add_handler(handlers.ping_handler, 'PING') # for keepalives
    cl.add_handler(handlers.JoinHandler(TEST_CHANNEL, rejoinmsg='%s sucks'))

    cl.add_handler(handlers.ReplyWhenQuoted("I'm busy!"))
    cl.add_handler(handlers.nick_in_use_handler, replycode.ERR_NICKNAMEINUSE)
    if password:
        cl.add_handler(handlers.AuthHandler(nickname, password))
    cl.add_handler(handlers.IRCShutdownHandler())
    return cl
Пример #3
0
class Barnsworth(object):
    def __init__(self, **kwargs):
        self.irc_nick = kwargs.pop('irc_nick', DEFAULT_IRC_NICK)
        self.irc_host = kwargs.pop('irc_host', DEFAULT_IRC_HOST)
        self.irc_port = kwargs.pop('irc_port', DEFAULT_IRC_PORT)
        self.irc_channels = [x.strip('#') for x in
                             kwargs.pop('irc_channels', DEFAULT_IRC_CHANNELS)]
        # TODO: validate channel formatting?
        self.irc_client = IRCClient(self.irc_host,
                                    self.irc_nick,
                                    self.irc_port,
                                    reconnect=True)
        self.irc_client.add_handler(ping_handler, 'PING')
        self.irc_client.add_handler(self.on_irc_connect, _JOIN_CODE)
        self.irc_client.add_handler(self._on_irc)
        self.irc_client.add_handler(self.on_message, 'PRIVMSG')

        self.ws_port = kwargs.pop('ws_port', DEFAULT_WS_PORT)
        self.ws_server = WebSocketServer(('', self.ws_port),
                                         Resource({'/': WebSocketApplication}))
        defer_start = kwargs.pop('defer_start', False)
        if not defer_start:
            self.start()

    def start(self):
        self._start_irc()
        self._start_ws()

    def _on_irc(self, client, msg):
        if DEBUG:
            msg_content = ' '.join(msg.params[1:]).decode('utf-8')
            clean_msg = parsers.clean_irc_markup(msg_content)
            BLOG.debug('irc message').success(clean_msg)

    def on_irc_connect(self, client, msg):
        # TODO: need another handler to register a join failure?
        for channel in self.irc_channels:
            with BLOG.critical('joining channel %s' % channel):
                client.send_message(Join(channel))

    def on_message(self, client, msg):
        msg_content = ' '.join(msg.params[1:]).decode('utf-8')
        msg_content.replace(u'\x02', '')  # hmm, TODO
        try:
            action_dict = parsers.parse_irc_message(msg_content)
        except Exception as e:
            # log
            return
        action_ctx = ActionContext(action_dict)
        with BLOG.debug('activity publish'):
            self.publish_activity(action_ctx)
        return

    def publish_activity(self, action_ctx):
        action_json = json.dumps(action_ctx.action, sort_keys=True)
        for addr, ws_client in self.ws_server.clients.iteritems():
            ws_client.ws.send(action_json)

        # TODO: store action for activity batch service?
        with BLOG.debug('action context augmentation') as r:
            self._augment_action_ctx(action_ctx)
        with BLOG.debug('event detection') as r:
            event_list = self._detect_events(action_ctx)
            r.success('detected %s events' % len(event_list))
        for event in event_list:
            event_cn = event.__class__.__name__
            with BLOG.critical('publishing %r' % event_cn) as r:
                r.extras.update(event.to_dict())
                action_ctx.add_event(event)
                event_json = event.to_json()
                for addr, ws_client in self.ws_server.clients.iteritems():
                    ws_client.ws.send(event_json)
        return

    def _augment_action_ctx(self, action_ctx):
        action = action_ctx.action
        if action['is_anon']:
            # TODO: geo-augmentor
            return  # TODO?
        username = action['user']
        rc = ransom.Client()
        resp = rc.get(_USERDAILY_URL_TMPL % username)
        try:
            udc_dict = json.loads(resp.text)['userdailycontribs']
        except KeyError:
            return  # Log?
        user_daily = UserDailyInfo.from_dict(username, udc_dict)
        action_ctx.user_daily_info = user_daily
        return

    def _detect_events(self, action_ctx):
        try:
            event_types = EVENT_MAP[action_ctx.action_type]
        except KeyError:
            return []
        event_list = []
        for event_type in event_types:
            try:
                event = event_type.from_action_context(action_ctx)
                event_list.append(event)
            except events.Uneventful:
                # probably won't even log this
                # Uneventful is uneventful for a reason
                #print 'event not applicable: ', ue
                pass
            except Exception:
                BLOG.critical('event detection error').exception()
        return event_list

    def _start_irc(self):
        self.irc_client.start()

    def _start_ws(self):
        self.ws_server.serve_forever()
Пример #4
0
                                bot._sabotage.set(False)

                # Now check if a bot is expecting a message, and pass it along.
                for bot in g.bots:
                    if bot.channel != channel:
                        continue
                    name = 'process_' + msg.params[1].upper()
                    if name == 'process_COMMENT':
                        pass
                    elif hasattr(bot, name):
                        process = getattr(bot, name)
                        process(msg.params)
                    elif bot.expecting:
                        bot.expecting(msg.params)


if __name__ == '__main__':

    server = 'localhost'
    if len(sys.argv) > 1:
        server = sys.argv[1]

    irc = Client(server, 'aigamedev', port=6667, local_hostname='localhost')
    h = ResistanceCompetitionHandler()
    irc.add_handler(h)
    try:
        irc.start()
        irc.join()
    except KeyboardInterrupt:
        h.upcoming.put(([], None))
Пример #5
0
                # Now check if a bot is expecting a message, and pass it along.
                for bot in g.bots:
                    if bot.channel != channel:
                        continue
                    name = 'process_'+msg.params[1].upper()
                    if name == 'process_COMMENT':
                        pass
                    elif hasattr(bot, name):
                        process = getattr(bot, name)
                        process(msg.params)
                    elif bot.expecting:
                        bot.expecting(msg.params)
 

if __name__ == '__main__':
    
    server = 'localhost'
    if len(sys.argv) > 1:
        server = sys.argv[1]

    irc = Client(server, 'aigamedev',  port=6667, local_hostname='localhost')
    OnlineRound.client = irc
    h = ResistanceCompetitionHandler()
    irc.add_handler(h)
    try:
        irc.start()
        irc.join()
    except KeyboardInterrupt:
        h.upcoming.put(([], None))

Пример #6
0
            self.client.send("No input required at this stage.")


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('--server', type=str, required=False, default='irc.aigamedev.com',
                help = "IRC server name to connect to hosting running games.") 
    parser.add_argument('--port', type=int, required=False, default=6667,
                help = "Port of the IRC server to connect to.")
    parser.add_argument('--name', type=str, required=False, default='aigamedev',
                help = "Name of the IRC client that connects to the server.")
    args = parser.parse_args()

    irc = Client(args.server, args.name,  port=args.port, local_hostname='localhost')
    OnlineRound.client = irc
    h = ResistanceCompetitionHandler()
    irc.add_handler(h)
    try:
        irc.start()
        irc.join()
    except KeyboardInterrupt:
        h.upcoming.put(([], None))


# COMPETITION
# - Check current games for players disconnecting and invalidate them.
# - Mark bots that timed out and punish them for it -- or notify channel.
# - For speed, use a constant set of bot channels rather than game channels.
# - For speed, run multiple games with the same bots, different configurations. 
Пример #7
0
"""
In this example, we have a basic 'hello world' IRC bot.
Upon joining the server and a channel, it will annouce 'Hello world!'.
Thereafter it will watch for any messages containing its nick (case-insensitive)
and respond to the sender with a "Hello, {sender}!"

Press ^C (ie. send SIGINT) to exit.
"""

import logging
import sys

from geventirc import Client

logging.basicConfig(level=logging.DEBUG)

host, nick, channel = sys.argv[1:4]

client = Client(host, nick=nick)
channel = client.channel(channel)

channel.join()
channel.msg("Hello world!")

@client.handler(command='PRIVMSG', payload=lambda value: nick.lower() in value.lower())
def mentioned(client, msg):
	channel.msg("Hello, {}!".format(msg.sender))

client.start()
client.join()
Пример #8
0
def create_client(host, nickname, password=None, **kwargs):
    """ Create quite simple default client"""
    cl = Client(host, nickname, **kwargs)
    cl.add_handler(handlers.ping_handler, 'PING')  # for keepalives
    cl.add_handler(handlers.JoinHandler(TEST_CHANNEL, rejoinmsg='%s sucks'))

    cl.add_handler(handlers.ReplyWhenQuoted("I'm busy!"))
    cl.add_handler(handlers.nick_in_use_handler, replycode.ERR_NICKNAMEINUSE)
    if password:
        cl.add_handler(handlers.AuthHandler(nickname, password))
    cl.add_handler(handlers.IRCShutdownHandler())
    return cl