Skip to content

Commit dbeac49

Browse files
authored
Merge pull request CloudBotIRC#128 from linuxdaemon/gonzobot+reddit-info-fix
Clean up and fixes for reddit_info.py
2 parents 7382c36 + 78769fa commit dbeac49

1 file changed

Lines changed: 49 additions & 50 deletions

File tree

plugins/reddit_info.py

Lines changed: 49 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,16 @@
44
from datetime import datetime
55
from bs4 import BeautifulSoup
66
from cloudbot import hook
7+
from cloudbot.util import colors
8+
from cloudbot.util.formatting import pluralize
79

810
search_pages = defaultdict(list)
911
search_page_indexes = {}
1012

1113
user_url = "http://reddit.com/user/{}/"
1214
subreddit_url = "http://reddit.com/r/{}/"
1315
# This agent should be unique for your cloudbot instance
14-
agent = {"User-Agent":"gonzobot a cloudbot (IRCbot) implementation for snoonet.org by /u/bloodygonzo"}
16+
agent = {"User-Agent": "gonzobot a cloudbot (IRCbot) implementation for snoonet.org by /u/bloodygonzo"}
1517

1618

1719
def two_lines(bigstring, chan):
@@ -30,9 +32,9 @@ def smart_truncate(content, length=355, suffix='...\n'):
3032
else:
3133
return content[:length].rsplit(' \u2022 ', 1)[0]+ suffix + content[:length].rsplit(' \u2022 ', 1)[1] + smart_truncate(content[length:])
3234

35+
3336
def statuscheck(status, item):
3437
"""since we are doing this a lot might as well return something more meaningful"""
35-
out = ""
3638
if status == 404:
3739
out = "It appears {} does not exist.".format(item)
3840
elif status == 403:
@@ -45,18 +47,18 @@ def statuscheck(status, item):
4547
out = "Reddit returned an error, response: {}".format(status)
4648
return out
4749

50+
4851
@hook.command("moremod", autohelp=False)
4952
def moremod(text, chan):
5053
"""if a sub or mod list has lots of results the results are pagintated. If the most recent search is paginated the pages are stored for retreival. If no argument is given the next page will be returned else a page number can be specified."""
5154
if not search_pages[chan]:
5255
return "There are modlist pages to show."
5356
if text:
54-
index = ""
5557
try:
5658
index = int(text)
57-
except:
59+
except ValueError:
5860
return "Please specify an integer value."
59-
if abs(int(index)) > len(search_pages[chan]) or index == 0:
61+
if abs(index) > len(search_pages[chan]) or index == 0:
6062
return "please specify a valid page number between 1 and {}.".format(len(search_pages[chan]))
6163
else:
6264
return "{}(page {}/{})".format(search_pages[chan][index-1], index, len(search_pages[chan]))
@@ -68,7 +70,7 @@ def moremod(text, chan):
6870
return "All pages have been shown."
6971

7072

71-
@hook.command("subs", "moderates", singlethreaded=True)
73+
@hook.command("subs", "moderates", singlethread=True)
7274
def moderates(text, chan):
7375
"""This plugin prints the list of subreddits a user moderates listed in a reddit users profile. Private subreddits will not be listed."""
7476
#This command was written using concepts from FurCode http://github.com/FurCode.
@@ -80,14 +82,14 @@ def moderates(text, chan):
8082
if r.status_code != 200:
8183
return statuscheck(r.status_code, user)
8284
soup = BeautifulSoup(r.text)
83-
try:
84-
modlist = soup.find('ul', id="side-mod-list").text
85-
except:
85+
mod_list = soup.find('ul', id="side-mod-list")
86+
if mod_list is None:
8687
return "{} does not moderate any public subreddits.".format(user)
87-
modlist = modlist.split('r/')
88-
del modlist[0]
89-
out = "\x02{}\x02 moderates these public subreddits: ".format(user)
90-
for sub in modlist:
88+
89+
mod_list = mod_list.text.split('r/')
90+
del mod_list[0]
91+
out = colors.parse("$(b){}$(b) moderates these public subreddits: ".format(user))
92+
for sub in mod_list:
9193
out += "{} \u2022 ".format(sub)
9294
out = out[:-2]
9395
out = smart_truncate(out)
@@ -97,7 +99,7 @@ def moderates(text, chan):
9799
return out
98100

99101

