From bc4af153afb40c63d6d001fedce2880646bd846d Mon Sep 17 00:00:00 2001 From: Dpeta <69427753+Dpeta@users.noreply.github.com> Date: Sat, 14 Jan 2023 21:52:07 +0100 Subject: [PATCH 1/6] Fix Pylint errors and further disable console, as it is unmaintained. Remove osVer function from ostools Remove isOSXLeopard only use chum.handle Fix bad except error Comment out console related function fix fix* except order fallback if i is not defined for log fix console Explicitly define nick() to appease pylint Comment out connect_cb, it's unused for pchum rn e is unsubscribable Explicitly define 'simple' irc commands fix exceptions part 2 fix send Explicitly define lastmsg as None on init iterate through copy or urls Comment out console for not as it's unmaintained --- console.py | 2 ++ convo.py | 13 +++++++++---- memos.py | 7 +------ ostools.py | 15 --------------- oyoyo/client.py | 12 ++++-------- oyoyo/helpers.py | 33 +++++++++++---------------------- pesterchum.py | 14 +++++++++----- profile.py | 12 +++++------- 8 files changed, 41 insertions(+), 67 deletions(-) diff --git a/console.py b/console.py index b9f8d1d..68a37fd 100644 --- a/console.py +++ b/console.py @@ -1,3 +1,4 @@ +""" # vim: set autoindent ts=4 sts=4 sw=4 textwidth=79 expandtab: # -*- coding=UTF-8; tab-width: 4 -*- # import os @@ -550,3 +551,4 @@ class ConsoleInput(QtWidgets.QLineEdit): parent.text.area.keyPressEvent(event) else: super(ConsoleInput, self).keyPressEvent(event) +""" diff --git a/convo.py b/convo.py index 612267e..7de6644 100644 --- a/convo.py +++ b/convo.py @@ -390,6 +390,7 @@ class PesterText(QtWidgets.QTextEdit): self.textSelected = False self.copyAvailable[bool].connect(self.textReady) self.urls = {} + self.lastmsg = None for k in smiledict: self.addAnimation( QtCore.QUrl("smilies/%s" % (smiledict[k])), @@ -549,9 +550,13 @@ class PesterText(QtWidgets.QTextEdit): and not parent.isBot(chum.handle) ): idlethreshhold = 60 - if ( - not hasattr(self, "lastmsg") - ) or datetime.now() - self.lastmsg > timedelta(0, idlethreshhold): + do_idle_send = False + if self.lastmsg is None: + do_idle_send = True + else: + if datetime.now() - self.lastmsg > timedelta(0, idlethreshhold): + do_idle_send = True + if do_idle_send: verb = window.theme["convo/text/idle"] idlemsg = me.idlemsg(systemColor, verb) parent.textArea.append(convertTags(idlemsg)) @@ -995,7 +1000,7 @@ class PesterConvo(QtWidgets.QFrame): def closeEvent(self, event): self.mainwindow.waitingMessages.messageAnswered(self.title()) - for movie in self.textArea.urls: + for movie in self.textArea.urls.copy(): movie.setFileName("") # Required, sometimes, for some reason. . . movie.stop() del movie diff --git a/memos.py b/memos.py index a3af349..005896d 100644 --- a/memos.py +++ b/memos.py @@ -398,12 +398,7 @@ class MemoText(PesterText): # new chum! time current newtime = timedelta(0) time = TimeTracker(newtime) - - # 'handle' undefined? - try: - parent.times[handle] = time - except: - parent.times[chum.handle] = time + parent.times[chum.handle] = time else: time = parent.time diff --git a/ostools.py b/ostools.py index 7b94d61..e598184 100644 --- a/ostools.py +++ b/ostools.py @@ -1,7 +1,6 @@ import os import sys import ctypes -import platform try: from PyQt6.QtCore import QStandardPaths @@ -26,20 +25,6 @@ def isOSXBundle(): return isOSX() and (os.path.abspath(".").find(".app") != -1) -def isOSXLeopard(): - return isOSX() and platform.mac_ver()[0].startswith("10.5") - - -def osVer(): - if isWin32(): - return " ".join(platform.win32_ver()) - elif isOSX(): - ver = platform.mac_ver() - return " ".join((ver[0], " (", ver[2], ")")) - elif isLinux(): - return " ".join(platform.linux_distribution()) - - def isRoot(): """Return True if running with elevated privileges.""" # Windows diff --git a/oyoyo/client.py b/oyoyo/client.py index e5f1689..0a0adcb 100644 --- a/oyoyo/client.py +++ b/oyoyo/client.py @@ -100,7 +100,7 @@ class IRCClient: self.username = None self.host = None self.port = None - self.connect_cb = None + #self.connect_cb = None self.timeout = None self.blocking = None self.ssl = None @@ -273,8 +273,8 @@ class IRCClient: helpers.nick(self, self.nick) helpers.user(self, self.username, self.realname) - if self.connect_cb: - self.connect_cb(self) + #if self.connect_cb: + # self.connect_cb(self) def conn(self): """returns a generator object.""" @@ -337,11 +337,7 @@ class IRCClient: PchumLog.warning("conn exception %s in %s" % (e, self)) if self._end: break - try: # a little dance of compatibility to get the errno - errno = e.errno - except AttributeError: - errno = e[0] - if not self.blocking and errno == 11: + if not self.blocking and e.errno == 11: pass else: raise e diff --git a/oyoyo/helpers.py b/oyoyo/helpers.py index 6dbb897..1d142cf 100644 --- a/oyoyo/helpers.py +++ b/oyoyo/helpers.py @@ -115,35 +115,24 @@ def identify(cli, passwd, authuser="NickServ"): def quit(cli, msg): cli.send("QUIT %s" % (msg)) +def nick(cli, nick): + cli.send(f"NICK", nick) def user(cli, username, realname): cli.send("USER", username, "0", "*", ":" + realname) +def join(cli, channel): + """Protocol potentially allows multiple channels or keys.""" + cli.send("JOIN", channel) -_simple = ( - "join", - "part", - "nick", - "notice", - "invite", -) +def part(cli, channel): + cli.send("PART", channel) +def notice(cli, target, text): + cli.send("NOTICE", target, text) -def _addsimple(): - import sys - - def simplecmd(cmd_name): - def f(cli, *args): - cli.send(cmd_name, *args) - - return f - - m = sys.modules[__name__] - for t in _simple: - setattr(m, t, simplecmd(t.upper())) - - -_addsimple() +def invite(cli, nick, channel): + cli.send("INVITE", nick, channel) def _addNumerics(): diff --git a/pesterchum.py b/pesterchum.py index 6de0ccf..7d08f17 100755 --- a/pesterchum.py +++ b/pesterchum.py @@ -1461,6 +1461,7 @@ class PesterWindow(MovingWindow): self.menu.setNativeMenuBar(False) self.menu.setObjectName("mainmenu") + """ if self.theme.has_key("main/menus/client/console"): self.console = AttrDict( dict( @@ -1498,7 +1499,8 @@ class PesterWindow(MovingWindow): # ~self.connect(self.console.shortcuts.curwgt, # ~ QtCore.SIGNAL('activate()'), self.console. self.console.is_open = False - + """ + filemenu = self.menu.addMenu(self.theme["main/menus/client/_name"]) self.filemenu = filemenu filemenu.addAction(opts) @@ -2003,6 +2005,7 @@ class PesterWindow(MovingWindow): self.tabmemo = MemoTabWindow(self) self.tabmemo.windowClosed.connect(self.memoTabsClosed) + """ @QtCore.pyqtSlot() def toggleConsole(self): if not _CONSOLE: @@ -2070,6 +2073,7 @@ class PesterWindow(MovingWindow): self.console.is_open = False self.console.window = None PchumLog.info("Console closed.") + """ def newMemo(self, channel, timestr, secret=False, invite=False): if channel == "#pesterchum": @@ -2215,10 +2219,10 @@ class PesterWindow(MovingWindow): ## else: ## self.console.action.setText("Console") # has_key doesn't work out here for some reason, possibly because of inherits? - try: - self.console.action.setText(self.theme["main/menus/client/console"]) - except: - self.console.action.setText("Console") + #try: + # self.console.action.setText(self.theme["main/menus/client/console"]) + #except: + # self.console.action.setText("Console") try: self.reportBugAction.setText(self.theme["main/menus/help/reportbug"]) diff --git a/profile.py b/profile.py index 90678f9..f93c6d9 100644 --- a/profile.py +++ b/profile.py @@ -225,15 +225,12 @@ with a backup from: %s" pzip.writestr(x, f.read()) PchumLog.info("Updated backups-%s." % current_backup) - except OSError as e: - PchumLog.warning("Failed to make backup, no permission?") - PchumLog.warning(e) except shutil.Error as e: - PchumLog.warning("Failed to make backup, shutil error?") - PchumLog.warning(e) + PchumLog.warning(f"Failed to make backup, shutil error?\n{e}") except zipfile.BadZipFile as e: - PchumLog.warning("Failed to make backup, BadZipFile?") - PchumLog.warning(e) + PchumLog.warning(f"Failed to make backup, BadZipFile?\n{e}") + except OSError as e: + PchumLog.warning(f"Failed to make backup, no permission?\n{e}") def chums(self): if "chums" not in self.config: @@ -736,6 +733,7 @@ class userProfile(object): return self.mentions def setMentions(self, mentions): + i = None try: for (i, m) in enumerate(mentions): re.compile(m) From 7e1b096be5e7eef2bf6f7a7b014105d059bd543c Mon Sep 17 00:00:00 2001 From: Dpeta <69427753+Dpeta@users.noreply.github.com> Date: Sat, 14 Jan 2023 22:52:30 +0100 Subject: [PATCH 2/6] Reformat with black and move console.py --- console.py => console.py.disabled | 0 oyoyo/client.py | 4 ++-- oyoyo/helpers.py | 6 ++++++ pesterchum.py | 6 +++--- profile.py | 2 +- 5 files changed, 12 insertions(+), 6 deletions(-) rename console.py => console.py.disabled (100%) diff --git a/console.py b/console.py.disabled similarity index 100% rename from console.py rename to console.py.disabled diff --git a/oyoyo/client.py b/oyoyo/client.py index 0a0adcb..0b08e29 100644 --- a/oyoyo/client.py +++ b/oyoyo/client.py @@ -100,7 +100,7 @@ class IRCClient: self.username = None self.host = None self.port = None - #self.connect_cb = None + # self.connect_cb = None self.timeout = None self.blocking = None self.ssl = None @@ -273,7 +273,7 @@ class IRCClient: helpers.nick(self, self.nick) helpers.user(self, self.username, self.realname) - #if self.connect_cb: + # if self.connect_cb: # self.connect_cb(self) def conn(self): diff --git a/oyoyo/helpers.py b/oyoyo/helpers.py index 1d142cf..902cd8a 100644 --- a/oyoyo/helpers.py +++ b/oyoyo/helpers.py @@ -115,22 +115,28 @@ def identify(cli, passwd, authuser="NickServ"): def quit(cli, msg): cli.send("QUIT %s" % (msg)) + def nick(cli, nick): cli.send(f"NICK", nick) + def user(cli, username, realname): cli.send("USER", username, "0", "*", ":" + realname) + def join(cli, channel): """Protocol potentially allows multiple channels or keys.""" cli.send("JOIN", channel) + def part(cli, channel): cli.send("PART", channel) + def notice(cli, target, text): cli.send("NOTICE", target, text) + def invite(cli, nick, channel): cli.send("INVITE", nick, channel) diff --git a/pesterchum.py b/pesterchum.py index 7d08f17..1197181 100755 --- a/pesterchum.py +++ b/pesterchum.py @@ -1500,7 +1500,7 @@ class PesterWindow(MovingWindow): # ~ QtCore.SIGNAL('activate()'), self.console. self.console.is_open = False """ - + filemenu = self.menu.addMenu(self.theme["main/menus/client/_name"]) self.filemenu = filemenu filemenu.addAction(opts) @@ -2219,9 +2219,9 @@ class PesterWindow(MovingWindow): ## else: ## self.console.action.setText("Console") # has_key doesn't work out here for some reason, possibly because of inherits? - #try: + # try: # self.console.action.setText(self.theme["main/menus/client/console"]) - #except: + # except: # self.console.action.setText("Console") try: diff --git a/profile.py b/profile.py index f93c6d9..8c264bc 100644 --- a/profile.py +++ b/profile.py @@ -850,7 +850,7 @@ class PesterProfileDB(dict): handle, color=QtGui.QColor(c["color"]), mood=Mood(c["mood"]), - **options + **options, ), ) ) From 3a78e4f5b88659273141af9ea1f0105960306390 Mon Sep 17 00:00:00 2001 From: Dpeta <69427753+Dpeta@users.noreply.github.com> Date: Sat, 14 Jan 2023 22:56:15 +0100 Subject: [PATCH 3/6] remove fstring --- oyoyo/helpers.py | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/oyoyo/helpers.py b/oyoyo/helpers.py index 902cd8a..bfc6b93 100644 --- a/oyoyo/helpers.py +++ b/oyoyo/helpers.py @@ -115,28 +115,22 @@ def identify(cli, passwd, authuser="NickServ"): def quit(cli, msg): cli.send("QUIT %s" % (msg)) - def nick(cli, nick): - cli.send(f"NICK", nick) - + cli.seld("NICK", nick) def user(cli, username, realname): cli.send("USER", username, "0", "*", ":" + realname) - def join(cli, channel): """Protocol potentially allows multiple channels or keys.""" cli.send("JOIN", channel) - def part(cli, channel): cli.send("PART", channel) - def notice(cli, target, text): cli.send("NOTICE", target, text) - def invite(cli, nick, channel): cli.send("INVITE", nick, channel) From 5b6d5d153f91039b7cc36677abdaeda4fae21f7c Mon Sep 17 00:00:00 2001 From: Dpeta <69427753+Dpeta@users.noreply.github.com> Date: Sat, 14 Jan 2023 22:59:59 +0100 Subject: [PATCH 4/6] Run all scripts through "pyupgrade --py38-plus" --- convo.py | 22 +++++++------- dataobjs.py | 61 +++++++++++++++++++------------------- generic.py | 20 ++++++------- irc.py | 40 +++++++++++++------------ logviewer.py | 14 ++++----- memos.py | 16 +++++----- menus.py | 6 ++-- mood.py | 2 +- oyoyo/client.py | 10 +++---- oyoyo/cmdhandler.py | 12 ++++---- oyoyo/helpers.py | 16 ++++++---- oyoyo/services.py | 4 +-- parsetools.py | 42 +++++++++++++------------- pesterchum.py | 72 +++++++++++++++++++++------------------------ pnc/dep/attrdict.py | 23 +++++++-------- pnc/lexercon.py | 9 ++---- pnc/unicolor.py | 10 ++----- profile.py | 56 ++++++++++++++++++----------------- pytwmn.py | 6 ++-- quirks.py | 6 ++-- toast.py | 6 ++-- 21 files changed, 228 insertions(+), 225 deletions(-) diff --git a/convo.py b/convo.py index 7de6644..5e240d7 100644 --- a/convo.py +++ b/convo.py @@ -23,7 +23,7 @@ PchumLog = logging.getLogger("pchumLogger") class PesterTabWindow(QtWidgets.QFrame): def __init__(self, mainwindow, parent=None, convo="convo"): - super(PesterTabWindow, self).__init__(parent) + super().__init__(parent) self.setAttribute(QtCore.Qt.WidgetAttribute.WA_QuitOnClose, False) self.setFocusPolicy(QtCore.Qt.FocusPolicy.ClickFocus) self.mainwindow = mainwindow @@ -337,7 +337,7 @@ class PesterTabWindow(QtWidgets.QFrame): class PesterMovie(QtGui.QMovie): def __init__(self, parent): - super(PesterMovie, self).__init__(parent) + super().__init__(parent) self.textwindow = parent @QtCore.pyqtSlot(int) @@ -374,7 +374,7 @@ class PesterMovie(QtGui.QMovie): class PesterText(QtWidgets.QTextEdit): def __init__(self, theme, parent=None): - super(PesterText, self).__init__(parent) + super().__init__(parent) if hasattr(self.parent(), "mainwindow"): self.mainwindow = self.parent().mainwindow else: @@ -594,7 +594,7 @@ class PesterText(QtWidgets.QTextEdit): parent.textInput.keyPressEvent(event) # Pass to the normal handler. - super(PesterText, self).keyPressEvent(event) + super().keyPressEvent(event) def mousePressEvent(self, event): if event.button() == QtCore.Qt.MouseButton.LeftButton: @@ -647,7 +647,7 @@ class PesterInput(QtWidgets.QLineEdit): stylesheet_path = "convo/input/style" def __init__(self, theme, parent=None): - super(PesterInput, self).__init__(parent) + super().__init__(parent) self.changeTheme(theme) def changeTheme(self, theme): @@ -662,7 +662,7 @@ class PesterInput(QtWidgets.QLineEdit): def focusInEvent(self, event): self.parent().clearNewMessage() self.parent().textArea.textCursor().clearSelection() - super(PesterInput, self).focusInEvent(event) + super().focusInEvent(event) def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key.Key_Up: @@ -677,12 +677,12 @@ class PesterInput(QtWidgets.QLineEdit): elif event.key() in [QtCore.Qt.Key.Key_PageUp, QtCore.Qt.Key.Key_PageDown]: self.parent().textArea.keyPressEvent(event) self.parent().mainwindow.idler.time = 0 - super(PesterInput, self).keyPressEvent(event) + super().keyPressEvent(event) class PesterConvo(QtWidgets.QFrame): def __init__(self, chum, initiated, mainwindow, parent=None): - super(PesterConvo, self).__init__(parent) + super().__init__(parent) self.setAttribute(QtCore.Qt.WidgetAttribute.WA_QuitOnClose, False) self.setObjectName(chum.handle) self.setFocusPolicy(QtCore.Qt.FocusPolicy.ClickFocus) @@ -691,7 +691,7 @@ class PesterConvo(QtWidgets.QFrame): theme = self.mainwindow.theme self.resize(*theme["convo/size"]) self.setStyleSheet( - "QtWidgets.QFrame#%s { %s }" % (chum.handle, theme["convo/style"]) + "QtWidgets.QFrame#{} {{ {} }}".format(chum.handle, theme["convo/style"]) ) self.setWindowIcon(self.icon()) self.setWindowTitle(self.title()) @@ -1012,7 +1012,9 @@ class PesterConvo(QtWidgets.QFrame): def changeTheme(self, theme): self.resize(*theme["convo/size"]) self.setStyleSheet( - "QtWidgets.QFrame#%s { %s }" % (self.chum.handle, theme["convo/style"]) + "QtWidgets.QFrame#{} {{ {} }}".format( + self.chum.handle, theme["convo/style"] + ) ) margins = theme["convo/margins"] diff --git a/dataobjs.py b/dataobjs.py index 1d63f4b..11eba6c 100644 --- a/dataobjs.py +++ b/dataobjs.py @@ -34,7 +34,7 @@ _memore = re.compile(r"(\s|^)(#[A-Za-z0-9_]+)") _handlere = re.compile(r"(\s|^)(@[A-Za-z0-9_]+)") -class pesterQuirk(object): +class pesterQuirk: def __init__(self, quirk): if type(quirk) != dict: raise ValueError("Quirks must be given a dictionary") @@ -112,14 +112,14 @@ class pesterQuirk(object): elif self.type == "suffix": return "END WITH: %s" % (self.quirk["value"]) elif self.type == "replace": - return "REPLACE %s WITH %s" % (self.quirk["from"], self.quirk["to"]) + return "REPLACE {} WITH {}".format(self.quirk["from"], self.quirk["to"]) elif self.type == "regexp": - return "REGEXP: %s REPLACED WITH %s" % ( + return "REGEXP: {} REPLACED WITH {}".format( self.quirk["from"], self.quirk["to"], ) elif self.type == "random": - return "REGEXP: %s RANDOMLY REPLACED WITH %s" % ( + return "REGEXP: {} RANDOMLY REPLACED WITH {}".format( self.quirk["from"], [r for r in self.quirk["randomlist"]], ) @@ -127,7 +127,7 @@ class pesterQuirk(object): return "MISPELLER: %d%%" % (self.quirk["percentage"]) -class pesterQuirks(object): +class pesterQuirks: def __init__(self, quirklist): self.quirklist = [] for q in quirklist: @@ -258,11 +258,10 @@ class pesterQuirks(object): return final def __iter__(self): - for q in self.quirklist: - yield q + yield from self.quirklist -class PesterProfile(object): +class PesterProfile: def __init__( self, handle, @@ -345,12 +344,12 @@ class PesterProfile(object): msg = convertTags(lexmsg[1:], "text") uppersuffix = suffix.upper() if time is not None: - handle = "%s %s" % (time.temporal, self.handle) + handle = f"{time.temporal} {self.handle}" initials = time.pcf + self.initials() + time.number + uppersuffix else: handle = self.handle initials = self.initials() + uppersuffix - return "-- %s%s [%s] %s --" % ( + return "-- {}{} [{}] {} --".format( syscolor.name(), handle, suffix, @@ -360,7 +359,7 @@ class PesterProfile(object): ) def pestermsg(self, otherchum, syscolor, verb): - return "-- %s [%s] %s %s [%s] at %s --" % ( + return "-- {} [{}] {} {} [{}] at {} --".format( syscolor.name(), self.handle, self.colorhtml(), @@ -386,7 +385,7 @@ class PesterProfile(object): ) def idlemsg(self, syscolor, verb): - return "-- %s [%s] %s --" % ( + return "-- {} [{}] {} --".format( syscolor.name(), self.handle, self.colorhtml(), @@ -396,14 +395,14 @@ class PesterProfile(object): def memoclosemsg(self, syscolor, initials, verb): if type(initials) == type(list()): - return "%s %s." % ( + return "{} {}.".format( syscolor.name(), self.colorhtml(), ", ".join(initials), verb, ) else: - return "%s%s%s %s." % ( + return "{}{}{} {}.".format( syscolor.name(), self.colorhtml(), initials.pcf, @@ -416,7 +415,7 @@ class PesterProfile(object): if len(initials) <= 0: return "Netsplit quits: None" % (syscolor.name()) else: - return "Netsplit quits: %s" % ( + return "Netsplit quits: {}".format( syscolor.name(), ", ".join(initials), ) @@ -427,7 +426,7 @@ class PesterProfile(object): PchumLog.debug("pre pcf+self.initials()") initials = timeGrammar.pcf + self.initials() PchumLog.debug("post pcf+self.initials()") - return "%s %s %s %s." % ( + return "{} {} {} {}.".format( syscolor.name(), self.colorhtml(), initials, @@ -440,11 +439,13 @@ class PesterProfile(object): opinit = opgrammar.pcf + opchum.initials() + opgrammar.number if type(initials) == type(list()): if opchum.handle == reason: - return "%s banned %s from responding to memo." % ( - opchum.colorhtml(), - opinit, - self.colorhtml(), - ", ".join(initials), + return ( + "{} banned {} from responding to memo.".format( + opchum.colorhtml(), + opinit, + self.colorhtml(), + ", ".join(initials), + ) ) else: return ( @@ -501,7 +502,7 @@ class PesterProfile(object): def memopermabanmsg(self, opchum, opgrammar, syscolor, timeGrammar): initials = timeGrammar.pcf + self.initials() + timeGrammar.number opinit = opgrammar.pcf + opchum.initials() + opgrammar.number - return "%s permabanned %s from the memo." % ( + return "{} permabanned {} from the memo.".format( opchum.colorhtml(), opinit, self.colorhtml(), @@ -512,7 +513,7 @@ class PesterProfile(object): # (temporal, pcf, when) = (timeGrammar.temporal, timeGrammar.pcf, timeGrammar.when) timetext = timeDifference(td) initials = timeGrammar.pcf + self.initials() + timeGrammar.number - return "%s %s [%s] %s %s." % ( + return "{} {} [{}] {} {}.".format( syscolor.name(), self.colorhtml(), timeGrammar.temporal, @@ -524,7 +525,7 @@ class PesterProfile(object): def memoopmsg(self, opchum, opgrammar, syscolor): opinit = opgrammar.pcf + opchum.initials() + opgrammar.number - return "%s made %s an OP." % ( + return "{} made {} an OP.".format( opchum.colorhtml(), opinit, self.colorhtml(), @@ -533,7 +534,7 @@ class PesterProfile(object): def memodeopmsg(self, opchum, opgrammar, syscolor): opinit = opgrammar.pcf + opchum.initials() + opgrammar.number - return "%s took away %s's OP powers." % ( + return "{} took away {}'s OP powers.".format( opchum.colorhtml(), opinit, self.colorhtml(), @@ -542,7 +543,7 @@ class PesterProfile(object): def memovoicemsg(self, opchum, opgrammar, syscolor): opinit = opgrammar.pcf + opchum.initials() + opgrammar.number - return "%s gave %s voice." % ( + return "{} gave {} voice.".format( opchum.colorhtml(), opinit, self.colorhtml(), @@ -551,7 +552,7 @@ class PesterProfile(object): def memodevoicemsg(self, opchum, opgrammar, syscolor): opinit = opgrammar.pcf + opchum.initials() + opgrammar.number - return "%s took away %s's voice." % ( + return "{} took away {}'s voice.".format( opchum.colorhtml(), opinit, self.colorhtml(), @@ -564,7 +565,7 @@ class PesterProfile(object): modeon = "now" else: modeon = "no longer" - return "Memo is %s %s by %s" % ( + return "Memo is {} {} by {}".format( syscolor.name(), modeon, modeverb, @@ -574,7 +575,7 @@ class PesterProfile(object): def memoquirkkillmsg(self, opchum, opgrammar, syscolor): opinit = opgrammar.pcf + opchum.initials() + opgrammar.number - return "%s turned off your quirk." % ( + return "{} turned off your quirk.".format( syscolor.name(), opchum.colorhtml(), opinit, @@ -598,7 +599,7 @@ class PesterProfile(object): return (True,) -class PesterHistory(object): +class PesterHistory: def __init__(self): self.history = [] self.current = 0 diff --git a/generic.py b/generic.py index 0f06980..3bf9297 100644 --- a/generic.py +++ b/generic.py @@ -19,19 +19,19 @@ class mysteryTime(timedelta): class CaseInsensitiveDict(dict): def __setitem__(self, key, value): - super(CaseInsensitiveDict, self).__setitem__(key.lower(), value) + super().__setitem__(key.lower(), value) def __getitem__(self, key): - return super(CaseInsensitiveDict, self).__getitem__(key.lower()) + return super().__getitem__(key.lower()) def __contains__(self, key): - return super(CaseInsensitiveDict, self).__contains__(key.lower()) + return super().__contains__(key.lower()) def has_key(self, key): - return key.lower() in super(CaseInsensitiveDict, self) + return key.lower() in super() def __delitem__(self, key): - super(CaseInsensitiveDict, self).__delitem__(key.lower()) + super().__delitem__(key.lower()) class PesterList(list): @@ -41,7 +41,7 @@ class PesterList(list): class PesterIcon(QtGui.QIcon): def __init__(self, *x): - super(PesterIcon, self).__init__(x[0]) + super().__init__(x[0]) if type(x[0]) in [str, str]: self.icon_pixmap = QtGui.QPixmap(x[0]) else: @@ -86,7 +86,7 @@ class RightClickTree(QtWidgets.QTreeWidget): class MultiTextDialog(QtWidgets.QDialog): def __init__(self, title, parent, *queries): - super(MultiTextDialog, self).__init__(parent) + super().__init__(parent) self.setWindowTitle(title) if len(queries) == 0: return @@ -131,7 +131,7 @@ class MovingWindow(QtWidgets.QFrame): # https://doc.qt.io/qt-5/qwindow.html#startSystemMove # This is also the only method that works on Wayland, which doesn't support setting position. def __init__(self, *x, **y): - super(MovingWindow, self).__init__(*x, **y) + super().__init__(*x, **y) self.moving = None self.moveupdate = 0 @@ -163,7 +163,7 @@ class MovingWindow(QtWidgets.QFrame): self.moving = None -class NoneSound(object): +class NoneSound: def __init__(self, *args, **kwargs): pass @@ -179,7 +179,7 @@ class NoneSound(object): class WMButton(QtWidgets.QPushButton): def __init__(self, icon, parent=None): - super(WMButton, self).__init__(icon, "", parent) + super().__init__(icon, "", parent) self.setIconSize(icon.realsize()) self.resize(icon.realsize()) self.setFlat(True) diff --git a/irc.py b/irc.py index dba6d0c..333fc40 100644 --- a/irc.py +++ b/irc.py @@ -96,10 +96,10 @@ class PesterIRC(QtCore.QThread): except socket.timeout as se: PchumLog.debug("timeout in thread %s" % (self)) self.cli.close() - self.stopIRC = "%s, %s" % (type(se), se) + self.stopIRC = "{}, {}".format(type(se), se) return except (OSError, IndexError, ValueError) as se: - self.stopIRC = "%s, %s" % (type(se), se) + self.stopIRC = "{}, {}".format(type(se), se) PchumLog.debug("socket error, exiting thread") return else: @@ -372,7 +372,7 @@ class PesterIRC(QtCore.QThread): reason = str(l[1]) if len(l) > 2: for x in l[2:]: - reason += str(":") + str(x) + reason += ":" + str(x) else: reason = "" try: @@ -387,7 +387,7 @@ class PesterIRC(QtCore.QThread): c = str(channel) m = str(mode) cmd = str(command) - PchumLog.debug("c=%s\nm=%s\ncmd=%s" % (c, m, cmd)) + PchumLog.debug("c={}\nm={}\ncmd={}".format(c, m, cmd)) if cmd == "": cmd = None try: @@ -483,7 +483,7 @@ class PesterIRC(QtCore.QThread): class PesterHandler(DefaultCommandHandler): def notice(self, nick, chan, msg): handle = nick[0 : nick.find("!")] - PchumLog.info('---> recv "NOTICE %s :%s"' % (handle, msg)) + PchumLog.info('---> recv "NOTICE {} :{}"'.format(handle, msg)) if ( handle == "ChanServ" and chan == self.parent.mainwindow.profile().handle @@ -501,13 +501,13 @@ class PesterHandler(DefaultCommandHandler): mood = Mood(int(value)) self.parent.moodUpdated.emit(nick, mood) except ValueError: - PchumLog.warning("Invalid mood value, %s, %s" % (nick, mood)) + PchumLog.warning("Invalid mood value, {}, {}".format(nick, mood)) elif key.lower() == "color": color = QtGui.QColor(value) # Invalid color becomes rgb 0,0,0 self.parent.colorUpdated.emit(nick, color) def tagmsg(self, prefix, tags, *args): - PchumLog.info("TAGMSG: %s %s %s" % (prefix, tags, str(args))) + PchumLog.info("TAGMSG: {} {} {}".format(prefix, tags, str(args))) message_tags = tags[1:].split(";") for m in message_tags: if m.startswith("+pesterchum"): @@ -516,7 +516,7 @@ class PesterHandler(DefaultCommandHandler): key, value = m.split("=") except ValueError: return - PchumLog.info("Pesterchum tag: %s=%s" % (key, value)) + PchumLog.info("Pesterchum tag: {}={}".format(key, value)) # PESTERCHUM: syntax check if ( (value == "BEGIN") @@ -563,7 +563,7 @@ class PesterHandler(DefaultCommandHandler): msg = "/me" + msg[7:-1] # CTCPs that don't need to be shown elif msg[0] == "\x01": - PchumLog.info('---> recv "CTCP %s :%s"' % (handle, msg[1:-1])) + PchumLog.info('---> recv "CTCP {} :{}"'.format(handle, msg[1:-1])) # VERSION, return version if msg[1:-1].startswith("VERSION"): helpers.ctcp_reply( @@ -609,7 +609,7 @@ class PesterHandler(DefaultCommandHandler): if chan != "#pesterchum": # We don't need anywhere near that much spam. - PchumLog.info('---> recv "PRIVMSG %s :%s"' % (handle, msg)) + PchumLog.info('---> recv "PRIVMSG {} :{}"'.format(handle, msg)) if chan == "#pesterchum": # follow instructions @@ -740,7 +740,7 @@ class PesterHandler(DefaultCommandHandler): self.parent.metadata_supported = True def cap(self, server, nick, subcommand, tag): - PchumLog.info("CAP %s %s %s %s" % (server, nick, subcommand, tag)) + PchumLog.info("CAP {} {} {} {}".format(server, nick, subcommand, tag)) # if tag == "message-tags": # if subcommand == "ACK": @@ -756,7 +756,7 @@ class PesterHandler(DefaultCommandHandler): def quit(self, nick, reason): handle = nick[0 : nick.find("!")] - PchumLog.info('---> recv "QUIT %s: %s"' % (handle, reason)) + PchumLog.info('---> recv "QUIT {}: {}"'.format(handle, reason)) if handle == self.parent.mainwindow.randhandler.randNick: self.parent.mainwindow.randhandler.setRunning(False) server = self.parent.mainwindow.config.server() @@ -769,19 +769,21 @@ class PesterHandler(DefaultCommandHandler): def kick(self, opnick, channel, handle, reason): op = opnick[0 : opnick.find("!")] - self.parent.userPresentUpdate.emit(handle, channel, "kick:%s:%s" % (op, reason)) + self.parent.userPresentUpdate.emit( + handle, channel, "kick:{}:{}".format(op, reason) + ) # ok i shouldnt be overloading that but am lazy def part(self, nick, channel, reason="nanchos"): handle = nick[0 : nick.find("!")] - PchumLog.info('---> recv "PART %s: %s"' % (handle, channel)) + PchumLog.info('---> recv "PART {}: {}"'.format(handle, channel)) self.parent.userPresentUpdate.emit(handle, channel, "left") if channel == "#pesterchum": self.parent.moodUpdated.emit(handle, Mood("offline")) def join(self, nick, channel): handle = nick[0 : nick.find("!")] - PchumLog.info('---> recv "JOIN %s: %s"' % (handle, channel)) + PchumLog.info('---> recv "JOIN {}: {}"'.format(handle, channel)) self.parent.userPresentUpdate.emit(handle, channel, "join") if channel == "#pesterchum": if handle == self.parent.mainwindow.randhandler.randNick: @@ -887,7 +889,7 @@ class PesterHandler(DefaultCommandHandler): if l in ["+", "-"]: cur = l else: - modes.append("%s%s" % (cur, l)) + modes.append("{}{}".format(cur, l)) PchumLog.debug("handles=" + str(handles)) PchumLog.debug("enumerate(modes) = " + str(list(enumerate(modes)))) for (i, m) in enumerate(modes): @@ -911,7 +913,7 @@ class PesterHandler(DefaultCommandHandler): # self.parent.userPresentUpdate.emit("", channel, m+":%s" % (op)) def nick(self, oldnick, newnick, hopcount=0): - PchumLog.info("%s, %s" % (oldnick, newnick)) + PchumLog.info("{}, {}".format(oldnick, newnick)) # svsnick if oldnick == self.mainwindow.profile().handle: # Server changed our handle, svsnick? @@ -926,7 +928,9 @@ class PesterHandler(DefaultCommandHandler): self.parent.myHandleChanged.emit(newnick) newchum = PesterProfile(newnick, chumdb=self.mainwindow.chumdb) self.parent.moodUpdated.emit(oldhandle, Mood("offline")) - self.parent.userPresentUpdate.emit("%s:%s" % (oldhandle, newnick), "", "nick") + self.parent.userPresentUpdate.emit( + "{}:{}".format(oldhandle, newnick), "", "nick" + ) if newnick in self.mainwindow.chumList.chums: self.getMood(newchum) if oldhandle == self.parent.mainwindow.randhandler.randNick: diff --git a/logviewer.py b/logviewer.py index 737423d..38f7679 100644 --- a/logviewer.py +++ b/logviewer.py @@ -65,8 +65,8 @@ class PesterLogUserSelect(QtWidgets.QDialog): instructions = QtWidgets.QLabel("Pick a memo or chumhandle:") - if os.path.exists("%s/%s" % (self.logpath, self.handle)): - chumMemoList = os.listdir("%s/%s/" % (self.logpath, self.handle)) + if os.path.exists("{}/{}".format(self.logpath, self.handle)): + chumMemoList = os.listdir("{}/{}/".format(self.logpath, self.handle)) else: chumMemoList = [] chumslist = config.chums() @@ -166,17 +166,17 @@ class PesterLogViewer(QtWidgets.QDialog): self.format = "bbcode" if os.path.exists( - "%s/%s/%s/%s" % (self.logpath, self.handle, chum, self.format) + "{}/{}/{}/{}".format(self.logpath, self.handle, chum, self.format) ): self.logList = os.listdir( - "%s/%s/%s/%s/" % (self.logpath, self.handle, self.chum, self.format) + "{}/{}/{}/{}/".format(self.logpath, self.handle, self.chum, self.format) ) else: self.logList = [] if ( not os.path.exists( - "%s/%s/%s/%s" % (self.logpath, self.handle, chum, self.format) + "{}/{}/{}/{}".format(self.logpath, self.handle, chum, self.format) ) or len(self.logList) == 0 ): @@ -248,7 +248,7 @@ class PesterLogViewer(QtWidgets.QDialog): for (i, l) in enumerate(self.logList): my = self.fileToMonthYear(l) if my[0] != last[0]: - child_1 = QtWidgets.QTreeWidgetItem(["%s %s" % (my[0], my[1])]) + child_1 = QtWidgets.QTreeWidgetItem(["{} {}".format(my[0], my[1])]) # child_1.setForeground(0, blackbrush) self.tree.addTopLevelItem(child_1) if i == 0: @@ -313,7 +313,7 @@ class PesterLogViewer(QtWidgets.QDialog): .replace("[url]", "") .replace("[/url]", "") ) - cline = re.sub("\[color=(#.{6})]", r"", cline) + cline = re.sub(r"\[color=(#.{6})]", r"", cline) self.textArea.append(convertTags(cline)) textCur = self.textArea.textCursor() # textCur.movePosition(1) diff --git a/memos.py b/memos.py index 005896d..21f9f95 100644 --- a/memos.py +++ b/memos.py @@ -103,7 +103,7 @@ def pcfGrammar(td): return (temporal, pcf, when) -class TimeGrammar(object): +class TimeGrammar: def __init__(self, temporal, pcf, when, number="0"): self.temporal = temporal self.pcf = pcf @@ -228,7 +228,7 @@ class TimeTracker(list): class TimeInput(QtWidgets.QLineEdit): def __init__(self, timeslider, parent): - super(TimeInput, self).__init__(parent) + super().__init__(parent) self.timeslider = timeslider self.setText("+0:00") self.timeslider.valueChanged[int].connect(self.setTime) @@ -260,7 +260,7 @@ class TimeInput(QtWidgets.QLineEdit): class TimeSlider(QtWidgets.QSlider): def __init__(self, orientation, parent): - super(TimeSlider, self).__init__(orientation, parent) + super().__init__(orientation, parent) self.setTracking(True) self.setMinimum(-50) self.setMaximum(50) @@ -278,7 +278,7 @@ class TimeSlider(QtWidgets.QSlider): class MemoTabWindow(PesterTabWindow): def __init__(self, mainwindow, parent=None): - super(MemoTabWindow, self).__init__(mainwindow, parent, "memos") + super().__init__(mainwindow, parent, "memos") def addChat(self, convo): self.convos[convo.channel] = convo @@ -302,7 +302,7 @@ _ctag_begin = re.compile(r"") class MemoText(PesterText): def __init__(self, theme, parent=None): - super(MemoText, self).__init__(theme, parent) + super().__init__(theme, parent) if hasattr(self.parent(), "mainwindow"): self.mainwindow = self.parent().mainwindow else: @@ -1590,7 +1590,7 @@ class PesterMemo(PesterConvo): t = self.times[h] grammar = t.getGrammar() allinitials.append( - "%s%s%s" % (grammar.pcf, chum.initials(), grammar.number) + "{}{}{}".format(grammar.pcf, chum.initials(), grammar.number) ) self.times[h].removeTime(t.getTime()) if update == "netsplit": @@ -1640,7 +1640,7 @@ class PesterMemo(PesterConvo): while ttracker.getTime() is not None: grammar = ttracker.getGrammar() allinitials.append( - "%s%s%s" % (grammar.pcf, chum.initials(), grammar.number) + "{}{}{}".format(grammar.pcf, chum.initials(), grammar.number) ) ttracker.removeTime(ttracker.getTime()) msg = chum.memobanmsg(opchum, opgrammar, systemColor, allinitials, reason) @@ -1873,7 +1873,7 @@ class PesterMemo(PesterConvo): ) if ok: self.mainwindow.kickUser.emit( - "%s:%s" % (currentHandle, reason), self.channel + "{}:{}".format(currentHandle, reason), self.channel ) @QtCore.pyqtSlot() diff --git a/menus.py b/menus.py index f88a476..29d5389 100644 --- a/menus.py +++ b/menus.py @@ -237,7 +237,7 @@ class PesterQuirkList(QtWidgets.QTreeWidget): ) if ok: gname = str(gname) - if re.search("[^A-Za-z0-9_\s]", gname) is not None: + if re.search(r"[^A-Za-z0-9_\s]", gname) is not None: msgbox = QtWidgets.QMessageBox() msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME") msgbox.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok) @@ -1304,9 +1304,7 @@ class PesterOptions(QtWidgets.QDialog): self.volume.valueChanged[int].connect(self.printValue) # Disable the volume slider if we can't actually use it. if parent.canSetVolume(): - self.currentVol = QtWidgets.QLabel( - "{0!s}%".format(self.config.volume()), self - ) + self.currentVol = QtWidgets.QLabel(f"{self.config.volume()!s}%", self) # We don't need to explicitly set this, but it helps drive the # point home self.volume.setEnabled(True) diff --git a/mood.py b/mood.py index e6de84d..749df7c 100644 --- a/mood.py +++ b/mood.py @@ -7,7 +7,7 @@ except ImportError: from generic import PesterIcon -class Mood(object): +class Mood: moods = [ "chummy", "rancorous", diff --git a/oyoyo/client.py b/oyoyo/client.py index 0b08e29..ed5411c 100644 --- a/oyoyo/client.py +++ b/oyoyo/client.py @@ -246,7 +246,7 @@ class IRCClient: passing the 'verify_hostname' parameter. The user is asked if they want to disable it if this functions raises a certificate validation error, in which case the function may be called again with 'verify_hostname'.""" - PchumLog.info("connecting to %s:%s" % (self.host, self.port)) + PchumLog.info("connecting to {}:{}".format(self.host, self.port)) # Open connection plaintext_socket = socket.create_connection((self.host, self.port)) @@ -279,7 +279,7 @@ class IRCClient: def conn(self): """returns a generator object.""" try: - buffer = bytes() + buffer = b"" while not self._end: # Block for connection-killing exceptions try: @@ -334,7 +334,7 @@ class IRCClient: except ssl.SSLEOFError as e: raise e except OSError as e: - PchumLog.warning("conn exception %s in %s" % (e, self)) + PchumLog.warning("conn exception {} in {}".format(e, self)) if self._end: break if not self.blocking and e.errno == 11: @@ -430,7 +430,7 @@ class IRCApp: warning: if you add a client that has blocking set to true, timers will no longer function properly""" - PchumLog.info("added client %s (ar=%s)" % (client, autoreconnect)) + PchumLog.info("added client {} (ar={})".format(client, autoreconnect)) self._clients[client] = self._ClientDesc(autoreconnect=autoreconnect) def addTimer(self, seconds, cb): @@ -439,7 +439,7 @@ class IRCApp: ( the only advantage to these timers is they dont use threads ) """ assert callable(cb) - PchumLog.info("added timer to call %s in %ss" % (cb, seconds)) + PchumLog.info("added timer to call {} in {}s".format(cb, seconds)) self._timers.append((time.time() + seconds, cb)) def run(self): diff --git a/oyoyo/cmdhandler.py b/oyoyo/cmdhandler.py index 3ead782..3d2c07c 100644 --- a/oyoyo/cmdhandler.py +++ b/oyoyo/cmdhandler.py @@ -44,7 +44,7 @@ class ProtectedCommandError(CommandError): return 'Command "%s" is protected' % ".".join(self.cmd) -class CommandHandler(object): +class CommandHandler: """The most basic CommandHandler""" def __init__(self, client): @@ -91,7 +91,7 @@ class CommandHandler(object): arguments_str = "" for x in args: arguments_str += str(x) + " " - PchumLog.debug("processCommand %s(%s)" % (command, arguments_str.strip())) + PchumLog.debug("processCommand {}({})".format(command, arguments_str.strip())) try: f = self.get(command) @@ -118,7 +118,7 @@ class CommandHandler(object): """The default handler for commands. Override this method to apply custom behavior (example, printing) unhandled commands. """ - PchumLog.debug("unhandled command %s(%s)" % (cmd, args)) + PchumLog.debug("unhandled command {}({})".format(cmd, args)) class DefaultCommandHandler(CommandHandler): @@ -150,7 +150,7 @@ class DefaultBotCommandHandler(CommandHandler): def help(self, sender, dest, arg=None): """list all available commands or get help on a specific command""" - PchumLog.info("help sender=%s dest=%s arg=%s" % (sender, dest, arg)) + PchumLog.info("help sender={} dest={} arg={}".format(sender, dest, arg)) if not arg: commands = self.getVisibleCommands() commands.sort() @@ -171,7 +171,7 @@ class DefaultBotCommandHandler(CommandHandler): if subcommands: doc += " [sub commands: %s]" % " ".join(subcommands) - helpers.msg(self.client, dest, "%s: %s" % (arg, doc)) + helpers.msg(self.client, dest, "{}: {}".format(arg, doc)) class BotCommandHandler(DefaultCommandHandler): @@ -190,7 +190,7 @@ class BotCommandHandler(DefaultCommandHandler): and calls self.processBotCommand(cmd, sender) if its is. """ - PchumLog.debug("tryBotCommand('%s' '%s' '%s')" % (prefix, dest, msg)) + PchumLog.debug("tryBotCommand('{}' '{}' '{}')".format(prefix, dest, msg)) if dest == self.client.nick: dest = parse_nick(prefix)[0] diff --git a/oyoyo/helpers.py b/oyoyo/helpers.py index bfc6b93..873dd2a 100644 --- a/oyoyo/helpers.py +++ b/oyoyo/helpers.py @@ -46,13 +46,13 @@ def channel_list(cli): def kick(cli, handle, channel, reason=""): - cli.send("KICK %s %s %s" % (channel, handle, reason)) + cli.send("KICK {} {} {}".format(channel, handle, reason)) def mode(cli, channel, mode, options=None): PchumLog.debug("mode = " + str(mode)) PchumLog.debug("options = " + str(options)) - cmd = "MODE %s %s" % (channel, mode) + cmd = "MODE {} {}".format(channel, mode) if options: cmd += " %s" % (options) cli.send(cmd) @@ -63,11 +63,11 @@ def ctcp(cli, handle, cmd, msg=""): if msg == "": cli.send("PRIVMSG", handle, "\x01%s\x01" % (cmd)) else: - cli.send("PRIVMSG", handle, "\x01%s %s\x01" % (cmd, msg)) + cli.send("PRIVMSG", handle, "\x01{} {}\x01".format(cmd, msg)) def ctcp_reply(cli, handle, cmd, msg=""): - notice(cli, str(handle), "\x01%s %s\x01" % (cmd.upper(), msg)) + notice(cli, str(handle), "\x01{} {}\x01".format(cmd.upper(), msg)) def metadata(cli, target, subcommand, *params): @@ -115,22 +115,28 @@ def identify(cli, passwd, authuser="NickServ"): def quit(cli, msg): cli.send("QUIT %s" % (msg)) + def nick(cli, nick): - cli.seld("NICK", nick) + cli.send("NICK", nick) + def user(cli, username, realname): cli.send("USER", username, "0", "*", ":" + realname) + def join(cli, channel): """Protocol potentially allows multiple channels or keys.""" cli.send("JOIN", channel) + def part(cli, channel): cli.send("PART", channel) + def notice(cli, target, text): cli.send("NOTICE", target, text) + def invite(cli, nick, channel): cli.send("INVITE", nick, channel) diff --git a/oyoyo/services.py b/oyoyo/services.py index c0c4848..7c58e50 100644 --- a/oyoyo/services.py +++ b/oyoyo/services.py @@ -111,14 +111,14 @@ def _addServ(serv, funcs, prefix=""): setattr(serv, t, simplecmd(t.upper())) -class NickServ(object): +class NickServ: def __init__(self, nick="NickServ"): self.name = nick _addServ(self, _nickservfuncs) _addServ(self, _nickservsetfuncs, "set") -class ChanServ(object): +class ChanServ: def __init__(self, nick="ChanServ"): self.name = nick _addServ(self, _chanservfuncs) diff --git a/parsetools.py b/parsetools.py index bbc264f..59617f6 100644 --- a/parsetools.py +++ b/parsetools.py @@ -115,7 +115,7 @@ class colorBegin(lexercon.Chunk): return "[color=%s]" % (qc.name()) elif format == "ctag": (r, g, b, a) = qc.getRgb() - return "" % (r, g, b) + return "".format(r, g, b) class colorEnd(lexercon.Chunk): @@ -171,7 +171,7 @@ class hyperlink(lexercon.Chunk): def convert(self, format): if format == "html": - return "%s" % (self.string, self.string) + return "{}".format(self.string, self.string) elif format == "bbcode": return "[url]%s[/url]" % (self.string) else: @@ -211,7 +211,9 @@ class memolex(lexercon.Chunk): def convert(self, format): if format == "html": - return "%s%s" % (self.space, self.channel, self.channel) + return "{}{}".format( + self.space, self.channel, self.channel + ) else: return self.string @@ -224,7 +226,7 @@ class chumhandlelex(lexercon.Chunk): def convert(self, format): if format == "html": - return "%s%s" % (self.space, self.handle, self.handle) + return "{}{}".format(self.space, self.handle, self.handle) else: return self.string @@ -235,7 +237,7 @@ class smiley(lexercon.Chunk): def convert(self, format): if format == "html": - return "%s" % ( + return "{}".format( smiledict[self.string], self.string, self.string, @@ -461,7 +463,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False): while len(lexed) > 0: rounds += 1 if debug: - PchumLog.info("[Starting round {}...]".format(rounds)) + PchumLog.info(f"[Starting round {rounds}...]") msg = lexed.popleft() msglen = 0 is_text = False @@ -502,9 +504,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False): # instead? subround += 1 if debug: - PchumLog.info( - "[Splitting round {}-{}...]".format(rounds, subround) - ) + PchumLog.info(f"[Splitting round {rounds}-{subround}...]") point = msg.rfind(" ", 0, lenl) if point < 0: # No spaces to break on...ugh. Break at the last space @@ -517,12 +517,12 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False): # Remove what we just added. msg = msg[point:] if debug: - PchumLog.info("msg = {!r}".format(msg)) + PchumLog.info(f"msg = {msg!r}") else: # Catch the remainder. stack.append(msg) if debug: - PchumLog.info("msg caught; stack = {!r}".format(stack)) + PchumLog.info(f"msg caught; stack = {stack!r}") # Done processing. Pluck out the first portion so we can # continue processing, clean it up a bit, then add the rest to # our waiting list. @@ -564,7 +564,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False): working.extend([cte] * len(open_ctags)) if debug: print( - "\tRound {0} linebreak: Added {1} closing ctags".format( + "\tRound {} linebreak: Added {} closing ctags".format( rounds, len(open_ctags) ) ) @@ -573,7 +573,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False): working = "".join(kxpclexer.list_convert(working)) if debug: print( - "\tRound {0} add: len == {1} (of {2})".format( + "\tRound {} add: len == {} (of {})".format( rounds, len(working), maxlen ) ) @@ -591,7 +591,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False): # We have more to go. # Reset working, starting it with the unclosed ctags. if debug: - print("\tRound {0}: More to lex".format(rounds)) + print(f"\tRound {rounds}: More to lex") working = open_ctags[:] # Calculate the length of the starting tags, add it before # anything else. @@ -606,7 +606,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False): if debug or True: # This probably shouldn't happen, and if it does, I want to # know if it *works* properly. - print("\tRound {0}: No more to lex".format(rounds)) + print(f"\tRound {rounds}: No more to lex") # Clean up, just in case. working = [] open_ctags = [] @@ -655,7 +655,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False): working = kxpclexer.list_convert(working) if len(working) > 0: if debug: - print("Adding end trails: {!r}".format(working)) + print(f"Adding end trails: {working!r}") working = "".join(working) output.append(working) @@ -722,7 +722,7 @@ def kxhandleInput(ctx, text=None, flavor=None): # Determine if the line actually *is* OOC. if is_ooc and not oocDetected: # If we're supposed to be OOC, apply it artificially. - msg = "(( {} ))".format(msg) + msg = f"(( {msg} ))" # Also, quirk stuff. should_quirk = ctx.applyquirks else: @@ -861,7 +861,7 @@ def kxhandleInput(ctx, text=None, flavor=None): clientMsg, colorcmd, grammar.pcf, initials, grammar.number ) # Not sure if this needs a space at the end...? - serverMsg = "{2}: {0}".format(serverMsg, colorcmd, initials) + serverMsg = f"{initials}: {serverMsg}" ctx.addMessage(clientMsg, True) if flavor != "menus": @@ -935,7 +935,7 @@ def nonerep(text): return text -class parseLeaf(object): +class parseLeaf: def __init__(self, function, parent): self.nodes = [] self.function = function @@ -957,7 +957,7 @@ class parseLeaf(object): return out -class backreference(object): +class backreference: def __init__(self, number): self.number = number @@ -1071,7 +1071,7 @@ smiledict = { ":honk:": "honk.png", } -reverse_smiley = dict((v, k) for k, v in smiledict.items()) +reverse_smiley = {v: k for k, v in smiledict.items()} _smilere = re.compile("|".join(list(smiledict.keys()))) diff --git a/pesterchum.py b/pesterchum.py index 1197181..94e33ab 100755 --- a/pesterchum.py +++ b/pesterchum.py @@ -210,7 +210,7 @@ except ImportError: ) -class waitingMessageHolder(object): +class waitingMessageHolder: def __init__(self, mainwindow, **msgfuncs): self.mainwindow = mainwindow self.funcs = msgfuncs @@ -246,14 +246,14 @@ class waitingMessageHolder(object): class chumListing(QtWidgets.QTreeWidgetItem): def __init__(self, chum, window): - super(chumListing, self).__init__([chum.handle]) + super().__init__([chum.handle]) self.mainwindow = window self.chum = chum self.handle = chum.handle self.setMood(Mood("offline")) self.status = None self.setToolTip( - 0, "%s: %s" % (chum.handle, window.chumdb.getNotes(chum.handle)) + 0, "{}: {}".format(chum.handle, window.chumdb.getNotes(chum.handle)) ) def setMood(self, mood): @@ -330,11 +330,9 @@ class chumListing(QtWidgets.QTreeWidgetItem): 0, QtGui.QBrush( QtGui.QColor( - ( - self.mainwindow.theme["main/chums/moods"][self.mood.name()][ - "color" - ] - ) + self.mainwindow.theme["main/chums/moods"][self.mood.name()][ + "color" + ] ) ), ) @@ -342,9 +340,7 @@ class chumListing(QtWidgets.QTreeWidgetItem): self.setForeground( 0, QtGui.QBrush( - QtGui.QColor( - (self.mainwindow.theme["main/chums/moods/chummy/color"]) - ) + QtGui.QColor(self.mainwindow.theme["main/chums/moods/chummy/color"]) ), ) @@ -379,7 +375,7 @@ class chumArea(RightClickTree): # This is the class that controls the actual main chumlist, I think. # Looking into how the groups work might be wise. def __init__(self, chums, parent=None): - super(chumArea, self).__init__(parent) + super().__init__(parent) self.notify = False QtCore.QTimer.singleShot(30000, self.beginNotify) self.mainwindow = parent @@ -1061,7 +1057,7 @@ class chumArea(RightClickTree): if ok: notes = str(notes) self.mainwindow.chumdb.setNotes(currentChum.handle, notes) - currentChum.setToolTip(0, "%s: %s" % (currentChum.handle, notes)) + currentChum.setToolTip(0, "{}: {}".format(currentChum.handle, notes)) @QtCore.pyqtSlot() def renameGroup(self): @@ -1073,7 +1069,7 @@ class chumArea(RightClickTree): ) if ok: gname = str(gname) - if re.search("[^A-Za-z0-9_\s]", gname) is not None: + if re.search(r"[^A-Za-z0-9_\s]", gname) is not None: msgbox = QtWidgets.QMessageBox() msgbox.setStyleSheet( "QMessageBox{ %s }" @@ -1210,7 +1206,7 @@ class trollSlum(chumArea): class TrollSlumWindow(QtWidgets.QFrame): def __init__(self, trolls, mainwindow, parent=None): - super(TrollSlumWindow, self).__init__(parent) + super().__init__(parent) self.mainwindow = mainwindow theme = self.mainwindow.theme self.slumlabel = QtWidgets.QLabel(self) @@ -1298,7 +1294,7 @@ class PesterWindow(MovingWindow): sendMessage = QtCore.pyqtSignal("QString", "QString") def __init__(self, options, parent=None, app=None): - super(PesterWindow, self).__init__( + super().__init__( None, ( QtCore.Qt.WindowType.CustomizeWindowHint @@ -1357,7 +1353,7 @@ class PesterWindow(MovingWindow): msgBox.setText( "

