Ticket #4929: ircLogBot.py

File ircLogBot.py, 5.1 KB (added by Upasana, 16 months ago)

Use Case for my patch

Line 
1# Copyright (c) Twisted Matrix Laboratories.
2# See LICENSE for details.
3
4
5"""
6An example IRC log bot - logs a channel's events to a file.
7
8If someone says the bot's name in the channel followed by a ':',
9e.g.
10
11  <foo> logbot: hello!
12
13the bot will reply:
14
15  <logbot> foo: I am a log bot
16
17Run this script with two arguments, the channel name the bot should
18connect to, and file to log to, e.g.:
19
20  $ python ircLogBot.py test test.log
21
22will log channel #test to the file 'test.log'.
23"""
24
25
26# twisted imports
27from twisted.words.protocols import irc
28from twisted.internet import reactor, protocol
29from twisted.python import log
30
31# system imports
32import time, sys
33
34class LogBot(irc.IRCClient):
35    """A logging IRC bot."""
36   
37    nickname = "twistbot"
38
39
40    def __init(self):
41        self.j = 0
42        self.listChannels = []
43        # print(listChannels)
44   
45    def connectionMade(self):
46        irc.IRCClient.connectionMade(self)
47        self.j = 0
48        self.listChannels = ["#testing", # one channel only
49         "#testing,#test", #two channels, separated by a comma
50         "#testing, #test" #two channel, separated by a comma and a space
51         ]
52        print(self.listChannels)
53        print("[connected at %s]" % time.asctime(time.localtime(time.time())))
54
55
56    def channelListStart(self, params):
57        print "%s" % (params)
58
59
60    def gotChannelList(self, channel, usersCount, topic):
61        print "%s\t%d\t%s" % (channel, usersCount, topic)
62
63
64    def channelListEnd(self, params):
65        print "%s" % (params)
66
67
68    def connectionLost(self, reason):
69        irc.IRCClient.connectionLost(self, reason)
70        print("[disconnected at %s]" % (time.asctime(time.localtime(time.time()))))
71
72    def signedOn(self):
73        """
74        Called when bot has succesfully signed on to server.
75        """
76        self.join(self.factory.channel)
77       
78    def joined(self, channel):
79        """
80        This will get called when the bot joins the channel.
81        """
82        # self.logger.log("[I have joined %s]" % channel)
83        print("[I have joined %s]" % channel)
84
85    def privmsg(self, user, channel, msg):
86        """
87        This will get called when the bot receives a message.
88        """
89        user = user.split('!', 1)[0]
90        # self.logger.log("<%s> %s" % (user, msg))
91        # print("<%s> %s" % (user, msg))
92       
93        # Check to see if they're sending me a private message
94        if channel == self.nickname:
95            msg = "It isn't nice to whisper!  Play nice with the group."
96            self.msg(user, msg)
97            return
98
99        # Otherwise check to see if it is a message directed at me
100        if msg.startswith(self.nickname + ":"):
101            msg = "%s: I am a log bot" % user
102            self.msg(channel, msg)
103            # self.logger.log("<%s> %s" % (self.nickname, msg))
104            # print("<%s> %s" % (self.nickname, msg))
105
106    def action(self, user, channel, msg):
107        """
108        This will get called when the bot sees someone do an action.
109        """
110        user = user.split('!', 1)[0]
111        # self.logger.log("* %s %s" % (user, msg))
112        print("* %s %s" % (user, msg))
113        print("I've got an action message, now I'll send LIST to server")
114        #sending a channel list
115        print(self.listChannels[self.j])
116        self.channelList(self.listChannels[self.j])
117        self.j += 1
118
119    # irc callbacks
120
121    def irc_NICK(self, prefix, params):
122        """
123        Called when an IRC user changes their nickname.
124        """
125        old_nick = prefix.split('!')[0]
126        new_nick = params[0]
127        # self.logger.log("%s is now known as %s" % (old_nick, new_nick))
128        print("%s is now known as %s" % (old_nick, new_nick))
129
130    def irc_unknown(self, prefix, command, params):
131        print "In irc_unknown:"
132        print "prefix : %s" % ( prefix )
133        print "command : %s" % ( command )
134        print "params : %s" % ( params )
135
136
137    # For fun, override the method that determines how a nickname is changed on
138    # collisions. The default method appends an underscore.
139    def alterCollidedNick(self, nickname):
140        """
141        Generate an altered version of a nickname that caused a collision in an
142        effort to create an unused related name for subsequent registration.
143        """
144        return nickname + '^'
145
146
147
148class LogBotFactory(protocol.ClientFactory):
149    """
150    A factory for LogBots.
151
152    A new protocol instance will be created each time we connect to the server.
153    """
154
155    def __init__(self, channel):
156        self.channel = channel
157
158    def buildProtocol(self, addr):
159        p = LogBot()
160        p.factory = self
161        return p
162
163    def clientConnectionLost(self, connector, reason):
164        """If we get disconnected, reconnect to server."""
165        connector.connect()
166
167    def clientConnectionFailed(self, connector, reason):
168        print("connection failed:", reason)
169        reactor.stop()
170
171
172if __name__ == '__main__':
173    # initialize logging
174    # log.startLogging(sys.stdout)
175   
176    # create factory protocol and application
177    f = LogBotFactory("test")
178
179    # connect factory to this host and port
180    reactor.connectTCP("irc.dal.net", 6667, f)
181
182    # run bot
183    reactor.run()