コード例 #1
0
ファイル: __init__.py プロジェクト: FujiMakoto/firefly-irc
 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
ファイル: bot.py プロジェクト: inversesquarelaw/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)
コード例 #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
ファイル: __init__.py プロジェクト: FujiMakoto/firefly-irc
    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
ファイル: logger.py プロジェクト: oubiwann/bot-prakasha-ke
 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
ファイル: twitch.py プロジェクト: gkistler/pytwitchirc
	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
ファイル: __init__.py プロジェクト: FujiMakoto/firefly-irc
    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
ファイル: twitch.py プロジェクト: gkistler/pytwitchirc
	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
ファイル: fschfsch.py プロジェクト: AlanBell/Supybot-plugins
    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
ファイル: bot.py プロジェクト: inversesquarelaw/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!
コード例 #23
0
ファイル: twitch.py プロジェクト: gkistler/pytwitchirc
	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
ファイル: twitch.py プロジェクト: gkistler/pytwitchirc
	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
ファイル: publisher.py プロジェクト: oubiwann/bot-prakasha-ke
    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
ファイル: publisher.py プロジェクト: mindpool/bot-prakasha-ke
    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
ファイル: __init__.py プロジェクト: FujiMakoto/firefly-irc
    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
ファイル: test_irc.py プロジェクト: swift1911/twisted
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()
コード例 #52
0
 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)