idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
23,700 | async def part ( self , channel , message = None ) : if not self . in_channel ( channel ) : raise NotInChannel ( channel ) # Message seems to be an extension to the spec. if message : await self . rawmsg ( 'PART' , channel , message ) else : await self . rawmsg ( 'PART' , channel ) | Leave channel optionally with message . | 74 | 6 |
23,701 | async def kick ( self , channel , target , reason = None ) : if not self . in_channel ( channel ) : raise NotInChannel ( channel ) if reason : await self . rawmsg ( 'KICK' , channel , target , reason ) else : await self . rawmsg ( 'KICK' , channel , target ) | Kick user from channel . | 71 | 5 |
23,702 | async def unban ( self , channel , target , range = 0 ) : if target in self . users : host = self . users [ target ] [ 'hostname' ] else : host = target host = self . _format_host_range ( host , range ) mask = self . _format_host_mask ( '*' , '*' , host ) await self . rawmsg ( 'MODE' , channel , '-b' , mask ) | Unban user from channel . Target can be either a user or a host . See ban documentation for the range parameter . | 98 | 24 |
23,703 | async def kickban ( self , channel , target , reason = None , range = 0 ) : await self . ban ( channel , target , range ) await self . kick ( channel , target , reason ) | Kick and ban user from channel . | 43 | 7 |
23,704 | async def quit ( self , message = None ) : if message is None : message = self . DEFAULT_QUIT_MESSAGE await self . rawmsg ( 'QUIT' , message ) await self . disconnect ( expected = True ) | Quit network . | 53 | 4 |
23,705 | async def cycle ( self , channel ) : if not self . in_channel ( channel ) : raise NotInChannel ( channel ) password = self . channels [ channel ] [ 'password' ] await self . part ( channel ) await self . join ( channel , password ) | Rejoin channel . | 57 | 4 |
23,706 | async def message ( self , target , message ) : hostmask = self . _format_user_mask ( self . nickname ) # Leeway. chunklen = protocol . MESSAGE_LENGTH_LIMIT - len ( '{hostmask} PRIVMSG {target} :' . format ( hostmask = hostmask , target = target ) ) - 25 for line in message . replace ( '\r' , '' ) . split ( '\n' ) : for chunk in chunkify ( line , chunklen ) : # Some IRC servers respond with "412 Bot :No text to send" on empty messages. await self . rawmsg ( 'PRIVMSG' , target , chunk or ' ' ) | Message channel or user . | 155 | 5 |
23,707 | async def set_topic ( self , channel , topic ) : if not self . is_channel ( channel ) : raise ValueError ( 'Not a channel: {}' . format ( channel ) ) elif not self . in_channel ( channel ) : raise NotInChannel ( channel ) await self . rawmsg ( 'TOPIC' , channel , topic ) | Set topic on channel . Users should only rely on the topic actually being changed when receiving an on_topic_change callback . | 76 | 25 |
23,708 | async def on_raw_error ( self , message ) : error = protocol . ServerError ( ' ' . join ( message . params ) ) await self . on_data_error ( error ) | Server encountered an error and will now close the connection . | 42 | 11 |
23,709 | async def on_raw_invite ( self , message ) : nick , metadata = self . _parse_user ( message . source ) self . _sync_user ( nick , metadata ) target , channel = message . params target , metadata = self . _parse_user ( target ) if self . is_same_nick ( self . nickname , target ) : await self . on_invite ( channel , nick ) else : await self . on_user_invite ( target , channel , nick ) | INVITE command . | 107 | 5 |
23,710 | async def on_raw_join ( self , message ) : nick , metadata = self . _parse_user ( message . source ) self . _sync_user ( nick , metadata ) channels = message . params [ 0 ] . split ( ',' ) if self . is_same_nick ( self . nickname , nick ) : # Add to our channel list, we joined here. for channel in channels : if not self . in_channel ( channel ) : self . _create_channel ( channel ) # Request channel mode from IRCd. await self . rawmsg ( 'MODE' , channel ) else : # Add user to channel user list. for channel in channels : if self . in_channel ( channel ) : self . channels [ channel ] [ 'users' ] . add ( nick ) for channel in channels : await self . on_join ( channel , nick ) | JOIN command . | 183 | 4 |
23,711 | async def on_raw_kick ( self , message ) : kicker , kickermeta = self . _parse_user ( message . source ) self . _sync_user ( kicker , kickermeta ) if len ( message . params ) > 2 : channels , targets , reason = message . params else : channels , targets = message . params reason = None channels = channels . split ( ',' ) targets = targets . split ( ',' ) for channel , target in itertools . product ( channels , targets ) : target , targetmeta = self . _parse_user ( target ) self . _sync_user ( target , targetmeta ) if self . is_same_nick ( target , self . nickname ) : self . _destroy_channel ( channel ) else : # Update nick list on channel. if self . in_channel ( channel ) : self . _destroy_user ( target , channel ) await self . on_kick ( channel , target , kicker , reason ) | KICK command . | 203 | 4 |
23,712 | async def on_raw_kill ( self , message ) : by , bymeta = self . _parse_user ( message . source ) target , targetmeta = self . _parse_user ( message . params [ 0 ] ) reason = message . params [ 1 ] self . _sync_user ( target , targetmeta ) if by in self . users : self . _sync_user ( by , bymeta ) await self . on_kill ( target , by , reason ) if self . is_same_nick ( self . nickname , target ) : await self . disconnect ( expected = False ) else : self . _destroy_user ( target ) | KILL command . | 137 | 4 |
23,713 | async def on_raw_mode ( self , message ) : nick , metadata = self . _parse_user ( message . source ) target , modes = message . params [ 0 ] , message . params [ 1 : ] self . _sync_user ( nick , metadata ) if self . is_channel ( target ) : if self . in_channel ( target ) : # Parse modes. self . channels [ target ] [ 'modes' ] = self . _parse_channel_modes ( target , modes ) await self . on_mode_change ( target , modes , nick ) else : target , targetmeta = self . _parse_user ( target ) self . _sync_user ( target , targetmeta ) # Update own modes. if self . is_same_nick ( self . nickname , nick ) : self . _mode = self . _parse_user_modes ( nick , modes , current = self . _mode ) await self . on_user_mode_change ( modes ) | MODE command . | 213 | 3 |
23,714 | async def on_raw_nick ( self , message ) : nick , metadata = self . _parse_user ( message . source ) new = message . params [ 0 ] self . _sync_user ( nick , metadata ) # Acknowledgement of nickname change: set it internally, too. # Alternatively, we were force nick-changed. Nothing much we can do about it. if self . is_same_nick ( self . nickname , nick ) : self . nickname = new # Go through all user lists and replace. self . _rename_user ( nick , new ) # Call handler. await self . on_nick_change ( nick , new ) | NICK command . | 139 | 4 |
23,715 | async def on_raw_notice ( self , message ) : nick , metadata = self . _parse_user ( message . source ) target , message = message . params self . _sync_user ( nick , metadata ) await self . on_notice ( target , nick , message ) if self . is_channel ( target ) : await self . on_channel_notice ( target , nick , message ) else : await self . on_private_notice ( target , nick , message ) | NOTICE command . | 102 | 4 |
23,716 | async def on_raw_part ( self , message ) : nick , metadata = self . _parse_user ( message . source ) channels = message . params [ 0 ] . split ( ',' ) if len ( message . params ) > 1 : reason = message . params [ 1 ] else : reason = None self . _sync_user ( nick , metadata ) if self . is_same_nick ( self . nickname , nick ) : # We left the channel. Remove from channel list. :( for channel in channels : if self . in_channel ( channel ) : self . _destroy_channel ( channel ) await self . on_part ( channel , nick , reason ) else : # Someone else left. Remove them. for channel in channels : self . _destroy_user ( nick , channel ) await self . on_part ( channel , nick , reason ) | PART command . | 181 | 3 |
23,717 | async def on_raw_privmsg ( self , message ) : nick , metadata = self . _parse_user ( message . source ) target , message = message . params self . _sync_user ( nick , metadata ) await self . on_message ( target , nick , message ) if self . is_channel ( target ) : await self . on_channel_message ( target , nick , message ) else : await self . on_private_message ( target , nick , message ) | PRIVMSG command . | 103 | 6 |
23,718 | async def on_raw_quit ( self , message ) : nick , metadata = self . _parse_user ( message . source ) self . _sync_user ( nick , metadata ) if message . params : reason = message . params [ 0 ] else : reason = None await self . on_quit ( nick , reason ) # Remove user from database. if not self . is_same_nick ( self . nickname , nick ) : self . _destroy_user ( nick ) # Else, we quit. elif self . connected : await self . disconnect ( expected = True ) | QUIT command . | 122 | 4 |
23,719 | async def on_raw_topic ( self , message ) : setter , settermeta = self . _parse_user ( message . source ) target , topic = message . params self . _sync_user ( setter , settermeta ) # Update topic in our own channel list. if self . in_channel ( target ) : self . channels [ target ] [ 'topic' ] = topic self . channels [ target ] [ 'topic_by' ] = setter self . channels [ target ] [ 'topic_set' ] = datetime . datetime . now ( ) await self . on_topic_change ( target , topic , setter ) | TOPIC command . | 140 | 4 |
23,720 | async def on_raw_004 ( self , message ) : target , hostname , ircd , user_modes , channel_modes = message . params [ : 5 ] # Set valid channel and user modes. self . _channel_modes = set ( channel_modes ) self . _user_modes = set ( user_modes ) | Basic server information . | 78 | 4 |
23,721 | async def on_raw_301 ( self , message ) : target , nickname , message = message . params info = { 'away' : True , 'away_message' : message } if nickname in self . users : self . _sync_user ( nickname , info ) if nickname in self . _pending [ 'whois' ] : self . _whois_info [ nickname ] . update ( info ) | User is away . | 88 | 4 |
23,722 | async def on_raw_311 ( self , message ) : target , nickname , username , hostname , _ , realname = message . params info = { 'username' : username , 'hostname' : hostname , 'realname' : realname } self . _sync_user ( nickname , info ) if nickname in self . _pending [ 'whois' ] : self . _whois_info [ nickname ] . update ( info ) | WHOIS user info . | 97 | 5 |
23,723 | async def on_raw_312 ( self , message ) : target , nickname , server , serverinfo = message . params info = { 'server' : server , 'server_info' : serverinfo } if nickname in self . _pending [ 'whois' ] : self . _whois_info [ nickname ] . update ( info ) if nickname in self . _pending [ 'whowas' ] : self . _whowas_info [ nickname ] . update ( info ) | WHOIS server info . | 106 | 5 |
23,724 | async def on_raw_313 ( self , message ) : target , nickname = message . params [ : 2 ] info = { 'oper' : True } if nickname in self . _pending [ 'whois' ] : self . _whois_info [ nickname ] . update ( info ) | WHOIS operator info . | 64 | 5 |
23,725 | async def on_raw_314 ( self , message ) : target , nickname , username , hostname , _ , realname = message . params info = { 'username' : username , 'hostname' : hostname , 'realname' : realname } if nickname in self . _pending [ 'whowas' ] : self . _whowas_info [ nickname ] . update ( info ) | WHOWAS user info . | 88 | 6 |
23,726 | async def on_raw_317 ( self , message ) : target , nickname , idle_time = message . params [ : 3 ] info = { 'idle' : int ( idle_time ) , } if nickname in self . _pending [ 'whois' ] : self . _whois_info [ nickname ] . update ( info ) | WHOIS idle time . | 75 | 5 |
23,727 | async def on_raw_319 ( self , message ) : target , nickname , channels = message . params [ : 3 ] channels = { channel . lstrip ( ) for channel in channels . strip ( ) . split ( ' ' ) } info = { 'channels' : channels } if nickname in self . _pending [ 'whois' ] : self . _whois_info [ nickname ] . update ( info ) | WHOIS active channels . | 91 | 5 |
23,728 | async def on_raw_324 ( self , message ) : target , channel = message . params [ : 2 ] modes = message . params [ 2 : ] if not self . in_channel ( channel ) : return self . channels [ channel ] [ 'modes' ] = self . _parse_channel_modes ( channel , modes ) | Channel mode . | 73 | 3 |
23,729 | async def on_raw_329 ( self , message ) : target , channel , timestamp = message . params if not self . in_channel ( channel ) : return self . channels [ channel ] [ 'created' ] = datetime . datetime . fromtimestamp ( int ( timestamp ) ) | Channel creation time . | 62 | 4 |
23,730 | async def on_raw_332 ( self , message ) : target , channel , topic = message . params if not self . in_channel ( channel ) : return self . channels [ channel ] [ 'topic' ] = topic | Current topic on channel join . | 48 | 6 |
23,731 | async def on_raw_333 ( self , message ) : target , channel , setter , timestamp = message . params if not self . in_channel ( channel ) : return # No need to sync user since this is most likely outdated info. self . channels [ channel ] [ 'topic_by' ] = self . _parse_user ( setter ) [ 0 ] self . channels [ channel ] [ 'topic_set' ] = datetime . datetime . fromtimestamp ( int ( timestamp ) ) | Topic setter and time on channel join . | 108 | 9 |
23,732 | async def on_raw_375 ( self , message ) : await self . _registration_completed ( message ) self . motd = message . params [ 1 ] + '\n' | Start message of the day . | 42 | 6 |
23,733 | async def on_raw_422 ( self , message ) : await self . _registration_completed ( message ) self . motd = None await self . on_connect ( ) | MOTD is missing . | 40 | 6 |
23,734 | async def on_raw_433 ( self , message ) : if not self . registered : self . _registration_attempts += 1 # Attempt to set new nickname. if self . _attempt_nicknames : await self . set_nickname ( self . _attempt_nicknames . pop ( 0 ) ) else : await self . set_nickname ( self . _nicknames [ 0 ] + '_' * ( self . _registration_attempts - len ( self . _nicknames ) ) ) | Nickname in use . | 114 | 5 |
23,735 | async def connect ( self , hostname = None , port = None , tls = False , * * kwargs ) : if not port : if tls : port = DEFAULT_TLS_PORT else : port = rfc1459 . protocol . DEFAULT_PORT return await super ( ) . connect ( hostname , port , tls = tls , * * kwargs ) | Connect to a server optionally over TLS . See pydle . features . RFC1459Support . connect for misc parameters . | 85 | 25 |
23,736 | async def _connect ( self , hostname , port , reconnect = False , password = None , encoding = pydle . protocol . DEFAULT_ENCODING , channels = [ ] , tls = False , tls_verify = False , source_address = None ) : self . password = password # Create connection if we can't reuse it. if not reconnect : self . _autojoin_channels = channels self . connection = connection . Connection ( hostname , port , source_address = source_address , tls = tls , tls_verify = tls_verify , tls_certificate_file = self . tls_client_cert , tls_certificate_keyfile = self . tls_client_cert_key , tls_certificate_password = self . tls_client_cert_password , eventloop = self . eventloop ) self . encoding = encoding # Connect. await self . connection . connect ( ) | Connect to IRC server optionally over TLS . | 209 | 8 |
23,737 | def _reset_attributes ( self ) : # Record-keeping. self . channels = { } self . users = { } # Low-level data stuff. self . _receive_buffer = b'' self . _pending = { } self . _handler_top_level = False self . _ping_checker_handle = None # Misc. self . logger = logging . getLogger ( __name__ ) # Public connection attributes. self . nickname = DEFAULT_NICKNAME self . network = None | Reset attributes . | 110 | 4 |
23,738 | def _reset_connection_attributes ( self ) : self . connection = None self . encoding = None self . _autojoin_channels = [ ] self . _reconnect_attempts = 0 | Reset connection attributes . | 44 | 5 |
23,739 | def run ( self , * args , * * kwargs ) : self . eventloop . run_until_complete ( self . connect ( * args , * * kwargs ) ) try : self . eventloop . run_forever ( ) finally : self . eventloop . stop ( ) | Connect and run bot in event loop . | 63 | 8 |
23,740 | async def connect ( self , hostname = None , port = None , reconnect = False , * * kwargs ) : if ( not hostname or not port ) and not reconnect : raise ValueError ( 'Have to specify hostname and port if not reconnecting.' ) # Disconnect from current connection. if self . connected : await self . disconnect ( expected = True ) # Reset attributes and connect. if not reconnect : self . _reset_connection_attributes ( ) await self . _connect ( hostname = hostname , port = port , reconnect = reconnect , * * kwargs ) # Set logger name. if self . server_tag : self . logger = logging . getLogger ( self . __class__ . __name__ + ':' + self . server_tag ) self . eventloop . create_task ( self . handle_forever ( ) ) | Connect to IRC server . | 185 | 5 |
23,741 | async def _connect ( self , hostname , port , reconnect = False , channels = [ ] , encoding = protocol . DEFAULT_ENCODING , source_address = None ) : # Create connection if we can't reuse it. if not reconnect or not self . connection : self . _autojoin_channels = channels self . connection = connection . Connection ( hostname , port , source_address = source_address , eventloop = self . eventloop ) self . encoding = encoding # Connect. await self . connection . connect ( ) | Connect to IRC host . | 114 | 5 |
23,742 | def _reconnect_delay ( self ) : if self . RECONNECT_ON_ERROR and self . RECONNECT_DELAYED : if self . _reconnect_attempts >= len ( self . RECONNECT_DELAYS ) : return self . RECONNECT_DELAYS [ - 1 ] else : return self . RECONNECT_DELAYS [ self . _reconnect_attempts ] else : return 0 | Calculate reconnection delay . | 100 | 7 |
23,743 | async def _perform_ping_timeout ( self , delay : int ) : # pause for delay seconds await sleep ( delay ) # then continue error = TimeoutError ( 'Ping timeout: no data received from server in {timeout} seconds.' . format ( timeout = self . PING_TIMEOUT ) ) await self . on_data_error ( error ) | Handle timeout gracefully . | 77 | 5 |
23,744 | async def rawmsg ( self , command , * args , * * kwargs ) : message = str ( self . _create_message ( command , * args , * * kwargs ) ) await self . _send ( message ) | Send raw message . | 51 | 4 |
23,745 | async def handle_forever ( self ) : while self . connected : data = await self . connection . recv ( ) if not data : if self . connected : await self . disconnect ( expected = False ) break await self . on_data ( data ) | Handle data forever . | 55 | 4 |
23,746 | async def on_data_error ( self , exception ) : self . logger . error ( 'Encountered error on socket.' , exc_info = ( type ( exception ) , exception , None ) ) await self . disconnect ( expected = False ) | Handle error . | 53 | 3 |
23,747 | async def on_raw ( self , message ) : self . logger . debug ( '<< %s' , message . _raw ) if not message . _valid : self . logger . warning ( 'Encountered strictly invalid IRC message from server: %s' , message . _raw ) if isinstance ( message . command , int ) : cmd = str ( message . command ) . zfill ( 3 ) else : cmd = message . command # Invoke dispatcher, if we have one. method = 'on_raw_' + cmd . lower ( ) try : # Set _top_level so __getattr__() can decide whether to return on_unknown or _ignored for unknown handlers. # The reason for this is that features can always call super().on_raw_* safely and thus don't need to care for other features, # while unknown messages for which no handlers exist at all are still logged. self . _handler_top_level = True handler = getattr ( self , method ) self . _handler_top_level = False await handler ( message ) except : self . logger . exception ( 'Failed to execute %s handler.' , method ) | Handle a single message . | 247 | 5 |
23,748 | async def on_unknown ( self , message ) : self . logger . warning ( 'Unknown command: [%s] %s %s' , message . source , message . command , message . params ) | Unknown command . | 44 | 3 |
23,749 | def connect ( self , client : BasicClient , * args , * * kwargs ) : self . clients . add ( client ) self . connect_args [ client ] = ( args , kwargs ) # hack the clients event loop to use the pools own event loop client . eventloop = self . eventloop | Add client to pool . | 66 | 5 |
23,750 | def disconnect ( self , client ) : self . clients . remove ( client ) del self . connect_args [ client ] client . disconnect ( ) | Remove client from pool . | 30 | 5 |
23,751 | def normalize ( input , case_mapping = protocol . DEFAULT_CASE_MAPPING ) : if case_mapping not in protocol . CASE_MAPPINGS : raise pydle . protocol . ProtocolViolation ( 'Unknown case mapping ({})' . format ( case_mapping ) ) input = input . lower ( ) if case_mapping in ( 'rfc1459' , 'rfc1459-strict' ) : input = input . replace ( '{' , '[' ) . replace ( '}' , ']' ) . replace ( '|' , '\\' ) if case_mapping == 'rfc1459' : input = input . replace ( '~' , '^' ) return input | Normalize input according to case mapping . | 161 | 8 |
23,752 | def parse_user ( raw ) : nick = raw user = None host = None # Attempt to extract host. if protocol . HOST_SEPARATOR in raw : raw , host = raw . split ( protocol . HOST_SEPARATOR ) # Attempt to extract user. if protocol . USER_SEPARATOR in raw : nick , user = raw . split ( protocol . USER_SEPARATOR ) return nick , user , host | Parse nick ( !user ( | 93 | 7 |
23,753 | def parse ( cls , line , encoding = pydle . protocol . DEFAULT_ENCODING ) : valid = True # Decode message. try : message = line . decode ( encoding ) except UnicodeDecodeError : # Try our fallback encoding. message = line . decode ( pydle . protocol . FALLBACK_ENCODING ) # Sanity check for message length. if len ( message ) > protocol . MESSAGE_LENGTH_LIMIT : valid = False # Strip message separator. if message . endswith ( protocol . LINE_SEPARATOR ) : message = message [ : - len ( protocol . LINE_SEPARATOR ) ] elif message . endswith ( protocol . MINIMAL_LINE_SEPARATOR ) : message = message [ : - len ( protocol . MINIMAL_LINE_SEPARATOR ) ] # Sanity check for forbidden characters. if any ( ch in message for ch in protocol . FORBIDDEN_CHARACTERS ) : valid = False # Extract message sections. # Format: (:source)? command parameter* if message . startswith ( ':' ) : parts = protocol . ARGUMENT_SEPARATOR . split ( message [ 1 : ] , 2 ) else : parts = [ None ] + protocol . ARGUMENT_SEPARATOR . split ( message , 1 ) if len ( parts ) == 3 : source , command , raw_params = parts elif len ( parts ) == 2 : source , command = parts raw_params = '' else : raise pydle . protocol . ProtocolViolation ( 'Improper IRC message format: not enough elements.' , message = message ) # Sanity check for command. if not protocol . COMMAND_PATTERN . match ( command ) : valid = False # Extract parameters properly. # Format: (word|:sentence)* # Only parameter is a 'trailing' sentence. if raw_params . startswith ( protocol . TRAILING_PREFIX ) : params = [ raw_params [ len ( protocol . TRAILING_PREFIX ) : ] ] # We have a sentence in our parameters. elif ' ' + protocol . TRAILING_PREFIX in raw_params : index = raw_params . find ( ' ' + protocol . TRAILING_PREFIX ) # Get all single-word parameters. params = protocol . ARGUMENT_SEPARATOR . split ( raw_params [ : index ] . rstrip ( ' ' ) ) # Extract last parameter as sentence params . append ( raw_params [ index + len ( protocol . TRAILING_PREFIX ) + 1 : ] ) # We have some parameters, but no sentences. elif raw_params : params = protocol . ARGUMENT_SEPARATOR . split ( raw_params ) # No parameters. else : params = [ ] # Commands can be either [a-zA-Z]+ or [0-9]+. # In the former case, force it to uppercase. # In the latter case (a numeric command), try to represent it as such. try : command = int ( command ) except ValueError : command = command . upper ( ) # Return parsed message. return RFC1459Message ( command , params , source = source , _valid = valid , _raw = message ) | Parse given line into IRC message structure . Returns a Message . | 715 | 13 |
23,754 | def construct ( self , force = False ) : # Sanity check for command. command = str ( self . command ) if not protocol . COMMAND_PATTERN . match ( command ) and not force : raise pydle . protocol . ProtocolViolation ( 'The constructed command does not follow the command pattern ({pat})' . format ( pat = protocol . COMMAND_PATTERN . pattern ) , message = command ) message = command . upper ( ) # Add parameters. if not self . params : message += ' ' for idx , param in enumerate ( self . params ) : # Trailing parameter? if not param or ' ' in param or param [ 0 ] == ':' : if idx + 1 < len ( self . params ) and not force : raise pydle . protocol . ProtocolViolation ( 'Only the final parameter of an IRC message can be trailing and thus contain spaces, or start with a colon.' , message = param ) message += ' ' + protocol . TRAILING_PREFIX + param # Regular parameter. else : message += ' ' + param # Prepend source. if self . source : message = ':' + self . source + ' ' + message # Sanity check for characters. if any ( ch in message for ch in protocol . FORBIDDEN_CHARACTERS ) and not force : raise pydle . protocol . ProtocolViolation ( 'The constructed message contains forbidden characters ({chs}).' . format ( chs = ', ' . join ( protocol . FORBIDDEN_CHARACTERS ) ) , message = message ) # Sanity check for length. message += protocol . LINE_SEPARATOR if len ( message ) > protocol . MESSAGE_LENGTH_LIMIT and not force : raise pydle . protocol . ProtocolViolation ( 'The constructed message is too long. ({len} > {maxlen})' . format ( len = len ( message ) , maxlen = protocol . MESSAGE_LENGTH_LIMIT ) , message = message ) return message | Construct a raw IRC message . | 437 | 6 |
23,755 | def featurize ( * features ) : from functools import cmp_to_key def compare_subclass ( left , right ) : if issubclass ( left , right ) : return - 1 elif issubclass ( right , left ) : return 1 return 0 sorted_features = sorted ( features , key = cmp_to_key ( compare_subclass ) ) name = 'FeaturizedClient[{features}]' . format ( features = ', ' . join ( feature . __name__ for feature in sorted_features ) ) return type ( name , tuple ( sorted_features ) , { } ) | Put features into proper MRO order . | 132 | 8 |
23,756 | async def on_raw_join ( self , message ) : await super ( ) . on_raw_join ( message ) nick , metadata = self . _parse_user ( message . source ) channels = message . params [ 0 ] . split ( ',' ) if self . is_same_nick ( self . nickname , nick ) : # We joined. if 'WHOX' in self . _isupport and self . _isupport [ 'WHOX' ] : # Get more relevant channel info thanks to WHOX. await self . rawmsg ( 'WHO' , ',' . join ( channels ) , '%tnurha,{id}' . format ( id = WHOX_IDENTIFIER ) ) else : # Find account name of person. pass | Override JOIN to send WHOX . | 162 | 8 |
23,757 | async def on_raw_354 ( self , message ) : # Is the message for us? target , identifier = message . params [ : 2 ] if identifier != WHOX_IDENTIFIER : return # Great. Extract relevant information. metadata = { 'nickname' : message . params [ 4 ] , 'username' : message . params [ 2 ] , 'realname' : message . params [ 6 ] , 'hostname' : message . params [ 3 ] , } if message . params [ 5 ] != NO_ACCOUNT : metadata [ 'identified' ] = True metadata [ 'account' ] = message . params [ 5 ] self . _sync_user ( metadata [ 'nickname' ] , metadata ) | WHOX results have arrived . | 152 | 6 |
23,758 | def _create_channel ( self , channel ) : super ( ) . _create_channel ( channel ) if 'EXCEPTS' in self . _isupport : self . channels [ channel ] [ 'exceptlist' ] = None if 'INVEX' in self . _isupport : self . channels [ channel ] [ 'inviteexceptlist' ] = None | Create channel with optional ban and invite exception lists . | 79 | 10 |
23,759 | async def on_raw_005 ( self , message ) : isupport = { } # Parse response. # Strip target (first argument) and 'are supported by this server' (last argument). for feature in message . params [ 1 : - 1 ] : if feature . startswith ( FEATURE_DISABLED_PREFIX ) : value = False elif '=' in feature : feature , value = feature . split ( '=' , 1 ) else : value = True isupport [ feature . upper ( ) ] = value # Update internal dict first. self . _isupport . update ( isupport ) # And have callbacks update other internals. for entry , value in isupport . items ( ) : if value != False : # A value of True technically means there was no value supplied; correct this for callbacks. if value == True : value = None method = 'on_isupport_' + pydle . protocol . identifierify ( entry ) if hasattr ( self , method ) : await getattr ( self , method ) ( value ) | ISUPPORT indication . | 230 | 5 |
23,760 | async def on_isupport_casemapping ( self , value ) : if value in rfc1459 . protocol . CASE_MAPPINGS : self . _case_mapping = value self . channels = rfc1459 . parsing . NormalizingDict ( self . channels , case_mapping = value ) self . users = rfc1459 . parsing . NormalizingDict ( self . users , case_mapping = value ) | IRC case mapping for nickname and channel name comparisons . | 96 | 10 |
23,761 | async def on_isupport_chanlimit ( self , value ) : self . _channel_limits = { } for entry in value . split ( ',' ) : types , limit = entry . split ( ':' ) # Assign limit to channel type group and add lookup entry for type. self . _channel_limits [ frozenset ( types ) ] = int ( limit ) for prefix in types : self . _channel_limit_groups [ prefix ] = frozenset ( types ) | Simultaneous channel limits for user . | 104 | 8 |
23,762 | async def on_isupport_chanmodes ( self , value ) : list , param , param_set , noparams = [ set ( modes ) for modes in value . split ( ',' ) [ : 4 ] ] self . _channel_modes . update ( set ( value . replace ( ',' , '' ) ) ) # The reason we have to do it like this is because other ISUPPORTs (e.g. PREFIX) may update these values as well. if not rfc1459 . protocol . BEHAVIOUR_LIST in self . _channel_modes_behaviour : self . _channel_modes_behaviour [ rfc1459 . protocol . BEHAVIOUR_LIST ] = set ( ) self . _channel_modes_behaviour [ rfc1459 . protocol . BEHAVIOUR_LIST ] . update ( list ) if not rfc1459 . protocol . BEHAVIOUR_PARAMETER in self . _channel_modes_behaviour : self . _channel_modes_behaviour [ rfc1459 . protocol . BEHAVIOUR_PARAMETER ] = set ( ) self . _channel_modes_behaviour [ rfc1459 . protocol . BEHAVIOUR_PARAMETER ] . update ( param ) if not rfc1459 . protocol . BEHAVIOUR_PARAMETER_ON_SET in self . _channel_modes_behaviour : self . _channel_modes_behaviour [ rfc1459 . protocol . BEHAVIOUR_PARAMETER_ON_SET ] = set ( ) self . _channel_modes_behaviour [ rfc1459 . protocol . BEHAVIOUR_PARAMETER_ON_SET ] . update ( param_set ) if not rfc1459 . protocol . BEHAVIOUR_NO_PARAMETER in self . _channel_modes_behaviour : self . _channel_modes_behaviour [ rfc1459 . protocol . BEHAVIOUR_NO_PARAMETER ] = set ( ) self . _channel_modes_behaviour [ rfc1459 . protocol . BEHAVIOUR_NO_PARAMETER ] . update ( noparams ) | Valid channel modes and their behaviour . | 499 | 7 |
23,763 | async def on_isupport_excepts ( self , value ) : if not value : value = BAN_EXCEPT_MODE self . _channel_modes . add ( value ) self . _channel_modes_behaviour [ rfc1459 . protocol . BEHAVIOUR_LIST ] . add ( value ) | Server allows ban exceptions . | 71 | 5 |
23,764 | async def on_isupport_extban ( self , value ) : self . _extban_prefix , types = value . split ( ',' ) self . _extban_types = set ( types ) | Extended ban prefixes . | 45 | 6 |
23,765 | async def on_isupport_invex ( self , value ) : if not value : value = INVITE_EXCEPT_MODE self . _channel_modes . add ( value ) self . _channel_modes_behaviour [ rfc1459 . protocol . BEHAVIOUR_LIST ] . add ( value ) | Server allows invite exceptions . | 72 | 5 |
23,766 | async def on_isupport_maxbans ( self , value ) : if 'MAXLIST' not in self . _isupport : if not self . _list_limits : self . _list_limits = { } self . _list_limits [ 'b' ] = int ( value ) | Maximum entries in ban list . Replaced by MAXLIST . | 64 | 12 |
23,767 | async def on_isupport_maxchannels ( self , value ) : if 'CHANTYPES' in self . _isupport and 'CHANLIMIT' not in self . _isupport : self . _channel_limits = { } prefixes = self . _isupport [ 'CHANTYPES' ] # Assume the limit is for all types of channels. Make a single group for all types. self . _channel_limits [ frozenset ( prefixes ) ] = int ( value ) for prefix in prefixes : self . _channel_limit_groups [ prefix ] = frozenset ( prefixes ) | Old version of CHANLIMIT . | 136 | 9 |
23,768 | async def on_isupport_maxlist ( self , value ) : self . _list_limits = { } for entry in value . split ( ',' ) : modes , limit = entry . split ( ':' ) # Assign limit to mode group and add lookup entry for mode. self . _list_limits [ frozenset ( modes ) ] = int ( limit ) for mode in modes : self . _list_limit_groups [ mode ] = frozenset ( modes ) | Limits on channel modes involving lists . | 103 | 8 |
23,769 | async def on_isupport_prefix ( self , value ) : if not value : # No prefixes support. self . _nickname_prefixes = collections . OrderedDict ( ) return modes , prefixes = value . lstrip ( '(' ) . split ( ')' , 1 ) # Update valid channel modes and their behaviour as CHANMODES doesn't include PREFIX modes. self . _channel_modes . update ( set ( modes ) ) if not rfc1459 . protocol . BEHAVIOUR_PARAMETER in self . _channel_modes_behaviour : self . _channel_modes_behaviour [ rfc1459 . protocol . BEHAVIOUR_PARAMETER ] = set ( ) self . _channel_modes_behaviour [ rfc1459 . protocol . BEHAVIOUR_PARAMETER ] . update ( set ( modes ) ) self . _nickname_prefixes = collections . OrderedDict ( ) for mode , prefix in zip ( modes , prefixes ) : self . _nickname_prefixes [ prefix ] = mode | Nickname prefixes on channels and their associated modes . | 240 | 11 |
23,770 | async def on_isupport_targmax ( self , value ) : if not value : return for entry in value . split ( ',' ) : command , limit = entry . split ( ':' , 1 ) if not limit : continue self . _target_limits [ command ] = int ( limit ) | The maximum number of targets certain types of commands can affect . | 65 | 12 |
23,771 | async def on_isupport_wallchops ( self , value ) : for prefix , mode in self . _nickname_prefixes . items ( ) : if mode == 'o' : break else : prefix = '@' self . _status_message_prefixes . add ( prefix ) | Support for messaging every opped member or higher on a channel . Replaced by STATUSMSG . | 64 | 21 |
23,772 | def parse ( cls , line , encoding = pydle . protocol . DEFAULT_ENCODING ) : valid = True # Decode message. try : message = line . decode ( encoding ) except UnicodeDecodeError : # Try our fallback encoding. message = line . decode ( pydle . protocol . FALLBACK_ENCODING ) # Sanity check for message length. if len ( message ) > TAGGED_MESSAGE_LENGTH_LIMIT : valid = False # Strip message separator. if message . endswith ( rfc1459 . protocol . LINE_SEPARATOR ) : message = message [ : - len ( rfc1459 . protocol . LINE_SEPARATOR ) ] elif message . endswith ( rfc1459 . protocol . MINIMAL_LINE_SEPARATOR ) : message = message [ : - len ( rfc1459 . protocol . MINIMAL_LINE_SEPARATOR ) ] raw = message # Parse tags. tags = { } if message . startswith ( TAG_INDICATOR ) : message = message [ len ( TAG_INDICATOR ) : ] raw_tags , message = message . split ( ' ' , 1 ) for raw_tag in raw_tags . split ( TAG_SEPARATOR ) : if TAG_VALUE_SEPARATOR in raw_tag : tag , value = raw_tag . split ( TAG_VALUE_SEPARATOR , 1 ) else : tag = raw_tag value = True tags [ tag ] = value # Parse rest of message. message = super ( ) . parse ( message . lstrip ( ) . encode ( encoding ) , encoding = encoding ) return TaggedMessage ( _raw = raw , _valid = message . _valid and valid , tags = tags , * * message . _kw ) | Parse given line into IRC message structure . Returns a TaggedMessage . | 393 | 15 |
23,773 | def construct ( self , force = False ) : message = super ( ) . construct ( force = force ) # Add tags. if self . tags : raw_tags = [ ] for tag , value in self . tags . items ( ) : if value == True : raw_tags . append ( tag ) else : raw_tags . append ( tag + TAG_VALUE_SEPARATOR + value ) message = TAG_INDICATOR + TAG_SEPARATOR . join ( raw_tags ) + ' ' + message if len ( message ) > TAGGED_MESSAGE_LENGTH_LIMIT and not force : raise protocol . ProtocolViolation ( 'The constructed message is too long. ({len} > {maxlen})' . format ( len = len ( message ) , maxlen = TAGGED_MESSAGE_LENGTH_LIMIT ) , message = message ) return message | Construct raw IRC message and return it . | 193 | 8 |
23,774 | def _get_public_suffix_list ( ) : local_psl = os . environ . get ( 'PUBLIC_SUFFIX_LIST' ) if local_psl : with codecs . open ( local_psl , 'r' , 'utf-8' ) as f : psl_raw = f . readlines ( ) else : psl_raw = unicode ( urlopen ( PSL_URL ) . read ( ) , 'utf-8' ) . split ( '\n' ) psl = set ( ) for line in psl_raw : item = line . strip ( ) if item != '' and not item . startswith ( '//' ) : psl . add ( item ) return psl | Return a set containing all Public Suffixes . | 162 | 10 |
23,775 | def normalize ( url ) : url = url . strip ( ) if url == '' : return '' parts = split ( url ) if parts . scheme : netloc = parts . netloc if parts . scheme in SCHEMES : path = normalize_path ( parts . path ) else : path = parts . path # url is relative, netloc (if present) is part of path else : netloc = parts . path path = '' if '/' in netloc : netloc , path_raw = netloc . split ( '/' , 1 ) path = normalize_path ( '/' + path_raw ) username , password , host , port = split_netloc ( netloc ) host = normalize_host ( host ) port = _normalize_port ( parts . scheme , port ) query = normalize_query ( parts . query ) fragment = normalize_fragment ( parts . fragment ) return construct ( URL ( parts . scheme , username , password , None , host , None , port , path , query , fragment , None ) ) | Normalize a URL . | 223 | 5 |
23,776 | def _encode_query ( query ) : if query == '' : return query query_args = [ ] for query_kv in query . split ( '&' ) : k , v = query_kv . split ( '=' ) query_args . append ( k + "=" + quote ( v . encode ( 'utf-8' ) ) ) return '&' . join ( query_args ) | Quote all values of a query string . | 88 | 8 |
23,777 | def encode ( url ) : parts = extract ( url ) return construct ( URL ( parts . scheme , parts . username , parts . password , _idna_encode ( parts . subdomain ) , _idna_encode ( parts . domain ) , _idna_encode ( parts . tld ) , parts . port , quote ( parts . path . encode ( 'utf-8' ) ) , _encode_query ( parts . query ) , quote ( parts . fragment . encode ( 'utf-8' ) ) , None ) ) | Encode URL . | 117 | 4 |
23,778 | def construct ( parts ) : url = '' if parts . scheme : if parts . scheme in SCHEMES : url += parts . scheme + '://' else : url += parts . scheme + ':' if parts . username and parts . password : url += parts . username + ':' + parts . password + '@' elif parts . username : url += parts . username + '@' if parts . subdomain : url += parts . subdomain + '.' url += parts . domain if parts . tld : url += '.' + parts . tld if parts . port : url += ':' + parts . port if parts . path : url += parts . path if parts . query : url += '?' + parts . query if parts . fragment : url += '#' + parts . fragment return url | Construct a new URL from parts . | 169 | 7 |
23,779 | def _normalize_port ( scheme , port ) : if not scheme : return port if port and port != DEFAULT_PORT [ scheme ] : return port | Return port if it is not default port else None . | 33 | 11 |
23,780 | def unquote ( text , exceptions = [ ] ) : if not text : if text is None : raise TypeError ( 'None object cannot be unquoted' ) else : return text if '%' not in text : return text s = text . split ( '%' ) res = [ s [ 0 ] ] for h in s [ 1 : ] : c = _hextochr . get ( h [ : 2 ] ) if c and c not in exceptions : if len ( h ) > 2 : res . append ( c + h [ 2 : ] ) else : res . append ( c ) else : res . append ( '%' + h ) return '' . join ( res ) | Unquote a text but ignore the exceptions . | 147 | 9 |
23,781 | def split ( url ) : scheme = netloc = path = query = fragment = '' ip6_start = url . find ( '[' ) scheme_end = url . find ( ':' ) if ip6_start > 0 and ip6_start < scheme_end : scheme_end = - 1 if scheme_end > 0 : for c in url [ : scheme_end ] : if c not in SCHEME_CHARS : break else : scheme = url [ : scheme_end ] . lower ( ) rest = url [ scheme_end : ] . lstrip ( ':/' ) if not scheme : rest = url l_path = rest . find ( '/' ) l_query = rest . find ( '?' ) l_frag = rest . find ( '#' ) if l_path > 0 : if l_query > 0 and l_frag > 0 : netloc = rest [ : l_path ] path = rest [ l_path : min ( l_query , l_frag ) ] elif l_query > 0 : if l_query > l_path : netloc = rest [ : l_path ] path = rest [ l_path : l_query ] else : netloc = rest [ : l_query ] path = '' elif l_frag > 0 : netloc = rest [ : l_path ] path = rest [ l_path : l_frag ] else : netloc = rest [ : l_path ] path = rest [ l_path : ] else : if l_query > 0 : netloc = rest [ : l_query ] elif l_frag > 0 : netloc = rest [ : l_frag ] else : netloc = rest if l_query > 0 : if l_frag > 0 : query = rest [ l_query + 1 : l_frag ] else : query = rest [ l_query + 1 : ] if l_frag > 0 : fragment = rest [ l_frag + 1 : ] if not scheme : path = netloc + path netloc = '' return SplitResult ( scheme , netloc , path , query , fragment ) | Split URL into scheme netloc path query and fragment . | 463 | 11 |
23,782 | def split_netloc ( netloc ) : username = password = host = port = '' if '@' in netloc : user_pw , netloc = netloc . split ( '@' , 1 ) if ':' in user_pw : username , password = user_pw . split ( ':' , 1 ) else : username = user_pw netloc = _clean_netloc ( netloc ) if ':' in netloc and netloc [ - 1 ] != ']' : host , port = netloc . rsplit ( ':' , 1 ) else : host = netloc return username , password , host , port | Split netloc into username password host and port . | 137 | 10 |
23,783 | def split_host ( host ) : # host is IPv6? if '[' in host : return '' , host , '' # host is IPv4? for c in host : if c not in IP_CHARS : break else : return '' , host , '' # host is a domain name domain = subdomain = tld = '' parts = host . split ( '.' ) for i in range ( len ( parts ) ) : tld = '.' . join ( parts [ i : ] ) wildcard_tld = '*.' + tld exception_tld = '!' + tld if exception_tld in PSL : domain = '.' . join ( parts [ : i + 1 ] ) tld = '.' . join ( parts [ i + 1 : ] ) break if tld in PSL : domain = '.' . join ( parts [ : i ] ) break if wildcard_tld in PSL : domain = '.' . join ( parts [ : i - 1 ] ) tld = '.' . join ( parts [ i - 1 : ] ) break if '.' in domain : subdomain , domain = domain . rsplit ( '.' , 1 ) return subdomain , domain , tld | Use the Public Suffix List to split host into subdomain domain and tld . | 259 | 17 |
23,784 | def connection_made ( self , transport ) : self . transport = transport self . loop = transport . loop self . _cmd_lock = asyncio . Lock ( loop = self . loop ) self . _wd_lock = asyncio . Lock ( loop = self . loop ) self . _cmdq = asyncio . Queue ( loop = self . loop ) self . _msgq = asyncio . Queue ( loop = self . loop ) self . _updateq = asyncio . Queue ( loop = self . loop ) self . _readbuf = b'' self . _update_cb = None self . _received_lines = 0 self . _msg_task = self . loop . create_task ( self . _process_msgs ( ) ) self . _report_task = None self . _watchdog_task = None self . status = { } self . connected = True | Gets called when a connection to the gateway is established . Initialise the protocol object . | 189 | 18 |
23,785 | def connection_lost ( self , exc ) : _LOGGER . error ( "Disconnected: %s" , exc ) self . connected = False self . transport . close ( ) if self . _report_task is not None : self . _report_task . cancel ( ) self . _msg_task . cancel ( ) for q in [ self . _cmdq , self . _updateq , self . _msgq ] : while not q . empty ( ) : q . get_nowait ( ) self . status = { } | Gets called when the connection to the gateway is lost . Tear down and clean up the protocol object . | 114 | 22 |
23,786 | async def setup_watchdog ( self , cb , timeout ) : self . _watchdog_timeout = timeout self . _watchdog_cb = cb self . _watchdog_task = self . loop . create_task ( self . _watchdog ( timeout ) ) | Trigger a reconnect after | 60 | 4 |
23,787 | async def cancel_watchdog ( self ) : if self . _watchdog_task is not None : _LOGGER . debug ( "Canceling Watchdog task." ) self . _watchdog_task . cancel ( ) try : await self . _watchdog_task except asyncio . CancelledError : self . _watchdog_task = None | Cancel the watchdog task and related variables . | 76 | 9 |
23,788 | async def _inform_watchdog ( self ) : async with self . _wd_lock : if self . _watchdog_task is None : # Check within the Lock to deal with external cancel_watchdog # calls with queued _inform_watchdog tasks. return self . _watchdog_task . cancel ( ) try : await self . _watchdog_task except asyncio . CancelledError : self . _watchdog_task = self . loop . create_task ( self . _watchdog ( self . _watchdog_timeout ) ) | Inform the watchdog of activity . | 120 | 7 |
23,789 | async def _watchdog ( self , timeout ) : await asyncio . sleep ( timeout , loop = self . loop ) _LOGGER . debug ( "Watchdog triggered!" ) await self . cancel_watchdog ( ) await self . _watchdog_cb ( ) | Trigger and cancel the watchdog after timeout . Call callback . | 57 | 11 |
23,790 | def _dissect_msg ( self , match ) : recvfrom = match . group ( 1 ) frame = bytes . fromhex ( match . group ( 2 ) ) if recvfrom == 'E' : _LOGGER . warning ( "Received erroneous message, ignoring: %s" , frame ) return ( None , None , None , None , None ) msgtype = self . _get_msgtype ( frame [ 0 ] ) if msgtype in ( READ_ACK , WRITE_ACK , READ_DATA , WRITE_DATA ) : # Some info is best read from the READ/WRITE_DATA messages # as the boiler may not support the data ID. # Slice syntax is used to prevent implicit cast to int. data_id = frame [ 1 : 2 ] data_msb = frame [ 2 : 3 ] data_lsb = frame [ 3 : 4 ] return ( recvfrom , msgtype , data_id , data_msb , data_lsb ) return ( None , None , None , None , None ) | Split messages into bytes and return a tuple of bytes . | 221 | 11 |
23,791 | def _get_u16 ( self , msb , lsb ) : buf = struct . pack ( '>BB' , self . _get_u8 ( msb ) , self . _get_u8 ( lsb ) ) return int ( struct . unpack ( '>H' , buf ) [ 0 ] ) | Convert 2 bytes into an unsigned int . | 70 | 9 |
23,792 | def _get_s16 ( self , msb , lsb ) : buf = struct . pack ( '>bB' , self . _get_s8 ( msb ) , self . _get_u8 ( lsb ) ) return int ( struct . unpack ( '>h' , buf ) [ 0 ] ) | Convert 2 bytes into a signed int . | 71 | 9 |
23,793 | async def _report ( self ) : while True : oldstatus = dict ( self . status ) stat = await self . _updateq . get ( ) if self . _update_cb is not None and oldstatus != stat : # Each client gets its own copy of the dict. self . loop . create_task ( self . _update_cb ( dict ( stat ) ) ) | Call _update_cb with the status dict as an argument whenever a status update occurs . | 81 | 18 |
23,794 | async def set_update_cb ( self , cb ) : if self . _report_task is not None and not self . _report_task . cancelled ( ) : self . loop . create_task ( self . _report_task . cancel ( ) ) self . _update_cb = cb if cb is not None : self . _report_task = self . loop . create_task ( self . _report ( ) ) | Register the update callback . | 95 | 5 |
23,795 | async def issue_cmd ( self , cmd , value , retry = 3 ) : async with self . _cmd_lock : if not self . connected : _LOGGER . debug ( "Serial transport closed, not sending command %s" , cmd ) return while not self . _cmdq . empty ( ) : _LOGGER . debug ( "Clearing leftover message from command queue:" " %s" , await self . _cmdq . get ( ) ) _LOGGER . debug ( "Sending command: %s with value %s" , cmd , value ) self . transport . write ( '{}={}\r\n' . format ( cmd , value ) . encode ( 'ascii' ) ) if cmd == OTGW_CMD_REPORT : expect = r'^{}:\s*([A-Z]{{2}}|{}=[^$]+)$' . format ( cmd , value ) else : expect = r'^{}:\s*([^$]+)$' . format ( cmd ) async def send_again ( err ) : """Resend the command.""" nonlocal retry _LOGGER . warning ( "Command %s failed with %s, retrying..." , cmd , err ) retry -= 1 self . transport . write ( '{}={}\r\n' . format ( cmd , value ) . encode ( 'ascii' ) ) async def process ( msg ) : """Process a possible response.""" _LOGGER . debug ( "Got possible response for command %s: %s" , cmd , msg ) if msg in OTGW_ERRS : # Some errors appear by themselves on one line. if retry == 0 : raise OTGW_ERRS [ msg ] await send_again ( msg ) return if cmd == OTGW_CMD_MODE and value == 'R' : # Device was reset, msg contains build info while not re . match ( r'OpenTherm Gateway \d+\.\d+\.\d+' , msg ) : msg = await self . _cmdq . get ( ) return True match = re . match ( expect , msg ) if match : if match . group ( 1 ) in OTGW_ERRS : # Some errors are considered a response. if retry == 0 : raise OTGW_ERRS [ match . group ( 1 ) ] await send_again ( msg ) return ret = match . group ( 1 ) if cmd == OTGW_CMD_SUMMARY and ret == '1' : # Expects a second line part2 = await self . _cmdq . get ( ) ret = [ ret , part2 ] return ret if re . match ( r'Error 0[1-4]' , msg ) : _LOGGER . warning ( "Received %s. If this happens during a " "reset of the gateway it can be safely " "ignored." , msg ) return _LOGGER . warning ( "Unknown message in command queue: %s" , msg ) await send_again ( msg ) while True : msg = await self . _cmdq . get ( ) ret = await process ( msg ) if ret is not None : return ret | Issue a command then await and return the return value . | 678 | 11 |
23,796 | def get_target_temp ( self ) : if not self . _connected : return temp_ovrd = self . _protocol . status . get ( DATA_ROOM_SETPOINT_OVRD ) if temp_ovrd : return temp_ovrd return self . _protocol . status . get ( DATA_ROOM_SETPOINT ) | Get the target temperature . | 76 | 5 |
23,797 | async def get_reports ( self ) : cmd = OTGW_CMD_REPORT reports = { } for value in OTGW_REPORTS . keys ( ) : ret = await self . _wait_for_cmd ( cmd , value ) if ret is None : reports [ value ] = None continue reports [ value ] = ret [ 2 : ] status = { OTGW_ABOUT : reports . get ( OTGW_REPORT_ABOUT ) , OTGW_BUILD : reports . get ( OTGW_REPORT_BUILDDATE ) , OTGW_CLOCKMHZ : reports . get ( OTGW_REPORT_CLOCKMHZ ) , OTGW_MODE : reports . get ( OTGW_REPORT_GW_MODE ) , OTGW_SMART_PWR : reports . get ( OTGW_REPORT_SMART_PWR ) , OTGW_THRM_DETECT : reports . get ( OTGW_REPORT_THERMOSTAT_DETECT ) , OTGW_DHW_OVRD : reports . get ( OTGW_REPORT_DHW_SETTING ) , } ovrd_mode = reports . get ( OTGW_REPORT_SETPOINT_OVRD ) if ovrd_mode is not None : ovrd_mode = str . upper ( ovrd_mode [ 0 ] ) status . update ( { OTGW_SETP_OVRD_MODE : ovrd_mode } ) gpio_funcs = reports . get ( OTGW_REPORT_GPIO_FUNCS ) if gpio_funcs is not None : status . update ( { OTGW_GPIO_A : int ( gpio_funcs [ 0 ] ) , OTGW_GPIO_B : int ( gpio_funcs [ 1 ] ) , } ) led_funcs = reports . get ( OTGW_REPORT_LED_FUNCS ) if led_funcs is not None : status . update ( { OTGW_LED_A : led_funcs [ 0 ] , OTGW_LED_B : led_funcs [ 1 ] , OTGW_LED_C : led_funcs [ 2 ] , OTGW_LED_D : led_funcs [ 3 ] , OTGW_LED_E : led_funcs [ 4 ] , OTGW_LED_F : led_funcs [ 5 ] , } ) tweaks = reports . get ( OTGW_REPORT_TWEAKS ) if tweaks is not None : status . update ( { OTGW_IGNORE_TRANSITIONS : int ( tweaks [ 0 ] ) , OTGW_OVRD_HB : int ( tweaks [ 1 ] ) , } ) sb_temp = reports . get ( OTGW_REPORT_SETBACK_TEMP ) if sb_temp is not None : status . update ( { OTGW_SB_TEMP : float ( sb_temp ) } ) vref = reports . get ( OTGW_REPORT_VREF ) if vref is not None : status . update ( { OTGW_VREF : int ( vref ) } ) if ( ovrd_mode is not None and ovrd_mode != OTGW_SETP_OVRD_DISABLED ) : status [ DATA_ROOM_SETPOINT_OVRD ] = float ( reports [ OTGW_REPORT_SETPOINT_OVRD ] [ 1 : ] ) self . _update_status ( status ) return dict ( self . _protocol . status ) | Update the pyotgw object with the information from all of the PR commands and return the updated status dict . | 766 | 23 |
23,798 | async def add_alternative ( self , alt , timeout = OTGW_DEFAULT_TIMEOUT ) : cmd = OTGW_CMD_ADD_ALT alt = int ( alt ) if alt < 1 or alt > 255 : return None ret = await self . _wait_for_cmd ( cmd , alt , timeout ) if ret is not None : return int ( ret ) | Add the specified Data - ID to the list of alternative commands to send to the boiler instead of a Data - ID that is known to be unsupported by the boiler . Alternative Data - IDs will always be sent to the boiler in a Read - Data request message with the data - value set to zero . The table of alternative Data - IDs is stored in non - volatile memory so it will persist even if the gateway has been powered off . Data - ID values from 1 to 255 are allowed . Return the ID that was added to the list or None on failure . | 81 | 112 |
23,799 | async def del_alternative ( self , alt , timeout = OTGW_DEFAULT_TIMEOUT ) : cmd = OTGW_CMD_DEL_ALT alt = int ( alt ) if alt < 1 or alt > 255 : return None ret = await self . _wait_for_cmd ( cmd , alt , timeout ) if ret is not None : return int ( ret ) | Remove the specified Data - ID from the list of alternative commands . Only one occurrence is deleted . If the Data - ID appears multiple times in the list of alternative commands this command must be repeated to delete all occurrences . The table of alternative Data - IDs is stored in non - volatile memory so it will persist even if the gateway has been powered off . Data - ID values from 1 to 255 are allowed . Return the ID that was removed from the list or None on failure . | 82 | 95 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.