Search code examples
pythonbotsirc

How to make a Python IRC bot?


I am trying to make a working Python IRC bot for a channel of mine in freenode. For now all I want it to do is avoid a ping timeout and reply to a '!hi'message with a 'hello!' I am not placing the bot in a server and I just want it to run for 10-15 minutes from my computer.

The code looks like this: (I have replaced the original channel name and bot name)

import socket
import sys

server="irc.freenode.net"
channel="##mychannel"
botnick="testbot"
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect((server,6667))
irc.send("USER "+botnick+" "+botnick+" "+botnick+" :TestBot\n")
irc.send("NICK "+botnick+"\n")
irc.send("PRIVMSG nickserv :iNOOPE\r\n") #I don't know what this line does....
irc.send("JOIN "+channel+"\n")

while 1:
    text=irc.recv(2040)
    print (text)
    if text.find("PING")!=-1:
        irc.send("PONG "+text.split("PING ")[1]+"\r\n")
    if text.find(":!hi")!=-1:
        irc.send("PRIVMSG "+channel+" :Hello!\r\n")

Now when I run the program it says 'couldn't look up your username'. Then after a few seconds it displays some text too fast for me to catch and closes the console. And it doesn't connect to the channel. When I run in IDLE it says " 'str' does not support the buffer interface".

I want to learn to do this so that is why I avoided all the pre existing bots. And I am not an expert at Python. Javascript-HTML-CSS is my best programming combo.

Can anyone help?


Solution

  • I have solved the problem myself.... It was something wrong with "text.split("PING ")". I changed it to "text.split()" so that it splits at the first whitespace and it works without an issue.