Skip to content

Commit 8dd8afd

Browse files
author
Foxlet
committed
Merge remote-tracking branch 'upstream/python3.4' into python3.4
2 parents 7806698 + e5d21a6 commit 8dd8afd

38 files changed

Lines changed: 192 additions & 779 deletions

cloudbot/__init__.py

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

33
# check python version
44
if sys.version_info < (3, 4, 0):
5-
print("CloudBot3 requires Python 3.4 or newer.")
5+
print("CloudBot requires Python 3.4 or newer.")
66
sys.exit(1)
77

88
import json
@@ -12,33 +12,22 @@
1212

1313
__version__ = "0.1.1.dev0"
1414

15-
__all__ = ["util", "bot", "connection", "config", "permissions", "plugin", "event", "hook", "dev_mode", "log_dir"]
15+
__all__ = ["util", "bot", "connection", "config", "permissions", "plugin", "event", "hook", "log_dir"]
1616

1717

1818
def _setup():
19-
default_developer_mode = {"plugin_reloading": False, "config_reloading": True,
20-
"console_debug": False, "file_debug": True}
2119
if os.path.exists(os.path.abspath("config.json")):
2220
with open(os.path.abspath("config.json")) as config_file:
2321
json_conf = json.load(config_file)
24-
developer_mode = json_conf.get("developer_mode", default_developer_mode)
22+
logging_config = json_conf.get("logging", {})
2523
else:
26-
developer_mode = default_developer_mode
24+
logging_config = {}
2725

28-
if "config_reloading" not in developer_mode:
29-
developer_mode["config_reloading"] = default_developer_mode["config_reloading"]
30-
if "plugin_reloading" not in developer_mode:
31-
developer_mode["plugin_reloading"] = default_developer_mode["plugin_reloading"]
32-
if "console_debug" not in developer_mode:
33-
developer_mode["console_debug"] = default_developer_mode["console_debug"]
34-
if "file_debug" not in developer_mode:
35-
developer_mode["file_debug"] = default_developer_mode["file_debug"]
26+
global logging_dir
27+
logging_dir = os.path.join(os.path.abspath(os.path.curdir), "logs")
3628

37-
global log_dir
38-
log_dir = os.path.join(os.path.abspath(os.path.curdir), "logs")
39-
40-
if not os.path.exists(log_dir):
41-
os.makedirs(log_dir)
29+
if not os.path.exists(logging_dir):
30+
os.makedirs(logging_dir)
4231

4332
dict_config = {
4433
"version": 1,
@@ -66,7 +55,7 @@ def _setup():
6655
"formatter": "full",
6756
"level": "INFO",
6857
"encoding": "utf-8",
69-
"filename": os.path.join(log_dir, "bot.log")
58+
"filename": os.path.join(logging_dir, "bot.log")
7059
}
7160
},
7261
"loggers": {
@@ -77,24 +66,21 @@ def _setup():
7766
}
7867
}
7968

80-
if developer_mode["console_debug"]:
69+
if logging_config.get("console_debug", False):
8170
dict_config["handlers"]["console"]["level"] = "DEBUG"
8271

83-
if developer_mode["file_debug"]:
72+
if logging_config.get("file_debug", True):
8473
dict_config["handlers"]["debug_file"] = {
8574
"class": "logging.handlers.RotatingFileHandler",
8675
"maxBytes": 1000000,
8776
"backupCount": 5,
8877
"formatter": "full",
8978
"encoding": "utf-8",
9079
"level": "DEBUG",
91-
"filename": os.path.join(log_dir, "debug.log")
80+
"filename": os.path.join(logging_dir, "debug.log")
9281
}
9382
dict_config["loggers"]["cloudbot"]["handlers"].append("debug_file")
9483

9584
logging.config.dictConfig(dict_config)
9685

97-
return developer_mode
98-
99-
100-
dev_mode = _setup()
86+
_setup()

cloudbot/__main__.py

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,16 @@
55
import time
66
import signal
77

8-
print('CloudBot3 <http://git.io/refresh>')
8+
# store the original working directory, for use when restarting
9+
original_wd = os.path.realpath(".")
910

