Skip to content

Commit 369f94b

Browse files
committed
Add yarl lib to handle url parsing
1 parent 2f14e85 commit 369f94b

2 files changed

Lines changed: 16 additions & 14 deletions

File tree

plugins/reddit.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,26 @@
11
import random
22
import re
3-
import urllib.parse
43
from datetime import datetime
54

65
import requests
6+
from yarl import URL
77

88
from cloudbot import hook
99
from cloudbot.util import timeformat, formatting
1010

11-
reddit_re = re.compile(r'.*(((www\.)?reddit\.com/r|redd\.it)[^ ]+)', re.I)
11+
reddit_re = re.compile(r'.*(//((www\.)?reddit\.com/r|redd\.it)[^ ]+)', re.I)
1212

13-
base_url = "http://reddit.com/r/{}"
14-
short_url = "http://redd.it/{}"
13+
base_url = "https://reddit.com/r/{}"
14+
short_url = "https://redd.it/{}"
1515

1616

1717
def api_request(url, bot):
18-
url = url.rstrip('/') + "/.json"
19-
r = requests.get(url, headers={'User-Agent': bot.user_agent})
18+
"""
19+
:type url: yarl.URL
20+
:type bot: cloudbot.bot.CloudBot
21+
"""
22+
url = url.with_query("").with_scheme("https") / ".json"
23+
r = requests.get(str(url), headers={'User-Agent': bot.user_agent})
2024
r.raise_for_status()
2125
return r.json()
2226

@@ -48,15 +52,12 @@ def format_output(item, show_url=False):
4852
@hook.regex(reddit_re, singlethread=True)
4953
def reddit_url(match, bot):
5054
url = match.group(1)
55+
url = URL(url).with_scheme("https")
5156

52-
if "redd.it" in url:
53-
url = "https://" + url
57+
if url.host.endswith("redd.it"):
5458
response = requests.get(url)
5559
response.raise_for_status()
56-
url = response.url
57-
58-
if not urllib.parse.urlparse(url).scheme:
59-
url = "https://" + url
60+
url = URL(response.url).with_scheme("https")
6061

6162
data = api_request(url, bot)
6263
item = data[0]["data"]["children"][0]["data"]
@@ -81,10 +82,10 @@ def reddit(text, bot, reply):
8182
except ValueError:
8283
return "Invalid post number."
8384
else:
84-
url = "http://reddit.com"
85+
url = "https://reddit.com"
8586

8687
try:
87-
data = api_request(url, bot)
88+
data = api_request(URL(url), bot)
8889
except Exception as e:
8990
reply("Error: " + str(e))
9091
raise

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,4 @@ pyenchant
1717
pythonwhois
1818
imgurpython
1919
isodate
20+
yarl

0 commit comments

Comments
 (0)