Skip to content

Commit

Permalink
Use itertools to manage an infinite cycle of servers to which to connect
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Jan 4, 2019
1 parent 1bc522e commit c58407e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 14 deletions.
24 changes: 12 additions & 12 deletions irc/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
import itertools
import random

import more_itertools

import irc.client
import irc.modes
from .dict import IRCDict
Expand Down Expand Up @@ -45,6 +47,12 @@ def __repr__(self):
"with password" if self.password else "without password",
)

@classmethod
def ensure(cls, input):
spec = cls(*input) if isinstance(input, (list, tuple)) else input
assert isinstance(spec, cls)
return spec


class ReconnectStrategy(metaclass=abc.ABCMeta):
"""
Expand Down Expand Up @@ -144,16 +152,8 @@ def __init__(
super(SingleServerIRCBot, self).__init__()
self.__connect_params = connect_params
self.channels = IRCDict()
self.server_list = [
ServerSpec(*server)
if isinstance(server, (tuple, list))
else server
for server in server_list
]
assert all(
isinstance(server, ServerSpec)
for server in self.server_list
)
specs = map(ServerSpec.ensure, server_list)
self.servers = more_itertools.peekable(itertools.cycle(specs))
self.recon = recon
# for compatibility
if reconnection_interval is not missing:
Expand All @@ -174,7 +174,7 @@ def _connect(self):
"""
Establish a connection to the server at the front of the server_list.
"""
server = self.server_list[0]
server = self.servers.peek()
try:
self.connect(
server.host, server.port, self._nickname,
Expand Down Expand Up @@ -304,7 +304,7 @@ def jump_server(self, msg="Changing servers"):
if self.connection.is_connected():
self.connection.disconnect(msg)

self.server_list.append(self.server_list.pop(0))
next(self.servers)
self._connect()

def on_ctcp(self, connection, event):
Expand Down
3 changes: 1 addition & 2 deletions irc/tests/test_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,7 @@ def test_construct_bot(self):
realname='irclibbot',
nickname='irclibbot',
)
assert len(bot.server_list) == 1
svr = bot.server_list[0]
svr = bot.servers.peek()
assert svr.host == 'localhost'
assert svr.port == '9999'
assert svr.password is None
Expand Down

0 comments on commit c58407e

Please sign in to comment.