10-
# set up environment
11-
12-
# we need to make sure we are in the install directory
11+
# set up environment - we need to make sure we are in the install directory
1312
path0 = os.path.realpath(sys.path[0] or '.')
14-
cloudbot_dir = os.path.realpath(os.path.dirname(__file__))
15-
if path0 == cloudbot_dir:
16-
sys.path[0] = path0 = os.path.dirname(cloudbot_dir)
13+
install_dir = os.path.realpath(os.path.dirname(__file__))
14+
if path0 == install_dir:
15+
sys.path[0] = path0 = os.path.dirname(install_dir)
1716
os.chdir(path0)
1817

19-
# add 'lib' to path for libraries (currently unused)
20-
if os.path.exists(os.path.abspath('lib')):
21-
sys.path += ['lib']
22-
2318
# import bot
2419
from cloudbot.bot import CloudBot
2520

@@ -31,12 +26,10 @@ def main():
3126
logging.logProcesses = 0
3227

3328
logger = logging.getLogger("cloudbot")
34-
35-
# store the original working directory, for use when restarting
36-
original_wd = os.path.realpath(".")
29+
logger.info("Starting CloudBot.")
3730

3831
# create the bot
39-
cloudbot = CloudBot()
32+
bot = CloudBot()
4033

4134
# whether we are killed while restarting
4235
stopped_while_restarting = False
@@ -47,11 +40,11 @@ def main():
4740
# define closure for signal handling
4841
def exit_gracefully(signum, frame):
4942
nonlocal stopped_while_restarting
50-
if not cloudbot:
43+
if not bot:
5144
# we are currently in the process of restarting
5245
stopped_while_restarting = True
5346
else:
54-
cloudbot.loop.call_soon_threadsafe(lambda: asyncio.async(cloudbot.stop("Killed"), loop=cloudbot.loop))
47+
bot.loop.call_soon_threadsafe(lambda: asyncio.async(bot.stop("Killed"), loop=bot.loop))
5548

5649
# restore the original handler so if they do it again it triggers
5750
signal.signal(signal.SIGINT, original_sigint)
@@ -61,12 +54,12 @@ def exit_gracefully(signum, frame):
6154
# start the bot master
6255

6356
# CloudBot.run() will return True if it should restart, False otherwise
64-
restart = cloudbot.run()
57+
restart = bot.run()
6558

6659
# the bot has stopped, do we want to restart?
6760
if restart:
6861
# remove reference to cloudbot, so exit_gracefully won't try to stop it
69-
cloudbot = None
62+
bot = None
7063
# sleep one second for timeouts
7164
time.sleep(1)
7265
if stopped_while_restarting:
@@ -75,8 +68,8 @@ def exit_gracefully(signum, frame):
7568
# actually restart
7669
os.chdir(original_wd)
7770
args = sys.argv
78-
logger.info("Restarting CloudBot")
79-
logger.debug("Restarting - arguments {}".format(args))
71+
logger.info("Restarting Bot")
72+
logger.debug("Restart arguments: {}".format(args))
8073
for f in [sys.stdout, sys.stderr]:
8174
f.flush()
8275
# close logging, and exit the program.

cloudbot/bot.py

Lines changed: 20 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from cloudbot.plugin import PluginManager
1717
from cloudbot.event import Event, CommandEvent, RegexEvent, EventType
1818
from cloudbot.util import botvars, formatting
19-
from cloudbot.irc.client import IrcClient
19+
from cloudbot.clients.irc import IrcClient
2020

2121
logger = logging.getLogger("cloudbot")
2222

@@ -71,15 +71,9 @@ def __init__(self, loop=asyncio.get_event_loop()):
7171
self.config = Config(self)
7272
logger.debug("Config system initialised.")
7373

74-
# log developer mode
75-
if cloudbot.dev_mode.get("plugin_reloading"):
76-
logger.info("Enabling developer option: plugin reloading.")
77-
if cloudbot.dev_mode.get("config_reloading"):
78-
logger.info("Enabling developer option: config reloading.")
79-
if cloudbot.dev_mode.get("console_debug"):
80-
logger.info("Enabling developer option: console debug.")
81-
if cloudbot.dev_mode.get("file_debug"):
82-
logger.info("Enabling developer option: file debug")
74+
# set values for reloading
75+
self.plugin_reloading_enabled = self.config.get("reloading", {}).get("plugin_reloading", False)
76+
self.config_reloading_enabled = self.config.get("reloading", {}).get("config_reloading", True)
8377