A profile error occured, " "trying to switch to default pesterClient profile." - "

%s<\h3><\html>" % e + r"

%s<\h3><\html>" % e ) PchumLog.critical(e) msgBox.exec() @@ -1917,7 +1913,7 @@ class PesterWindow(MovingWindow): msg = addTimeInitial(msg, memo.times[handle].getGrammar()) if handle == "ChanServ": systemColor = QtGui.QColor(self.theme["memos/systemMsgColor"]) - msg = "%s" % (systemColor.name(), msg) + msg = "{}".format(systemColor.name(), msg) memo.addMessage(msg, handle) mentioned = False m = convertTags(msg, "text") @@ -2242,7 +2238,7 @@ class PesterWindow(MovingWindow): if hasattr(self, "moods"): self.moods.removeButtons() mood_list = theme["main/moods"] - mood_list = [dict([(str(k), v) for (k, v) in d.items()]) for d in mood_list] + mood_list = [{str(k): v for (k, v) in d.items()} for d in mood_list] self.moods = PesterMoodHandler( self, *[PesterMoodButton(self, **d) for d in mood_list] ) @@ -2391,7 +2387,7 @@ class PesterWindow(MovingWindow): QtCore.QUrl.fromLocalFile("themes/honk.wav") ) except Exception as err: - PchumLog.error("Warning: Error loading sounds! ({0!r})".format(err)) + PchumLog.error(f"Warning: Error loading sounds! ({err!r})") self.alarm = NoneSound() self.memosound = NoneSound() self.namesound = NoneSound() @@ -2419,7 +2415,7 @@ class PesterWindow(MovingWindow): if self.sound_type == QtMultimedia.QSoundEffect: sound.setVolume(vol) except Exception as err: - PchumLog.warning("Couldn't set volume: {}".format(err)) + PchumLog.warning(f"Couldn't set volume: {err}") def canSetVolume(self): """Returns the state of volume setting capabilities.""" @@ -2793,7 +2789,7 @@ class PesterWindow(MovingWindow): errormsg.showMessage("THIS IS NOT A VALID CHUMTAG!") self.addchumdialog = None return - if re.search("[^A-Za-z0-9_\s]", group) is not None: + if re.search(r"[^A-Za-z0-9_\s]", group) is not None: errormsg = QtWidgets.QErrorMessage(self) errormsg.showMessage("THIS IS NOT A VALID GROUP NAME") self.addchumdialog = None @@ -2817,7 +2813,7 @@ class PesterWindow(MovingWindow): "Enter the reason you are reporting this user (optional):", ) if ok: - self.sendMessage.emit("REPORT %s %s" % (handle, reason), "calSprite") + self.sendMessage.emit("REPORT {} {}".format(handle, reason), "calSprite") @QtCore.pyqtSlot(QString) def blockChum(self, handle): @@ -2946,7 +2942,7 @@ class PesterWindow(MovingWindow): f = QtWidgets.QFileDialog.getOpenFileName(self)[0] if f == "": return - fp = open(f, "r") + fp = open(f) regexp_state = None for l in fp: # import chumlist @@ -3139,7 +3135,7 @@ class PesterWindow(MovingWindow): ) if ok: gname = str(gname) - if re.search("[^A-Za-z0-9_\s]", gname) is not None: + if re.search(r"[^A-Za-z0-9_\s]", gname) is not None: msgbox = QtWidgets.QMessageBox() msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME") msgbox.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok) @@ -3500,7 +3496,7 @@ class PesterWindow(MovingWindow): "

" "If you got this message at launch you may want to " "change your default profile." - "

%s<\h3><\html>" + r"

%s<\h3><\html>" % (self.profiledir, self.profiledir, handle, e) ) @@ -3512,7 +3508,7 @@ class PesterWindow(MovingWindow): "file exists." "

If you got this message at launch you may " "want to change your default profile." - "

%s<\h3><\html>" % e + r"

%s<\h3><\html>" % e ) PchumLog.critical(e) msgBox.setText(msg) @@ -3769,7 +3765,7 @@ class PesterWindow(MovingWindow): self.chooseServer() return 1 - with open(_datadir + "serverlist.json", "r") as server_file: + with open(_datadir + "serverlist.json") as server_file: read_file = server_file.read() server_file.close() server_list_obj = json.loads(read_file) @@ -3826,7 +3822,7 @@ class PesterWindow(MovingWindow): def removeServer(self): server_list_items = [] try: - with open(_datadir + "serverlist.json", "r") as server_file: + with open(_datadir + "serverlist.json") as server_file: read_file = server_file.read() server_file.close() server_list_obj = json.loads(read_file) @@ -3928,7 +3924,7 @@ class PesterWindow(MovingWindow): # Read servers. server_list_items = [] try: - with open(_datadir + "serverlist.json", "r") as server_file: + with open(_datadir + "serverlist.json") as server_file: read_file = server_file.read() server_file.close() server_obj = json.loads(read_file) @@ -3988,7 +3984,7 @@ class PesterWindow(MovingWindow): else: PchumLog.info(self.serverBox.currentText() + " chosen.") - with open(_datadir + "serverlist.json", "r") as server_file: + with open(_datadir + "serverlist.json") as server_file: read_file = server_file.read() server_file.close() server_obj = json.loads(read_file) @@ -4031,7 +4027,7 @@ class PesterWindow(MovingWindow): # Read servers. server_list_items = [] try: - with open(_datadir + "serverlist.json", "r") as server_file: + with open(_datadir + "serverlist.json") as server_file: read_file = server_file.read() server_file.close() server_obj = json.loads(read_file) @@ -4103,7 +4099,7 @@ class PesterWindow(MovingWindow): msgbox.setIcon(QtWidgets.QMessageBox.Icon.Warning) msgbox.setText("Server certificate validation failed") msgbox.setInformativeText( - 'Reason: "%s (%s)"' % (e.verify_message, e.verify_code) + 'Reason: "{} ({})"'.format(e.verify_message, e.verify_code) + "\n\nConnect anyway?" ) msgbox.setStandardButtons( @@ -4154,7 +4150,7 @@ class PesterWindow(MovingWindow): class PesterTray(QtWidgets.QSystemTrayIcon): def __init__(self, icon, mainwindow, parent): - super(PesterTray, self).__init__(icon, parent) + super().__init__(icon, parent) self.mainwindow = mainwindow @QtCore.pyqtSlot(int) @@ -4171,7 +4167,7 @@ class PesterTray(QtWidgets.QSystemTrayIcon): class MainProgram(QtCore.QObject): def __init__(self): - super(MainProgram, self).__init__() + super().__init__() _oldhook = sys.excepthook sys.excepthook = self.uncaughtException @@ -4195,8 +4191,8 @@ class MainProgram(QtCore.QObject): windll.shell32.SetCurrentProcessExplicitAppUserModelID(wid) except Exception as err: # Log, but otherwise ignore any exceptions. - PchumLog.error("Failed to set AppUserModel ID: {0}".format(err)) - PchumLog.error("Attempted to set as {0!r}.".format(wid)) + PchumLog.error(f"Failed to set AppUserModel ID: {err}") + PchumLog.error(f"Attempted to set as {wid!r}.") # Back to our scheduled program. self.app = QtWidgets.QApplication(sys.argv) @@ -4563,7 +4559,7 @@ class MainProgram(QtCore.QObject): # Show error to end user and log. try: # Log to log file - PchumLog.error("%s, %s" % (exc, value)) + PchumLog.error("{}, {}".format(exc, value)) # Try to write to separate logfile try: diff --git a/pnc/dep/attrdict.py b/pnc/dep/attrdict.py index 6b29762..dea6063 100644 --- a/pnc/dep/attrdict.py +++ b/pnc/dep/attrdict.py @@ -1,4 +1,3 @@ -# -*- coding=UTF-8; tab-width: 4 -*- # Heavily modified version of the code featured at the given link ## {{{ http://code.activestate.com/recipes/473786/ (r1) class AttrDict(dict): @@ -11,7 +10,7 @@ class AttrDict(dict): Overload _is_reserved if you want to change this.""" def __init__(self, init={}): - super(AttrDict, self).__init__(init) + super().__init__(init) def __getstate__(self): return list(self.__dict__.items()) @@ -21,16 +20,16 @@ class AttrDict(dict): self.__dict__[key] = val def __repr__(self): - return "{0}({1})".format(type(self).__name__, super(AttrDict, self).__repr__()) + return f"{type(self).__name__}({super().__repr__()})" def __setitem__(self, name, value): - return super(AttrDict, self).__setitem__(name, value) + return super().__setitem__(name, value) def __getitem__(self, name): - return super(AttrDict, self).__getitem__(name) + return super().__getitem__(name) def __delitem__(self, name): - return super(AttrDict, self).__delitem__(name) + return super().__delitem__(name) def __getattr__(self, name): # NOTE: __getattr__ is called if the code has already failed to access @@ -50,7 +49,7 @@ class AttrDict(dict): # Raising KeyError here will confuse __deepcopy__, so don't do # that. # Throw a custom error. - raise AttributeError("No key/attr {0!r}".format(name)) + raise AttributeError(f"No key/attr {name!r}") return result def __setattr__(self, name, value): @@ -68,7 +67,7 @@ class AttrDict(dict): # in this particular function?... return object.__setattr__(self, name, value) else: - return super(AttrDict, self).__setitem__(name, value) + return super().__setitem__(name, value) def __delattr__(self, name): # We very *specifically* use self.__dict__ here, because we couldn't @@ -106,10 +105,10 @@ class DefAttrDict(AttrDict): def __init__(self, default_factory=None, *args, **kwargs): self.default_factory = default_factory - super(DefAttrDict, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def __repr__(self): - return "{0}({1!r}, {2})".format( + return "{}({!r}, {})".format( type(self).__name__, self.default_factory, # We skip normal processing here, since AttrDict provides basic @@ -119,7 +118,7 @@ class DefAttrDict(AttrDict): def __getitem__(self, name): try: - result = super(DefAttrDict, self).__getitem__(name) + result = super().__getitem__(name) except KeyError: result = None if self.default_factory is not None: @@ -129,7 +128,7 @@ class DefAttrDict(AttrDict): def __getattr__(self, name): try: - result = super(DefAttrDict, self).__getattr__(name) + result = super().__getattr__(name) except AttributeError: # Detect special/reserved names. if self._is_reserved(name): diff --git a/pnc/lexercon.py b/pnc/lexercon.py index 8337404..3c721c1 100644 --- a/pnc/lexercon.py +++ b/pnc/lexercon.py @@ -1,6 +1,3 @@ -# -*- coding=UTF-8; tab-width: 4 -*- - - from .unicolor import Color import re @@ -20,7 +17,7 @@ except NameError: # function appropriate to the given format - e.g. CTag.convert_pchum. -class Lexeme(object): +class Lexeme: def __init__(self, string, origin): # The 'string' property is just what it came from; the original # representation. It doesn't have to be used, and honestly probably @@ -104,7 +101,7 @@ class CTag(Specifier): sets_color = True def __init__(self, string, origin, color): - super(CTag, self).__init__(string, origin) + super().__init__(string, origin) # So we can also have None if isinstance(color, tuple): if len(color) < 2: @@ -256,7 +253,7 @@ class SpecifierEnd(CTagEnd, FTagEnd): # .sets_color to False -class Lexer(object): +class Lexer: # Subclasses need to supply a ref themselves ref = None compress_tags = False diff --git a/pnc/unicolor.py b/pnc/unicolor.py index 7a8208b..95dbe80 100644 --- a/pnc/unicolor.py +++ b/pnc/unicolor.py @@ -1,6 +1,3 @@ -# -*- coding=UTF-8; tab-width: 4 -*- - - __all__ = ["Color"] # karxi: Copied from my old Textsub script. Please forgive the mess, and keep @@ -26,7 +23,7 @@ else: LabTuple = collections.namedtuple("LabTuple", ["L", "a", "b"]) -class Color(object): +class Color: # The threshold at which to consider two colors noticeably different, even # if only barely jnd = 2.3 @@ -145,7 +142,7 @@ class Color(object): def __repr__(self): ##return "%s(%r)" % (type(self).__name__, str(self)) - return "%s(%r)" % (type(self).__name__, self.reduce_hexstr(self.hexstr)) + return "{}({!r})".format(type(self).__name__, self.reduce_hexstr(self.hexstr)) def __str__(self): ##return self.reduce_hexstr(self.hexstr) @@ -158,8 +155,7 @@ class Color(object): def __iter__(self): targs = (self.red, self.green, self.blue) - for t in targs: - yield t + yield from targs # If we got here, we're out of attributes to provide raise StopIteration diff --git a/profile.py b/profile.py index 8c264bc..d5502ed 100644 --- a/profile.py +++ b/profile.py @@ -25,7 +25,7 @@ _datadir = ostools.getDataDir() PchumLog = logging.getLogger("pchumLogger") -class PesterLog(object): +class PesterLog: def __init__(self, handle, parent=None): global _datadir self.parent = parent @@ -66,10 +66,12 @@ class PesterLog(object): self.convos[handle] = {} for (format, t) in modes.items(): if not os.path.exists( - "%s/%s/%s/%s" % (self.logpath, self.handle, handle, format) + "{}/{}/{}/{}".format(self.logpath, self.handle, handle, format) ): os.makedirs( - "%s/%s/%s/%s" % (self.logpath, self.handle, handle, format) + "{}/{}/{}/{}".format( + self.logpath, self.handle, handle, format + ) ) fp = codecs.open( "%s/%s/%s/%s/%s.%s.txt" @@ -94,7 +96,7 @@ class PesterLog(object): # for (format, t) in modes.items(): # self.finish(handle) - except (IOError, OSError, KeyError, IndexError, ValueError) as e: + except (OSError, KeyError, IndexError, ValueError) as e: # Catching this exception does not stop pchum from dying if we run out of file handles %s

