Skip to content

Commit d5dcd74

Browse files
committed
Switch reddit_info.py to using generic pager
1 parent 633999d commit d5dcd74

1 file changed

Lines changed: 37 additions & 52 deletions

File tree

plugins/reddit_info.py

Lines changed: 37 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,22 @@
1-
import requests
2-
31
from collections import defaultdict
42
from datetime import datetime
3+
4+
import requests
55
from bs4 import BeautifulSoup
6+
67
from cloudbot import hook
78
from cloudbot.util import colors
89
from cloudbot.util.formatting import pluralize
10+
from cloudbot.util.pager import paginated_list
911

10-
search_pages = defaultdict(list)
11-
search_page_indexes = {}
12+
search_pages = defaultdict(dict)
1213

1314
user_url = "http://reddit.com/user/{}/"
1415
subreddit_url = "http://reddit.com/r/{}/"
1516
# This agent should be unique for your cloudbot instance
1617
agent = {"User-Agent": "gonzobot a cloudbot (IRCbot) implementation for snoonet.org by /u/bloodygonzo"}
1718

1819

19-
def two_lines(bigstring, chan):
20-
"""Receives a string with new lines. Groups the string into a list of strings with up to 2 new lines per string element. Returns first string element then stores the remaining list in search_pages."""
21-
global search_pages
22-
temp = bigstring.split('\n')
23-
for i in range(0, len(temp), 2):
24-
search_pages[chan].append('\n'.join(temp[i:i+2]))
25-
search_page_indexes[chan] = 0
26-
return search_pages[chan][0]
27-
28-
29-
def smart_truncate(content, length=355, suffix='...\n'):
30-
if len(content) <= length:
31-
return content
32-
else:
33-
return content[:length].rsplit(' \u2022 ', 1)[0]+ suffix + content[:length].rsplit(' \u2022 ', 1)[1] + smart_truncate(content[length:])
34-
35-
3620
def statuscheck(status, item):
3721
"""since we are doing this a lot might as well return something more meaningful"""
3822
if status == 404:
@@ -49,34 +33,34 @@ def statuscheck(status, item):
4933

5034

5135
@hook.command("moremod", autohelp=False)
52-
def moremod(text, chan):
36+
def moremod(text, chan, conn):
5337
"""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."""
54-
if not search_pages[chan]:
38+
chan_cf = chan.casefold()
39+
pages = search_pages[conn.name].get(chan_cf)
40+
if not pages:
5541
return "There are modlist pages to show."
5642
if text:
5743
try:
5844
index = int(text)
5945
except ValueError:
6046
return "Please specify an integer value."
61-
if abs(index) > len(search_pages[chan]) or index == 0:
47+
page = pages[index - 1]
48+
if page is None:
6249
return "please specify a valid page number between 1 and {}.".format(len(search_pages[chan]))
6350
else:
64-
return "{}(page {}/{})".format(search_pages[chan][index-1], index, len(search_pages[chan]))
51+
return page
6552
else:
66-
search_page_indexes[chan] += 1
67-
if search_page_indexes[chan] < len(search_pages[chan]):
68-
return "{}(page {}/{})".format(search_pages[chan][search_page_indexes[chan]], search_page_indexes[chan] + 1, len(search_pages[chan]))
53+
page = pages.next()
54+
if page is not None:
55+
return page
6956
else:
7057
return "All pages have been shown."
7158

7259

7360
@hook.command("subs", "moderates", singlethread=True)
74-
def moderates(text, chan):
61+
def moderates(text, chan, conn):
7562
"""This plugin prints the list of subreddits a user moderates listed in a reddit users profile. Private subreddits will not be listed."""
7663
#This command was written using concepts from FurCode http://github.com/FurCode.
77-
global search_pages
78-
search_pages[chan] = []
79-
search_page_indexes[chan] = 0
8064
user = text
8165
r = requests.get(user_url.format(user), headers=agent)
8266
if r.status_code != 200:
@@ -89,14 +73,14 @@ def moderates(text, chan):
8973
mod_list = mod_list.text.split('r/')
9074
del mod_list[0]
9175
out = colors.parse("$(b){}$(b) moderates these public subreddits: ".format(user))
92-
for sub in mod_list:
93-
out += "{} \u2022 ".format(sub)
94-
out = out[:-2]
95-
out = smart_truncate(out)
96-
if len(out.split('\n')) > 2:
97-
out = two_lines(out, chan)
98-
return "{}(page {}/{}) .moremod".format(out, search_page_indexes[chan] + 1, len(search_pages[chan]))
99-
return out
76+
pager = paginated_list(mod_list)
77+
search_pages[conn.name][chan.casefold()] = pager
78+
page = pager.next()
79+
if len(page) > 1:
80+
page[-1] += " .moremod"
81+
82+
page[0] = out + page[0]
83+
return page
10084

10185

10286
@hook.command("karma", "ruser", singlethread=True)
@@ -160,11 +144,8 @@ def time_format(numdays):
160144

161145

162146
@hook.command("submods", "mods", "rmods", singlethread=True)
163-
def submods(text, chan):
147+
def submods(text, chan, conn):
164148
"""submods <subreddit> prints the moderators of the specified subreddit."""
165-
global search_pages
166-
search_pages[chan] = []
167-
search_page_indexes[chan] = 0
168149
sub = text
169150
if sub.startswith('/r/'):
170151
sub = sub[3:]
@@ -175,20 +156,24 @@ def submods(text, chan):
175156
if r.status_code != 200:
176157
return statuscheck(r.status_code, 'r/'+sub)
177158
data = r.json()
178-
out = colors.parse("/r/$(b){}$(b) mods: ".format(sub))
159+
moderators = []
179160
for mod in data['data']['children']:
180161
username = mod['name']
181162
# Showing the modtime makes the message too long for larger subs
182163
# if you want to show this information add modtime.days to out below
183164
modtime = datetime.now() - datetime.fromtimestamp(mod['date'])
184165
modtime = time_format(modtime.days)
185-
out += "{} ({}{}) \u2022 ".format(username, modtime[0], modtime[1])
186-
out = smart_truncate(out)
187-
out = out[:-3]
188-
if len(out.split('\n')) > 2:
189-
out = two_lines(out, chan)
190-
return "{}(page {}/{}) .moremod".format(out, search_page_indexes[chan] + 1, len(search_pages[chan]))
191-
return out
166+
moderators.append("{} ({}{})".format(username, modtime[0], modtime[1]))
167+
pager = paginated_list(moderators)
168+
search_pages[conn.name][chan.casefold()] = pager
169+
page = pager.next()
170+
if len(page) > 1:
171+
page[-1] += " .moremod"
172+
173+
out = colors.parse("/r/$(b){}$(b) mods: ".format(sub))
174+
page[0] = out + page[0]
175+
176+
return page
192177

193178

194179
@hook.command("subinfo","subreddit", "sub", "rinfo", singlethread=True)

0 commit comments

Comments
 (0)