Search code examples
pythonirc

Python IRC bot is responding endlessly


I am slowly learning Python and thumbing through the tutorials. I feel I have a basic understanding of how it works.

As a creative project I want to make an IRC bot. I don't want to use a pre-established framework. I do not intend to reinvent the wheel, I simply want to construct a bot from the ground-up as both a learning project and a creative outlet. One issue I am encountering consistently in my minute knowledge of how to do this is that my bot seems to be responding to my commands ad infinitum. Here's the code:

HOST="irc.durd.net"
PORT=6667
NICK="Data"
IDENT="data"
REALNAME="databot"
HOME='#zela'
feedback=""

s=socket.socket( )
s.connect((HOST, PORT))
s.send("NICK %s\r\n" % NICK)
s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
s.send("JOIN #zela" + "\r\n")
s.send("PRIVMSG nickserv identify ac}pcut]eobosbec" + "\r\n")


def sendmsg(chan, msg):
    s.send("PRIVMSG "+ chan +" :"+ msg +"\n")

def ping():
    s.send("PONG :pingis\n")




while 1:
    feedback=feedback+s.recv(1024)
    print (feedback)
    if feedback.find("PING :") != -1:
        ping()
    if feedback.find("say hello Data") != -1:
        sendmsg("#zela", "Hello Data!")
    if feedback.find("tell us a joke Data") != -1:
        sendmsg("#zela", "but Captain, I don't know how.")
    if feedback.find("terminate Data") != -1:
        s.send("QUIT\r\n")

Now, everything works fine and Data responds to his commands correctly. He even quits when I tell him to. Unfortunately, once one of these commands is triggered, he will repeat himself every time I say something new, and then repeat himself forever until I turn him off.

<~Jordan> say hello Data
<Data> Hello Data!
<~Jordan> a
<Data> Hello Data!
<~Jordan> a
<~Jordan> a
<Data> Hello Data!
<Data> Hello Data!
<Data> Hello Data!
<Data> Hello Data!

I have tested to see if the server is resending messages to the bot, and it is not, so I figure it's my fault and there is probably something very simple I am missing here.


Solution

  • You're concatenating onto the end of feedback repeatedly, without clearing it:

    feedback=feedback+s.recv(1024)
    

    This will cause the if feedback.find("say hello Data") != -1: condition to always be true.

    You need to do something like feedback="" or remove the concatenation part of the above expression.