PageRenderTime 64ms CodeModel.GetById 28ms app.highlight 28ms RepoModel.GetById 2ms app.codeStats 0ms

/examples/ircclient.py

https://bitbucket.org/prologic/circuits/
Python | 186 lines | 88 code | 48 blank | 50 comment | 6 complexity | ca0367b8f98d5e4cd835aef14df73db0 MD5 | raw file
  1#!/usr/bin/env python
  2# -*- coding: utf-8 -*-
  3
  4
  5"""Example IRC Client
  6
  7A basic IRC client with a very basic console interface.
  8
  9For usage type:
 10
 11   ./ircclient.py --help
 12
 13"""
 14
 15
 16from __future__ import print_function
 17
 18import os
 19from socket import gethostname
 20from optparse import OptionParser
 21
 22
 23from circuits import handler, Component
 24from circuits import __version__ as systemVersion
 25
 26from circuits.io import stdin
 27
 28from circuits.net.events import connect
 29from circuits.net.sockets import TCPClient
 30
 31from circuits.protocols.irc import IRC, PRIVMSG, USER, NICK, JOIN
 32
 33
 34USAGE = "%prog [options] host [port]"
 35VERSION = "%prog v" + systemVersion
 36
 37
 38def parse_options():
 39    parser = OptionParser(usage=USAGE, version=VERSION)
 40
 41    parser.add_option(
 42        "-n", "--nick",
 43        action="store", default=os.environ["USER"], dest="nick",
 44        help="Nickname to use"
 45    )
 46
 47    parser.add_option(
 48        "-c", "--channel",
 49        action="store", default="#circuits", dest="channel",
 50        help="Channel to join"
 51    )
 52
 53    opts, args = parser.parse_args()
 54
 55    if len(args) < 1:
 56        parser.print_help()
 57        raise SystemExit(1)
 58
 59    return opts, args
 60
 61
 62class Client(Component):
 63
 64    # Set a separate channel in case we want multiple ``Client`` instances.
 65    channel = "ircclient"
 66
 67    def init(self, host, port=6667, opts=None):
 68        self.host = host
 69        self.port = port
 70        self.opts = opts
 71        self.hostname = gethostname()
 72
 73        self.nick = opts.nick
 74        self.ircchannel = opts.channel
 75
 76        # Add TCPClient and IRC to the system.
 77        TCPClient(channel=self.channel).register(self)
 78        IRC(channel=self.channel).register(self)
 79
 80    def ready(self, component):
 81        """ready Event
 82
 83        This event is triggered by the underlying ``TCPClient`` Component
 84        when it is ready to start making a new connection.
 85        """
 86
 87        self.fire(connect(self.host, self.port))
 88
 89    def connected(self, host, port):
 90        """connected Event
 91
 92        This event is triggered by the underlying ``TCPClient`` Component
 93        when a successfully connection has been made.
 94        """
 95
 96        print("Connected to %s:%d" % (host, port))
 97
 98        nick = self.nick
 99        hostname = self.hostname
100        name = "%s on %s using circuits/%s" % (nick, hostname, systemVersion)
101
102        self.fire(NICK(nick))
103        self.fire(USER(nick, nick, self.hostname, name))
104
105    def numeric(self, source, numeric, *args):
106        """numeric Event
107
108        This event is triggered by the ``IRC`` Protocol Component when we have
109        received an IRC Numberic Event from server we are connected to.
110        """
111
112        if numeric == 1:
113            self.fire(JOIN(self.ircchannel))
114        elif numeric == 433:
115            self.nick = newnick = "%s_" % self.nick
116            self.fire(NICK(newnick))
117
118    def join(self, source, channel):
119        """join Event
120
121        This event is triggered by the ``IRC`` Protocol Component when a
122        user has joined a channel.
123        """
124
125        if source[0].lower() == self.nick.lower():
126            print("Joined %s" % channel)
127        else:
128            print(
129                "--> %s (%s) has joined %s" % (
130                    source[0], "@".join(source[1:]), channel
131                )
132            )
133
134    def notice(self, source, target, message):
135        """notice Event
136
137        This event is triggered by the ``IRC`` Protocol Component for each
138        notice we receieve from the server.
139        """
140
141        print("-%s- %s" % (source[0], message))
142
143    def privmsg(self, source, target, message):
144        """privmsg Event
145
146        This event is triggered by the ``IRC`` Protocol Component for each
147        message we receieve from the server.
148        """
149
150        if target[0] == "#":
151            print("<%s> %s" % (source[0], message))
152        else:
153            print("-%s- %s" % (source[0], message))
154
155    @handler("read", channel="stdin")
156    def stdin_read(self, data):
157        """read Event (on channel ``stdin``)
158
159        This is the event handler for ``read`` events specifically from the
160        ``stdin`` channel. This is triggered each time stdin has data that
161        it has read.
162        """
163
164        data = data.strip().decode("utf-8")
165
166        print("<{0:s}> {1:s}".format(self.nick, data))
167        self.fire(PRIVMSG(self.ircchannel, data))
168
169
170def main():
171    opts, args = parse_options()
172
173    host = args[0]
174    if len(args) > 1:
175        port = int(args[1])
176    else:
177        port = 6667
178
179    # Configure and run the system.
180    client = Client(host, port, opts=opts)
181    stdin.register(client)
182    client.run()
183
184
185if __name__ == "__main__":
186    main()