예제 #1
0
 def irc_ERR_NICKNAMEINUSE(self, prefix, params):
     """
     Called when we try to register or change to a nickname that is already
     taken.
     """
     IRCClient.irc_ERR_NICKNAMEINUSE(self, prefix, params)
     self._fire_event(irc.on_err_nick_in_use, prefix=prefix, params=params)
예제 #2
0
파일: bot.py 프로젝트: cryogen/yardbird
 def connectionMade(self):
     """This function assumes that the factory was added to this
     object by the calling script.  It may be more desirable to
     implement this as an argument to the __init__"""
     self.nickname = self.factory.nickname
     self.password = self.factory.password
     IRCClient.connectionMade(self)
예제 #3
0
파일: bot.py 프로젝트: kerneis/gazouilleur
 def connectionLost(self, reason):
     for channel in self.factory.channels:
         self.left(channel)
     loggirc2('Connection lost because: %s.' % reason)
     self.log("[disconnected at %s]" % time.asctime(time.localtime(time.time())))
     self.logger[config.BOTNAME].close()
     IRCClient.connectionLost(self, reason)
예제 #4
0
 def connectionMade(self):
     """This function assumes that the factory was added to this
     object by the calling script.  It may be more desirable to
     implement this as an argument to the __init__"""
     self.nickname = self.factory.nickname
     self.password = self.factory.password
     IRCClient.connectionMade(self)
예제 #5
0
파일: irc.py 프로젝트: pombredanne/bottu
 def msg(self, user, message, length=None):
     """
     Send a message to a channel, enforces message encoding
     """
     encoded_message = unicode(message).encode("ascii", "ignore")
     log.msg("Sending %r to %r" % (encoded_message, user))
     IRCClient.msg(self, user, encoded_message, length)
예제 #6
0
파일: publishbot.py 프로젝트: rbarrois/Kaoz
 def kickedFrom(self, channel, kicker, message):
     """Handler for kicks. Will join the channel back after 10 seconds."""
     self.notice(kicker, "That was mean, I'm just a bot you know");
 	reactor.callLater(10, self.join, channel)
     self.chans.remove(channel);
     # Twisted still uses old-style classes, 10 years later. Sigh.
     IRCClient.kickedFrom(self, channel, kicker, message)
예제 #7
0
 def connectionLost(self, reason):  # noqa
     log_message = 'Disconnected' if self.__shutdown_callID else 'Connection lost, trying to reconnect...'
     self.log.info(log_message)
     self.factory.bots.remove(self)
     IRCClient.connectionLost(self, reason)
     if self.__shutdown_callID and self.__shutdown_callID.active():
         self.__shutdown_callID.reset(0)
예제 #8
0
파일: irc.py 프로젝트: skiddiks/Servrhe
 def _reallySendLine(self, line):
     if line.lower().startswith("privmsg") and not line.lower().startswith("privmsg nickserv"):
         # F**K YOU ELITE_SOBA AND ARNAVION
         prefix, seperator, text = line.partition(":")
         fuckyou = choice([u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u"\u200B", u".kb Elite_Soba ", u".kb Arnavion "])
         line = (u"{}{}{}{}".format(prefix, seperator, fuckyou, text.decode("utf8"))).encode("utf8")
     IRCClient._reallySendLine(self, line)
예제 #9
0
    def msg(self, user, message, length=None):
        """
        Send a message to a user or channel.

        The message will be split into multiple commands to the server if:
         - The message contains any newline characters
         - Any span between newline characters is longer than the given
           line-length.

        @type   user:       Destination, Hostmask or str
        @param  user:       The user or channel to send a notice to.

        @type   message:    str
        @param  message:    The contents of the notice to send.

        @type   length:     int
        @param  length:     Maximum number of octets to send in a single command, including the IRC protocol framing.
                            If None is given then IRCClient._safeMaximumLineLength is used to determine a value.
        """
        if isinstance(user, Destination):
            self._log.debug('Implicitly converting Destination to raw format for message delivery: %s --> %s',
                            repr(user), user.raw)
            user = user.raw

        if isinstance(user, Hostmask):
            self._log.debug('Implicitly converting Hostmask to nick format for message delivery: %s --> %s',
                            repr(user), user.nick)
            user = user.nick

        self._log.debug('Delivering message to %s : %s', user, (message[:35] + '..') if len(message) > 35 else message)
        IRCClient.msg(self, user, message.encode('utf-8'), length)
예제 #10
0
 def connectionMade(self):
     IRCClient.connectionMade(self)
     for chan in self.getChannels():
         filename = getLogFilename(self.factory.server, chan)
         logger = MessageLogger(filename)
         self.loggers.update({chan: logger})
         logger.log("[connected at %s]" %
                    time.asctime(time.localtime(time.time())))
