Skip to content

Commit

Permalink
Add redd.it urls integration (#4)
Browse files Browse the repository at this point in the history
Add ability to link redd.it urls
Refactor reddit_linker
Add redd.it test case
  • Loading branch information
fabiosangregorio authored May 21, 2019
1 parent 7fa3e50 commit e2afd9f
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 22 deletions.
13 changes: 12 additions & 1 deletion helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,15 @@ def truncate_text(text, length=100):


def polish_text(text):
return text.replace('\n', ' ')
return text.replace('\n', ' ')


def get_urls_from_text(text):
polished = polish_text(text)
urls = list()
for w in polished.lower().split(' '):
if 'reddit.com' in w:
urls.append(w.partition('/?')[0] + '.json')
if 'redd.it' in w:
urls.append(f'https://www.reddit.com/comments/{w.partition("redd.it/")[2]}.json')
return urls
31 changes: 15 additions & 16 deletions reddit_linker.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,54 +22,53 @@ def send_random_posts(bot, chat_id, text):
if status == 'failed':
tries += 1
if status != 'success':
_send_exception_message(bot, chat_id, subreddit, fail_msg)
_send_exception_message(bot, chat_id, fail_msg)


def send_post_from_url(bot, chat_id, post_url):
subreddit = helpers.get_subreddit_names(post_url)
if not len(subreddit):
return
subreddit = subreddit[0]
status, fail_msg = send_post(bot, chat_id, subreddit, post_url)
status, fail_msg = send_post(bot, chat_id, post_url=post_url)
if status == 'failed':
_send_exception_message(bot, chat_id, subreddit, fail_msg)
_send_exception_message(bot, chat_id, fail_msg)


def _get_post(subreddit, post_url=None):
def _get_post(subreddit=None, post_url=None):
if not post_url:
post_url = f'https://www.reddit.com/{subreddit}/random.json'
try:
json = requests.get(post_url, headers={'User-agent': 'telereddit_bot'}).json()
except ValueError:
return None, f"I'm sorry, I can't find {subreddit}."
return None, f"I'm sorry, I can't find that subreddit."

if not json:
return None, f"I'm sorry, I can't find {subreddit}."
return None, f"I'm sorry, I can't find that subreddit."

# some subreddits have the json data wrapped in brackets, some do not
json = json if isinstance(json, dict) else json[0]

if json.get('reason') == 'private':
return None, f"I'm sorry, the subreddit {subreddit} is private."
return None, f"I'm sorry, this subreddit is private."

not_found = json.get('error', 200) == 404 or len(json['data']['children']) == 0
if not_found:
return None, f"I'm sorry, the subreddit {subreddit} doesn't exist!"
return None, f"I'm sorry, this subreddit doesn't exist!"

return json, None


def send_post(bot, chat_id, subreddit, post_url=None):
def send_post(bot, chat_id, subreddit=None, post_url=None):
if not subreddit and not post_url:
return

json, err_msg = _get_post(subreddit, post_url)
if err_msg:
bot.sendMessage(chat_id, err_msg)
return 'success', None

subreddit_url = f'https://www.reddit.com/{subreddit}'
try:
idx = random.randint(0, len(json['data']['children']) - 1)
data = json['data']['children'][idx]['data']

subreddit = data['subreddit_name_prefixed']
subreddit_url = f'https://www.reddit.com/{subreddit}'
post_text = data['selftext']
content_url = data['url']
permalink = data['permalink']
Expand Down Expand Up @@ -164,7 +163,7 @@ def more_button_callback(bot, msg):
send_random_posts(bot, chat_id, subreddit)


def _send_exception_message(bot, chat_id, subreddit, msg):
def _send_exception_message(bot, chat_id, msg):
keyboard = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='Try with another random post', callback_data='reddit')]
])
Expand Down
9 changes: 4 additions & 5 deletions telereddit.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@ def on_chat_message(msg):
return

text = msg['text']
if 'reddit.com' in text.lower():
polished = helpers.polish_text(text)
post_url = [w for w in polished.lower().split(' ') if 'reddit.com' in w][0]
post_url = post_url.partition('/?')[0] + '.json'
reddit_linker.send_post_from_url(bot, chat_id, post_url)
if any(r in text.lower() for r in ['reddit.com', 'redd.it']):
posts_url = helpers.get_urls_from_text(text)
for url in posts_url:
reddit_linker.send_post_from_url(bot, chat_id, url)
elif 'r/' in text.lower():
reddit_linker.send_random_posts(bot, chat_id, text)

Expand Down
10 changes: 10 additions & 0 deletions test_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import unittest
import helpers


class TestHelpers(unittest.TestCase):
def test_get_urls_from_text(self):
text = 'https://redd.it/bqdlxe https://redd.it/bqekoq'
urls = ['https://www.reddit.com/comments/bqdlxe.json',
'https://www.reddit.com/comments/bqekoq.json']
self.assertListEqual(helpers.get_urls_from_text(text), urls)

0 comments on commit e2afd9f

Please sign in to comment.