Commit 95bb61f0 authored by Guillaume Binet's avatar Guillaume Binet Committed by Guillaume Binet

Refactoring to fstrings.

parent 8d5fe9a3
......@@ -360,14 +360,14 @@ def arg_botcmd(*args,
args = shlex.split(args)
parsed_args = err_command_parser.parse_args(args)
except ArgumentParseError as e:
yield "I'm sorry, I couldn't parse the arguments; %s" % e
yield f"I couldn't parse the arguments; {e}"
yield err_command_parser.format_usage()
return
except HelpRequested:
yield err_command_parser.format_help()
return
except ValueError as ve:
yield "I'm sorry, I couldn't parse this command; %s" % ve
yield f"I couldn't parse this command; {ve}"
yield err_command_parser.format_help()
return
......@@ -410,7 +410,7 @@ def arg_botcmd(*args,
def _tag_webhook(func, uri_rule, methods, form_param, raw):
log.info("webhooks: Flag to bind %s to %30s" % (uri_rule, getattr(func, '__name__', func)))
log.info(f"webhooks: Flag to bind {uri_rule} to {getattr(func, '__name__', func)}")
func._err_webhook_uri_rule = uri_rule
func._err_webhook_methods = methods
func._err_webhook_form_param = form_param
......
......@@ -34,7 +34,7 @@ class BackendPluginManager:
if plugin_info.name == plugin_name:
self.plugin_info = plugin_info
return
raise PluginNotFoundException('Could not find the plugin named %s in %s.' % (plugin_name, all_plugins_paths))
raise PluginNotFoundException(f'Could not find the plugin named {plugin_name} in {all_plugin_paths}.')
def load_plugin(self) -> Any:
plugin_path = self.plugin_info.location.parent
......@@ -42,7 +42,7 @@ class BackendPluginManager:
sys.path.append(plugin_path)
plugin_classes = self.plugin_info.load_plugin_classes(self._base_module, self._base_class)
if len(plugin_classes) != 1:
raise PluginNotFoundException('Found more that one plugin for %s.' % self._base_class)
raise PluginNotFoundException(f'Found more that one plugin for {self._base_class}.')
_, clazz = plugin_classes[0]
return clazz(self._config)
......@@ -499,11 +499,11 @@ class Presence(object):
def __str__(self):
response = ''
if self._identifier:
response += 'identifier: "%s" ' % self._identifier
response += f'identifier: "{self._identifier}" '
if self._status:
response += 'status: "%s" ' % self._status
response += f'status: "{self._status}" '
if self._message:
response += 'message: "%s" ' % self._message
response += f'message: "{self._message}" '
return response
def __unicode__(self):
......@@ -698,23 +698,21 @@ class Backend(ABC):
if self.serve_once():
break # Truth-y exit from serve_once means shutdown was requested
except KeyboardInterrupt:
log.info("Interrupt received, shutting down..")
log.info('Interrupt received, shutting down..')
break
except Exception:
log.exception("Exception occurred in serve_once:")
log.exception('Exception occurred in serve_once:')
log.info(
"Reconnecting in {delay} seconds ({count} attempted reconnections so far)".format(
delay=self._reconnection_delay, count=self._reconnection_count)
)
log.info('Reconnecting in %d seconds (%d attempted reconnections so far).'
, self._reconnection_delay, self._reconnection_count)
try:
self._delay_reconnect()
self._reconnection_count += 1
except KeyboardInterrupt:
log.info("Interrupt received, shutting down..")
log.info('Interrupt received, shutting down..')
break
log.info("Trigger shutdown")
log.info('Trigger shutdown')
self.shutdown()
def _delay_reconnect(self):
......
......@@ -96,12 +96,12 @@ class CommandBox(QtGui.QPlainTextEdit, object):
if key == Qt.Key_Up:
if self.history_index > 0:
self.history_index -= 1
self.setPlainText('%s%s' % (self.prefix, ' '.join(self.history[self.history_index])))
self.setPlainText(f'{self.prefix}{" ".join(self.history[self.history_index])}')
return
elif key == Qt.Key_Down:
if self.history_index < len(self.history) - 1:
self.history_index += 1
self.setPlainText('%s%s' % (self.prefix, ' '.join(self.history[self.history_index])))
self.setPlainText(f'{self.prefix}{" ".join(self.history[self.history_index])}')
return
elif key == QtCore.Qt.Key_Return and (ctrl or alt):
self.newCommand.emit(self.toPlainText())
......@@ -122,7 +122,7 @@ style_path = os.path.join(backends_path, 'styles')
css_path = os.path.join(style_path, 'style.css')
demo_css_path = os.path.join(style_path, 'style-demo.css')
TOP = '<html><body style="background-image: url(\'file://%s\');">' % bg_path
TOP = f'<html><body style="background-image: url(\'file://{bg_path}\');">'
BOTTOM = '</body></html>'
......@@ -172,11 +172,9 @@ class ChatApplication(QtGui.QApplication):
def new_message(self, text, receiving=True):
size = 50 if self.demo_mode else 25
user = '<img src="file://%s" height=%d />' % (prompt_path, size)
bot = '<img src="file://%s" height=%d/>' % (icon_path, size)
self.buffer += '<div class="%s">%s<br/>%s</div>' % ('receiving' if receiving else 'sending',
bot if receiving else user,
text)
user = f'<img src="file://{prompt_path}" height={size:d} />'
bot = f'<img src="file://{icon_path}" height={size:d}/>'
self.buffer += f'<div class="{"receiving" if receiving else "sending"}">{bot if receiving else user}<br/>{text}</div>'
self.update_webpage()
......@@ -248,4 +246,4 @@ class GraphicBackend(TextBackend):
def prefix_groupchat_reply(self, message, identifier):
super().prefix_groupchat_reply(message, identifier)
message.body = '@{0} {1}'.format(identifier.nick, message.body)
message.body = f'@{identifier.nick} {message.body}'
This diff is collapsed.
......@@ -130,13 +130,13 @@ class IRCRoomOccupant(IRCPerson, RoomOccupant):
return self._room
def __unicode__(self):
return "%s" % self._nickmask
return self._nickmask
def __str__(self):
return self.__unicode__()
def __repr__(self):
return "<{} - {}>".format(self.__unicode__(), super().__repr__())
return f'<{self.__unicode__()} - {super().__repr__()}>'
class IRCRoom(Room):
......@@ -163,7 +163,7 @@ class IRCRoom(Room):
return self.__unicode__()
def __repr__(self):
return "<{} - {}>".format(self.__unicode__(), super().__repr__())
return f"<{self.__unicode__()} - {super().__repr__()}>"
def cb_set_topic(self, current_topic):
"""
......@@ -191,7 +191,7 @@ class IRCRoom(Room):
password = "" # nosec
self.connection.join(self.room, key=password)
log.info("Joined room {}".format(self.room))
log.info('Joined room %s.', self.room)
def leave(self, reason=None):
"""
......@@ -204,23 +204,20 @@ class IRCRoom(Room):
reason = ""
self.connection.part(self.room, reason)
log.info("Leaving room {} with reason '{}'".format(self.room, reason if reason is not None else ''))
log.info('Leaving room %s with reason %s.', self.room, reason if reason is not None else '')
def create(self):
"""
Not supported on this back-end. Will join the room to ensure it exists, instead.
"""
logging.warning(
"IRC back-end does not support explicit creation, joining room "
"instead to ensure it exists."
)
logging.warning('IRC back-end does not support explicit creation, joining room instead to ensure it exists.')
self.join()
def destroy(self):
"""
Not supported on IRC, will raise :class:`~errbot.backends.base.RoomError`.
"""
raise RoomError("IRC back-end does not support destroying rooms.")
raise RoomError('IRC back-end does not support destroying rooms.')
@property
def exists(self):
......@@ -230,10 +227,8 @@ class IRCRoom(Room):
:getter:
Returns `True` if the room exists, `False` otherwise.
"""
logging.warning(
"IRC back-end does not support determining if a room exists. "
"Returning the result of joined instead."
)
logging.warning('IRC back-end does not support determining if a room exists. '
'Returning the result of joined instead.')
return self.joined
@property
......@@ -256,7 +251,7 @@ class IRCRoom(Room):
topic has been set at all.
"""
if not self.joined:
raise RoomNotJoinedError("Must join the room to get the topic")
raise RoomNotJoinedError('Must join the room to get the topic.')
with self._topic_lock:
return self._topic
......@@ -269,7 +264,7 @@ class IRCRoom(Room):
The topic to set.
"""
if not self.joined:
raise RoomNotJoinedError("Must join the room to set the topic")
raise RoomNotJoinedError('Must join the room to set the topic.')
self.connection.topic(self.room, topic)
@property
......@@ -287,8 +282,7 @@ class IRCRoom(Room):
for nick in self._bot.conn.channels[self.room].users():
occupants.append(IRCRoomOccupant(nick, room=self.room))
except KeyError:
raise RoomNotJoinedError("Must be in a room in order to \
see occupants.")
raise RoomNotJoinedError('Must be in a room in order to see occupants.')
return occupants
def invite(self, *args):
......@@ -300,11 +294,11 @@ class IRCRoom(Room):
"""
for nick in args:
self.connection.invite(nick, self.room)
log.info("Invited {} to {}".format(nick, self.room))
log.info('Invited %s to %s.', nick, self.room)
def __eq__(self, other):
if not isinstance(other, IRCRoom):
log.warning("This is weird you are comparing an IRCRoom to a %s", type(other))
log.warning('This is weird you are comparing an IRCRoom to a %s.', type(other))
return False
return self.room == other.room
......@@ -367,12 +361,12 @@ class IRCConnection(SingleServerIRCBot):
self.connection.connect(*args, connect_factory=connection_factory, **kwargs)
def on_welcome(self, _, e):
log.info("IRC welcome %s" % e)
log.info("IRC welcome %s", e)
# try to identify with NickServ if there is a NickServ password in the
# config
if self.nickserv_password:
msg = 'identify %s' % self.nickserv_password
msg = f'identify {self.nickserv_password}'
self.send_private_message('NickServ', msg)
# Must be done in a background thread, otherwise the join room
......@@ -386,7 +380,7 @@ class IRCConnection(SingleServerIRCBot):
msg = Message(e.arguments[0], extras={'notice': notice})
room_name = e.target
if room_name[0] != '#' and room_name[0] != '$':
raise Exception('[%s] is not a room' % room_name)
raise Exception(f'[{room_name}] is not a room')
room = IRCRoom(room_name, self.bot)
msg.frm = IRCRoomOccupant(e.source, room)
msg.to = room
......@@ -422,10 +416,10 @@ class IRCConnection(SingleServerIRCBot):
if not self._reconnect_on_kick:
log.info("RECONNECT_ON_KICK is 0 or None, won't try to reconnect")
return
log.info("Got kicked out of %s... reconnect in %d seconds... " % (e.target, self._reconnect_on_kick))
log.info('Got kicked out of %s... reconnect in %d seconds... ', e.target, self._reconnect_on_kick)
def reconnect_channel(name):
log.info("Reconnecting to %s after having beeing kicked" % name)
log.info('Reconnecting to %s after having beeing kicked.', name)
self.bot.query_room(name).join()
t = threading.Timer(self._reconnect_on_kick, reconnect_channel, [e.target, ])
t.daemon = True
......@@ -467,9 +461,9 @@ class IRCConnection(SingleServerIRCBot):
def on_dcc_connect(self, dcc, event):
stream = self.transfers.get(dcc, None)
if stream is None:
log.error("DCC connect on a none registered connection")
log.error('DCC connect on a none registered connection')
return
log.debug("Start transfer for %s" % stream.identifier)
log.debug('Start transfer for %s.', stream.identifier)
stream.accept()
self.send_chunk(stream, dcc)
......@@ -497,7 +491,7 @@ class IRCConnection(SingleServerIRCBot):
if self.bot.bot_identifier.nick == leaving_nick:
with self._rooms_lock:
self.bot.callback_room_left(self._rooms[leaving_room])
log.info("Left room {}".format(leaving_room))
log.info('Left room {}.', leaving_room)
def on_endofnames(self, connection, event):
"""
......@@ -602,24 +596,24 @@ class IRCConnection(SingleServerIRCBot):
return
acked = struct.unpack("!I", event.arguments[0])[0]
if acked == stream.size:
log.info("File %s successfully transfered to %s" % (stream.name, stream.identifier))
log.info('File %s successfully transfered to %s', stream.name, stream.identifier)
dcc.disconnect()
self.transfers.pop(dcc)
elif acked == stream.transfered:
log.debug("Chunk for file %s successfully transfered to %s (%d/%d) " %
(stream.name, stream.identifier, stream.transfered, stream.size))
log.debug('Chunk for file %s successfully transfered to %s (%d/%d).',
stream.name, stream.identifier, stream.transfered, stream.size)
self.send_chunk(stream, dcc)
else:
log.debug("Partial chunk for file %s successfully transfered to %s (%d/%d), wait for more" %
(stream.name, stream.identifier, stream.transfered, stream.size))
log.debug('Partial chunk for file %s successfully transfered to %s (%d/%d), wait for more',
stream.name, stream.identifier, stream.transfered, stream.size)
def away(self, message=""):
def away(self, message=''):
"""
Extend the original implementation to support AWAY.
To set an away message, set message to something.
To cancel an away message, leave message at empty string.
"""
self.connection.send_raw(" ".join(["AWAY", message]).strip())
self.connection.send_raw(' '.join(['AWAY', message]).strip())
class IRCBackend(ErrBot):
......@@ -685,7 +679,7 @@ class IRCBackend(ErrBot):
if status == ONLINE:
self.conn.away() # cancels the away message
else:
self.conn.away('[%s] %s' % (status, message))
self.conn.away(f'[{status}] {message}')
def send_stream_request(self, identifier, fsource, name=None, size=None, stream_type=None):
return self.conn.send_stream_request(identifier, fsource, name, size, stream_type)
......@@ -724,7 +718,7 @@ class IRCBackend(ErrBot):
return super().build_message(text)
def build_identifier(self, txtrep):
log.debug("Build identifier from [%s]" % txtrep)
log.debug('Build identifier from %s.', txtrep)
# A textual representation starting with # means that we are talking
# about an IRC channel -- IRCRoom in internal err-speak.
if txtrep.startswith('#'):
......@@ -769,4 +763,4 @@ class IRCBackend(ErrBot):
def prefix_groupchat_reply(self, message, identifier):
super().prefix_groupchat_reply(message, identifier)
message.body = '{0}: {1}'.format(identifier.nick, message.body)
message.body = f'{identifier.nick}: {message.body}'
This diff is collapsed.
......@@ -283,9 +283,7 @@ class TelegramBackend(ErrBot):
self.telegram.sendMessage(msg.to.id, body)
except Exception:
log.exception(
"An exception occurred while trying to send the following message "
"to %s: %s" % (msg.to.id, msg.body)
)
f'An exception occurred while trying to send the following message to {msg.to.id}: {msg.body}')
raise
def change_presence(self, status: str = ONLINE, message: str = '') -> None:
......@@ -296,9 +294,9 @@ class TelegramBackend(ErrBot):
"""
Convert a textual representation into a :class:`~TelegramPerson` or :class:`~TelegramRoom`.
"""
log.debug("building an identifier from %s" % txtrep)
log.debug('building an identifier from %s.', txtrep)
if not self._is_numeric(txtrep):
raise ValueError("Telegram identifiers must be numeric")
raise ValueError('Telegram identifiers must be numeric.')
id_ = int(txtrep)
if id_ > 0:
return TelegramPerson(id=id_)
......@@ -336,7 +334,7 @@ class TelegramBackend(ErrBot):
def prefix_groupchat_reply(self, message, identifier):
super().prefix_groupchat_reply(message, identifier)
message.body = '@{0}: {1}'.format(identifier.nick, message.body)
message.body = f'@{identifier.nick}: {message.body}'
def _telegram_special_message(self, chat_id, content, msg_type, **kwargs):
"""Send special message."""
......@@ -368,8 +366,7 @@ class TelegramBackend(ErrBot):
longitude=kwargs.pop('longitude', ''),
**kwargs)
else:
raise ValueError('Expected a valid choice for `msg_type`, '
'got: {}.'.format(msg_type))
raise ValueError(f'Expected a valid choice for `msg_type`, got: {msg_type}.')
return msg
def _telegram_upload_stream(self, stream, **kwargs):
......@@ -382,8 +379,7 @@ class TelegramBackend(ErrBot):
msg_type=stream.stream_type,
**kwargs)
except Exception:
log.exception("Upload of {0} to {1} failed.".format(stream.name,
stream.identifier))
log.exception(f'Upload of {stream.name} to {stream.identifier} failed.')
else:
if msg is None:
stream.error()
......@@ -439,22 +435,20 @@ class TelegramBackend(ErrBot):
content, meta = _telegram_metadata(fsource)
if isinstance(content, str):
if not _is_valid_url(content):
raise ValueError("Not valid URL: {}".format(content))
raise ValueError(f'Not valid URL: {content}')
self._telegram_special_message(chat_id=identifier.id,
content=content,
msg_type=stream_type,
**meta)
log.debug("Requesting upload of {0} to {1} (size hint: {2}, stream type: {3})".format(name,
identifier.username,
size, stream_type))
log.debug('Requesting upload of %s to %s (size hint: %d, stream type: %s).',
name, identifier.username, size, stream_type)
stream = content
else:
stream = Stream(identifier, content, name, size, stream_type)
log.debug("Requesting upload of {0} to {1} (size hint: {2}, stream type: {3})".format(name,
identifier, size,
stream_type))
log.debug('Requesting upload of %s to %s (size hint: %d, stream type: %s)',
name, identifier, size, stream_type)
self.thread_pool.apply_async(self._telegram_upload_stream, (stream,))
return stream
......
......@@ -72,8 +72,8 @@ class TestPerson(Person):
def __unicode__(self):
if self.client:
return '{}/{}'.format(self._person, self._client)
return '{}'.format(self._person)
return f'{self._person}/{self._client}'
return f'{self._person}'
__str__ = __unicode__
......@@ -144,26 +144,26 @@ class TestRoom(Room):
def join(self, username=None, password=None):
if self.joined:
logging.warning("Attempted to join room '{!s}', but already in this room".format(self))
logging.warning('Attempted to join room %s, but already in this room.', self)
return
if not self.exists:
log.debug("Room {!s} doesn't exist yet, creating it".format(self))
log.debug("Room %s doesn't exist yet, creating it.", self)
self.create()
room = self.find_croom()
room._occupants.append(self._bot_mucid)
log.info("Joined room {!s}".format(self))
log.info('Joined room %s.', self)
self._bot.callback_room_joined(room)
def leave(self, reason=None):
if not self.joined:
logging.warning("Attempted to leave room '{!s}', but not in this room".format(self))
logging.warning('Attempted to leave room %s, but not in this room.', self)
return
room = self.find_croom()
room._occupants.remove(self._bot_mucid)
log.info("Left room {!s}".format(self))
log.info('Left room %s.', self)
self._bot.callback_room_left(room)
@property
......@@ -172,19 +172,19 @@ class TestRoom(Room):
def create(self):
if self.exists:
logging.warning("Room {!s} already created".format(self))
logging.warning('Room %s already created.', self)
return
self._bot._rooms.append(self)
log.info("Created room {!s}".format(self))
log.info('Created room %s.', self)
def destroy(self):
if not self.exists:
logging.warning("Cannot destroy room {!s}, it doesn't exist".format(self))
logging.warning("Cannot destroy room %s, it doesn't exist.", self)
return
self._bot._rooms.remove(self)
log.info("Destroyed room {!s}".format(self))
log.info('Destroyed room %s.', self)
@property
def topic(self):
......@@ -195,7 +195,7 @@ class TestRoom(Room):
self._topic = topic
room = self.find_croom()
room._topic = self._topic
log.info("Topic for room {!s} set to '{}'".format(self, topic))
log.info('Topic for room %s set to %s.', self, topic)
self._bot.callback_room_topic(self)
def __unicode__(self):
......@@ -302,7 +302,7 @@ class TestBackend(ErrBot):
def prefix_groupchat_reply(self, message, identifier):
super().prefix_groupchat_reply(message, identifier)
message.body = '@{0} {1}'.format(identifier.nick, message.body)
message.body = f'@{identifier.nick} {message.body}'
def pop_message(self, timeout=5, block=True):
return self.outgoing_message_queue.get(timeout=timeout, block=block)
......@@ -318,11 +318,11 @@ class TestBackend(ErrBot):
def zap_queues(self):
while not self.incoming_stanza_queue.empty():
msg = self.incoming_stanza_queue.get(block=False)
log.error('Message left in the incoming queue during a test : %s' % msg)
log.error('Message left in the incoming queue during a test: %s.', msg)
while not self.outgoing_message_queue.empty():
msg = self.outgoing_message_queue.get(block=False)
log.error('Message left in the outgoing queue during a test : %s' % msg)
log.error('Message left in the outgoing queue during a test: %s.', msg)
def reset_rooms(self):
"""Reset/clear all rooms"""
......@@ -368,7 +368,7 @@ class TestBot(object):
config.STORAGE = 'Memory'
if extra_config is not None:
log.debug('Merging %s to the bot config.' % repr(extra_config))
log.debug('Merging %s to the bot config.', repr(extra_config))
for k, v in extra_config.items():
setattr(config, k, v)
......@@ -454,7 +454,7 @@ class TestBot(object):
"""Assert the given command returns the given response"""
self.bot.push_message(command)
msg = self.bot.pop_message(timeout)
assert response in msg, "'{}' not in '{}'".format(response, msg)
assert response in msg, f'{response} not in {msg}.'
def assertCommandFound(self, command, timeout=5):
"""Assert the given command exists"""
......
......@@ -153,7 +153,7 @@ class TextOccupant(TextPerson, RoomOccupant):
return self._room
def __str__(self):
return '#%s/%s' % (self._room.name, self._person.person)
return f'#{self._room.name}/{self._person.person}'
def __eq__(self, other):
return self.person == other.person and self.room == other.room
......@@ -260,10 +260,10 @@ class TextBackend(ErrBot):
prompt = '[␍] ' if full_msg else '>>> '
if ANSI or self.demo_mode:
color = fg.red if self.user.person in self.bot_config.BOT_ADMINS[0] else fg.green
prompt = str(color) + '[%s ➡ %s] ' % (frm, to) + str(fg.cyan) + prompt + str(fx.reset)
prompt = f'{color}[{frm} ➡ {to}] {fg.cyan}{prompt}{fx.reset}'
entry = input(prompt)
else:
entry = input('[%s ➡ %s] ' % (frm, to) + prompt)
entry = input(f'[{frm} ➡ {to}] {prompt}')
if not self._multiline:
full_msg = entry
......@@ -351,7 +351,7 @@ class TextBackend(ErrBot):
self._react('-', msg, reaction)
def _react(self, sign, msg, reaction):
self.send(msg.frm, 'reaction {}:{}:'.format(sign, reaction), in_reply_to=msg)
self.send(msg.frm, f'reaction {sign}:{reaction}:', in_reply_to=msg)
def change_presence(self, status: str = ONLINE, message: str = '') -> None:
log.debug("*** Changed presence to [%s] %s", (status, message))
......@@ -393,4 +393,4 @@ class TextBackend(ErrBot):
return self._rooms
def prefix_groupchat_reply(self, message, identifier):
message.body = '{0} {1}'.format(identifier.person, message.body)
message.body = f'{identifier.person} {message.body}'
......@@ -115,14 +115,8 @@ class XMPPRoom(XMPPIdentifier, Room):
"""
room = str(self)
self.xep0045.joinMUC(room, username, password=password, wait=True)
self._bot.conn.add_event_handler(
"muc::{}::got_online".format(room),
self._bot.user_joined_chat
)
self._bot.conn.add_event_handler(
"muc::{}::got_offline".format(room),
self._bot.user_left_chat
)
self._bot.conn.add_event_handler(f'muc::{room}::got_online', self._bot.user_joined_chat)
self._bot.conn.add_event_handler(f'muc::{room}::got_offline', self._bot.user_left_chat)
# Room configuration can only be done once a MUC presence stanza
# has been received from the server. This HAS to take place in a
# separate thread because of how SleekXMPP processes these stanzas.
......@@ -130,7 +124,7 @@ class XMPPRoom(XMPPIdentifier, Room):
t.setDaemon(True)
t.start()
self._bot.callback_room_joined(self)
log.info("Joined room {}".format(room))
log.info('Joined room %s.', room)
def leave(self, reason=None):
"""
......@@ -145,18 +139,12 @@ class XMPPRoom(XMPPIdentifier, Room):
try:
self.xep0045.leaveMUC(room=room, nick=self.xep0045.ourNicks[room], msg=reason)
self._bot.conn.del_event_handler(
"muc::{}::got_online".format(room),
self._bot.user_joined_chat
)
self._bot.conn.del_event_handler(
"muc::{}::got_offline".format(room),
self._bot.user_left_chat
)
log.info("Left room {}".format(room))
self._bot.conn.del_event_handler(f'muc::{room}::got_online', self._bot.user_joined_chat)
self._bot.conn.del_event_handler(f'muc::{room}::got_offline', self._bot.user_left_chat)
log.info('Left room %s.', room)
self._bot.callback_room_left(self)
except KeyError:
log.debug("Trying to leave {} while not in this room".format(room))
log.debug('Trying to leave %s while not in this room.', room)
def create(self):
"""
......@@ -176,7 +164,7 @@ class XMPPRoom(XMPPIdentifier, Room):
Calling this on a non-existing room is a no-op.
"""
self.xep0045.destroy(str(self))
log.info("Destroyed room {!s}".format(self))
log.info('Destroyed room %s.', self)
@property
def exists(self):
......@@ -187,9 +175,7 @@ class XMPPRoom(XMPPIdentifier, Room):
Returns `True` if the room exists, `False` otherwise.
"""
logging.warning(
"XMPP back-end does not support determining if a room exists. "
"Returning the result of joined instead."
)
'XMPP back-end does not support determining if a room exists. Returning the result of joined instead.')
return self.joined
@property
......@@ -261,7 +247,7 @@ class XMPPRoom(XMPPIdentifier, Room):
room = str(self)
for jid in args:
self.xep0045.invite(room, jid)
log.info("Invited {} to {}".format(jid, room))
log.info('Invited %s to %s.', jid, room)
def configure(self):
"""
......@@ -282,12 +268,11 @@ class XMPPRoom(XMPPIdentifier, Room):
)
if affiliation == "owner":
log.debug("Configuring room {} because we have owner affiliation".format(room))
log.debug('Configuring room %s: we have owner affiliation.', room)
form = self.xep0045.getRoomConfig(room)
self.xep0045.configureRoom(room, form)
else:
log.debug("Not configuring room {} because we don't have owner affiliation (affiliation={})"
.format(room, affiliation))
log.debug("Not configuring room %s: we don't have owner affiliation (affiliation=%s)", room, affiliation)
class XMPPRoomOccupant(XMPPPerson, RoomOccupant):
......@@ -464,23 +449,23 @@ class XMPPBackend(ErrBot):
return self._build_room_occupant(txtrep) if 'muc' in event else self._build_person(txtrep)
def contact_online(self, event):
log.debug("contact_online %s" % event)
log.debug('contact_online %s.', event)
self.callback_presence(Presence(identifier=self._idd_from_event(event), status=ONLINE))
def contact_offline(self, event):