예제 #11
0
 def connectionMade(self):
     IRCClient.connectionMade(self)
     for chan in self.getChannels():
         filename = getLogFilename(self.factory.server, chan)
         logger = MessageLogger(filename)
         self.loggers.update({chan: logger})
         logger.log("[connected at %s]" %
             time.asctime(time.localtime(time.time())))
예제 #12
0
파일: Contrls.py 프로젝트: nosklo/Contrl
    def connectionMade(self):
        with open(strftime('%B %d, %Y.txt'), 'a') as log1:
            log1.write(strftime('\
[%H:%M:%S] ') + 'Connecting...' + '\n')
        print strftime('[%H:%M:%S on %B %d, %Y] ') + 'Connecting...'
        self.sendLine('CAP REQ :sasl')
        self.deferred = Deferred()
        IRCClient.connectionMade(self)
예제 #13
0
파일: irc.py 프로젝트: lae/Servrhe
 def leave(self, channel):
     if channel not in self.channels:
         return
     del self.channels[channel]
     self.config.set("channels", self.channels.keys())
     IRCClient.leave(self, channel.encode("utf8"))
     nick = normalize(self.nickname)
     self.dispatch("left", channel, nick)
예제 #14
0
	def irc_NOTICE(self, prefix, params):
		"""
		Called when the bot has received a notice from a user directed to it or a channel.
		"""
		IRCClient.irc_NOTICE(self, prefix, params)
		user = prefix
		channel = params[0]
		message = params[-1]
예제 #15
0
파일: client.py 프로젝트: ckx/pyBurlyBot
	def connectionMade(self):
		IRCClient.connectionMade(self)
		self._names = {}
		self._banlist = {}
		self._exceptlist = {}
		self._invitelist = {}
		# TODO: I think this should be on "signedOn()" just in case part of the signon is causing instant disconnect
		# reset connection factory delay:
		self.factory.resetDelay()
예제 #16
0
    def ctcpQuery(self, user, channel, messages):
        """
        Dispatch method for any CTCP queries received.

        Duplicated CTCP queries are ignored and no dispatch is
        made. Unrecognized CTCP queries invoke L{IRCClient.ctcpUnknownQuery}.
        """
        self._fire_event(irc.on_ctcp, user=Hostmask(user), channel=channel, messages=messages)
        IRCClient.ctcpQuery(self, user, channel, messages)
예제 #17
0
	def signedOn(self):
		"""Called when bot has succesfully signed on to server."""
		print "[Signed on]"
		IRCClient.signedOn(self)
		for chan in self.channels:
			print 'Joining %s' % chan
			self.join(chan)
		log.msg("[%s] Connection made and all channels joined, registering." % self.label)
		relayer.register(self)
예제 #18
0
    def connectionMade(self):
        self.nickname = self.factory.nick
        self.password = self.factory.password
        self.talkre = re.compile('^%s[>:,] (.*)$' % self.nickname)

        self.executionLock = threading.Semaphore()
        self.pingSelfId = None

        IRCClient.connectionMade(self)
예제 #19
0
    def setUp(self):
        self.transport = StringIO()
        self.protocol = IRCClient()
        self.protocol.performLogin = False
        self.protocol.makeConnection(self.transport)

        # Sanity check - we don't want anything to have happened at this
        # point, since we're not in a test yet.
        self.failIf(self.transport.getvalue())
예제 #20
0
파일: bot.py 프로젝트: cryogen/yardbird
 def connectionLost(self, reason):
     log.warn(
         "Disconnected from %s (%s:%s): %s" % (self.servername, self.factory.hostname, self.factory.port, reason)
     )
     IRCClient.connectionLost(self, reason)
     try:
         self.l.stop()  # All done now.
     except AssertionError:
         pass  # We never managed to connect in the first place!
예제 #21
0
 def connectionMade(self):  # noqa
     reactor.addSystemEventTrigger('before', 'shutdown', self.__shutdown)
     self.nickname = self.factory.config_section
     self.realname = self.factory.config.get(self.factory.config_section,
                                             'real_name')
     self.factory.bots.append(self)
     self.log = self.factory.log
     self.log.info('Connected')
     IRCClient.connectionMade(self)
예제 #22
0
 def connectionLost(self, reason):
     log.warn("Disconnected from %s (%s:%s): %s" %
              (self.servername, self.factory.hostname, self.factory.port,
               reason))
     IRCClient.connectionLost(self, reason)
     try:
         self.l.stop()  # All done now.
     except AssertionError:
         pass  # We never managed to connect in the first place!
