Skip to content

Commit d9612ce

Browse files
authored
Merge branch 'gonzobot' into gonzobot+asyncio-threadsafe-wrap
2 parents 59019d8 + 134c97e commit d9612ce

68 files changed

Lines changed: 823 additions & 284 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

cloudbot/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
__version__ = "1.0.9"
1414

15-
__all__ = ["util", "bot", "connection", "config", "permissions", "plugin", "event", "hook", "log_dir"]
15+
__all__ = ["clients", "util", "bot", "client", "config", "event", "hook", "permissions", "plugin", "reloader", "logging_dir"]
1616

1717

1818
def _setup():

cloudbot/config.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33
import os
44
import sys
55
import time
6+
from collections import OrderedDict
67

78
logger = logging.getLogger("cloudbot")
89

910

10-
class Config(dict):
11+
class Config(OrderedDict):
1112
"""
1213
:type filename: str
1314
:type path: str
@@ -41,8 +42,10 @@ def load_config(self):
4142
sys.exit()
4243

4344
with open(self.path) as f:
44-
self.update(json.load(f))
45-
logger.debug("Config loaded from file.")
45+
data = json.load(f, object_pairs_hook=OrderedDict)
46+
47+
self.update(data)
48+
logger.debug("Config loaded from file.")
4649

4750
# reload permissions
4851
if self.bot.connections:
@@ -51,5 +54,7 @@ def load_config(self):
5154

5255
def save_config(self):
5356
"""saves the contents of the config dict to the config file"""
54-
json.dump(self, open(self.path, 'w'), sort_keys=True, indent=4)
57+
with open(self.path, 'w') as f:
58+
json.dump(self, f, indent=4)
59+
5560
logger.info("Config saved to file.")

plugins/admin_channel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def kick(text, chan, conn, notice, nick, admin_log):
114114
target = split[1]
115115
if len(split) > 2:
116116
reason = " ".join(split[2:])
117-
out = "KICK {} {}: {}".format(channel, target, reason)
117+
out = "KICK {} {} :{}".format(channel, target, reason)
118118
else:
119119
out = "KICK {} {}".format(channel, target)
120120
else:

plugins/amazon.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import requests
22
import re
33
from bs4 import BeautifulSoup
4+
from requests import HTTPError
45

56
from cloudbot import hook
67
from cloudbot.util import web, formatting, colors
@@ -19,14 +20,14 @@
1920

2021

2122
@hook.regex(AMAZON_RE)
22-
def amazon_url(match):
23+
def amazon_url(match, reply):
2324
cc = match.group(1)
2425
asin = match.group(2)
25-
return amazon(asin, _parsed=cc)
26+
return amazon(asin, reply, _parsed=cc)
2627

2728

2829
@hook.command("amazon", "az")
29-
def amazon(text, _parsed=False):
30+
def amazon(text, reply, _parsed=False):
3031
"""<query> -- Searches Amazon for query"""
3132
headers = {
3233
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, '
@@ -43,6 +44,12 @@ def amazon(text, _parsed=False):
4344
else:
4445
request = requests.get(SEARCH_URL.format(REGION), params=params, headers=headers)
4546

47+
try:
48+
request.raise_for_status()
49+
except HTTPError:
50+
reply("Amazon API error occurred.")
51+
raise
52+
4653
soup = BeautifulSoup(request.text)
4754

4855
# check if there are any results on the amazon page

plugins/bible.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@ def bible(text, reply):
1111
'formatting':'plain',
1212
'type':'json'
1313
}
14-
r = requests.get("https://labs.bible.org/api", params=params)
1514
try:
15+
r = requests.get("https://labs.bible.org/api", params=params)
16+
r.raise_for_status()
1617
response = r.json()[0]
1718
except Exception:
1819
reply("Something went wrong, either you entered an invalid passage or the API is down.")

plugins/bing.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import requests
44
from lxml import html
5+
from requests import HTTPError
56

67
from cloudbot import hook
78
from cloudbot.util import formatting, filesize, colors
@@ -30,7 +31,7 @@ def bingify(s):
3031

3132

3233
@hook.command("bing", "b")
33-
def bing(text, bot):
34+
def bing(text, bot, reply):
3435
"""<query> - returns the first bing search result for <query>"""
3536
api_key = bot.config.get("api_keys", {}).get("bing_azure")
3637

@@ -55,6 +56,12 @@ def bing(text, bot):
5556

5657
request = requests.get(API_URL, params=params, auth=(api_key, api_key))
5758

59+
try:
60+
request.raise_for_status()
61+
except HTTPError:
62+
reply("Bing API error occurred.")
63+
raise
64+
5865
# I'm not even going to pretend to know why results are in ['d']['results'][0]
5966
j = request.json()['d']['results'][0]
6067

@@ -72,7 +79,7 @@ def bing(text, bot):
7279

7380

7481
@hook.command("bingimage", "bis")
75-
def bingimage(text, bot):
82+
def bingimage(text, bot, reply):
7683
"""<query> - returns the first bing image search result for <query>"""
7784
api_key = bot.config.get("api_keys", {}).get("bing_azure")
7885

@@ -98,6 +105,12 @@ def bingimage(text, bot):
98105

99106
request = requests.get(API_URL, params=params, auth=(api_key, api_key))
100107

108+
try:
109+
request.raise_for_status()
110+
except HTTPError:
111+
reply("Bing API error occurred.")
112+
raise
113+
101114
# I'm not even going to pretend to know why results are in ['d']['results'][0]
102115
j = request.json()['d']['results'][0]
103116

plugins/books.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import requests
2+
from requests import HTTPError
23

34
from cloudbot import hook
45
from cloudbot.util import formatting, web
@@ -14,12 +15,20 @@ def load_key(bot):
1415

1516

1617
@hook.command("books", "gbooks")
17-
def books(text):
18+
def books(text, reply):
1819
"""books <query> -- Searches Google Books for <query>."""
1920
if not dev_key:
2021
return "This command requires a Google Developers Console API key."
2122

22-
json = requests.get(book_search_api, params={"q": text, "key": dev_key, "country": "US"}).json()
23+
request = requests.get(book_search_api, params={"q": text, "key": dev_key, "country": "US"})
24+
25+
try:
26+
request.raise_for_status()
27+
except HTTPError:
28+
reply("Bing API error occurred.")
29+
raise
30+
31+
json = request.json()
2332

2433
if json.get('error'):
2534
if json['error']['code'] == 403:

plugins/brew.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import requests
2+
from requests import HTTPError
23

34
from cloudbot import hook
45

@@ -12,7 +13,7 @@ def load_key(bot):
1213

1314

1415
@hook.command('brew')
15-
def brew(text, bot):
16+
def brew(text, reply):
1617
"""<query> - returns the first brewerydb search result for <query>"""
1718

1819
if not api_key:
@@ -21,8 +22,11 @@ def brew(text, bot):
2122
params = {'key': api_key, 'type': 'beer', 'withBreweries': 'Y', 'q': text}
2223
request = requests.get(api_url, params=params)
2324

24-
if request.status_code != requests.codes.ok:
25-
return "Failed to fetch info ({})".format(request.status_code)
25+
try:
26+
request.raise_for_status()
27+
except HTTPError:
28+
reply("Failed to fetch info ({})".format(request.status_code))
29+
raise
2630

2731
response = request.json()
2832

@@ -58,6 +62,7 @@ def brew(text, bot):
5862

5963
except Exception as e:
6064
print(e)
61-
output = "Error parsing results."
65+
reply("Error parsing results.")
66+
raise
6267

6368
return output

plugins/cats.py

Lines changed: 21 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,31 @@
11
import requests
2+
from requests import HTTPError
3+
24
from cloudbot import hook
35

46

7+
def get_data(url, reply, bot, params=None):
8+
try:
9+
r = requests.get(url, headers={'User-Agent': bot.user_agent}, params=params)
10+
r.raise_for_status()
11+
except HTTPError:
12+
reply("API error occurred.")
13+
raise
14+
15+
return r
16+
17+
518
@hook.command(autohelp=False)
6-
def cats(reply):
19+
def cats(reply, bot):
720
"""gets a fucking fact about cats."""
21+
r = get_data('https://catfact.ninja/fact', reply, bot, params={'max_length': 100})
22+
json = r.json()
23+
response = json['facts']
24+
return response
825

9-
attempts = 0
10-
while True:
11-
try:
12-
r = requests.get(
13-
'http://catfacts-api.appspot.com/api/facts?number=1')
14-
except Exception:
15-
if attempts > 2:
16-
reply("There was an error contacting the API.")
17-
raise
18-
else:
19-
attempts += 1
20-
continue
21-
json = r.json()
22-
response = json['facts']
23-
return response
2426

2527
@hook.command(autohelp=False)
26-
def catgifs(reply):
28+
def catgifs(reply, bot):
2729
"""gets a fucking cat gif."""
28-
attempts = 0
29-
while True:
30-
try:
31-
r = requests.get("http://marume.herokuapp.com/random.gif")
32-
except Exception:
33-
if attempts > 2:
34-
reply("there was an error finding a cat gif for you.")
35-
raise
36-
else:
37-
attempts += 1
38-
continue
39-
response = r.url
40-
return "OMG A CAT GIF: {}".format(response)
30+
r = get_data("http://marume.herokuapp.com/random.gif", reply, bot)
31+
return "OMG A CAT GIF: {}".format(r.url)

0 commit comments

Comments
 (0)