" if not os.path.exists(self.logpath): os.makedirs(self.logpath) try: - with open("%s/groups.js" % (self.logpath), "r") as fp: + with open("%s/groups.js" % (self.logpath)) as fp: self.groups = json.load(fp) - except (IOError, ValueError): + except (OSError, ValueError): self.groups = {} with open("%s/groups.js" % (self.logpath), "w") as fp: json.dump(self.groups, fp) @@ -442,7 +444,7 @@ with a backup from: %s" if hasattr(self.parent, "serverOverride"): return self.parent.serverOverride try: - with open(_datadir + "server.json", "r") as server_file: + with open(_datadir + "server.json") as server_file: read_file = server_file.read() server_file.close() server_obj = json.loads(read_file) @@ -465,7 +467,7 @@ with a backup from: %s" if hasattr(self.parent, "portOverride"): return self.parent.portOverride try: - with open(_datadir + "server.json", "r") as server_file: + with open(_datadir + "server.json") as server_file: read_file = server_file.read() server_file.close() server_obj = json.loads(read_file) @@ -478,7 +480,7 @@ with a backup from: %s" # if hasattr(self.parent, 'tlsOverride'): # return self.parent.tlsOverride try: - with open(_datadir + "server.json", "r") as server_file: + with open(_datadir + "server.json") as server_file: read_file = server_file.read() server_file.close() server_obj = json.loads(read_file) @@ -575,7 +577,7 @@ with a backup from: %s" + "" + "