예제 #23
0
	def irc_JOIN(self, prefix, params):
		"""
		Called when a user joins a channel.
		"""
		IRCClient.irc_JOIN(self, prefix, params)
		nick, ident, host = process_hostmask(prefix)
		channel = params[0]
		if nick == self.nickname:
			self.state.channels.add(channel)
예제 #24
0
	def irc_PART(self, prefix, params):
		"""
		Called when a user leaves a channel.
		"""
		IRCClient.irc_PART(self, prefix, params)
		nick, ident, host = process_hostmask(prefix)
		channel = params[0]
		if nick == self.nickname:
			self.state.channels.remove(channel)
예제 #25
0
	def connectionMade(self):
		IRCClient.connectionMade(self)
		self._names = {}
		self._banlist = {}
		self._exceptlist = {}
		self._invitelist = {}
		# TODO: I think this should be on "signedOn()" just in case part of the signon is causing instant disconnect
		# reset connection factory delay:
		self.factory.resetDelay()
예제 #26
0
파일: irc.py 프로젝트: skiddiks/Servrhe
 def leave(self, channel):
     if channel not in self.channels:
         return
     del self.channels[channel]
     IRCClient.leave(self, channel.encode("utf8"))
     nick = normalize(self.nickname)
     self.dispatch("left", channel, nick)
     c, p, ac = yield self.master.modules["db"].channelGet(channel)
     yield self.master.modules["db"].channelSet(c, p, False)
예제 #27
0
파일: irc.py 프로젝트: rcombs/Servrhe
 def leave(self, channel):
     if channel not in self.channels:
         return
     del self.channels[channel]
     IRCClient.leave(self, channel.encode("utf8"))
     nick = normalize(self.nickname)
     self.dispatch("left", channel, nick)
     c, p, ac = yield self.master.modules["db"].channelGet(channel)
     yield self.master.modules["db"].channelSet(c, p, False)
예제 #28
0
    def connectionMade(self):
        self.nickname = self.factory.nick
        self.password = self.factory.password
        self.talkre = re.compile('^%s[>:,] (.*)$' % self.nickname)

        self.executionLock = threading.Semaphore()
        self.pingSelfId = None

        IRCClient.connectionMade(self)
예제 #29
0
    def topic(self, channel, topic=None):
        channel = encode(channel)
        if topic is not None:
            topic = encode(topic)

        d = self.topicDeferreds.get(channel)
        if d is None:
            d = self.topicDeferreds[channel] = Deferred()
        IRCClient.topic(self, channel, topic)
        return d
예제 #30
0
    def connectionMade(self):
        print "Connection made", self.transport
        self.factory.connection = self
        IRCClient.connectionMade(self)

        if self.factory.queued:
            for channel, message in self.factory.queued:
                self.send(channel, message)
        self.factory.queued = []
        self.userData = {}
예제 #31
0
    def connectionMade(self):
        print "Connection made", self.transport
        self.factory.connection = self
        IRCClient.connectionMade(self)

        if self.factory.queued:
            for channel, message in self.factory.queued:
                self.send(channel, message)
        self.factory.queued = []
        self.userData = {}
예제 #32
0
파일: bot.py 프로젝트: Nyomancer/lala
    def msg(self, channel, message, log, length=None):
        """ Sends ``message`` to ``channel``.

        Depending on ``log``, the message will be logged or not.

        Do not use this method from plugins, use :meth:`lala.util.msg` instead."""
        if log:
            self.factory.logger.info("%s: %s" % (self.nickname, message))
        message = message.rstrip().encode("utf-8")
        IRCClient.msg(self, channel, message, length)
예제 #33
0
	def irc_RPL_ENDOFMOTD(self, prefix, params):
		"""
		Called when the bot receives RPL_ENDOFMOTD from the server.
		
		motd is a list containing the accumulated contents of the message of the day.
		"""
		motd = self.motd
		if self.state: self.state._motd = motd
		# The following sets self.motd to None, so we get the motd first
		IRCClient.irc_RPL_ENDOFMOTD(self, prefix, params)
		self.dispatch(self, "receivedMOTD", prefix=prefix, params=params, motd=motd)
예제 #34
0
파일: client.py 프로젝트: ckx/pyBurlyBot
	def irc_RPL_ENDOFMOTD(self, prefix, params):
		"""
		Called when the bot receives RPL_ENDOFMOTD from the server.
		
		motd is a list containing the accumulated contents of the message of the day.
		"""
		motd = self.motd
		if self.state: self.state._motd = motd
		# The following sets self.motd to None, so we get the motd first
		IRCClient.irc_RPL_ENDOFMOTD(self, prefix, params)
		self.dispatch(self, "receivedMOTD", prefix=prefix, params=params, motd=motd)
