11import asyncio
22import logging
3+ import random
34import re
45import ssl
56from _ssl import PROTOCOL_SSLv23
@@ -106,7 +107,20 @@ def describe_server(self):
106107 return "{}:{}" .format (self .server , self .port )
107108
108109 @asyncio .coroutine
109- def connect (self ):
110+ def try_connect (self ):
111+ timeout = self .config ["connection" ].get ("timeout" , 30 )
112+ while True :
113+ try :
114+ yield from self .connect (timeout )
115+ except (asyncio .TimeoutError , OSError ):
116+ logger .exception ("[%s] Error occurred while connecting" , self .name )
117+ else :
118+ break
119+
120+ yield from asyncio .sleep (random .randrange (timeout ))
121+
122+ @asyncio .coroutine
123+ def connect (self , timeout = None ):
110124 """
111125 Connects to the IRC server, or reconnects if already connected.
112126 """
@@ -125,8 +139,15 @@ def connect(self):
125139 optional_params = {}
126140 if self .local_bind :
127141 optional_params ["local_addr" ] = self .local_bind
128- self ._transport , self ._protocol = yield from self .loop .create_connection (
129- lambda : _IrcProtocol (self ), host = self .server , port = self .port , ssl = self .ssl_context , ** optional_params )
142+
143+ coro = self .loop .create_connection (
144+ lambda : _IrcProtocol (self ), host = self .server , port = self .port , ssl = self .ssl_context , ** optional_params
145+ )
146+
147+ if timeout is not None :
148+ coro = asyncio .wait_for (coro , timeout )
149+
150+ self ._transport , self ._protocol = yield from coro
130151
131152 tasks = [
132153 self .bot .plugin_manager .launch (hook , Event (bot = self .bot , conn = self , hook = hook ))
0 commit comments