8478
# this doesn't REALLY need to be here but it's nice
8579
self.user_agent = self.config.get('user_agent', 'CloudBot/3.0 - CloudBot Refresh '
@@ -91,6 +85,7 @@ def __init__(self, loop=asyncio.get_event_loop()):
9185
self.db_factory = sessionmaker(bind=self.db_engine)
9286
self.db_session = scoped_session(self.db_factory)
9387
self.db_metadata = MetaData()
88+
9489
# set botvars.metadata so plugins can access when loading
9590
botvars.metadata = self.db_metadata
9691
logger.debug("Database system initialised.")
@@ -101,7 +96,7 @@ def __init__(self, loop=asyncio.get_event_loop()):
10196
# create bot connections
10297
self.create_connections()
10398

104-
if cloudbot.dev_mode.get("plugin_reloading"):
99+
if self.plugin_reloading_enabled:
105100
self.reloader = PluginReloader(self)
106101

107102
self.plugin_manager = PluginManager(self)
@@ -122,40 +117,39 @@ def run(self):
122117

123118
def create_connections(self):
124119
""" Create a BotConnection for all the networks defined in the config """
125-
for conf in self.config['connections']:
120+
for config in self.config['connections']:
126121
# strip all spaces and capitalization from the connection name
127-
readable_name = conf['name']
128-
name = clean_name(readable_name)
129-
nick = conf['nick']
130-
server = conf['connection']['server']
131-
port = conf['connection'].get('port', 6667)
132-
local_bind = (conf['connection'].get('bind_addr', False), conf['connection'].get('bind_port', 0))
122+
name = clean_name(config['name'])
123+
nick = config['nick']
124+
server = config['connection']['server']
125+
port = config['connection'].get('port', 6667)
126+
local_bind = (config['connection'].get('bind_addr', False), config['connection'].get('bind_port', 0))
133127
if local_bind[0] is False:
134128
local_bind = False
135129

136-
self.connections.append(IrcClient(self, name, nick, config=conf, channels=conf['channels'],
137-
readable_name=readable_name, server=server, port=port,
138-
use_ssl=conf['connection'].get('ssl', False), local_bind=local_bind))
139-
logger.debug("[{}] Created connection.".format(readable_name))
130+
self.connections.append(IrcClient(self, name, nick, config=config, channels=config['channels'],
131+
server=server, port=port, use_ssl=config['connection'].get('ssl', False),
132+
local_bind=local_bind))
133+
logger.debug("[{}] Created connection.".format(name))
140134

141135
@asyncio.coroutine
142136
def stop(self, reason=None, *, restart=False):
143137
"""quits all networks and shuts the bot down"""
144138
logger.info("Stopping bot.")
145139

146-
if cloudbot.dev_mode.get("config_reloading"):
140+
if self.config_reloading_enabled:
147141
logger.debug("Stopping config reloader.")
148142
self.config.stop()
149143

150-
if cloudbot.dev_mode.get("plugin_reloading"):
144+
if self.plugin_reloading_enabled:
151145
logger.debug("Stopping plugin reloader.")
152146
self.reloader.stop()
153147

154148
for connection in self.connections:
155149
if not connection.connected:
156150
# Don't quit a connection that hasn't connected
157151
continue
158-
logger.debug("[{}] Closing connection.".format(connection.readable_name))
152+
logger.debug("[{}] Closing connection.".format(connection.name))
159153

160154
connection.quit(reason)
161155

@@ -186,7 +180,7 @@ def _init_routine(self):
186180
logger.info("Killed while loading, exiting")
187181
return
188182

189-
if cloudbot.dev_mode.get("plugin_reloading"):
183+
if self.plugin_reloading_enabled:
190184
# start plugin reloader
191185
self.reloader.start(os.path.abspath("plugins"))
192186

cloudbot/client.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ class Client:
1212
:type bot: cloudbot.bot.CloudBot
1313
:type loop: asyncio.events.AbstractEventLoop
1414
:type name: str
15-
:type readable_name: str
1615
:type channels: list[str]
1716
:type config: dict[str, unknown]
1817
:type nick: str
@@ -21,11 +20,10 @@ class Client:
2120
:type permissions: PermissionManager
2221
"""
2322

24-
def __init__(self, bot, name, nick, *, readable_name, channels=None, config=None):
23+
def __init__(self, bot, name, nick, *, channels=None, config=None):
2524
"""
2625
:type bot: cloudbot.bot.CloudBot
2726
:type name: str
28-
:type readable_name: str
2927
:type nick: str
3028
:type channels: list[str]
3129
:type config: dict[str, unknown]
@@ -34,7 +32,6 @@ def __init__(self, bot, name, nick, *, readable_name, channels=None, config=None
3432
self.loop = bot.loop
3533
self.name = name
3634
self.nick = nick
37-
self.readable_name = readable_name
3835

3936
if channels is None:
4037
self.channels = []
Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,11 @@ class IrcClient(Client):
4646
:type _ignore_cert_errors: bool
4747
"""
4848

49-
def __init__(self, bot, name, nick, *, readable_name, channels=None, config=None,
49+
def __init__(self, bot, name, nick, *, channels=None, config=None,
5050
server, port=6667, use_ssl=False, ignore_cert_errors=True, timeout=300, local_bind=False):
5151
"""
5252
:type bot: cloudbot.bot.CloudBot
5353
:type name: str
54-
:type readable_name: str
5554
:type nick: str
5655
:type channels: list[str]
5756
:type config: dict[str, unknown]
@@ -61,7 +60,7 @@ def __init__(self, bot, name, nick, *, readable_name, channels=None, config=None
6160
:type ignore_cert_errors: bool
6261
:type timeout: int
6362
"""
64-
super().__init__(bot, name, nick, readable_name=readable_name, channels=channels, config=config)
63+
super().__init__(bot, name, nick, channels=channels, config=config)
6564

6665
self.use_ssl = use_ssl
6766
self._ignore_cert_errors = ignore_cert_errors
@@ -99,18 +98,18 @@ def connect(self):
9998
"""
10099
Connects to the IRC server, or reconnects if already connected.
101100
"""
102-
# connect to the irc server
101+
# connect to the clients server
103102
if self._quit:
104103
# we've quit, so close instead (because this has probably been called because of EOF received)
105104
self.close()
106105
return
107106

108107
if self._connected:
109-
logger.info("[{}] Reconnecting".format(self.readable_name))
108+
logger.info("[{}] Reconnecting".format(self.name))
110109
self._transport.close()
111110
else:
112111
self._connected = True
113-
logger.info("[{}] Connecting".format(self.readable_name))
112+
logger.info("[{}] Connecting".format(self.name))
114113
optional_params = {}
115114
if self.local_bind:
116115
optional_params["local_addr"] = self.local_bind
@@ -208,7 +207,7 @@ def _send(self, line):
208207
Sends a raw IRC line unchecked. Doesn't do connected check, and is *not* threadsafe
209208
:type line: str
210209
"""
211-
logger.info("[{}] >> {}".format(self.readable_name, line))
210+
logger.info("[{}] >> {}".format(self.name, line))
212211
asyncio.async(self._protocol.send(line), loop=self.loop)
213212

214213

@@ -262,14 +261,14 @@ def connection_lost(self, exc):
262261
if exc is None:
263262
# we've been closed intentionally, so don't reconnect
264263
return
265-
logger.error("[{}] Connection lost: {}".format(self.conn.readable_name, exc))
264+
logger.error("[{}] Connection lost: {}".format(self.conn.name, exc))
266265
asyncio.async(self.conn.connect(), loop=self.loop)
267266

268267
def eof_received(self):
269268
self._connected = False
270269
# create a new connected_future for when we are connected.
271270
self._connected_future = asyncio.Future(loop=self.loop)
272-
logger.info("[{}] EOF received.".format(self.conn.readable_name))
271+
logger.info("[{}] EOF received.".format(self.conn.name))
273272
asyncio.async(self.conn.connect(), loop=self.loop)
274273
return True
275274

@@ -294,7 +293,7 @@ def data_received(self, data):
294293
prefix_line_match = irc_prefix_re.match(line)
295294
if prefix_line_match is None:
296295
logger.critical("[{}] Received invalid IRC line '{}' from {}".format(
297-
self.conn.readable_name, line, self.conn.describe_server()))
296+
self.conn.name, line, self.conn.describe_server()))
298297
continue
299298

300299
netmask_prefix, command, params = prefix_line_match.groups()
@@ -316,7 +315,7 @@ def data_received(self, data):
316315
noprefix_line_match = irc_noprefix_re.match(line)
317316
if noprefix_line_match is None:
318317
logger.critical("[{}] Received invalid IRC line '{}' from {}".format(
319-
self.conn.readable_name, line, self.conn.describe_server()))
318+
self.conn.name, line, self.conn.describe_server()))
320319
continue
321320
command = noprefix_line_match.group(1)
322321
params = noprefix_line_match.group(2)

0 commit comments

Comments
 (0)