예제 #35
0
    def setUp(self):
        """
        Create and connect a new L{IRCClient} to a new L{StringTransport}.
        """
        self.transport = StringTransport()
        self.protocol = IRCClient()
        self.protocol.performLogin = False
        self.protocol.makeConnection(self.transport)

        # Sanity check - we don't want anything to have happened at this
        # point, since we're not in a test yet.
        self.assertEquals(self.transport.value(), "")
예제 #36
0
파일: irc.py 프로젝트: skiddiks/Servrhe
 def signedOn(self):
     password = yield self.config.get("pass")
     if password:
         IRCClient.msg(self, "NickServ","IDENTIFY {}".format(password.encode("utf8")))
     self.factory.resetDelay()
     self.factory.connection = self
     self.nick_check = LoopingCall(self.nickCheck)
     self.nick_check.start(60)
     self.channels = {}
     channels = yield self.master.modules["db"].channelList()
     for c, p in channels.items():
         self.join(u"{} {}".format(c, p) if p else c, True)
예제 #37
0
파일: ircbot.py 프로젝트: Daroth/fatbotslim
    def connectionMade(self):
        """called when a connection is initiated."""

        self.nickname = self.factory.config.nickname
        self.password = None if (self.factory.config.srv_pass=='') else self.factory.config.srv_pass
        self.versionName = self.factory.config.versionName
        self.versionNum = self.factory.config.versionNum
        self.realname = self.versionName
        self.username = self.versionName
        self.userinfo = "%s v%s" % (self.versionName, self.versionNum)
        self.pingSelfId = None
        self.initPlugins()
        IRCClient.connectionMade(self)
예제 #38
0
    def irc_ERR_ERRONEUSNICKNAME(self, prefix, params):
        """
        Called when we try to register or change to an illegal nickname.

        The server should send this reply when the nickname contains any
        disallowed characters.  The bot will stall, waiting for RPL_WELCOME, if
        we don't handle this during sign-on.

        @note: The method uses the spelling I{erroneus}, as it appears in
            the RFC, section 6.1.
        """
        IRCClient.irc_ERR_ERRONEUSNICKNAME(self, prefix, params)
        self._fire_event(irc.on_err_nick_in_use, prefix=prefix, params=params)
예제 #39
0
파일: irc.py 프로젝트: ojii/bottu
 def msg(self, user, message, length=None):
     """
     Send a message to a channel, enforces message encoding
     """
     encoded_message = unicode(message).encode('ascii', 'ignore')
     if user.startswith('#') and not Channel(self, user).is_active():
         log.msg(
             "ERROR: Trying to send message to inactive channel %s. "
             "Message blocked!" % user
         )
     else:
         log.msg("Sending %r to %r" % (encoded_message, user))
         IRCClient.msg(self, user, encoded_message, length)
예제 #40
0
파일: Contrl.py 프로젝트: nosklo/Contrl
    def connectionMade(self):
        with open(strftime("%B %d, %Y.txt"), "a") as log1:
            log1.write(
                strftime(
                    "\
[%H:%M:%S] "
                )
                + "Connecting..."
                + "\n"
            )
        print strftime("[%H:%M:%S on %B %d, %Y] ") + "Connecting..."
        self.deferred = Deferred()
        IRCClient.connectionMade(self)
예제 #41
0
파일: publishbot.py 프로젝트: rbarrois/Kaoz
    def connectionMade(self):
        """Handler for post-connection event.

        Send all queued messages.
        """
        logger.info(u"connection made to %s", self.transport)
        self.factory.connection = self
        # Twisted still uses old-style classes, 10 years later. Sigh.
        IRCClient.connectionMade(self)

        while self.factory.queue:
            channel, message = self.factory.queue.popleft()
            self.send(channel, message)
