Goodnight Byte: Coding an IRC Bot in Python (For Beginners)
Our first Community Byte went well! We had around 8 people in the room coding collaboratively and watching to learn. LukeStav did the kind task of hosting it on Gobby for all of us, so big thanks to him!
At minimum, our task was to create an IRC bot for #nullbytez that could connect to the channel. Well, we surpassed our goal and got a bot working. The bot can also print strings to the channel upon entering. It's a good start and will help in our next challenge. I'm hoping to have the next Community Byte work on making the bot have privileges and making certain members channel operators upon request.
Here is a link to our bot's source code. I'm going to explain how it works below, line by line, so follow along with the source code open.
- Line 1 is a shebang. This tells our computer where it can find the python executeable.
- Lines 9-15 are our variables. These hold values that the rest of the program uses. These values can also be changed to switch servers, nicknames, etc.
- Line 17 creates a socket.
- Line 18 connects using the host and port variables to tell it where to connect to.
- Line 19 sends the IRC command NICK to set the bot's nickname.
- Line 20 identifies the bot to the server.
- Line 21 tells the bot to join the channel #nullbytez with the JOIN IRC command.
- Lines 22-23 send channel messages to everyone.
- Lines 25-28 keep the bot connected to IRC and listening to the channel. It's also for storing things in its buffer. It stores it in a list and reads it line-by-line while removing preceding text.
- Lines 30-32 is the part that actually reads from the buffer.
- Lines 34-35 take ping requests from the server, and pings back to let it know we are alive, thus keeping us connected.
That's all there is to it!
This was a great turnout for the first week, and I'm hoping to see more people and coders show up in the future. Most of all, I hope you all learned something from the session (or this post). Here is an awesome video of our bot connecting to the Null Byte IRC!
Join in next week for our next project!