This site runs best with JavaScript enabled.

Python Twisted IRC Bot: Lazy Coder

Photo by Colin Watts on Unsplash


IRC Bot that repsonds to the word "why" with lazy coder responses

A friend pointed me to this simple yet humorous website yesterday which essentially gives a new lazy coder excuse whenever the page is refreshed.

I couldn't help but whip out a bot to plug in to our IRC channel. My lazy coder bot will give a random excuse whenever someone mentions the word "why".

I used my Rollbot script as a base to write this up quickly.

requirements.txt

1Twisted==13.1.0
2beautifulsoup4==4.2.1
3requests==1.2.3

because.py

1from bs4 import BeautifulSoup
2import requests
3from twisted.words.protocols import irc
4from twisted.internet import protocol, reactor
5
6NICK = '_lazy_coder_'
7CHANNEL = '#yourchannel'
8PASSWORD = 'channel_password'
9
10class MyBot(irc.IRCClient):
11 def _get_nickname(self):
12 return self.factory.nickname
13 nickname = property(_get_nickname)
14
15 def signedOn(self):
16 self.join(self.factory.channel)
17 print "Signed on as {}.".format(self.nickname)
18
19 def joined(self, channel):
20 print "Joined %s." % channel
21
22 def privmsg(self, user, channel, msg):
23 """
24 Whenever someone says "why" give a lazy programmer response
25 """
26 if 'why' in msg.lower():
27 # get lazy response
28 because = self._get_because()
29
30 # post message
31 self.msg(CHANNEL, because)
32
33 def _get_because(self):
34 req = requests.get('http://developerexcuses.com/')
35 soup = BeautifulSoup(req.text)
36 elem = soup.find('a')
37 return elem.text.encode('ascii', 'ignore')
38
39class MyBotFactory(protocol.ClientFactory):
40 protocol = MyBot
41
42 def __init__(self, channel, nickname=NICK):
43 self.channel = channel
44 self.nickname = nickname
45
46 def clientConnectionLost(self, connector, reason):
47 print "Lost connection (%s), reconnecting." % reason
48 connector.connect()
49
50 def clientConnectionFailed(self, connector, reason):
51 print "Could not connect: %s" % reason
52
53if __name__ == "__main__":
54 channel = CHANNEL
55 if PASSWORD:
56 channel += ' {}'.format(PASSWORD)
57 reactor.connectTCP('irc.freenode.net', 6667, MyBotFactory(channel))
58 reactor.run()

UPDATE:

I've made some minor modifications and posted the project on Github

Discuss on TwitterEdit post on GitHub

Share article
Dustin Davis

Dustin Davis is a software engineer, people manager, hacker, and entreprenuer. He loves to develop systems and automation. He lives with his wife and five kids in Utah.

Join the Newsletter



Dustin Davis