Skip to content

Commit

Permalink
Merge pull request CloudBotIRC#203 from linuxdaemon/gonzobot+merge-fixes
Browse files Browse the repository at this point in the history
Fix issues arising from multiple PR merges
  • Loading branch information
edwardslabs authored Mar 12, 2018
2 parents 393da30 + 84ea6ff commit 4fa4a95
Show file tree
Hide file tree
Showing 11 changed files with 52 additions and 32 deletions.
4 changes: 3 additions & 1 deletion cloudbot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,10 @@ def _setup():
dict_config["handlers"]["console"]["level"] = "DEBUG"
dict_config["loggers"]["asyncio"] = {
"level": "DEBUG",
"handlers": ["console", "file"]
"handlers": ["console"]
}
if file_log:
dict_config["loggers"]["asyncio"]["handlers"].append("file")

if logging_config.get("file_debug", False):
dict_config["handlers"]["debug_file"] = {
Expand Down
2 changes: 1 addition & 1 deletion cloudbot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ def _init_routine(self):
self.observer.start()

# Connect to servers
yield from asyncio.gather(*[conn.try_connect() for conn in self.connections.values()], loop=self.loop)
yield from asyncio.gather(*[conn.connect() for conn in self.connections.values()], loop=self.loop)

# Activate web interface.
if self.config.get("web", {}).get("enabled", False) and web_installed:
Expand Down
2 changes: 1 addition & 1 deletion cloudbot/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def connect(self, timeout=None):
"""
raise NotImplementedError

def quit(self, reason=None):
def quit(self, reason=None, set_inactive=True):
"""
Gracefully disconnects from the server with reason <reason>, close() should be called shortly after.
"""
Expand Down
5 changes: 3 additions & 2 deletions cloudbot/clients/irc.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,9 @@ def _connect(self, timeout=None):
# TODO stop connecting if a connect hook fails?
yield from asyncio.gather(*tasks)

def quit(self, reason=None):
self._active = False
def quit(self, reason=None, set_inactive=True):
if set_inactive:
self._active = False

if self.connected:
if reason:
Expand Down
2 changes: 1 addition & 1 deletion cloudbot/util/func_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

class ParameterError(Exception):
def __init__(self, name, valid_args):
self.__init__(name, list(valid_args))
super().__init__(name, list(valid_args))

def __str__(self):
return "'{}' is not a valid parameter, valid parameters are: {}".format(self.args[0], self.args[1])
Expand Down
32 changes: 16 additions & 16 deletions cloudbot/util/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,12 @@ def try_shorten(self, url, custom=None, key=None):
return url

def expand(self, url):
r = requests.get(url, allow_redirects=False)
try:
r = requests.get(url, allow_redirects=False)
r.raise_for_status()
except RequestException as e:
r = e.response
raise ServiceError(r.status_code, r)
raise ServiceError(r.reason, r)

if 'location' in r.headers:
return r.headers['location']
Expand Down Expand Up @@ -132,12 +132,12 @@ def _decorate(impl):
class Isgd(Shortener):
def shorten(self, url, custom=None, key=None):
p = {'url': url, 'shorturl': custom, 'format': 'json'}
r = requests.get('http://is.gd/create.php', params=p)
try:
r = requests.get('http://is.gd/create.php', params=p)
r.raise_for_status()
except RequestException as e:
r = e.response
raise ServiceError(r.status_code, r)
raise ServiceError(r.reason, r)

j = r.json()

Expand All @@ -148,12 +148,12 @@ def shorten(self, url, custom=None, key=None):

def expand(self, url):
p = {'shorturl': url, 'format': 'json'}
r = requests.get('http://is.gd/forward.php', params=p)
try:
r = requests.get('http://is.gd/forward.php', params=p)
r.raise_for_status()
except RequestException as e:
r = e.response
raise ServiceError(r.status_code, r)
raise ServiceError(r.reason, r)

j = r.json()

Expand All @@ -169,12 +169,12 @@ def shorten(self, url, custom=None, key=None):
h = {'content-type': 'application/json'}
k = {'key': key}
p = {'longUrl': url}
r = requests.post('https://www.googleapis.com/urlshortener/v1/url', params=k, data=json.dumps(p), headers=h)
try:
r = requests.post('https://www.googleapis.com/urlshortener/v1/url', params=k, data=json.dumps(p), headers=h)
r.raise_for_status()
except RequestException as e:
r = e.response
raise ServiceError(r.status_code, r)
raise ServiceError(r.reason, r)

j = r.json()

Expand All @@ -185,12 +185,12 @@ def shorten(self, url, custom=None, key=None):

def expand(self, url):
p = {'shortUrl': url}
r = requests.get('https://www.googleapis.com/urlshortener/v1/url', params=p)
try:
r = requests.get('https://www.googleapis.com/urlshortener/v1/url', params=p)
r.raise_for_status()
except RequestException as e:
r = e.response
raise ServiceError(r.status_code, r)
raise ServiceError(r.reason, r)

j = r.json()

Expand All @@ -204,12 +204,12 @@ def expand(self, url):
class Gitio(Shortener):
def shorten(self, url, custom=None, key=None):
p = {'url': url, 'code': custom}
r = requests.post('http://git.io', data=p)
try:
r = requests.post('http://git.io', data=p)
r.raise_for_status()
except RequestException as e:
r = e.response
raise ServiceError(r.status_code, r)
raise ServiceError(r.reason, r)

if r.status_code == requests.codes.created:
s = r.headers['location']
Expand All @@ -224,12 +224,12 @@ def shorten(self, url, custom=None, key=None):
@_pastebin('hastebin')
class Hastebin(Pastebin):
def paste(self, data, ext):
r = requests.post(HASTEBIN_SERVER + '/documents', data=data)
try:
r = requests.post(HASTEBIN_SERVER + '/documents', data=data)
r.raise_for_status()
except RequestException as e:
r = e.response
raise ServiceError(r.status_code, r)
raise ServiceError(r.reason, r)
else:
j = r.json()

Expand All @@ -246,11 +246,11 @@ def paste(self, data, ext):
'text': data,
'expire': '1d'
}
r = requests.post(SNOONET_PASTE + '/paste/new', data=params)
try:
r = requests.post(SNOONET_PASTE + '/paste/new', data=params)
r.raise_for_status()
except RequestException as e:
r = e.response
raise ServiceError(r.status_code, r)
raise ServiceError(r.reason, r)
else:
return '{}'.format(r.url)
15 changes: 9 additions & 6 deletions plugins/core/chan_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,16 @@ def on_hook_end(error, launched_hook, launched_event, admin_log):
lines = traceback.format_exception(*error)
last_line = lines[-1]
messages.append(last_line.strip())
except Exception as e:
messages.append("Error occurred while formatting error {}: {}".format(type(e), e))
except Exception:
msg = traceback.format_exc()[-1]
messages.append("Error occurred while formatting error {}".format(msg))
else:
try:
url = web.paste('\n'.join(lines))
messages.append("Traceback: " + url)
except Exception as e:
messages.append("Error occurred while gathering traceback {}: {}".format(type(e), e))
except Exception:
msg = traceback.format_exc()[-1]
messages.append("Error occurred while gathering traceback {}".format(msg))

try:
lines = ["{} = {}".format(k, v) for k, v in _dump_attrs(launched_event)]
Expand All @@ -56,8 +58,9 @@ def on_hook_end(error, launched_hook, launched_event, admin_log):

url = web.paste('\n'.join(lines))
messages.append("Event: " + url)
except Exception as e:
messages.append("Error occurred while gathering error data {}: {}".format(type(e), e))
except Exception:
msg = traceback.format_exc()[-1]
messages.append("Error occurred while gathering error data {}".format(msg))

for message in messages:
admin_log(message, should_broadcast)
9 changes: 8 additions & 1 deletion plugins/core/check_conn.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,21 @@ def do_reconnect(conn, auto=True):
if conn.connected:
conn.quit("Reconnecting...")
yield from asyncio.sleep(5)
did_quit = True
else:
did_quit = False

if auto:
if auto and not did_quit:
coro = conn.auto_reconnect()
else:
coro = conn.connect(30)

try:
yield from coro
except asyncio.TimeoutError:
if auto:
raise

return "Connection timed out"

return "Reconnected to '{}'".format(conn.name)
Expand Down Expand Up @@ -87,6 +93,7 @@ def on_connect(conn):
conn.memory["last_activity"] = now
conn.memory["lag"] = 0
conn.memory["needs_reconnect"] = False
conn.memory['last_ping_rpl'] = now


@hook.command("lagcheck", autohelp=False, permissions=["botcontrol"])
Expand Down
10 changes: 8 additions & 2 deletions plugins/cryptocurrency.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
License:
GPL v3
"""
import asyncio
from collections import defaultdict
from datetime import datetime, timedelta
from operator import itemgetter
Expand All @@ -19,7 +20,9 @@
from yarl import URL

from cloudbot import hook
from cloudbot.event import CommandEvent
from cloudbot.util import colors, web
from cloudbot.util.func_utils import call_with_args

CURRENCY_SYMBOLS = {
'USD': '$',
Expand All @@ -38,11 +41,13 @@ class APIRateLimitError(APIError):

class TickerNotFound(APIError):
def __init__(self, name):
super().__init__(name)
self.currency = name


class CurrencyConversionError(APIError):
def __init__(self, in_name, out_name):
super().__init__(in_name, out_name)
self.in_name = in_name
self.out_name = out_name

Expand Down Expand Up @@ -153,8 +158,9 @@ def __init__(self, name, *cmds):


def alias_wrapper(alias):
def func(text, reply):
return crypto_command(" ".join((alias.name, text)), reply)
def func(text, event):
event.text = alias.name + " " + text
return call_with_args(crypto_command, event)

func.__doc__ = """- Returns the current {} value""".format(alias.name)
func.__name__ = alias.name + "_alias"
Expand Down
1 change: 1 addition & 0 deletions plugins/stock.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class APIError(Exception):

class StockSymbolNotFoundError(APIError):
def __init__(self, symbol):
super().__init__(symbol)
self.symbol = symbol


Expand Down
2 changes: 1 addition & 1 deletion tests/core_tests/test_plugin_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def test_hook_args(hook):
if hook.type in ("irc_raw", "perm_check", "periodic", "on_start", "on_stop", "event", "on_connect"):
event = Event(bot=bot)
elif hook.type == "command":
event = CommandEvent(bot=bot, hook=hook, text="", triggered_command="")
event = CommandEvent(bot=bot, hook=hook, text="", triggered_command="", cmd_prefix='.')
elif hook.type == "regex":
event = RegexEvent(bot=bot, hook=hook, match=None)
elif hook.type.startswith("on_cap"):
Expand Down

0 comments on commit 4fa4a95

Please sign in to comment.