" + str(e) - + "<\h3><\html>" + + r"<\h3><\html>" ) # "\" if pesterchum acts oddly you might want to try backing up and then deleting \"" + \ # _datadir+"pesterchum.js" + \ @@ -586,7 +588,7 @@ with a backup from: %s" return [userProfile(p) for p in profs] -class userProfile(object): +class userProfile: def __init__(self, user): self.profiledir = _datadir + "profiles" @@ -607,8 +609,8 @@ class userProfile(object): if len(initials) >= 2: initials = ( initials, - "%s%s" % (initials[0].lower(), initials[1]), - "%s%s" % (initials[0], initials[1].lower()), + "{}{}".format(initials[0].lower(), initials[1]), + "{}{}".format(initials[0], initials[1].lower()), ) self.mentions = [r"\b(%s)\b" % ("|".join(initials))] else: @@ -621,7 +623,7 @@ class userProfile(object): # u'XXX\\AppData\\Local\\pesterchum/profiles/XXX.js' # Part 3 :( try: - with open("%s/%s.js" % (self.profiledir, user)) as fp: + with open("{}/{}.js".format(self.profiledir, user)) as fp: self.userprofile = json.load(fp) except (json.JSONDecodeError, FileNotFoundError) as e: msgBox = QtWidgets.QMessageBox() @@ -641,7 +643,7 @@ class userProfile(object): + "