100-
@hook.command("karma", "ruser", singlethreaded=True)
102+
@hook.command("karma", "ruser", singlethread=True)
101103
def karma(text):
102104
"""karma <reddituser> will return the information about the specified reddit username"""
103105
user = text
@@ -106,28 +108,27 @@ def karma(text):
106108
if r.status_code != 200:
107109
return statuscheck(r.status_code, user)
108110
data = r.json()
109-
out = "\x02{}\x02 ".format(user)
110-
out += "\x02{:,}\x02 link karma and ".format(data['data']['link_karma'])
111-
out += "\x02{:,}\x02 comment karma | ".format(data['data']['comment_karma'])
111+
out = "$(b){}$(b) ".format(user)
112+
out += "$(b){:,}$(b) link karma and ".format(data['data']['link_karma'])
113+
out += "$(b){:,}$(b) comment karma | ".format(data['data']['comment_karma'])
112114
if data['data']['is_gold']:
113115
out += "has reddit gold | "
114116
if data['data']['is_mod']:
115117
out += "is a moderator | "
116118
if data['data']['has_verified_email']:
117119
out += "email has been verified | "
118-
out += "cake day is {} | ".format(datetime.fromtimestamp(data['data']['created_utc']).strftime('%B %d') )
120+
out += "cake day is {} | ".format(datetime.fromtimestamp(data['data']['created_utc']).strftime('%B %d'))
119121
account_age = datetime.now() - datetime.fromtimestamp(data['data']['created'])
120-
if account_age.days > 365:
121-
age = int(account_age.days / 365)
122-
if age == 1:
123-
out += "redditor for {} year.".format(age)
124-
else:
125-
out += "redditor for {} years.".format(age)
126-
else:
127-
out += "redditor for {} days.".format(account_age.days)
128-
return out
122+
age = account_age.days
123+
age_unit = "day"
124+
if age > 365:
125+
age //= 365
126+
age_unit = "year"
127+
out += "redditor for {}.".format(pluralize(age, age_unit))
128+
return colors.parse(out)
129+
129130

130-
@hook.command("cakeday", singlethreaded=True)
131+
@hook.command("cakeday", singlethread=True)
131132
def cake_day(text):
132133
"""cakeday <reddituser> will return the cakeday for the given reddit username."""
133134
user = text
@@ -136,21 +137,19 @@ def cake_day(text):
136137
if r.status_code != 200:
137138
return statuscheck(r.status_code, user)
138139
data = r.json()
139-
out = "\x02{}'s\x02 ".format(user)
140-
out += "cake day is {}, ".format(datetime.fromtimestamp(data['data']['created_utc']).strftime('%B %d') )
140+
out = colors.parse("$(b){}'s$(b) ".format(user))
141+
out += "cake day is {}, ".format(datetime.fromtimestamp(data['data']['created_utc']).strftime('%B %d'))
141142
account_age = datetime.now() - datetime.fromtimestamp(data['data']['created'])
142-
if account_age.days > 365:
143-
age = int(account_age.days / 365)
144-
if age == 1:
145-
out += "they have been a redditor for {} year.".format(age)
146-
else:
147-
out += "they have been a redditor for {} years.".format(age)
148-
else:
149-
out += "they have been a redditor for {} days.".format(account_age.days)
143+
age = account_age.days
144+
age_unit = "day"
145+
if age > 365:
146+
age //= 365
147+
age_unit = "year"
148+
out += "they have been a redditor for {}.".format(pluralize(age, age_unit))
150149
return out
151150

151+
152152
def time_format(numdays):
153-
age = ()
154153
if numdays >= 365:
155154
age = (int(numdays / 365), "y")
156155
if age[0] > 1:
@@ -159,7 +158,8 @@ def time_format(numdays):
159158
age = (numdays, "d")
160159
return age
161160

162-
@hook.command("submods", "mods", "rmods", singlethreaded=True)
161+
162+
@hook.command("submods", "mods", "rmods", singlethread=True)
163163
def submods(text, chan):
164164
"""submods <subreddit> prints the moderators of the specified subreddit."""
165165
global search_pages
@@ -175,7 +175,7 @@ def submods(text, chan):
175175
if r.status_code != 200:
176176
return statuscheck(r.status_code, 'r/'+sub)
177177
data = r.json()
178-
out = "/r/\x02{}\x02 mods: ".format(sub)
178+
out = colors.parse("/r/$(b){}$(b) mods: ".format(sub))
179179
for mod in data['data']['children']:
180180
username = mod['name']
181181
# Showing the modtime makes the message too long for larger subs
@@ -190,7 +190,8 @@ def submods(text, chan):
190190
return "{}(page {}/{}) .moremod".format(out, search_page_indexes[chan] + 1, len(search_pages[chan]))
191191
return out
192192

193-
@hook.command("subinfo","subreddit", "sub", "rinfo", singlethreaded=True)
193+
194+
@hook.command("subinfo","subreddit", "sub", "rinfo", singlethread=True)
194195
def subinfo(text):
195196
"""subinfo <subreddit> fetches information about the specified subreddit."""
196197
sub = text
@@ -211,12 +212,10 @@ def subinfo(text):
211212
subscribers = data['data']['subscribers']
212213
active = data['data']['accounts_active']
213214
sub_age = datetime.now() - datetime.fromtimestamp(data['data']['created'])
214-
age = ()
215-
if sub_age.days >= 365:
216-
age = (int(sub_age.days / 365), "y")
217-
else:
218-
age = (sub_age.days, "d")
219-
out = "/r/\x03{}\x02 - {} - a community for {}{}, there are {:,} subscribers and {:,} people online now.".format(name, title, age[0], age[1], subscribers, active)
215+
age, age_unit = time_format(sub_age.days)
216+
out = "/r/$(b){}$(clear) - {} - a community for {}{}, there are {:,} subscribers and {:,} people online now.".format(
217+
name, title, age, age_unit, subscribers, active
218+
)
220219
if nsfw:
221-
out += " \x0304NSFW\x0304"
222-
return out
220+
out += " $(red)NSFW$(clear)"
221+
return colors.parse(out)

0 commit comments

Comments
 (0)