Skip to content

Commit 29bbf22

Browse files
committed
New command !reddit - minor enhancements
modified: bot_core/irc_bot.py new file: functions/reddit.py
1 parent 2587e63 commit 29bbf22

File tree

2 files changed

+68
-4
lines changed

2 files changed

+68
-4
lines changed

bot_core/irc_bot.py

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from karma.karma_rate import KarmaRateLimiter
1111
from functions.welcome_machine import WelcomeMachine
1212
from functions.dice_roller import DiceRoller
13+
from functions.reddit import RedditManager
1314

1415
class IRCBot(irc.IRCClient):
1516
"""Python Twisted IRC BOT. irc.IRCClient specialization."""
@@ -32,6 +33,7 @@ def connectionMade(self):
3233
)
3334
self.karma_manager = KarmaManager(self.logger)
3435
self.karmrator = KarmaRateLimiter()
36+
self.reddit = RedditManager()
3537
# Singleton WelcomeMachine class
3638
self.welcome_machine = WelcomeMachine(self.factory.cm.greetings_file_path)
3739

@@ -78,7 +80,10 @@ def privmsg(self, user, channel, msg):
7880

7981
# Check if you are talking with BOT
8082
if nickname_pattern.match(msg):
81-
self.msg(channel, "%s: I am BOT, do not waste your time!" % user)
83+
#self.msg(channel, "%s: I am BOT, do not waste your time!" % user)
84+
deferred_reddit = threads.deferToThread(self.reddit.retrieve_hot, rand=True, nick=user)
85+
deferred_reddit.addCallback(self.threadSafeMsg)
86+
8287
elif msg.startswith('!'):
8388
self.evaluate_command(user, channel, msg)
8489
elif re.match(re.compile('\w+\+\+$|\w+--$'), msg):
@@ -102,6 +107,7 @@ def evaluate_command(self, user, channel, msg):
102107
# dice command !roll NdF with Faces = 3|4|6|8|10|20
103108
dice_pattern = re.compile("!roll\s\d+d([3468]|10|20)$", flags = re.IGNORECASE)
104109
rand_pattern = re.compile("!rand\s\d+$", flags = re.IGNORECASE)
110+
reddit_pattern = re.compile("!reddit\s?(\d+|\d+\s\w+)?$", flags = re.IGNORECASE)
105111
msg_splits = msg.split()
106112

107113
# check for commands starting with bang!
@@ -123,6 +129,19 @@ def evaluate_command(self, user, channel, msg):
123129
deferred_roll = threads.deferToThread(DiceRoller.roll, msg)
124130
deferred_roll.addCallback(self.threadSafeMsg)
125131

132+
elif reddit_pattern.match(msg):
133+
deferred_reddit = None
134+
if len(msg_splits) == 1:
135+
deferred_reddit = threads.deferToThread(self.reddit.retrieve_hot)
136+
elif len(msg_splits) == 2:
137+
deferred_reddit = threads.deferToThread(self.reddit.retrieve_hot, num_entries=int(msg_splits[1]))
138+
elif len(msg_splits) == 3:
139+
deferred_reddit = threads.deferToThread(self.reddit.retrieve_hot, num_entries=int(msg_splits[1]), subject=msg_splits[2])
140+
141+
if deferred_reddit is not None:
142+
deferred_reddit.addCallback(self.threadSafeMsg)
143+
144+
126145
elif rand_pattern.match(msg):
127146
if len(msg_splits) == 2:
128147
self.msg(channel, "Random number: %d" % (random.randint(0, int(msg_splits[1]) )) )
@@ -193,7 +212,12 @@ def threadSafeMsg(self, message):
193212

194213
# see https://github.com/zencoders/pyircbot/issues/3
195214
chan = "#" + self.factory.channel
196-
reactor.callFromThread(self.msg, chan , message)
215+
if type(message) is str:
216+
reactor.callFromThread(self.msg, chan , message)
217+
elif type(message) is list:
218+
for el in message:
219+
reactor.callFromThread(self.msg, chan , str(el))
220+
197221

198222
def get_current_timestamp(self):
199223
return time.asctime(time.localtime(time.time()))
@@ -202,22 +226,25 @@ def _help_command(self, command=None):
202226

203227
"""This method returns the help message"""
204228

205-
help_msg = "Valid commands: !help <command>, !commands, !karma [user], !roll Nd(3|4|6|8|10|20), !rand arg, !randtime"
229+
help_msg = "Valid commands: !help <command>, !commands, !karma [user], !roll Nd(3|4|6|8|10|20), !rand arg, !randtime, !reddit [entries] [subject]"
206230
if command is not None:
207231

208232
if command == "karma":
209233
help_msg = "!karma [user]: returns user's karma score. "
210234
help_msg += "<user>++ or <user>-- to modify karma score of the specified user."
211235

212236
elif command == "roll":
213-
help_msg = "!roll NdN: roll dice (like D&D: d2, d4, d6, d8, d10, d20)"
237+
help_msg = "!roll NdN: roll dice (like D&D: d3, d4, d6, d8, d10, d20)"
214238

215239
elif command == "rand":
216240
help_msg = "!rand returns randint(0, arg)"
217241

218242
elif command == "randtime":
219243
help_msg = "!randtime returns a random 24h (HH:MM) timestamp"
220244

245+
elif command == "reddit":
246+
help_msg = "!reddit [NUMBER] [SUBJECT] to retrieve the latest NUMBER hot reddit news about SUBJECT, otherwise list the last 3 about computer programming"
247+
221248
else:
222249
help_msg = "%s is not a valid command!" % command
223250

functions/reddit.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import praw
2+
import random
3+
4+
MAX_ENTRIES = 10 # max articles returned
5+
6+
class RedditManager:
7+
8+
def __init__(self):
9+
bot_user_agent = "pyircbot v0.1 by /u/sentenza github.com/zencoders/pyircbot"
10+
self.reddit = praw.UnauthenticatedReddit(user_agent=bot_user_agent)
11+
12+
def retrieve_hot(self, subject="programming", num_entries=3, rand=False, nick=None):
13+
14+
""" This method returns a list of num_entries hop articles OR a single pseudo-random top story
15+
selected from the first top 100 entries """
16+
17+
retrieved_list = list()
18+
try:
19+
topic = self.reddit.get_subreddit(subject)
20+
21+
if not rand:
22+
# return num_entries articles
23+
submissions = topic.get_hot(limit=min(num_entries, MAX_ENTRIES))
24+
for single in submissions:
25+
info = str(single)
26+
retrieved_list.append(str(single) + " " + str(single.short_link))
27+
elif nick is not None:
28+
#select a random set
29+
max_list = [story for story in topic.get_hot(limit=MAX_ENTRIES)]
30+
selected = random.choice(max_list)
31+
res = "%s: I am BOT, do not waste your time! Instead > " % nick
32+
retrieved_list.append(res + str(selected) + " " + selected.short_link)
33+
except requests.exceptions.HTTPError:
34+
retrieved_list.append("[REDDIT] %s is not a valid subject" % subject)
35+
finally:
36+
return retrieved_list
37+

0 commit comments

Comments
 (0)