If you got this message at launch you may want to change your default profile." + "

" + str(e) - + "<\h3><\html>" + + r"<\h3><\html>" ) # "\" if pesterchum acts oddly you might want to try backing up and then deleting \"" + \ # _datadir+"pesterchum.js" + \ @@ -671,8 +673,8 @@ class userProfile(object): if len(initials) >= 2: initials = ( initials, - "%s%s" % (initials[0].lower(), initials[1]), - "%s%s" % (initials[0], initials[1].lower()), + "{}{}".format(initials[0].lower(), initials[1]), + "{}{}".format(initials[0], initials[1].lower()), ) self.userprofile["mentions"] = [r"\b(%s)\b" % ("|".join(initials))] else: @@ -738,7 +740,7 @@ class userProfile(object): for (i, m) in enumerate(mentions): re.compile(m) except re.error as e: - PchumLog.error("#%s Not a valid regular expression: %s" % (i, e)) + PchumLog.error("#{} Not a valid regular expression: {}".format(i, e)) else: self.mentions = mentions self.userprofile["mentions"] = mentions @@ -792,7 +794,7 @@ class userProfile(object): jsonoutput = json.dumps(self.userprofile) except ValueError as e: raise e - with open("%s/%s.js" % (self.profiledir, handle), "w") as fp: + with open("{}/{}.js".format(self.profiledir, handle), "w") as fp: fp.write(jsonoutput) def saveNickServPass(self): @@ -809,7 +811,7 @@ class userProfile(object): @staticmethod def newUserProfile(chatprofile): - if os.path.exists("%s/%s.js" % (_datadir + "profiles", chatprofile.handle)): + if os.path.exists("{}/{}.js".format(_datadir + "profiles", chatprofile.handle)): newprofile = userProfile(chatprofile.handle) else: newprofile = userProfile(chatprofile) @@ -824,9 +826,9 @@ class PesterProfileDB(dict): if not os.path.exists(self.logpath): os.makedirs(self.logpath) try: - with open("%s/chums.js" % (self.logpath), "r") as fp: + with open("%s/chums.js" % (self.logpath)) as fp: chumdict = json.load(fp) - except (IOError, ValueError): + except (OSError, ValueError): # karxi: This code feels awfully familiar.... chumdict = {} with open("%s/chums.js" % (self.logpath), "w") as fp: @@ -926,7 +928,7 @@ class pesterTheme(dict): try: with open(self.path + "/style.js") as fp: theme = json.load(fp, object_hook=self.pathHook) - except IOError: + except OSError: theme = json.loads("{}") self.update(theme) if "inherits" in self: @@ -937,7 +939,7 @@ class pesterTheme(dict): def __getitem__(self, key): keys = key.split("/") try: - v = super(pesterTheme, self).__getitem__(keys.pop(0)) + v = super().__getitem__(keys.pop(0)) except KeyError as e: if hasattr(self, "inheritedTheme"): return self.inheritedTheme[key] @@ -967,7 +969,7 @@ class pesterTheme(dict): def get(self, key, default): keys = key.split("/") try: - v = super(pesterTheme, self).__getitem__(keys.pop(0)) + v = super().__getitem__(keys.pop(0)) for k in keys: v = v[k] return default if v is None else v @@ -980,7 +982,7 @@ class pesterTheme(dict): def has_key(self, key): keys = key.split("/") try: - v = super(pesterTheme, self).__getitem__(keys.pop(0)) + v = super().__getitem__(keys.pop(0)) for k in keys: v = v[k] return v is not None diff --git a/pytwmn.py b/pytwmn.py index 74b4efc..368f2e0 100755 --- a/pytwmn.py +++ b/pytwmn.py @@ -40,16 +40,16 @@ def init(host="127.0.0.1", port=None): if line.startswith("port=") and line[5:-1].isdigit(): port = int(line[5:-1]) break - except IOError: + except OSError: raise TwmnError(TwmnError.NO_CONF) - if type(port) == type(str()): + if type(port) == type(""): port = int(port) global s s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((host, port)) -class Notification(object): +class Notification: def __init__(self, title="", msg="", icon=""): self.title = str(title) self.msg = str(msg) diff --git a/quirks.py b/quirks.py index fa49a53..fcb3e9f 100644 --- a/quirks.py +++ b/quirks.py @@ -7,7 +7,7 @@ _datadir = ostools.getDataDir() PchumLog = logging.getLogger("pchumLogger") -class ScriptQuirks(object): +class ScriptQuirks: def __init__(self): self._datadir = ostools.getDataDir() self.home = os.getcwd() @@ -73,7 +73,9 @@ class ScriptQuirks(object): continue except Exception as e: PchumLog.warning( - "Error loading %s: %s (in quirks.py)" % (os.path.basename(name), e) + "Error loading {}: {} (in quirks.py)".format( + os.path.basename(name), e + ) ) else: if self.modHas(module, "setup"): diff --git a/toast.py b/toast.py index 26d82e0..0ac6c7b 100644 --- a/toast.py +++ b/toast.py @@ -24,7 +24,7 @@ PchumLog = logging.getLogger("pchumLogger") pynotify = None -class DefaultToast(object): +class DefaultToast: def __init__(self, machine, title, msg, icon): self.machine = machine self.title = title @@ -43,8 +43,8 @@ class DefaultToast(object): PchumLog.info("Done") -class ToastMachine(object): - class __Toast__(object): +class ToastMachine: + class __Toast__: def __init__(self, machine, title, msg, time=3000, icon="", importance=0): self.machine = machine self.title = title From 30569d4a956d700b62cac7b027f8dd16aaaf4913 Mon Sep 17 00:00:00 2001 From: Dpeta <69427753+Dpeta@users.noreply.github.com> Date: Sat, 14 Jan 2023 23:05:38 +0100 Subject: [PATCH 5/6] Run autoflake --- convo.py | 1 - irc.py | 2 -- logviewer.py | 1 - menus.py | 1 - pesterchum.py | 1 - 5 files changed, 6 deletions(-) diff --git a/convo.py b/convo.py index 5e240d7..61b33a2 100644 --- a/convo.py +++ b/convo.py @@ -1,4 +1,3 @@ -import sys import logging from string import Template from time import strftime diff --git a/irc.py b/irc.py index 333fc40..ada4891 100644 --- a/irc.py +++ b/irc.py @@ -2,7 +2,6 @@ import logging import socket import random import time -import json import ssl try: @@ -873,7 +872,6 @@ class PesterHandler(DefaultCommandHandler): PchumLog.warning( "Can't remove channel mode that isn't set." ) - pass self.parent.userPresentUpdate.emit( "", channel, channel_mode + ":%s" % (op) ) diff --git a/logviewer.py b/logviewer.py index 38f7679..803b284 100644 --- a/logviewer.py +++ b/logviewer.py @@ -1,5 +1,4 @@ import os -import sys import codecs import re import ostools diff --git a/menus.py b/menus.py index 29d5389..dcb880f 100644 --- a/menus.py +++ b/menus.py @@ -1,4 +1,3 @@ -import sys import re from os import remove diff --git a/pesterchum.py b/pesterchum.py index 94e33ab..52deef9 100755 --- a/pesterchum.py +++ b/pesterchum.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import os import sys -import shutil import argparse import traceback import logging From 3ae70e4fe023d743bd95b0073cad40c7f23e4b09 Mon Sep 17 00:00:00 2001 From: Dpeta <69427753+Dpeta@users.noreply.github.com> Date: Sat, 14 Jan 2023 23:10:19 +0100 Subject: [PATCH 6/6] More aggressive autoflake --- convo.py | 1 - dataobjs.py | 1 - irc.py | 1 - memos.py | 1 - mood.py | 4 ++-- parsetools.py | 1 - pesterchum.py | 4 ++-- pyquirks.py | 1 - randomer.py | 1 - setup.py | 1 - 10 files changed, 4 insertions(+), 12 deletions(-) diff --git a/convo.py b/convo.py index 61b33a2..eda8da1 100644 --- a/convo.py +++ b/convo.py @@ -11,7 +11,6 @@ except ImportError: from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QAction, QShortcut -import ostools from dataobjs import PesterHistory from parsetools import convertTags, lexMessage, mecmd, colorBegin, colorEnd, smiledict import parsetools diff --git a/dataobjs.py b/dataobjs.py index 11eba6c..80761a6 100644 --- a/dataobjs.py +++ b/dataobjs.py @@ -1,5 +1,4 @@ import logging -import ostools PchumLog = logging.getLogger("pchumLogger") try: diff --git a/irc.py b/irc.py index ada4891..fc74fb9 100644 --- a/irc.py +++ b/irc.py @@ -10,7 +10,6 @@ except ImportError: print("PyQt5 fallback (irc.py)") from PyQt5 import QtCore, QtGui -import ostools from mood import Mood from dataobjs import PesterProfile from generic import PesterList diff --git a/memos.py b/memos.py index 21f9f95..7a91596 100644 --- a/memos.py +++ b/memos.py @@ -11,7 +11,6 @@ except ImportError: from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QAction -import ostools import parsetools from dataobjs import PesterProfile, PesterHistory from generic import PesterIcon, RightClickList, mysteryTime diff --git a/mood.py b/mood.py index 749df7c..0dc566e 100644 --- a/mood.py +++ b/mood.py @@ -1,8 +1,8 @@ try: - from PyQt6 import QtCore, QtGui, QtWidgets + from PyQt6 import QtCore, QtWidgets except ImportError: print("PyQt5 fallback (mood.py)") - from PyQt5 import QtCore, QtGui, QtWidgets + from PyQt5 import QtCore, QtWidgets from generic import PesterIcon diff --git a/parsetools.py b/parsetools.py index 59617f6..1538e91 100644 --- a/parsetools.py +++ b/parsetools.py @@ -11,7 +11,6 @@ except ImportError: from PyQt5 import QtGui, QtWidgets import dataobjs -import ostools # karxi: My own contribution to this - a proper lexer. import pnc.lexercon as lexercon diff --git a/pesterchum.py b/pesterchum.py index 52deef9..99f34b1 100755 --- a/pesterchum.py +++ b/pesterchum.py @@ -60,11 +60,11 @@ from toast import PesterToastMachine, PesterToast try: from PyQt6 import QtCore, QtGui, QtWidgets - from PyQt6.QtGui import QShortcut, QAction, QActionGroup + from PyQt6.QtGui import QAction, QActionGroup except ImportError: print("PyQt5 fallback (pesterchum.py)") from PyQt5 import QtCore, QtGui, QtWidgets - from PyQt5.QtWidgets import QAction, QShortcut, QActionGroup + from PyQt5.QtWidgets import QAction, QActionGroup # Data directory ostools.validateDataDir() diff --git a/pyquirks.py b/pyquirks.py index 487e121..971695b 100644 --- a/pyquirks.py +++ b/pyquirks.py @@ -7,7 +7,6 @@ except ImportError: print("PyQt5 fallback (pyquirks.py)") from PyQt5 import QtWidgets -import ostools from quirks import ScriptQuirks PchumLog = logging.getLogger("pchumLogger") diff --git a/randomer.py b/randomer.py index 1352c26..3a2fef6 100644 --- a/randomer.py +++ b/randomer.py @@ -6,7 +6,6 @@ except ImportError: print("PyQt5 fallback (randomer.py)") from PyQt5 import QtCore, QtWidgets -import ostools PchumLog = logging.getLogger("pchumLogger") diff --git a/setup.py b/setup.py index 077ec0f..5037d6b 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,6 @@ import sys from cx_Freeze import setup, Executable -import pygame from version import buildVersion