11import random
22import re
3- import urllib .parse
43from datetime import datetime
54
65import requests
6+ from yarl import URL
77
88from cloudbot import hook
99from 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
1717def 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 )
4953def 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
0 commit comments