Skip to content

Commit d726e0a

Browse files
authored
Merge branch 'gonzobot' into gonzobot+pytest-leaks
2 parents c2d8470 + 957d9ce commit d726e0a

124 files changed

Lines changed: 685 additions & 631 deletions

Some content is hidden

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

CONTRIBUTING.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,12 @@ The following guidelines for contribution should be followed if you want to subm
2222

2323
* You need a [GitHub account](https://github.com/signup/free)
2424
* Submit an [issue ticket](https://github.com/ClouDev/CloudBot/issues) for your issue if there is no one yet.
25-
* Try to describe the issue and include steps to reproduce if it's a bug.
25+
* Try to describe the issue and include steps to reproduce if it's a bug.
2626
* If you are able and want to fix this, fork the repository on GitHub
2727

2828
## Make Changes
2929

30-
* In your forked repository, create a topic branch for your upcoming patch. (optional)
30+
* In your forked repository, create a topic branch for your upcoming patch. (optional)
3131
* Make sure you stick to the coding style that is used already.
3232
* Make use of the [`.editorconfig`](http://editorconfig.org/) file.
3333
* Make commits that make sense and describe them properly.
@@ -38,7 +38,7 @@ The following guidelines for contribution should be followed if you want to subm
3838

3939
* Push your changes to a topic branch in your fork of the repository.
4040
* Open a pull request to the original repository and choose the `python3.4` branch.
41-
_Advanced users may use [`hub`](https://github.com/defunkt/hub#git-pull-request) gem for that._
41+
_Advanced users may use [`hub`](https://github.com/defunkt/hub#git-pull-request) gem for that._
4242
* If not done in commit messages (which you really should do) please reference and update your issue with the code changes. But _please do not close the issue yourself_.
4343
_Notice: You can [turn your previously filed issues into a pull-request here](http://issue2pr.herokuapp.com/)._
4444

cloudbot/__init__.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212

1313
__version__ = "1.0.9"
1414

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

1718

1819
def _setup():
@@ -23,6 +24,8 @@ def _setup():
2324
else:
2425
logging_config = {}
2526

27+
file_log = logging_config.get("file_log", False)
28+
2629
global logging_dir
2730
logging_dir = os.path.join(os.path.abspath(os.path.curdir), "logs")
2831

@@ -49,25 +52,29 @@ def _setup():
4952
"formatter": "brief",
5053
"level": "INFO",
5154
"stream": "ext://sys.stdout"
52-
},
53-
"file": {
54-
"class": "logging.handlers.RotatingFileHandler",
55-
"maxBytes": 1000000,
56-
"backupCount": 5,
57-
"formatter": "full",
58-
"level": "INFO",
59-
"encoding": "utf-8",
60-
"filename": os.path.join(logging_dir, "bot.log")
6155
}
6256
},
6357
"loggers": {
6458
"cloudbot": {
6559
"level": "DEBUG",
66-
"handlers": ["console", "file"]
60+
"handlers": ["console"]
6761
}
6862
}
6963
}
7064

65+
if file_log:
66+
dict_config["handlers"]["file"] = {
67+
"class": "logging.handlers.RotatingFileHandler",
68+
"maxBytes": 1000000,
69+
"backupCount": 5,
70+
"formatter": "full",
71+
"level": "INFO",
72+
"encoding": "utf-8",
73+
"filename": os.path.join(logging_dir, "bot.log")
74+
}
75+
76+
dict_config["loggers"]["cloudbot"]["handlers"].append("file")
77+
7178
if logging_config.get("console_debug", False):
7279
dict_config["handlers"]["console"]["level"] = "DEBUG"
7380
dict_config["loggers"]["asyncio"] = {
@@ -89,4 +96,5 @@ def _setup():
8996

9097
logging.config.dictConfig(dict_config)
9198

99+
92100
_setup()

cloudbot/__main__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ def main():
4141
# define closure for signal handling
4242
# The handler is called with two arguments: the signal number and the current stack frame
4343
# These parameters should NOT be removed
44+
# noinspection PyUnusedLocal
4445
def exit_gracefully(signum, frame):
4546
nonlocal stopped_while_restarting
4647
if not _bot:

cloudbot/bot.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727

2828
web_installed = True
2929
except ImportError:
30+
WebInterface = None
3031
web_installed = False
3132

3233
logger = logging.getLogger("cloudbot")
@@ -44,7 +45,7 @@ class CloudBot:
4445
"""
4546
:type start_time: float
4647
:type running: bool
47-
:type connections: list[Client | IrcClient]
48+
:type connections: dict[str, Client]
4849
:type data_dir: bytes
4950
:type config: core.config.Config
5051
:type plugin_manager: PluginManager

cloudbot/hook.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ def sieve(param=None, **kwargs):
318318
"""
319319

320320
def _sieve_hook(func):
321-
assert len(inspect.getfullargspec(func).args) == 3, \
321+
assert len(inspect.signature(func).parameters) == 3, \
322322
"Sieve plugin has incorrect argument count. Needs params: bot, input, plugin"
323323

324324
hook = _get_hook(func, "sieve")

cloudbot/permissions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
from fnmatch import fnmatch
21
import logging
2+
from fnmatch import fnmatch
33

44
logger = logging.getLogger("cloudbot")
55

cloudbot/util/colors.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@
3939
import re
4040
from random import randint
4141

42-
4342
IRC_COLOUR_DICT = {
4443
"white": "00",
4544
"black": "01",
@@ -90,7 +89,6 @@
9089
"clear": "\x0F"
9190
}
9291

93-
9492
COLOR_RE = re.compile(r"\$\(.*?\)", re.I)
9593
IRC_COLOR_RE = re.compile(r"(\x03(\d+,\d+|\d)|[\x0f\x02\x16\x1f])", re.I)
9694

cloudbot/util/filesize.py

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -52,50 +52,50 @@
5252
are listed in the accompanying credits file.
5353
"""
5454

55-
traditional = [
55+
traditional = (
5656
(1024 ** 5, 'P'),
5757
(1024 ** 4, 'T'),
5858
(1024 ** 3, 'G'),
5959
(1024 ** 2, 'M'),
6060
(1024 ** 1, 'K'),
6161
(1024 ** 0, 'B'),
62-
]
62+
)
6363

64-
alternative = [
64+
alternative = (
6565
(1024 ** 5, ' PB'),
6666
(1024 ** 4, ' TB'),
6767
(1024 ** 3, ' GB'),
6868
(1024 ** 2, ' MB'),
6969
(1024 ** 1, ' KB'),
7070
(1024 ** 0, (' byte', ' bytes')),
71-
]
71+
)
7272

73-
verbose = [
73+
verbose = (
7474
(1024 ** 5, (' petabyte', ' petabytes')),
7575
(1024 ** 4, (' terabyte', ' terabytes')),
7676
(1024 ** 3, (' gigabyte', ' gigabytes')),
7777
(1024 ** 2, (' megabyte', ' megabytes')),
7878
(1024 ** 1, (' kilobyte', ' kilobytes')),
7979
(1024 ** 0, (' byte', ' bytes')),
80-
]
80+
)
8181

82-
iec = [
82+
iec = (
8383
(1024 ** 5, 'Pi'),
8484
(1024 ** 4, 'Ti'),
8585
(1024 ** 3, 'Gi'),
8686
(1024 ** 2, 'Mi'),
8787
(1024 ** 1, 'Ki'),
8888
(1024 ** 0, ''),
89-
]
89+
)
9090

91-
si = [
91+
si = (
9292
(1000 ** 5, 'P'),
9393
(1000 ** 4, 'T'),
9494
(1000 ** 3, 'G'),
9595
(1000 ** 2, 'M'),
9696
(1000 ** 1, 'K'),
9797
(1000 ** 0, 'B'),
98-
]
98+
)
9999

100100
# re.I style aliases
101101
T = traditional
@@ -109,7 +109,7 @@ def size(b, system=traditional):
109109
"""Human-readable file size.
110110
111111
Using the traditional system, where a factor of 1024 is used::
112-
112+
113113
>>> size(10)
114114
'10B'
115115
>>> size(100)
@@ -130,7 +130,7 @@ def size(b, system=traditional):
130130
'976K'
131131
>>> size(2000000)
132132
'1M'
133-
133+
134134
Using the SI system, with a factor 1000::
135135
136136
>>> size(10, system=si)
@@ -153,11 +153,14 @@ def size(b, system=traditional):
153153
'1M'
154154
>>> size(2000000, system=si)
155155
'2M'
156-
156+
157157
"""
158158
for factor, suffix in system:
159159
if b >= factor:
160160
break
161+
else:
162+
return
163+
161164
amount = int(b / factor)
162165
if isinstance(suffix, tuple):
163166
singular, multiple = suffix

cloudbot/util/formatting.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,12 @@
4545
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4646
"""
4747
import copy
48-
import re
4948
import html.entities
50-
49+
import re
5150
from html.parser import HTMLParser
5251

5352
from cloudbot.util.colors import strip_irc
5453

55-
5654
# Constants
5755

5856
IRC_COLOR_RE = re.compile(r"(\x03(\d+,\d+|\d)|[\x0f\x02\x16\x1f])")
@@ -119,6 +117,7 @@ class HTMLTextExtractor(HTMLParser):
119117
"""
120118
Takes HTML and provides cleaned and stripped text.
121119
"""
120+
122121
def __init__(self):
123122
HTMLParser.__init__(self)
124123
self.result = []
@@ -166,6 +165,7 @@ def munge(text, count=0):
166165
break
167166
return text
168167

168+
169169
def ireplace(text, old, new, count=None):
170170
"""
171171
A case-insensitive replace() clone. Return a copy of text with all occurrences of substring
@@ -193,6 +193,7 @@ def translate(match):
193193

194194
return rc.sub(translate, text)
195195

196+
196197
# compatibility
197198
multiword_replace = multi_replace
198199

@@ -220,6 +221,7 @@ def truncate(content, length=100, suffix='...'):
220221
else:
221222
return content[:length].rsplit(' ', 1)[0] + suffix
222223

224+
223225
# compatibility
224226
truncate_str = truncate
225227
strip_colors = strip_irc
@@ -230,11 +232,13 @@ def chunk_str(content, length=420):
230232
Chunks a string into smaller strings of given length. Returns chunks.
231233
:rtype list
232234
"""
235+
233236
def chunk(c, l):
234237
while c:
235-
out = (c+' ')[:l].rsplit(' ', 1)[0]
238+
out = (c + ' ')[:l].rsplit(' ', 1)[0]
236239
c = c[len(out):].strip()
237240
yield out
241+
238242
return list(chunk(content, length))
239243

240244

@@ -245,6 +249,7 @@ def pluralize(num=0, text=''):
245249
"""
246250
return "{:,} {}{}".format(num, text, "s"[num == 1:])
247251

252+
248253
# alternate form
249254
pluralise = pluralize
250255

@@ -261,7 +266,7 @@ def dict_format(args, formats):
261266
# Check if values can be mapped
262267
m = f.format(**args)
263268
# Insert match and number of matched values (max matched values if already in dict)
264-
matches[m] = max([matches.get(m, 0), len(re.findall(r'(\{.*?\})', f))])
269+
matches[m] = max([matches.get(m, 0), len(re.findall(r'({.*?\})', f))])
265270
except Exception:
266271
continue
267272

cloudbot/util/http.py

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,21 @@
22

33
import http.cookiejar
44
import json
5-
import urllib.request
6-
import urllib.parse
75
import urllib.error
8-
import urllib.request
96
import urllib.error
107
import urllib.parse
118
import urllib.parse
9+
import urllib.parse
10+
import urllib.request
11+
import urllib.request
12+
# noinspection PyUnresolvedReferences
13+
import warnings
1214
# noinspection PyUnresolvedReferences
1315
from urllib.parse import quote, quote_plus as _quote_plus
1416

1517
from bs4 import BeautifulSoup
1618
from lxml import etree, html
1719

18-
# noinspection PyUnresolvedReferences
19-
from urllib.error import URLError, HTTPError
20-
2120
# security
2221
parser = etree.XMLParser(resolve_entities=False, no_network=True)
2322

@@ -36,13 +35,13 @@
3635

3736
def get(*args, **kwargs):
3837
if kwargs.get("decode", True):
39-
return open(*args, **kwargs).read().decode()
38+
return open_request(*args, **kwargs).read().decode()
4039
else:
41-
return open(*args, **kwargs).read()
40+
return open_request(*args, **kwargs).read()
4241

4342

4443
def get_url(*args, **kwargs):
45-
return open(*args, **kwargs).geturl()
44+
return open_request(*args, **kwargs).geturl()
4645

4746

4847
def get_html(*args, **kwargs):
@@ -62,8 +61,8 @@ def get_json(*args, **kwargs):
6261
return json.loads(get(*args, **kwargs))
6362

6463

65-
def open(url, query_params=None, user_agent=None, post_data=None,
66-
referer=None, get_method=None, cookies=False, timeout=None, headers=None, **kwargs):
64+
def open_request(url, query_params=None, user_agent=None, post_data=None, referer=None, get_method=None, cookies=False,
65+
timeout=None, headers=None, **kwargs):
6766
if query_params is None:
6867
query_params = {}
6968

@@ -99,6 +98,21 @@ def open(url, query_params=None, user_agent=None, post_data=None,
9998
return opener.open(request)
10099

101100

101+
# noinspection PyShadowingBuiltins
102+
def open(url, query_params=None, user_agent=None, post_data=None,
103+
referer=None, get_method=None, cookies=False, timeout=None, headers=None,
104+
**kwargs): # pylint: disable=locally-disabled, redefined-builtin
105+
warnings.warn(
106+
"http.open() is deprecated, use http.open_request() instead.",
107+
DeprecationWarning
108+
)
109+
110+
return open_request(
111+
url, query_params=query_params, user_agent=user_agent, post_data=post_data, referer=referer,
112+
get_method=get_method, cookies=cookies, timeout=timeout, headers=headers, **kwargs
113+
)
114+
115+
102116
def prepare_url(url, queries):
103117
if queries:
104118
scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)

0 commit comments

Comments
 (0)