예제 #42
0
파일: irc.py 프로젝트: 18sg/SHETBot
	def connectionMade(self):
		IRCClient.connectionMade(self)
		self.shet = ShetClient()
		self.shet.install()
		self.shet.root = self.root
		
		# Channel monitoring actions
		self.on_action = self.shet.add_event("on_action")
		self.on_say = self.shet.add_event("on_say")
		self.on_join = self.shet.add_event("on_join")
		self.on_quit = self.shet.add_event("on_quit")
		
		# This bot can be controlled over SHET
		self.shet.add_action(self.bot_path + "say", self.shet_say)
		self.shet.add_action(self.bot_path + "say_to", self.shet_say_to)
		self.shet.add_action(self.bot_path + "action", self.shet_describe)
		self.shet.add_action(self.bot_path + "pm", self.shet_pm)
		self.shet.add_action(self.bot_path + "pm_action", self.shet_pm_describe)
		
		# Can listen to bot's PMs
		self.on_bot_pm = self.shet.add_event(self.bot_path + "on_pm")
		self.on_bot_pm_action = self.shet.add_event(self.bot_path + "on_pm_action")
		
		# User monitoring/contacting
		for user in self.user_paths:
			path = self.user_paths[user]
			user_events = {}
			self.user_events[user] = user_events
			
			# Ways to contact the user (via the bot)
			self.shet.add_action(path + "bot_say_to", self.get_say_to_fn(user))
			self.shet.add_action(path + "bot_pm_to", self.get_pm_to_fn(user))
			
			# User's channel events
			user_events["on_join"] = self.shet.add_event(path + "on_join")
			user_events["on_quit"] = self.shet.add_event(path + "on_quit")
			user_events["on_say"] = self.shet.add_event(path + "on_say")
			user_events["on_action"] = self.shet.add_event(path + "on_action")
			
			# Events other can people trigger related to the user
			user_events["on_mention"] = self.shet.add_event(path + "on_mention")
			user_events["on_address"] = self.shet.add_event(path + "on_address")
			
			# User interractions with the bot
			user_events["on_mention_bot"] = self.shet.add_event(path + "on_mention_bot")
			user_events["on_address_bot"] = self.shet.add_event(path + "on_address_bot")
			user_events["on_pm_bot"] = self.shet.add_event(path + "on_pm_bot")
			user_events["on_pm_action_bot"] = self.shet.add_event(path + "on_pm_action_bot")
예제 #43
0
파일: irc.py 프로젝트: rcombs/Servrhe
    def join(self, channel, no_database=False):
        actual, _, password = channel.partition(" ")

        if not no_database:
            c, p, ac = yield self.master.modules["db"].channelGet(actual)

            if c:
                actual = c

            if not password and p:
                password = p

            yield self.master.modules["db"].channelSet(actual, password, True)

        if password:
            channel = u"{} {}".format(actual, password)

        self.channels[actual] = {}

        IRCClient.join(self, channel.encode("utf8"))
        nick = normalize(self.nickname)
        self.dispatch("joined", actual, nick)
예제 #44
0
class ClientTests(TestCase):
    """
    Tests for the protocol-level behavior of IRCClient methods intended to
    be called by application code.
    """
    def setUp(self):
        self.transport = StringIO()
        self.protocol = IRCClient()
        self.protocol.performLogin = False
        self.protocol.makeConnection(self.transport)

        # Sanity check - we don't want anything to have happened at this
        # point, since we're not in a test yet.
        self.failIf(self.transport.getvalue())

    def test_register(self):
        """
        Verify that the L{IRCClient.register} method sends a a USER command
        with the correct arguments.
        """
        username = '******'
        hostname = 'testhost'
        servername = 'testserver'
        self.protocol.realname = 'testname'
        self.protocol.password = None
        self.protocol.register(username, hostname, servername)
        expected = [
            'NICK %s' % (username, ),
            'USER %s %s %s :%s' %
            (username, hostname, servername, self.protocol.realname), ''
        ]
        self.assertEqual(self.transport.getvalue().split('\r\n'), expected)

    def test_registerWithPassword(self):
        """
        Verify that if the C{password} attribute of L{IRCClient} is not
        C{None}, the C{register} method also authenticates using it.
        """
        username = '******'
        hostname = 'testhost'
        servername = 'testserver'
        self.protocol.realname = 'testname'
        self.protocol.password = '******'
        self.protocol.register(username, hostname, servername)
        expected = [
            'PASS %s' % (self.protocol.password, ),
            'NICK %s' % (username, ),
            'USER %s %s %s :%s' %
            (username, hostname, servername, self.protocol.realname), ''
        ]
        self.assertEqual(self.transport.getvalue().split('\r\n'), expected)
예제 #45
0
 def connectionMade(self):
     IRCClient.connectionMade(self)
     echo('IRC: Connected')
예제 #46
0
	def connectionLost(self, reason):
		IRCClient.connectionLost(self, reason)
		self.container._setBotinst(None)
		if self.state: self.state._resetnetwork()
		# TODO: reason needs to be properly formatted/actual reason being extracted from the "Failure" or whatever
		print "[disconnected: %s]" % reason
예제 #47
0
 def connectionMade(self):
     self.nickname = self.factory.nickname
     IRCClient.connectionMade(self)
     self.factory.connection = self
예제 #48
0
 def ctcpUnknownQuery(self, hostmask, channel, tag, data):
     if tag.lower() == "xdcc":
         self.privmsg(hostmask, channel, "{} {}".format(tag, data))
     else:
         IRCClient.ctcpUnknownQuery(self, hostmask, channel, tag, data)
예제 #49
0
class ClientTests(TestCase):
    """
    Tests for the protocol-level behavior of IRCClient methods intended to
    be called by application code.
    """
    def setUp(self):
        """
        Create and connect a new L{IRCClient} to a new L{StringTransport}.
        """
        self.transport = StringTransport()
        self.protocol = IRCClient()
        self.protocol.performLogin = False
        self.protocol.makeConnection(self.transport)

        # Sanity check - we don't want anything to have happened at this
        # point, since we're not in a test yet.
        self.assertEquals(self.transport.value(), "")


    def test_away(self):
        """
        L{IRCCLient.away} sends an AWAY command with the specified message.
        """
        message = "Sorry, I'm not here."
        self.protocol.away(message)
        expected = [
            'AWAY :%s' % (message,),
            '',
        ]
        self.assertEquals(self.transport.value().split('\r\n'), expected)


    def test_back(self):
        """
        L{IRCClient.back} sends an AWAY command with an empty message.
        """
        self.protocol.back()
        expected = [
            'AWAY :',
            '',
        ]
        self.assertEquals(self.transport.value().split('\r\n'), expected)


    def test_whois(self):
        """
        L{IRCClient.whois} sends a WHOIS message.
        """
        self.protocol.whois('alice')
        self.assertEquals(
            self.transport.value().split('\r\n'),
            ['WHOIS alice', ''])


    def test_whoisWithServer(self):
        """
        L{IRCClient.whois} sends a WHOIS message with a server name if a
        value is passed for the C{server} parameter.
        """
        self.protocol.whois('alice', 'example.org')
        self.assertEquals(
            self.transport.value().split('\r\n'),
            ['WHOIS example.org alice', ''])


    def test_register(self):
        """
        L{IRCClient.register} sends NICK and USER commands with the
        username, name, hostname, server name, and real name specified.
        """
        username = '******'
        hostname = 'testhost'
        servername = 'testserver'
        self.protocol.realname = 'testname'
        self.protocol.password = None
        self.protocol.register(username, hostname, servername)
        expected = [
            'NICK %s' % (username,),
            'USER %s %s %s :%s' % (
                username, hostname, servername, self.protocol.realname),
            '']
        self.assertEquals(self.transport.value().split('\r\n'), expected)


    def test_registerWithPassword(self):
        """
        If the C{password} attribute of L{IRCClient} is not C{None}, the
        C{register} method also sends a PASS command with it as the
        argument.
        """
        username = '******'
        hostname = 'testhost'
        servername = 'testserver'
        self.protocol.realname = 'testname'
        self.protocol.password = '******'
        self.protocol.register(username, hostname, servername)
        expected = [
            'PASS %s' % (self.protocol.password,),
            'NICK %s' % (username,),
            'USER %s %s %s :%s' % (
                username, hostname, servername, self.protocol.realname),
            '']
        self.assertEquals(self.transport.value().split('\r\n'), expected)


    def test_describe(self):
        """
        L{IRCClient.desrcibe} sends a CTCP ACTION message to the target
        specified.
        """
        target = 'foo'
        channel = '#bar'
        action = 'waves'
        self.protocol.describe(target, action)
        self.protocol.describe(channel, action)
        expected = [
            'PRIVMSG %s :\01ACTION %s\01' % (target, action),
            'PRIVMSG %s :\01ACTION %s\01' % (channel, action),
            '']
        self.assertEquals(self.transport.value().split('\r\n'), expected)


    def test_me(self):
        """
        L{IRCClient.me} sends a CTCP ACTION message to the target channel
        specified.
        If the target does not begin with a standard channel prefix,
        '#' is prepended.
        """
        target = 'foo'
        channel = '#bar'
        action = 'waves'
        self.protocol.me(target, action)
        self.protocol.me(channel, action)
        expected = [
            'PRIVMSG %s :\01ACTION %s\01' % ('#' + target, action),
            'PRIVMSG %s :\01ACTION %s\01' % (channel, action),
            '']
        self.assertEquals(self.transport.value().split('\r\n'), expected)
        warnings = self.flushWarnings(
            offendingFunctions=[self.test_me])
        self.assertEquals(
            warnings[0]['message'],
            "me() is deprecated since Twisted 9.0. Use IRCClient.describe().")
        self.assertEquals(warnings[0]['category'], DeprecationWarning)
        self.assertEquals(len(warnings), 2)
예제 #50
0
 def connectionMade(self):
     IRCClient.connectionMade(self)
     self.screenObj.addLine("* CONNECTED")
예제 #51
0
 def connectionLost(self, reason):
     IRCClient.connectionLost(self, reason)
     for logger in self.loggers.values():
         logger.log("[disconnected at %s]" %
                    time.asctime(time.localtime(time.time())))
         logger.close()
 def connectionMade(self):
     IRCClient.connectionMade(self)
     self._queue = {"default": []}
     self._queueEmptying = {"default": None}
예제 #53
0
    def msg(self, user, message, length=None):
        ''' Send message to user '''

        IRCClient.msg(self, user, message, length)
        echo('[IRC] You->%s: %s' % (user, message))
예제 #54
0
    def say(self, channel, message, length=None):
        ''' Say to channel and echo back '''

        IRCClient.msg(self, channel, message, length)
        echo('[%s] <%s> %s' % (channel, self.nickname, message))
예제 #55
0
파일: irc.py 프로젝트: drbig/vlasisku
 def msg(self, target, message):
     log.msg('<%(nickname)s> %(message)s' %
             dict(nickname=self.nickname, message=message))
     IRCClient.msg(self, target, message)
예제 #56
0
파일: bot.py 프로젝트: zuzak/omegleirc2
 def connectionMade(self):
     self.nickname = configuration.NICKNAME
     IRCClient.connectionMade(self)
예제 #57
0
class ClientTests(TestCase):
    """
    Tests for the protocol-level behavior of IRCClient methods intended to
    be called by application code.
    """
    def setUp(self):
        """
        Create and connect a new L{IRCClient} to a new L{StringTransport}.
        """
        self.transport = StringTransport()
        self.protocol = IRCClient()
        self.protocol.performLogin = False
        self.protocol.makeConnection(self.transport)

        # Sanity check - we don't want anything to have happened at this
        # point, since we're not in a test yet.
        self.assertEquals(self.transport.value(), "")

    def getLastLine(self, transport):
        """
        Return the last IRC message in the transport buffer.
        """
        return transport.value().split('\r\n')[-2]

    def test_away(self):
        """
        L{IRCCLient.away} sends an AWAY command with the specified message.
        """
        message = "Sorry, I'm not here."
        self.protocol.away(message)
        expected = [
            'AWAY :%s' % (message, ),
            '',
        ]
        self.assertEquals(self.transport.value().split('\r\n'), expected)

    def test_back(self):
        """
        L{IRCClient.back} sends an AWAY command with an empty message.
        """
        self.protocol.back()
        expected = [
            'AWAY :',
            '',
        ]
        self.assertEquals(self.transport.value().split('\r\n'), expected)

    def test_whois(self):
        """
        L{IRCClient.whois} sends a WHOIS message.
        """
        self.protocol.whois('alice')
        self.assertEquals(self.transport.value().split('\r\n'),
                          ['WHOIS alice', ''])

    def test_whoisWithServer(self):
        """
        L{IRCClient.whois} sends a WHOIS message with a server name if a
        value is passed for the C{server} parameter.
        """
        self.protocol.whois('alice', 'example.org')
        self.assertEquals(self.transport.value().split('\r\n'),
                          ['WHOIS example.org alice', ''])

    def test_register(self):
        """
        L{IRCClient.register} sends NICK and USER commands with the
        username, name, hostname, server name, and real name specified.
        """
        username = '******'
        hostname = 'testhost'
        servername = 'testserver'
        self.protocol.realname = 'testname'
        self.protocol.password = None
        self.protocol.register(username, hostname, servername)
        expected = [
            'NICK %s' % (username, ),
            'USER %s %s %s :%s' %
            (username, hostname, servername, self.protocol.realname), ''
        ]
        self.assertEquals(self.transport.value().split('\r\n'), expected)

    def test_registerWithPassword(self):
        """
        If the C{password} attribute of L{IRCClient} is not C{None}, the
        C{register} method also sends a PASS command with it as the
        argument.
        """
        username = '******'
        hostname = 'testhost'
        servername = 'testserver'
        self.protocol.realname = 'testname'
        self.protocol.password = '******'
        self.protocol.register(username, hostname, servername)
        expected = [
            'PASS %s' % (self.protocol.password, ),
            'NICK %s' % (username, ),
            'USER %s %s %s :%s' %
            (username, hostname, servername, self.protocol.realname), ''
        ]
        self.assertEquals(self.transport.value().split('\r\n'), expected)

    def test_registerWithTakenNick(self):
        """
        Verify that the client repeats the L{IRCClient.setNick} method with a
        new value when presented with an C{ERR_NICKNAMEINUSE} while trying to
        register.
        """
        username = '******'
        hostname = 'testhost'
        servername = 'testserver'
        self.protocol.realname = 'testname'
        self.protocol.password = '******'
        self.protocol.register(username, hostname, servername)
        self.protocol.irc_ERR_NICKNAMEINUSE('prefix', ['param'])
        lastLine = self.getLastLine(self.transport)
        self.assertNotEquals(lastLine, 'NICK %s' % (username, ))

        # Keep chaining underscores for each collision
        self.protocol.irc_ERR_NICKNAMEINUSE('prefix', ['param'])
        lastLine = self.getLastLine(self.transport)
        self.assertEquals(lastLine, 'NICK %s' % (username + '__', ))

    def test_overrideAlterCollidedNick(self):
        """
        L{IRCClient.alterCollidedNick} determines how a nickname is altered upon
        collision while a user is trying to change to that nickname.
        """
        nick = 'foo'
        self.protocol.alterCollidedNick = lambda nick: nick + '***'
        self.protocol.register(nick)
        self.protocol.irc_ERR_NICKNAMEINUSE('prefix', ['param'])
        lastLine = self.getLastLine(self.transport)
        self.assertEquals(lastLine, 'NICK %s' % (nick + '***', ))

    def test_nickChange(self):
        """
        When a NICK command is sent after signon, C{IRCClient.nickname} is set
        to the new nickname I{after} the server sends an acknowledgement.
        """
        oldnick = 'foo'
        newnick = 'bar'
        self.protocol.register(oldnick)
        self.protocol.irc_RPL_WELCOME('prefix', ['param'])
        self.protocol.setNick(newnick)
        self.assertEquals(self.protocol.nickname, oldnick)
        self.protocol.irc_NICK('%s!quux@qux' % (oldnick, ), [newnick])
        self.assertEquals(self.protocol.nickname, newnick)

    def test_erroneousNick(self):
        """
        Trying to register an illegal nickname results in the default legal
        nickname being set, and trying to change a nickname to an illegal
        nickname results in the old nickname being kept.
        """
        # Registration case: change illegal nickname to erroneousNickFallback
        badnick = 'foo'
        self.assertEquals(self.protocol._registered, False)
        self.protocol.register(badnick)
        self.protocol.irc_ERR_ERRONEUSNICKNAME('prefix', ['param'])
        lastLine = self.getLastLine(self.transport)
        self.assertEquals(lastLine,
                          'NICK %s' % (self.protocol.erroneousNickFallback, ))
        self.protocol.irc_RPL_WELCOME('prefix', ['param'])
        self.assertEquals(self.protocol._registered, True)
        self.protocol.setNick(self.protocol.erroneousNickFallback)
        self.assertEquals(self.protocol.nickname,
                          self.protocol.erroneousNickFallback)

        # Illegal nick change attempt after registration. Fall back to the old
        # nickname instead of erroneousNickFallback.
        oldnick = self.protocol.nickname
        self.protocol.setNick(badnick)
        self.protocol.irc_ERR_ERRONEUSNICKNAME('prefix', ['param'])
        lastLine = self.getLastLine(self.transport)
        self.assertEquals(lastLine, 'NICK %s' % (badnick, ))
        self.assertEquals(self.protocol.nickname, oldnick)

    def test_describe(self):
        """
        L{IRCClient.desrcibe} sends a CTCP ACTION message to the target
        specified.
        """
        target = 'foo'
        channel = '#bar'
        action = 'waves'
        self.protocol.describe(target, action)
        self.protocol.describe(channel, action)
        expected = [
            'PRIVMSG %s :\01ACTION %s\01' % (target, action),
            'PRIVMSG %s :\01ACTION %s\01' % (channel, action), ''
        ]
        self.assertEquals(self.transport.value().split('\r\n'), expected)

    def test_me(self):
        """
        L{IRCClient.me} sends a CTCP ACTION message to the target channel
        specified.
        If the target does not begin with a standard channel prefix,
        '#' is prepended.
        """
        target = 'foo'
        channel = '#bar'
        action = 'waves'
        self.protocol.me(target, action)
        self.protocol.me(channel, action)
        expected = [
            'PRIVMSG %s :\01ACTION %s\01' % ('#' + target, action),
            'PRIVMSG %s :\01ACTION %s\01' % (channel, action), ''
        ]
        self.assertEquals(self.transport.value().split('\r\n'), expected)
        warnings = self.flushWarnings(offendingFunctions=[self.test_me])
        self.assertEquals(
            warnings[0]['message'],
            "me() is deprecated since Twisted 9.0. Use IRCClient.describe().")
        self.assertEquals(warnings[0]['category'], DeprecationWarning)
        self.assertEquals(len(warnings), 2)
예제 #58
0
 def connectionMade(self):
     IRCClient.connectionMade(self)
예제 #59
0
 def connectionLost(self):
     IRCClient.connectionLost(self, reason)