Merge pull request #111 from Dpeta/lint-req

Fix a decent amount of pylint errors, run autoflake + pyupgrade
This commit is contained in:
Dpeta 2023-01-26 21:59:32 +01:00 committed by GitHub
commit 48e994b9cf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
26 changed files with 270 additions and 307 deletions

View file

@ -1,3 +1,4 @@
"""
# vim: set autoindent ts=4 sts=4 sw=4 textwidth=79 expandtab: # vim: set autoindent ts=4 sts=4 sw=4 textwidth=79 expandtab:
# -*- coding=UTF-8; tab-width: 4 -*- # -*- coding=UTF-8; tab-width: 4 -*-
# import os # import os
@ -550,3 +551,4 @@ class ConsoleInput(QtWidgets.QLineEdit):
parent.text.area.keyPressEvent(event) parent.text.area.keyPressEvent(event)
else: else:
super(ConsoleInput, self).keyPressEvent(event) super(ConsoleInput, self).keyPressEvent(event)
"""

View file

@ -1,4 +1,3 @@
import sys
import logging import logging
from string import Template from string import Template
from time import strftime from time import strftime
@ -12,7 +11,6 @@ except ImportError:
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QAction, QShortcut from PyQt5.QtWidgets import QAction, QShortcut
import ostools
from dataobjs import PesterHistory from dataobjs import PesterHistory
from parsetools import convertTags, lexMessage, mecmd, colorBegin, colorEnd, smiledict from parsetools import convertTags, lexMessage, mecmd, colorBegin, colorEnd, smiledict
import parsetools import parsetools
@ -23,7 +21,7 @@ PchumLog = logging.getLogger("pchumLogger")
class PesterTabWindow(QtWidgets.QFrame): class PesterTabWindow(QtWidgets.QFrame):
def __init__(self, mainwindow, parent=None, convo="convo"): 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.setAttribute(QtCore.Qt.WidgetAttribute.WA_QuitOnClose, False)
self.setFocusPolicy(QtCore.Qt.FocusPolicy.ClickFocus) self.setFocusPolicy(QtCore.Qt.FocusPolicy.ClickFocus)
self.mainwindow = mainwindow self.mainwindow = mainwindow
@ -337,7 +335,7 @@ class PesterTabWindow(QtWidgets.QFrame):
class PesterMovie(QtGui.QMovie): class PesterMovie(QtGui.QMovie):
def __init__(self, parent): def __init__(self, parent):
super(PesterMovie, self).__init__(parent) super().__init__(parent)
self.textwindow = parent self.textwindow = parent
@QtCore.pyqtSlot(int) @QtCore.pyqtSlot(int)
@ -374,7 +372,7 @@ class PesterMovie(QtGui.QMovie):
class PesterText(QtWidgets.QTextEdit): class PesterText(QtWidgets.QTextEdit):
def __init__(self, theme, parent=None): def __init__(self, theme, parent=None):
super(PesterText, self).__init__(parent) super().__init__(parent)
if hasattr(self.parent(), "mainwindow"): if hasattr(self.parent(), "mainwindow"):
self.mainwindow = self.parent().mainwindow self.mainwindow = self.parent().mainwindow
else: else:
@ -390,6 +388,7 @@ class PesterText(QtWidgets.QTextEdit):
self.textSelected = False self.textSelected = False
self.copyAvailable[bool].connect(self.textReady) self.copyAvailable[bool].connect(self.textReady)
self.urls = {} self.urls = {}
self.lastmsg = None
for k in smiledict: for k in smiledict:
self.addAnimation( self.addAnimation(
QtCore.QUrl("smilies/%s" % (smiledict[k])), QtCore.QUrl("smilies/%s" % (smiledict[k])),
@ -549,9 +548,13 @@ class PesterText(QtWidgets.QTextEdit):
and not parent.isBot(chum.handle) and not parent.isBot(chum.handle)
): ):
idlethreshhold = 60 idlethreshhold = 60
if ( do_idle_send = False
not hasattr(self, "lastmsg") if self.lastmsg is None:
) or datetime.now() - self.lastmsg > timedelta(0, idlethreshhold): 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"] verb = window.theme["convo/text/idle"]
idlemsg = me.idlemsg(systemColor, verb) idlemsg = me.idlemsg(systemColor, verb)
parent.textArea.append(convertTags(idlemsg)) parent.textArea.append(convertTags(idlemsg))
@ -589,7 +592,7 @@ class PesterText(QtWidgets.QTextEdit):
parent.textInput.keyPressEvent(event) parent.textInput.keyPressEvent(event)
# Pass to the normal handler. # Pass to the normal handler.
super(PesterText, self).keyPressEvent(event) super().keyPressEvent(event)
def mousePressEvent(self, event): def mousePressEvent(self, event):
if event.button() == QtCore.Qt.MouseButton.LeftButton: if event.button() == QtCore.Qt.MouseButton.LeftButton:
@ -642,7 +645,7 @@ class PesterInput(QtWidgets.QLineEdit):
stylesheet_path = "convo/input/style" stylesheet_path = "convo/input/style"
def __init__(self, theme, parent=None): def __init__(self, theme, parent=None):
super(PesterInput, self).__init__(parent) super().__init__(parent)
self.changeTheme(theme) self.changeTheme(theme)
def changeTheme(self, theme): def changeTheme(self, theme):
@ -657,7 +660,7 @@ class PesterInput(QtWidgets.QLineEdit):
def focusInEvent(self, event): def focusInEvent(self, event):
self.parent().clearNewMessage() self.parent().clearNewMessage()
self.parent().textArea.textCursor().clearSelection() self.parent().textArea.textCursor().clearSelection()
super(PesterInput, self).focusInEvent(event) super().focusInEvent(event)
def keyPressEvent(self, event): def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key.Key_Up: if event.key() == QtCore.Qt.Key.Key_Up:
@ -672,12 +675,12 @@ class PesterInput(QtWidgets.QLineEdit):
elif event.key() in [QtCore.Qt.Key.Key_PageUp, QtCore.Qt.Key.Key_PageDown]: elif event.key() in [QtCore.Qt.Key.Key_PageUp, QtCore.Qt.Key.Key_PageDown]:
self.parent().textArea.keyPressEvent(event) self.parent().textArea.keyPressEvent(event)
self.parent().mainwindow.idler.time = 0 self.parent().mainwindow.idler.time = 0
super(PesterInput, self).keyPressEvent(event) super().keyPressEvent(event)
class PesterConvo(QtWidgets.QFrame): class PesterConvo(QtWidgets.QFrame):
def __init__(self, chum, initiated, mainwindow, parent=None): 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.setAttribute(QtCore.Qt.WidgetAttribute.WA_QuitOnClose, False)
self.setObjectName(chum.handle) self.setObjectName(chum.handle)
self.setFocusPolicy(QtCore.Qt.FocusPolicy.ClickFocus) self.setFocusPolicy(QtCore.Qt.FocusPolicy.ClickFocus)
@ -686,7 +689,7 @@ class PesterConvo(QtWidgets.QFrame):
theme = self.mainwindow.theme theme = self.mainwindow.theme
self.resize(*theme["convo/size"]) self.resize(*theme["convo/size"])
self.setStyleSheet( self.setStyleSheet(
"QtWidgets.QFrame#%s { %s }" % (chum.handle, theme["convo/style"]) "QtWidgets.QFrame#{} {{ {} }}".format(chum.handle, theme["convo/style"])
) )
self.setWindowIcon(self.icon()) self.setWindowIcon(self.icon())
self.setWindowTitle(self.title()) self.setWindowTitle(self.title())
@ -995,7 +998,7 @@ class PesterConvo(QtWidgets.QFrame):
def closeEvent(self, event): def closeEvent(self, event):
self.mainwindow.waitingMessages.messageAnswered(self.title()) 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.setFileName("") # Required, sometimes, for some reason. . .
movie.stop() movie.stop()
del movie del movie
@ -1007,7 +1010,9 @@ class PesterConvo(QtWidgets.QFrame):
def changeTheme(self, theme): def changeTheme(self, theme):
self.resize(*theme["convo/size"]) self.resize(*theme["convo/size"])
self.setStyleSheet( 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"] margins = theme["convo/margins"]

View file

@ -1,5 +1,4 @@
import logging import logging
import ostools
PchumLog = logging.getLogger("pchumLogger") PchumLog = logging.getLogger("pchumLogger")
try: try:
@ -34,7 +33,7 @@ _memore = re.compile(r"(\s|^)(#[A-Za-z0-9_]+)")
_handlere = 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): def __init__(self, quirk):
if type(quirk) != dict: if type(quirk) != dict:
raise ValueError("Quirks must be given a dictionary") raise ValueError("Quirks must be given a dictionary")
@ -112,14 +111,14 @@ class pesterQuirk(object):
elif self.type == "suffix": elif self.type == "suffix":
return "END WITH: %s" % (self.quirk["value"]) return "END WITH: %s" % (self.quirk["value"])
elif self.type == "replace": 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": elif self.type == "regexp":
return "REGEXP: %s REPLACED WITH %s" % ( return "REGEXP: {} REPLACED WITH {}".format(
self.quirk["from"], self.quirk["from"],
self.quirk["to"], self.quirk["to"],
) )
elif self.type == "random": elif self.type == "random":
return "REGEXP: %s RANDOMLY REPLACED WITH %s" % ( return "REGEXP: {} RANDOMLY REPLACED WITH {}".format(
self.quirk["from"], self.quirk["from"],
[r for r in self.quirk["randomlist"]], [r for r in self.quirk["randomlist"]],
) )
@ -127,7 +126,7 @@ class pesterQuirk(object):
return "MISPELLER: %d%%" % (self.quirk["percentage"]) return "MISPELLER: %d%%" % (self.quirk["percentage"])
class pesterQuirks(object): class pesterQuirks:
def __init__(self, quirklist): def __init__(self, quirklist):
self.quirklist = [] self.quirklist = []
for q in quirklist: for q in quirklist:
@ -258,11 +257,10 @@ class pesterQuirks(object):
return final return final
def __iter__(self): def __iter__(self):
for q in self.quirklist: yield from self.quirklist
yield q
class PesterProfile(object): class PesterProfile:
def __init__( def __init__(
self, self,
handle, handle,
@ -345,12 +343,12 @@ class PesterProfile(object):
msg = convertTags(lexmsg[1:], "text") msg = convertTags(lexmsg[1:], "text")
uppersuffix = suffix.upper() uppersuffix = suffix.upper()
if time is not None: 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 initials = time.pcf + self.initials() + time.number + uppersuffix
else: else:
handle = self.handle handle = self.handle
initials = self.initials() + uppersuffix initials = self.initials() + uppersuffix
return "<c=%s>-- %s%s <c=%s>[%s]</c> %s --</c>" % ( return "<c={}>-- {}{} <c={}>[{}]</c> {} --</c>".format(
syscolor.name(), syscolor.name(),
handle, handle,
suffix, suffix,
@ -360,7 +358,7 @@ class PesterProfile(object):
) )
def pestermsg(self, otherchum, syscolor, verb): def pestermsg(self, otherchum, syscolor, verb):
return "<c=%s>-- %s <c=%s>[%s]</c> %s %s <c=%s>[%s]</c> at %s --</c>" % ( return "<c={}>-- {} <c={}>[{}]</c> {} {} <c={}>[{}]</c> at {} --</c>".format(
syscolor.name(), syscolor.name(),
self.handle, self.handle,
self.colorhtml(), self.colorhtml(),
@ -386,7 +384,7 @@ class PesterProfile(object):
) )
def idlemsg(self, syscolor, verb): def idlemsg(self, syscolor, verb):
return "<c=%s>-- %s <c=%s>[%s]</c> %s --</c>" % ( return "<c={}>-- {} <c={}>[{}]</c> {} --</c>".format(
syscolor.name(), syscolor.name(),
self.handle, self.handle,
self.colorhtml(), self.colorhtml(),
@ -396,14 +394,14 @@ class PesterProfile(object):
def memoclosemsg(self, syscolor, initials, verb): def memoclosemsg(self, syscolor, initials, verb):
if type(initials) == type(list()): if type(initials) == type(list()):
return "<c=%s><c=%s>%s</c> %s.</c>" % ( return "<c={}><c={}>{}</c> {}.</c>".format(
syscolor.name(), syscolor.name(),
self.colorhtml(), self.colorhtml(),
", ".join(initials), ", ".join(initials),
verb, verb,
) )
else: else:
return "<c=%s><c=%s>%s%s%s</c> %s.</c>" % ( return "<c={}><c={}>{}{}{}</c> {}.</c>".format(
syscolor.name(), syscolor.name(),
self.colorhtml(), self.colorhtml(),
initials.pcf, initials.pcf,
@ -416,7 +414,7 @@ class PesterProfile(object):
if len(initials) <= 0: if len(initials) <= 0:
return "<c=%s>Netsplit quits: <c=black>None</c></c>" % (syscolor.name()) return "<c=%s>Netsplit quits: <c=black>None</c></c>" % (syscolor.name())
else: else:
return "<c=%s>Netsplit quits: <c=black>%s</c></c>" % ( return "<c={}>Netsplit quits: <c=black>{}</c></c>".format(
syscolor.name(), syscolor.name(),
", ".join(initials), ", ".join(initials),
) )
@ -427,7 +425,7 @@ class PesterProfile(object):
PchumLog.debug("pre pcf+self.initials()") PchumLog.debug("pre pcf+self.initials()")
initials = timeGrammar.pcf + self.initials() initials = timeGrammar.pcf + self.initials()
PchumLog.debug("post pcf+self.initials()") PchumLog.debug("post pcf+self.initials()")
return "<c=%s><c=%s>%s</c> %s %s %s.</c>" % ( return "<c={}><c={}>{}</c> {} {} {}.</c>".format(
syscolor.name(), syscolor.name(),
self.colorhtml(), self.colorhtml(),
initials, initials,
@ -440,12 +438,14 @@ class PesterProfile(object):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
if type(initials) == type(list()): if type(initials) == type(list()):
if opchum.handle == reason: if opchum.handle == reason:
return "<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo." % ( return (
"<c={}>{}</c> banned <c={}>{}</c> from responding to memo.".format(
opchum.colorhtml(), opchum.colorhtml(),
opinit, opinit,
self.colorhtml(), self.colorhtml(),
", ".join(initials), ", ".join(initials),
) )
)
else: else:
return ( return (
"<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo: <c=black>[%s]</c>." "<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo: <c=black>[%s]</c>."
@ -501,7 +501,7 @@ class PesterProfile(object):
def memopermabanmsg(self, opchum, opgrammar, syscolor, timeGrammar): def memopermabanmsg(self, opchum, opgrammar, syscolor, timeGrammar):
initials = timeGrammar.pcf + self.initials() + timeGrammar.number initials = timeGrammar.pcf + self.initials() + timeGrammar.number
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> permabanned <c=%s>%s</c> from the memo." % ( return "<c={}>{}</c> permabanned <c={}>{}</c> from the memo.".format(
opchum.colorhtml(), opchum.colorhtml(),
opinit, opinit,
self.colorhtml(), self.colorhtml(),
@ -512,7 +512,7 @@ class PesterProfile(object):
# (temporal, pcf, when) = (timeGrammar.temporal, timeGrammar.pcf, timeGrammar.when) # (temporal, pcf, when) = (timeGrammar.temporal, timeGrammar.pcf, timeGrammar.when)
timetext = timeDifference(td) timetext = timeDifference(td)
initials = timeGrammar.pcf + self.initials() + timeGrammar.number initials = timeGrammar.pcf + self.initials() + timeGrammar.number
return "<c=%s><c=%s>%s %s [%s]</c> %s %s.</c>" % ( return "<c={}><c={}>{} {} [{}]</c> {} {}.</c>".format(
syscolor.name(), syscolor.name(),
self.colorhtml(), self.colorhtml(),
timeGrammar.temporal, timeGrammar.temporal,
@ -524,7 +524,7 @@ class PesterProfile(object):
def memoopmsg(self, opchum, opgrammar, syscolor): def memoopmsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> made <c=%s>%s</c> an OP." % ( return "<c={}>{}</c> made <c={}>{}</c> an OP.".format(
opchum.colorhtml(), opchum.colorhtml(),
opinit, opinit,
self.colorhtml(), self.colorhtml(),
@ -533,7 +533,7 @@ class PesterProfile(object):
def memodeopmsg(self, opchum, opgrammar, syscolor): def memodeopmsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> took away <c=%s>%s</c>'s OP powers." % ( return "<c={}>{}</c> took away <c={}>{}</c>'s OP powers.".format(
opchum.colorhtml(), opchum.colorhtml(),
opinit, opinit,
self.colorhtml(), self.colorhtml(),
@ -542,7 +542,7 @@ class PesterProfile(object):
def memovoicemsg(self, opchum, opgrammar, syscolor): def memovoicemsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> gave <c=%s>%s</c> voice." % ( return "<c={}>{}</c> gave <c={}>{}</c> voice.".format(
opchum.colorhtml(), opchum.colorhtml(),
opinit, opinit,
self.colorhtml(), self.colorhtml(),
@ -551,7 +551,7 @@ class PesterProfile(object):
def memodevoicemsg(self, opchum, opgrammar, syscolor): def memodevoicemsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> took away <c=%s>%s</c>'s voice." % ( return "<c={}>{}</c> took away <c={}>{}</c>'s voice.".format(
opchum.colorhtml(), opchum.colorhtml(),
opinit, opinit,
self.colorhtml(), self.colorhtml(),
@ -564,7 +564,7 @@ class PesterProfile(object):
modeon = "now" modeon = "now"
else: else:
modeon = "no longer" modeon = "no longer"
return "<c=%s>Memo is %s <c=black>%s</c> by <c=%s>%s</c></c>" % ( return "<c={}>Memo is {} <c=black>{}</c> by <c={}>{}</c></c>".format(
syscolor.name(), syscolor.name(),
modeon, modeon,
modeverb, modeverb,
@ -574,7 +574,7 @@ class PesterProfile(object):
def memoquirkkillmsg(self, opchum, opgrammar, syscolor): def memoquirkkillmsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s><c=%s>%s</c> turned off your quirk.</c>" % ( return "<c={}><c={}>{}</c> turned off your quirk.</c>".format(
syscolor.name(), syscolor.name(),
opchum.colorhtml(), opchum.colorhtml(),
opinit, opinit,
@ -598,7 +598,7 @@ class PesterProfile(object):
return (True,) return (True,)
class PesterHistory(object): class PesterHistory:
def __init__(self): def __init__(self):
self.history = [] self.history = []
self.current = 0 self.current = 0

View file

@ -19,19 +19,19 @@ class mysteryTime(timedelta):
class CaseInsensitiveDict(dict): class CaseInsensitiveDict(dict):
def __setitem__(self, key, value): def __setitem__(self, key, value):
super(CaseInsensitiveDict, self).__setitem__(key.lower(), value) super().__setitem__(key.lower(), value)
def __getitem__(self, key): def __getitem__(self, key):
return super(CaseInsensitiveDict, self).__getitem__(key.lower()) return super().__getitem__(key.lower())
def __contains__(self, key): def __contains__(self, key):
return super(CaseInsensitiveDict, self).__contains__(key.lower()) return super().__contains__(key.lower())
def has_key(self, key): def has_key(self, key):
return key.lower() in super(CaseInsensitiveDict, self) return key.lower() in super()
def __delitem__(self, key): def __delitem__(self, key):
super(CaseInsensitiveDict, self).__delitem__(key.lower()) super().__delitem__(key.lower())
class PesterList(list): class PesterList(list):
@ -41,7 +41,7 @@ class PesterList(list):
class PesterIcon(QtGui.QIcon): class PesterIcon(QtGui.QIcon):
def __init__(self, *x): def __init__(self, *x):
super(PesterIcon, self).__init__(x[0]) super().__init__(x[0])
if type(x[0]) in [str, str]: if type(x[0]) in [str, str]:
self.icon_pixmap = QtGui.QPixmap(x[0]) self.icon_pixmap = QtGui.QPixmap(x[0])
else: else:
@ -86,7 +86,7 @@ class RightClickTree(QtWidgets.QTreeWidget):
class MultiTextDialog(QtWidgets.QDialog): class MultiTextDialog(QtWidgets.QDialog):
def __init__(self, title, parent, *queries): def __init__(self, title, parent, *queries):
super(MultiTextDialog, self).__init__(parent) super().__init__(parent)
self.setWindowTitle(title) self.setWindowTitle(title)
if len(queries) == 0: if len(queries) == 0:
return return
@ -131,7 +131,7 @@ class MovingWindow(QtWidgets.QFrame):
# https://doc.qt.io/qt-5/qwindow.html#startSystemMove # 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. # This is also the only method that works on Wayland, which doesn't support setting position.
def __init__(self, *x, **y): def __init__(self, *x, **y):
super(MovingWindow, self).__init__(*x, **y) super().__init__(*x, **y)
self.moving = None self.moving = None
self.moveupdate = 0 self.moveupdate = 0
@ -163,7 +163,7 @@ class MovingWindow(QtWidgets.QFrame):
self.moving = None self.moving = None
class NoneSound(object): class NoneSound:
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
pass pass
@ -179,7 +179,7 @@ class NoneSound(object):
class WMButton(QtWidgets.QPushButton): class WMButton(QtWidgets.QPushButton):
def __init__(self, icon, parent=None): def __init__(self, icon, parent=None):
super(WMButton, self).__init__(icon, "", parent) super().__init__(icon, "", parent)
self.setIconSize(icon.realsize()) self.setIconSize(icon.realsize())
self.resize(icon.realsize()) self.resize(icon.realsize())
self.setFlat(True) self.setFlat(True)

43
irc.py
View file

@ -2,7 +2,6 @@ import logging
import socket import socket
import random import random
import time import time
import json
import ssl import ssl
try: try:
@ -11,7 +10,6 @@ except ImportError:
print("PyQt5 fallback (irc.py)") print("PyQt5 fallback (irc.py)")
from PyQt5 import QtCore, QtGui from PyQt5 import QtCore, QtGui
import ostools
from mood import Mood from mood import Mood
from dataobjs import PesterProfile from dataobjs import PesterProfile
from generic import PesterList from generic import PesterList
@ -96,10 +94,10 @@ class PesterIRC(QtCore.QThread):
except socket.timeout as se: except socket.timeout as se:
PchumLog.debug("timeout in thread %s" % (self)) PchumLog.debug("timeout in thread %s" % (self))
self.cli.close() self.cli.close()
self.stopIRC = "%s, %s" % (type(se), se) self.stopIRC = "{}, {}".format(type(se), se)
return return
except (OSError, IndexError, ValueError) as se: 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") PchumLog.debug("socket error, exiting thread")
return return
else: else:
@ -372,7 +370,7 @@ class PesterIRC(QtCore.QThread):
reason = str(l[1]) reason = str(l[1])
if len(l) > 2: if len(l) > 2:
for x in l[2:]: for x in l[2:]:
reason += str(":") + str(x) reason += ":" + str(x)
else: else:
reason = "" reason = ""
try: try:
@ -387,7 +385,7 @@ class PesterIRC(QtCore.QThread):
c = str(channel) c = str(channel)
m = str(mode) m = str(mode)
cmd = str(command) 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 == "": if cmd == "":
cmd = None cmd = None
try: try:
@ -483,7 +481,7 @@ class PesterIRC(QtCore.QThread):
class PesterHandler(DefaultCommandHandler): class PesterHandler(DefaultCommandHandler):
def notice(self, nick, chan, msg): def notice(self, nick, chan, msg):
handle = nick[0 : nick.find("!")] handle = nick[0 : nick.find("!")]
PchumLog.info('---> recv "NOTICE %s :%s"' % (handle, msg)) PchumLog.info('---> recv "NOTICE {} :{}"'.format(handle, msg))
if ( if (
handle == "ChanServ" handle == "ChanServ"
and chan == self.parent.mainwindow.profile().handle and chan == self.parent.mainwindow.profile().handle
@ -501,13 +499,13 @@ class PesterHandler(DefaultCommandHandler):
mood = Mood(int(value)) mood = Mood(int(value))
self.parent.moodUpdated.emit(nick, mood) self.parent.moodUpdated.emit(nick, mood)
except ValueError: except ValueError:
PchumLog.warning("Invalid mood value, %s, %s" % (nick, mood)) PchumLog.warning("Invalid mood value, {}, {}".format(nick, mood))
elif key.lower() == "color": elif key.lower() == "color":
color = QtGui.QColor(value) # Invalid color becomes rgb 0,0,0 color = QtGui.QColor(value) # Invalid color becomes rgb 0,0,0
self.parent.colorUpdated.emit(nick, color) self.parent.colorUpdated.emit(nick, color)
def tagmsg(self, prefix, tags, *args): 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(";") message_tags = tags[1:].split(";")
for m in message_tags: for m in message_tags:
if m.startswith("+pesterchum"): if m.startswith("+pesterchum"):
@ -516,7 +514,7 @@ class PesterHandler(DefaultCommandHandler):
key, value = m.split("=") key, value = m.split("=")
except ValueError: except ValueError:
return return
PchumLog.info("Pesterchum tag: %s=%s" % (key, value)) PchumLog.info("Pesterchum tag: {}={}".format(key, value))
# PESTERCHUM: syntax check # PESTERCHUM: syntax check
if ( if (
(value == "BEGIN") (value == "BEGIN")
@ -563,7 +561,7 @@ class PesterHandler(DefaultCommandHandler):
msg = "/me" + msg[7:-1] msg = "/me" + msg[7:-1]
# CTCPs that don't need to be shown # CTCPs that don't need to be shown
elif msg[0] == "\x01": 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 # VERSION, return version
if msg[1:-1].startswith("VERSION"): if msg[1:-1].startswith("VERSION"):
helpers.ctcp_reply( helpers.ctcp_reply(
@ -609,7 +607,7 @@ class PesterHandler(DefaultCommandHandler):
if chan != "#pesterchum": if chan != "#pesterchum":
# We don't need anywhere near that much spam. # 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": if chan == "#pesterchum":
# follow instructions # follow instructions
@ -740,7 +738,7 @@ class PesterHandler(DefaultCommandHandler):
self.parent.metadata_supported = True self.parent.metadata_supported = True
def cap(self, server, nick, subcommand, tag): 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 tag == "message-tags":
# if subcommand == "ACK": # if subcommand == "ACK":
@ -756,7 +754,7 @@ class PesterHandler(DefaultCommandHandler):
def quit(self, nick, reason): def quit(self, nick, reason):
handle = nick[0 : nick.find("!")] 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: if handle == self.parent.mainwindow.randhandler.randNick:
self.parent.mainwindow.randhandler.setRunning(False) self.parent.mainwindow.randhandler.setRunning(False)
server = self.parent.mainwindow.config.server() server = self.parent.mainwindow.config.server()
@ -769,19 +767,21 @@ class PesterHandler(DefaultCommandHandler):
def kick(self, opnick, channel, handle, reason): def kick(self, opnick, channel, handle, reason):
op = opnick[0 : opnick.find("!")] 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 # ok i shouldnt be overloading that but am lazy
def part(self, nick, channel, reason="nanchos"): def part(self, nick, channel, reason="nanchos"):
handle = nick[0 : nick.find("!")] 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") self.parent.userPresentUpdate.emit(handle, channel, "left")
if channel == "#pesterchum": if channel == "#pesterchum":
self.parent.moodUpdated.emit(handle, Mood("offline")) self.parent.moodUpdated.emit(handle, Mood("offline"))
def join(self, nick, channel): def join(self, nick, channel):
handle = nick[0 : nick.find("!")] 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") self.parent.userPresentUpdate.emit(handle, channel, "join")
if channel == "#pesterchum": if channel == "#pesterchum":
if handle == self.parent.mainwindow.randhandler.randNick: if handle == self.parent.mainwindow.randhandler.randNick:
@ -871,7 +871,6 @@ class PesterHandler(DefaultCommandHandler):
PchumLog.warning( PchumLog.warning(
"Can't remove channel mode that isn't set." "Can't remove channel mode that isn't set."
) )
pass
self.parent.userPresentUpdate.emit( self.parent.userPresentUpdate.emit(
"", channel, channel_mode + ":%s" % (op) "", channel, channel_mode + ":%s" % (op)
) )
@ -887,7 +886,7 @@ class PesterHandler(DefaultCommandHandler):
if l in ["+", "-"]: if l in ["+", "-"]:
cur = l cur = l
else: else:
modes.append("%s%s" % (cur, l)) modes.append("{}{}".format(cur, l))
PchumLog.debug("handles=" + str(handles)) PchumLog.debug("handles=" + str(handles))
PchumLog.debug("enumerate(modes) = " + str(list(enumerate(modes)))) PchumLog.debug("enumerate(modes) = " + str(list(enumerate(modes))))
for (i, m) in enumerate(modes): for (i, m) in enumerate(modes):
@ -911,7 +910,7 @@ class PesterHandler(DefaultCommandHandler):
# self.parent.userPresentUpdate.emit("", channel, m+":%s" % (op)) # self.parent.userPresentUpdate.emit("", channel, m+":%s" % (op))
def nick(self, oldnick, newnick, hopcount=0): def nick(self, oldnick, newnick, hopcount=0):
PchumLog.info("%s, %s" % (oldnick, newnick)) PchumLog.info("{}, {}".format(oldnick, newnick))
# svsnick # svsnick
if oldnick == self.mainwindow.profile().handle: if oldnick == self.mainwindow.profile().handle:
# Server changed our handle, svsnick? # Server changed our handle, svsnick?
@ -926,7 +925,9 @@ class PesterHandler(DefaultCommandHandler):
self.parent.myHandleChanged.emit(newnick) self.parent.myHandleChanged.emit(newnick)
newchum = PesterProfile(newnick, chumdb=self.mainwindow.chumdb) newchum = PesterProfile(newnick, chumdb=self.mainwindow.chumdb)
self.parent.moodUpdated.emit(oldhandle, Mood("offline")) 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: if newnick in self.mainwindow.chumList.chums:
self.getMood(newchum) self.getMood(newchum)
if oldhandle == self.parent.mainwindow.randhandler.randNick: if oldhandle == self.parent.mainwindow.randhandler.randNick:

View file

@ -1,5 +1,4 @@
import os import os
import sys
import codecs import codecs
import re import re
import ostools import ostools
@ -65,8 +64,8 @@ class PesterLogUserSelect(QtWidgets.QDialog):
instructions = QtWidgets.QLabel("Pick a memo or chumhandle:") instructions = QtWidgets.QLabel("Pick a memo or chumhandle:")
if os.path.exists("%s/%s" % (self.logpath, self.handle)): if os.path.exists("{}/{}".format(self.logpath, self.handle)):
chumMemoList = os.listdir("%s/%s/" % (self.logpath, self.handle)) chumMemoList = os.listdir("{}/{}/".format(self.logpath, self.handle))
else: else:
chumMemoList = [] chumMemoList = []
chumslist = config.chums() chumslist = config.chums()
@ -166,17 +165,17 @@ class PesterLogViewer(QtWidgets.QDialog):
self.format = "bbcode" self.format = "bbcode"
if os.path.exists( 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( 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: else:
self.logList = [] self.logList = []
if ( if (
not os.path.exists( 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 or len(self.logList) == 0
): ):
@ -248,7 +247,7 @@ class PesterLogViewer(QtWidgets.QDialog):
for (i, l) in enumerate(self.logList): for (i, l) in enumerate(self.logList):
my = self.fileToMonthYear(l) my = self.fileToMonthYear(l)
if my[0] != last[0]: 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) # child_1.setForeground(0, blackbrush)
self.tree.addTopLevelItem(child_1) self.tree.addTopLevelItem(child_1)
if i == 0: if i == 0:
@ -313,7 +312,7 @@ class PesterLogViewer(QtWidgets.QDialog):
.replace("[url]", "") .replace("[url]", "")
.replace("[/url]", "") .replace("[/url]", "")
) )
cline = re.sub("\[color=(#.{6})]", r"<c=\1>", cline) cline = re.sub(r"\[color=(#.{6})]", r"<c=\1>", cline)
self.textArea.append(convertTags(cline)) self.textArea.append(convertTags(cline))
textCur = self.textArea.textCursor() textCur = self.textArea.textCursor()
# textCur.movePosition(1) # textCur.movePosition(1)

View file

@ -11,7 +11,6 @@ except ImportError:
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QAction from PyQt5.QtWidgets import QAction
import ostools
import parsetools import parsetools
from dataobjs import PesterProfile, PesterHistory from dataobjs import PesterProfile, PesterHistory
from generic import PesterIcon, RightClickList, mysteryTime from generic import PesterIcon, RightClickList, mysteryTime
@ -103,7 +102,7 @@ def pcfGrammar(td):
return (temporal, pcf, when) return (temporal, pcf, when)
class TimeGrammar(object): class TimeGrammar:
def __init__(self, temporal, pcf, when, number="0"): def __init__(self, temporal, pcf, when, number="0"):
self.temporal = temporal self.temporal = temporal
self.pcf = pcf self.pcf = pcf
@ -228,7 +227,7 @@ class TimeTracker(list):
class TimeInput(QtWidgets.QLineEdit): class TimeInput(QtWidgets.QLineEdit):
def __init__(self, timeslider, parent): def __init__(self, timeslider, parent):
super(TimeInput, self).__init__(parent) super().__init__(parent)
self.timeslider = timeslider self.timeslider = timeslider
self.setText("+0:00") self.setText("+0:00")
self.timeslider.valueChanged[int].connect(self.setTime) self.timeslider.valueChanged[int].connect(self.setTime)
@ -260,7 +259,7 @@ class TimeInput(QtWidgets.QLineEdit):
class TimeSlider(QtWidgets.QSlider): class TimeSlider(QtWidgets.QSlider):
def __init__(self, orientation, parent): def __init__(self, orientation, parent):
super(TimeSlider, self).__init__(orientation, parent) super().__init__(orientation, parent)
self.setTracking(True) self.setTracking(True)
self.setMinimum(-50) self.setMinimum(-50)
self.setMaximum(50) self.setMaximum(50)
@ -278,7 +277,7 @@ class TimeSlider(QtWidgets.QSlider):
class MemoTabWindow(PesterTabWindow): class MemoTabWindow(PesterTabWindow):
def __init__(self, mainwindow, parent=None): def __init__(self, mainwindow, parent=None):
super(MemoTabWindow, self).__init__(mainwindow, parent, "memos") super().__init__(mainwindow, parent, "memos")
def addChat(self, convo): def addChat(self, convo):
self.convos[convo.channel] = convo self.convos[convo.channel] = convo
@ -302,7 +301,7 @@ _ctag_begin = re.compile(r"<c=(.*?)>")
class MemoText(PesterText): class MemoText(PesterText):
def __init__(self, theme, parent=None): def __init__(self, theme, parent=None):
super(MemoText, self).__init__(theme, parent) super().__init__(theme, parent)
if hasattr(self.parent(), "mainwindow"): if hasattr(self.parent(), "mainwindow"):
self.mainwindow = self.parent().mainwindow self.mainwindow = self.parent().mainwindow
else: else:
@ -398,11 +397,6 @@ class MemoText(PesterText):
# new chum! time current # new chum! time current
newtime = timedelta(0) newtime = timedelta(0)
time = TimeTracker(newtime) time = TimeTracker(newtime)
# 'handle' undefined?
try:
parent.times[handle] = time
except:
parent.times[chum.handle] = time parent.times[chum.handle] = time
else: else:
time = parent.time time = parent.time
@ -1595,7 +1589,7 @@ class PesterMemo(PesterConvo):
t = self.times[h] t = self.times[h]
grammar = t.getGrammar() grammar = t.getGrammar()
allinitials.append( allinitials.append(
"%s%s%s" % (grammar.pcf, chum.initials(), grammar.number) "{}{}{}".format(grammar.pcf, chum.initials(), grammar.number)
) )
self.times[h].removeTime(t.getTime()) self.times[h].removeTime(t.getTime())
if update == "netsplit": if update == "netsplit":
@ -1645,7 +1639,7 @@ class PesterMemo(PesterConvo):
while ttracker.getTime() is not None: while ttracker.getTime() is not None:
grammar = ttracker.getGrammar() grammar = ttracker.getGrammar()
allinitials.append( allinitials.append(
"%s%s%s" % (grammar.pcf, chum.initials(), grammar.number) "{}{}{}".format(grammar.pcf, chum.initials(), grammar.number)
) )
ttracker.removeTime(ttracker.getTime()) ttracker.removeTime(ttracker.getTime())
msg = chum.memobanmsg(opchum, opgrammar, systemColor, allinitials, reason) msg = chum.memobanmsg(opchum, opgrammar, systemColor, allinitials, reason)
@ -1878,7 +1872,7 @@ class PesterMemo(PesterConvo):
) )
if ok: if ok:
self.mainwindow.kickUser.emit( self.mainwindow.kickUser.emit(
"%s:%s" % (currentHandle, reason), self.channel "{}:{}".format(currentHandle, reason), self.channel
) )
@QtCore.pyqtSlot() @QtCore.pyqtSlot()

View file

@ -1,4 +1,3 @@
import sys
import re import re
from os import remove from os import remove
@ -237,7 +236,7 @@ class PesterQuirkList(QtWidgets.QTreeWidget):
) )
if ok: if ok:
gname = str(gname) 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 = QtWidgets.QMessageBox()
msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME") msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME")
msgbox.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok) msgbox.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok)
@ -1304,9 +1303,7 @@ class PesterOptions(QtWidgets.QDialog):
self.volume.valueChanged[int].connect(self.printValue) self.volume.valueChanged[int].connect(self.printValue)
# Disable the volume slider if we can't actually use it. # Disable the volume slider if we can't actually use it.
if parent.canSetVolume(): if parent.canSetVolume():
self.currentVol = QtWidgets.QLabel( self.currentVol = QtWidgets.QLabel(f"{self.config.volume()!s}%", self)
"{0!s}%".format(self.config.volume()), self
)
# We don't need to explicitly set this, but it helps drive the # We don't need to explicitly set this, but it helps drive the
# point home # point home
self.volume.setEnabled(True) self.volume.setEnabled(True)

View file

@ -1,13 +1,13 @@
try: try:
from PyQt6 import QtCore, QtGui, QtWidgets from PyQt6 import QtCore, QtWidgets
except ImportError: except ImportError:
print("PyQt5 fallback (mood.py)") print("PyQt5 fallback (mood.py)")
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtWidgets
from generic import PesterIcon from generic import PesterIcon
class Mood(object): class Mood:
moods = [ moods = [
"chummy", "chummy",
"rancorous", "rancorous",

View file

@ -1,7 +1,6 @@
import os import os
import sys import sys
import ctypes import ctypes
import platform
try: try:
from PyQt6.QtCore import QStandardPaths from PyQt6.QtCore import QStandardPaths
@ -26,20 +25,6 @@ def isOSXBundle():
return isOSX() and (os.path.abspath(".").find(".app") != -1) 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(): def isRoot():
"""Return True if running with elevated privileges.""" """Return True if running with elevated privileges."""
# Windows # Windows

View file

@ -100,7 +100,7 @@ class IRCClient:
self.username = None self.username = None
self.host = None self.host = None
self.port = None self.port = None
self.connect_cb = None # self.connect_cb = None
self.timeout = None self.timeout = None
self.blocking = None self.blocking = None
self.ssl = None self.ssl = None
@ -246,7 +246,7 @@ class IRCClient:
passing the 'verify_hostname' parameter. The user is asked if they passing the 'verify_hostname' parameter. The user is asked if they
want to disable it if this functions raises a certificate validation error, want to disable it if this functions raises a certificate validation error,
in which case the function may be called again with 'verify_hostname'.""" 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 # Open connection
plaintext_socket = socket.create_connection((self.host, self.port)) plaintext_socket = socket.create_connection((self.host, self.port))
@ -273,13 +273,13 @@ class IRCClient:
helpers.nick(self, self.nick) helpers.nick(self, self.nick)
helpers.user(self, self.username, self.realname) helpers.user(self, self.username, self.realname)
if self.connect_cb: # if self.connect_cb:
self.connect_cb(self) # self.connect_cb(self)
def conn(self): def conn(self):
"""returns a generator object.""" """returns a generator object."""
try: try:
buffer = bytes() buffer = b""
while not self._end: while not self._end:
# Block for connection-killing exceptions # Block for connection-killing exceptions
try: try:
@ -334,14 +334,10 @@ class IRCClient:
except ssl.SSLEOFError as e: except ssl.SSLEOFError as e:
raise e raise e
except OSError as 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: if self._end:
break break
try: # a little dance of compatibility to get the errno if not self.blocking and e.errno == 11:
errno = e.errno
except AttributeError:
errno = e[0]
if not self.blocking and errno == 11:
pass pass
else: else:
raise e raise e
@ -434,7 +430,7 @@ class IRCApp:
warning: if you add a client that has blocking set to true, warning: if you add a client that has blocking set to true,
timers will no longer function properly""" 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) self._clients[client] = self._ClientDesc(autoreconnect=autoreconnect)
def addTimer(self, seconds, cb): def addTimer(self, seconds, cb):
@ -443,7 +439,7 @@ class IRCApp:
( the only advantage to these timers is they dont use threads ) ( the only advantage to these timers is they dont use threads )
""" """
assert callable(cb) 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)) self._timers.append((time.time() + seconds, cb))
def run(self): def run(self):

View file

@ -44,7 +44,7 @@ class ProtectedCommandError(CommandError):
return 'Command "%s" is protected' % ".".join(self.cmd) return 'Command "%s" is protected' % ".".join(self.cmd)
class CommandHandler(object): class CommandHandler:
"""The most basic CommandHandler""" """The most basic CommandHandler"""
def __init__(self, client): def __init__(self, client):
@ -91,7 +91,7 @@ class CommandHandler(object):
arguments_str = "" arguments_str = ""
for x in args: for x in args:
arguments_str += str(x) + " " arguments_str += str(x) + " "
PchumLog.debug("processCommand %s(%s)" % (command, arguments_str.strip())) PchumLog.debug("processCommand {}({})".format(command, arguments_str.strip()))
try: try:
f = self.get(command) f = self.get(command)
@ -118,7 +118,7 @@ class CommandHandler(object):
"""The default handler for commands. Override this method to """The default handler for commands. Override this method to
apply custom behavior (example, printing) unhandled commands. 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): class DefaultCommandHandler(CommandHandler):
@ -150,7 +150,7 @@ class DefaultBotCommandHandler(CommandHandler):
def help(self, sender, dest, arg=None): def help(self, sender, dest, arg=None):
"""list all available commands or get help on a specific command""" """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: if not arg:
commands = self.getVisibleCommands() commands = self.getVisibleCommands()
commands.sort() commands.sort()
@ -171,7 +171,7 @@ class DefaultBotCommandHandler(CommandHandler):
if subcommands: if subcommands:
doc += " [sub commands: %s]" % " ".join(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): class BotCommandHandler(DefaultCommandHandler):
@ -190,7 +190,7 @@ class BotCommandHandler(DefaultCommandHandler):
and calls self.processBotCommand(cmd, sender) if its is. 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: if dest == self.client.nick:
dest = parse_nick(prefix)[0] dest = parse_nick(prefix)[0]

View file

@ -46,13 +46,13 @@ def channel_list(cli):
def kick(cli, handle, channel, reason=""): 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): def mode(cli, channel, mode, options=None):
PchumLog.debug("mode = " + str(mode)) PchumLog.debug("mode = " + str(mode))
PchumLog.debug("options = " + str(options)) PchumLog.debug("options = " + str(options))
cmd = "MODE %s %s" % (channel, mode) cmd = "MODE {} {}".format(channel, mode)
if options: if options:
cmd += " %s" % (options) cmd += " %s" % (options)
cli.send(cmd) cli.send(cmd)
@ -63,11 +63,11 @@ def ctcp(cli, handle, cmd, msg=""):
if msg == "": if msg == "":
cli.send("PRIVMSG", handle, "\x01%s\x01" % (cmd)) cli.send("PRIVMSG", handle, "\x01%s\x01" % (cmd))
else: 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=""): 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): def metadata(cli, target, subcommand, *params):
@ -116,34 +116,29 @@ def quit(cli, msg):
cli.send("QUIT %s" % (msg)) cli.send("QUIT %s" % (msg))
def nick(cli, nick):
cli.send("NICK", nick)
def user(cli, username, realname): def user(cli, username, realname):
cli.send("USER", username, "0", "*", ":" + realname) cli.send("USER", username, "0", "*", ":" + realname)
_simple = ( def join(cli, channel):
"join", """Protocol potentially allows multiple channels or keys."""
"part", cli.send("JOIN", channel)
"nick",
"notice",
"invite",
)
def _addsimple(): def part(cli, channel):
import sys cli.send("PART", channel)
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 notice(cli, target, text):
cli.send("NOTICE", target, text)
def invite(cli, nick, channel):
cli.send("INVITE", nick, channel)
def _addNumerics(): def _addNumerics():

View file

@ -111,14 +111,14 @@ def _addServ(serv, funcs, prefix=""):
setattr(serv, t, simplecmd(t.upper())) setattr(serv, t, simplecmd(t.upper()))
class NickServ(object): class NickServ:
def __init__(self, nick="NickServ"): def __init__(self, nick="NickServ"):
self.name = nick self.name = nick
_addServ(self, _nickservfuncs) _addServ(self, _nickservfuncs)
_addServ(self, _nickservsetfuncs, "set") _addServ(self, _nickservsetfuncs, "set")
class ChanServ(object): class ChanServ:
def __init__(self, nick="ChanServ"): def __init__(self, nick="ChanServ"):
self.name = nick self.name = nick
_addServ(self, _chanservfuncs) _addServ(self, _chanservfuncs)

View file

@ -11,7 +11,6 @@ except ImportError:
from PyQt5 import QtGui, QtWidgets from PyQt5 import QtGui, QtWidgets
import dataobjs import dataobjs
import ostools
# karxi: My own contribution to this - a proper lexer. # karxi: My own contribution to this - a proper lexer.
import pnc.lexercon as lexercon import pnc.lexercon as lexercon
@ -115,7 +114,7 @@ class colorBegin(lexercon.Chunk):
return "[color=%s]" % (qc.name()) return "[color=%s]" % (qc.name())
elif format == "ctag": elif format == "ctag":
(r, g, b, a) = qc.getRgb() (r, g, b, a) = qc.getRgb()
return "<c=%s,%s,%s>" % (r, g, b) return "<c={},{},{}>".format(r, g, b)
class colorEnd(lexercon.Chunk): class colorEnd(lexercon.Chunk):
@ -171,7 +170,7 @@ class hyperlink(lexercon.Chunk):
def convert(self, format): def convert(self, format):
if format == "html": if format == "html":
return "<a href='%s'>%s</a>" % (self.string, self.string) return "<a href='{}'>{}</a>".format(self.string, self.string)
elif format == "bbcode": elif format == "bbcode":
return "[url]%s[/url]" % (self.string) return "[url]%s[/url]" % (self.string)
else: else:
@ -211,7 +210,9 @@ class memolex(lexercon.Chunk):
def convert(self, format): def convert(self, format):
if format == "html": if format == "html":
return "%s<a href='%s'>%s</a>" % (self.space, self.channel, self.channel) return "{}<a href='{}'>{}</a>".format(
self.space, self.channel, self.channel
)
else: else:
return self.string return self.string
@ -224,7 +225,7 @@ class chumhandlelex(lexercon.Chunk):
def convert(self, format): def convert(self, format):
if format == "html": if format == "html":
return "%s<a href='%s'>%s</a>" % (self.space, self.handle, self.handle) return "{}<a href='{}'>{}</a>".format(self.space, self.handle, self.handle)
else: else:
return self.string return self.string
@ -235,7 +236,7 @@ class smiley(lexercon.Chunk):
def convert(self, format): def convert(self, format):
if format == "html": if format == "html":
return "<img src='smilies/%s' alt='%s' title='%s' />" % ( return "<img src='smilies/{}' alt='{}' title='{}' />".format(
smiledict[self.string], smiledict[self.string],
self.string, self.string,
self.string, self.string,
@ -461,7 +462,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
while len(lexed) > 0: while len(lexed) > 0:
rounds += 1 rounds += 1
if debug: if debug:
PchumLog.info("[Starting round {}...]".format(rounds)) PchumLog.info(f"[Starting round {rounds}...]")
msg = lexed.popleft() msg = lexed.popleft()
msglen = 0 msglen = 0
is_text = False is_text = False
@ -502,9 +503,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
# instead? # instead?
subround += 1 subround += 1
if debug: if debug:
PchumLog.info( PchumLog.info(f"[Splitting round {rounds}-{subround}...]")
"[Splitting round {}-{}...]".format(rounds, subround)
)
point = msg.rfind(" ", 0, lenl) point = msg.rfind(" ", 0, lenl)
if point < 0: if point < 0:
# No spaces to break on...ugh. Break at the last space # No spaces to break on...ugh. Break at the last space
@ -517,12 +516,12 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
# Remove what we just added. # Remove what we just added.
msg = msg[point:] msg = msg[point:]
if debug: if debug:
PchumLog.info("msg = {!r}".format(msg)) PchumLog.info(f"msg = {msg!r}")
else: else:
# Catch the remainder. # Catch the remainder.
stack.append(msg) stack.append(msg)
if debug: 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 # Done processing. Pluck out the first portion so we can
# continue processing, clean it up a bit, then add the rest to # continue processing, clean it up a bit, then add the rest to
# our waiting list. # our waiting list.
@ -564,7 +563,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
working.extend([cte] * len(open_ctags)) working.extend([cte] * len(open_ctags))
if debug: if debug:
print( print(
"\tRound {0} linebreak: Added {1} closing ctags".format( "\tRound {} linebreak: Added {} closing ctags".format(
rounds, len(open_ctags) rounds, len(open_ctags)
) )
) )
@ -573,7 +572,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
working = "".join(kxpclexer.list_convert(working)) working = "".join(kxpclexer.list_convert(working))
if debug: if debug:
print( print(
"\tRound {0} add: len == {1} (of {2})".format( "\tRound {} add: len == {} (of {})".format(
rounds, len(working), maxlen rounds, len(working), maxlen
) )
) )
@ -591,7 +590,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
# We have more to go. # We have more to go.
# Reset working, starting it with the unclosed ctags. # Reset working, starting it with the unclosed ctags.
if debug: if debug:
print("\tRound {0}: More to lex".format(rounds)) print(f"\tRound {rounds}: More to lex")
working = open_ctags[:] working = open_ctags[:]
# Calculate the length of the starting tags, add it before # Calculate the length of the starting tags, add it before
# anything else. # anything else.
@ -606,7 +605,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
if debug or True: if debug or True:
# This probably shouldn't happen, and if it does, I want to # This probably shouldn't happen, and if it does, I want to
# know if it *works* properly. # 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. # Clean up, just in case.
working = [] working = []
open_ctags = [] open_ctags = []
@ -655,7 +654,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
working = kxpclexer.list_convert(working) working = kxpclexer.list_convert(working)
if len(working) > 0: if len(working) > 0:
if debug: if debug:
print("Adding end trails: {!r}".format(working)) print(f"Adding end trails: {working!r}")
working = "".join(working) working = "".join(working)
output.append(working) output.append(working)
@ -722,7 +721,7 @@ def kxhandleInput(ctx, text=None, flavor=None):
# Determine if the line actually *is* OOC. # Determine if the line actually *is* OOC.
if is_ooc and not oocDetected: if is_ooc and not oocDetected:
# If we're supposed to be OOC, apply it artificially. # If we're supposed to be OOC, apply it artificially.
msg = "(( {} ))".format(msg) msg = f"(( {msg} ))"
# Also, quirk stuff. # Also, quirk stuff.
should_quirk = ctx.applyquirks should_quirk = ctx.applyquirks
else: else:
@ -861,7 +860,7 @@ def kxhandleInput(ctx, text=None, flavor=None):
clientMsg, colorcmd, grammar.pcf, initials, grammar.number clientMsg, colorcmd, grammar.pcf, initials, grammar.number
) )
# Not sure if this needs a space at the end...? # Not sure if this needs a space at the end...?
serverMsg = "<c={1}>{2}: {0}</c>".format(serverMsg, colorcmd, initials) serverMsg = f"<c={colorcmd}>{initials}: {serverMsg}</c>"
ctx.addMessage(clientMsg, True) ctx.addMessage(clientMsg, True)
if flavor != "menus": if flavor != "menus":
@ -935,7 +934,7 @@ def nonerep(text):
return text return text
class parseLeaf(object): class parseLeaf:
def __init__(self, function, parent): def __init__(self, function, parent):
self.nodes = [] self.nodes = []
self.function = function self.function = function
@ -957,7 +956,7 @@ class parseLeaf(object):
return out return out
class backreference(object): class backreference:
def __init__(self, number): def __init__(self, number):
self.number = number self.number = number
@ -1071,7 +1070,7 @@ smiledict = {
":honk:": "honk.png", ":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()))) _smilere = re.compile("|".join(list(smiledict.keys())))

View file

@ -1,7 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import os import os
import sys import sys
import shutil
import argparse import argparse
import traceback import traceback
import logging import logging
@ -61,11 +60,11 @@ from toast import PesterToastMachine, PesterToast
try: try:
from PyQt6 import QtCore, QtGui, QtWidgets from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6.QtGui import QShortcut, QAction, QActionGroup from PyQt6.QtGui import QAction, QActionGroup
except ImportError: except ImportError:
print("PyQt5 fallback (pesterchum.py)") print("PyQt5 fallback (pesterchum.py)")
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QAction, QShortcut, QActionGroup from PyQt5.QtWidgets import QAction, QActionGroup
# Data directory # Data directory
ostools.validateDataDir() ostools.validateDataDir()
@ -210,7 +209,7 @@ except ImportError:
) )
class waitingMessageHolder(object): class waitingMessageHolder:
def __init__(self, mainwindow, **msgfuncs): def __init__(self, mainwindow, **msgfuncs):
self.mainwindow = mainwindow self.mainwindow = mainwindow
self.funcs = msgfuncs self.funcs = msgfuncs
@ -246,14 +245,14 @@ class waitingMessageHolder(object):
class chumListing(QtWidgets.QTreeWidgetItem): class chumListing(QtWidgets.QTreeWidgetItem):
def __init__(self, chum, window): def __init__(self, chum, window):
super(chumListing, self).__init__([chum.handle]) super().__init__([chum.handle])
self.mainwindow = window self.mainwindow = window
self.chum = chum self.chum = chum
self.handle = chum.handle self.handle = chum.handle
self.setMood(Mood("offline")) self.setMood(Mood("offline"))
self.status = None self.status = None
self.setToolTip( 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): def setMood(self, mood):
@ -330,21 +329,17 @@ class chumListing(QtWidgets.QTreeWidgetItem):
0, 0,
QtGui.QBrush( QtGui.QBrush(
QtGui.QColor( QtGui.QColor(
(
self.mainwindow.theme["main/chums/moods"][self.mood.name()][ self.mainwindow.theme["main/chums/moods"][self.mood.name()][
"color" "color"
] ]
) )
)
), ),
) )
except KeyError: except KeyError:
self.setForeground( self.setForeground(
0, 0,
QtGui.QBrush( QtGui.QBrush(
QtGui.QColor( QtGui.QColor(self.mainwindow.theme["main/chums/moods/chummy/color"])
(self.mainwindow.theme["main/chums/moods/chummy/color"])
)
), ),
) )
@ -379,7 +374,7 @@ class chumArea(RightClickTree):
# This is the class that controls the actual main chumlist, I think. # This is the class that controls the actual main chumlist, I think.
# Looking into how the groups work might be wise. # Looking into how the groups work might be wise.
def __init__(self, chums, parent=None): def __init__(self, chums, parent=None):
super(chumArea, self).__init__(parent) super().__init__(parent)
self.notify = False self.notify = False
QtCore.QTimer.singleShot(30000, self.beginNotify) QtCore.QTimer.singleShot(30000, self.beginNotify)
self.mainwindow = parent self.mainwindow = parent
@ -1061,7 +1056,7 @@ class chumArea(RightClickTree):
if ok: if ok:
notes = str(notes) notes = str(notes)
self.mainwindow.chumdb.setNotes(currentChum.handle, 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() @QtCore.pyqtSlot()
def renameGroup(self): def renameGroup(self):
@ -1073,7 +1068,7 @@ class chumArea(RightClickTree):
) )
if ok: if ok:
gname = str(gname) 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 = QtWidgets.QMessageBox()
msgbox.setStyleSheet( msgbox.setStyleSheet(
"QMessageBox{ %s }" "QMessageBox{ %s }"
@ -1210,7 +1205,7 @@ class trollSlum(chumArea):
class TrollSlumWindow(QtWidgets.QFrame): class TrollSlumWindow(QtWidgets.QFrame):
def __init__(self, trolls, mainwindow, parent=None): def __init__(self, trolls, mainwindow, parent=None):
super(TrollSlumWindow, self).__init__(parent) super().__init__(parent)
self.mainwindow = mainwindow self.mainwindow = mainwindow
theme = self.mainwindow.theme theme = self.mainwindow.theme
self.slumlabel = QtWidgets.QLabel(self) self.slumlabel = QtWidgets.QLabel(self)
@ -1298,7 +1293,7 @@ class PesterWindow(MovingWindow):
sendMessage = QtCore.pyqtSignal("QString", "QString") sendMessage = QtCore.pyqtSignal("QString", "QString")
def __init__(self, options, parent=None, app=None): def __init__(self, options, parent=None, app=None):
super(PesterWindow, self).__init__( super().__init__(
None, None,
( (
QtCore.Qt.WindowType.CustomizeWindowHint QtCore.Qt.WindowType.CustomizeWindowHint
@ -1357,7 +1352,7 @@ class PesterWindow(MovingWindow):
msgBox.setText( msgBox.setText(
"<html><h3>A profile error occured, " "<html><h3>A profile error occured, "
"trying to switch to default pesterClient profile." "trying to switch to default pesterClient profile."
"<br><br>%s<\h3><\html>" % e r"<br><br>%s<\h3><\html>" % e
) )
PchumLog.critical(e) PchumLog.critical(e)
msgBox.exec() msgBox.exec()
@ -1461,6 +1456,7 @@ class PesterWindow(MovingWindow):
self.menu.setNativeMenuBar(False) self.menu.setNativeMenuBar(False)
self.menu.setObjectName("mainmenu") self.menu.setObjectName("mainmenu")
"""
if self.theme.has_key("main/menus/client/console"): if self.theme.has_key("main/menus/client/console"):
self.console = AttrDict( self.console = AttrDict(
dict( dict(
@ -1498,6 +1494,7 @@ class PesterWindow(MovingWindow):
# ~self.connect(self.console.shortcuts.curwgt, # ~self.connect(self.console.shortcuts.curwgt,
# ~ QtCore.SIGNAL('activate()'), self.console. # ~ QtCore.SIGNAL('activate()'), self.console.
self.console.is_open = False self.console.is_open = False
"""
filemenu = self.menu.addMenu(self.theme["main/menus/client/_name"]) filemenu = self.menu.addMenu(self.theme["main/menus/client/_name"])
self.filemenu = filemenu self.filemenu = filemenu
@ -1915,7 +1912,7 @@ class PesterWindow(MovingWindow):
msg = addTimeInitial(msg, memo.times[handle].getGrammar()) msg = addTimeInitial(msg, memo.times[handle].getGrammar())
if handle == "ChanServ": if handle == "ChanServ":
systemColor = QtGui.QColor(self.theme["memos/systemMsgColor"]) systemColor = QtGui.QColor(self.theme["memos/systemMsgColor"])
msg = "<c=%s>%s</c>" % (systemColor.name(), msg) msg = "<c={}>{}</c>".format(systemColor.name(), msg)
memo.addMessage(msg, handle) memo.addMessage(msg, handle)
mentioned = False mentioned = False
m = convertTags(msg, "text") m = convertTags(msg, "text")
@ -2003,6 +2000,7 @@ class PesterWindow(MovingWindow):
self.tabmemo = MemoTabWindow(self) self.tabmemo = MemoTabWindow(self)
self.tabmemo.windowClosed.connect(self.memoTabsClosed) self.tabmemo.windowClosed.connect(self.memoTabsClosed)
"""
@QtCore.pyqtSlot() @QtCore.pyqtSlot()
def toggleConsole(self): def toggleConsole(self):
if not _CONSOLE: if not _CONSOLE:
@ -2070,6 +2068,7 @@ class PesterWindow(MovingWindow):
self.console.is_open = False self.console.is_open = False
self.console.window = None self.console.window = None
PchumLog.info("Console closed.") PchumLog.info("Console closed.")
"""
def newMemo(self, channel, timestr, secret=False, invite=False): def newMemo(self, channel, timestr, secret=False, invite=False):
if channel == "#pesterchum": if channel == "#pesterchum":
@ -2215,10 +2214,10 @@ class PesterWindow(MovingWindow):
## else: ## else:
## self.console.action.setText("Console") ## self.console.action.setText("Console")
# has_key doesn't work out here for some reason, possibly because of inherits? # 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"]) # self.console.action.setText(self.theme["main/menus/client/console"])
except: # except:
self.console.action.setText("Console") # self.console.action.setText("Console")
try: try:
self.reportBugAction.setText(self.theme["main/menus/help/reportbug"]) self.reportBugAction.setText(self.theme["main/menus/help/reportbug"])
@ -2238,7 +2237,7 @@ class PesterWindow(MovingWindow):
if hasattr(self, "moods"): if hasattr(self, "moods"):
self.moods.removeButtons() self.moods.removeButtons()
mood_list = theme["main/moods"] 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.moods = PesterMoodHandler(
self, *[PesterMoodButton(self, **d) for d in mood_list] self, *[PesterMoodButton(self, **d) for d in mood_list]
) )
@ -2387,7 +2386,7 @@ class PesterWindow(MovingWindow):
QtCore.QUrl.fromLocalFile("themes/honk.wav") QtCore.QUrl.fromLocalFile("themes/honk.wav")
) )
except Exception as err: 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.alarm = NoneSound()
self.memosound = NoneSound() self.memosound = NoneSound()
self.namesound = NoneSound() self.namesound = NoneSound()
@ -2415,7 +2414,7 @@ class PesterWindow(MovingWindow):
if self.sound_type == QtMultimedia.QSoundEffect: if self.sound_type == QtMultimedia.QSoundEffect:
sound.setVolume(vol) sound.setVolume(vol)
except Exception as err: except Exception as err:
PchumLog.warning("Couldn't set volume: {}".format(err)) PchumLog.warning(f"Couldn't set volume: {err}")
def canSetVolume(self): def canSetVolume(self):
"""Returns the state of volume setting capabilities.""" """Returns the state of volume setting capabilities."""
@ -2789,7 +2788,7 @@ class PesterWindow(MovingWindow):
errormsg.showMessage("THIS IS NOT A VALID CHUMTAG!") errormsg.showMessage("THIS IS NOT A VALID CHUMTAG!")
self.addchumdialog = None self.addchumdialog = None
return 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 = QtWidgets.QErrorMessage(self)
errormsg.showMessage("THIS IS NOT A VALID GROUP NAME") errormsg.showMessage("THIS IS NOT A VALID GROUP NAME")
self.addchumdialog = None self.addchumdialog = None
@ -2813,7 +2812,7 @@ class PesterWindow(MovingWindow):
"Enter the reason you are reporting this user (optional):", "Enter the reason you are reporting this user (optional):",
) )
if ok: if ok:
self.sendMessage.emit("REPORT %s %s" % (handle, reason), "calSprite") self.sendMessage.emit("REPORT {} {}".format(handle, reason), "calSprite")
@QtCore.pyqtSlot(QString) @QtCore.pyqtSlot(QString)
def blockChum(self, handle): def blockChum(self, handle):
@ -2942,7 +2941,7 @@ class PesterWindow(MovingWindow):
f = QtWidgets.QFileDialog.getOpenFileName(self)[0] f = QtWidgets.QFileDialog.getOpenFileName(self)[0]
if f == "": if f == "":
return return
fp = open(f, "r") fp = open(f)
regexp_state = None regexp_state = None
for l in fp: for l in fp:
# import chumlist # import chumlist
@ -3135,7 +3134,7 @@ class PesterWindow(MovingWindow):
) )
if ok: if ok:
gname = str(gname) 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 = QtWidgets.QMessageBox()
msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME") msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME")
msgbox.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok) msgbox.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok)
@ -3496,7 +3495,7 @@ class PesterWindow(MovingWindow):
"<br><br>" "<br><br>"
"If you got this message at launch you may want to " "If you got this message at launch you may want to "
"change your default profile." "change your default profile."
"<br><br>%s<\h3><\html>" r"<br><br>%s<\h3><\html>"
% (self.profiledir, self.profiledir, handle, e) % (self.profiledir, self.profiledir, handle, e)
) )
@ -3508,7 +3507,7 @@ class PesterWindow(MovingWindow):
"file exists." "file exists."
"<br><br>If you got this message at launch you may " "<br><br>If you got this message at launch you may "
"want to change your default profile." "want to change your default profile."
"<br><br>%s<\h3><\html>" % e r"<br><br>%s<\h3><\html>" % e
) )
PchumLog.critical(e) PchumLog.critical(e)
msgBox.setText(msg) msgBox.setText(msg)
@ -3765,7 +3764,7 @@ class PesterWindow(MovingWindow):
self.chooseServer() self.chooseServer()
return 1 return 1
with open(_datadir + "serverlist.json", "r") as server_file: with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read() read_file = server_file.read()
server_file.close() server_file.close()
server_list_obj = json.loads(read_file) server_list_obj = json.loads(read_file)
@ -3822,7 +3821,7 @@ class PesterWindow(MovingWindow):
def removeServer(self): def removeServer(self):
server_list_items = [] server_list_items = []
try: try:
with open(_datadir + "serverlist.json", "r") as server_file: with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read() read_file = server_file.read()
server_file.close() server_file.close()
server_list_obj = json.loads(read_file) server_list_obj = json.loads(read_file)
@ -3924,7 +3923,7 @@ class PesterWindow(MovingWindow):
# Read servers. # Read servers.
server_list_items = [] server_list_items = []
try: try:
with open(_datadir + "serverlist.json", "r") as server_file: with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read() read_file = server_file.read()
server_file.close() server_file.close()
server_obj = json.loads(read_file) server_obj = json.loads(read_file)
@ -3984,7 +3983,7 @@ class PesterWindow(MovingWindow):
else: else:
PchumLog.info(self.serverBox.currentText() + " chosen.") 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() read_file = server_file.read()
server_file.close() server_file.close()
server_obj = json.loads(read_file) server_obj = json.loads(read_file)
@ -4027,7 +4026,7 @@ class PesterWindow(MovingWindow):
# Read servers. # Read servers.
server_list_items = [] server_list_items = []
try: try:
with open(_datadir + "serverlist.json", "r") as server_file: with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read() read_file = server_file.read()
server_file.close() server_file.close()
server_obj = json.loads(read_file) server_obj = json.loads(read_file)
@ -4099,7 +4098,7 @@ class PesterWindow(MovingWindow):
msgbox.setIcon(QtWidgets.QMessageBox.Icon.Warning) msgbox.setIcon(QtWidgets.QMessageBox.Icon.Warning)
msgbox.setText("Server certificate validation failed") msgbox.setText("Server certificate validation failed")
msgbox.setInformativeText( msgbox.setInformativeText(
'Reason: "%s (%s)"' % (e.verify_message, e.verify_code) 'Reason: "{} ({})"'.format(e.verify_message, e.verify_code)
+ "\n\nConnect anyway?" + "\n\nConnect anyway?"
) )
msgbox.setStandardButtons( msgbox.setStandardButtons(
@ -4150,7 +4149,7 @@ class PesterWindow(MovingWindow):
class PesterTray(QtWidgets.QSystemTrayIcon): class PesterTray(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, mainwindow, parent): def __init__(self, icon, mainwindow, parent):
super(PesterTray, self).__init__(icon, parent) super().__init__(icon, parent)
self.mainwindow = mainwindow self.mainwindow = mainwindow
@QtCore.pyqtSlot(int) @QtCore.pyqtSlot(int)
@ -4167,7 +4166,7 @@ class PesterTray(QtWidgets.QSystemTrayIcon):
class MainProgram(QtCore.QObject): class MainProgram(QtCore.QObject):
def __init__(self): def __init__(self):
super(MainProgram, self).__init__() super().__init__()
_oldhook = sys.excepthook _oldhook = sys.excepthook
sys.excepthook = self.uncaughtException sys.excepthook = self.uncaughtException
@ -4191,8 +4190,8 @@ class MainProgram(QtCore.QObject):
windll.shell32.SetCurrentProcessExplicitAppUserModelID(wid) windll.shell32.SetCurrentProcessExplicitAppUserModelID(wid)
except Exception as err: except Exception as err:
# Log, but otherwise ignore any exceptions. # Log, but otherwise ignore any exceptions.
PchumLog.error("Failed to set AppUserModel ID: {0}".format(err)) PchumLog.error(f"Failed to set AppUserModel ID: {err}")
PchumLog.error("Attempted to set as {0!r}.".format(wid)) PchumLog.error(f"Attempted to set as {wid!r}.")
# Back to our scheduled program. # Back to our scheduled program.
self.app = QtWidgets.QApplication(sys.argv) self.app = QtWidgets.QApplication(sys.argv)
@ -4559,7 +4558,7 @@ class MainProgram(QtCore.QObject):
# Show error to end user and log. # Show error to end user and log.
try: try:
# Log to log file # Log to log file
PchumLog.error("%s, %s" % (exc, value)) PchumLog.error("{}, {}".format(exc, value))
# Try to write to separate logfile # Try to write to separate logfile
try: try:

View file

@ -1,4 +1,3 @@
# -*- coding=UTF-8; tab-width: 4 -*-
# Heavily modified version of the code featured at the given link # Heavily modified version of the code featured at the given link
## {{{ http://code.activestate.com/recipes/473786/ (r1) ## {{{ http://code.activestate.com/recipes/473786/ (r1)
class AttrDict(dict): class AttrDict(dict):
@ -11,7 +10,7 @@ class AttrDict(dict):
Overload _is_reserved if you want to change this.""" Overload _is_reserved if you want to change this."""
def __init__(self, init={}): def __init__(self, init={}):
super(AttrDict, self).__init__(init) super().__init__(init)
def __getstate__(self): def __getstate__(self):
return list(self.__dict__.items()) return list(self.__dict__.items())
@ -21,16 +20,16 @@ class AttrDict(dict):
self.__dict__[key] = val self.__dict__[key] = val
def __repr__(self): 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): def __setitem__(self, name, value):
return super(AttrDict, self).__setitem__(name, value) return super().__setitem__(name, value)
def __getitem__(self, name): def __getitem__(self, name):
return super(AttrDict, self).__getitem__(name) return super().__getitem__(name)
def __delitem__(self, name): def __delitem__(self, name):
return super(AttrDict, self).__delitem__(name) return super().__delitem__(name)
def __getattr__(self, name): def __getattr__(self, name):
# NOTE: __getattr__ is called if the code has already failed to access # 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 # Raising KeyError here will confuse __deepcopy__, so don't do
# that. # that.
# Throw a custom error. # Throw a custom error.
raise AttributeError("No key/attr {0!r}".format(name)) raise AttributeError(f"No key/attr {name!r}")
return result return result
def __setattr__(self, name, value): def __setattr__(self, name, value):
@ -68,7 +67,7 @@ class AttrDict(dict):
# in this particular function?... # in this particular function?...
return object.__setattr__(self, name, value) return object.__setattr__(self, name, value)
else: else:
return super(AttrDict, self).__setitem__(name, value) return super().__setitem__(name, value)
def __delattr__(self, name): def __delattr__(self, name):
# We very *specifically* use self.__dict__ here, because we couldn't # 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): def __init__(self, default_factory=None, *args, **kwargs):
self.default_factory = default_factory self.default_factory = default_factory
super(DefAttrDict, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
def __repr__(self): def __repr__(self):
return "{0}({1!r}, {2})".format( return "{}({!r}, {})".format(
type(self).__name__, type(self).__name__,
self.default_factory, self.default_factory,
# We skip normal processing here, since AttrDict provides basic # We skip normal processing here, since AttrDict provides basic
@ -119,7 +118,7 @@ class DefAttrDict(AttrDict):
def __getitem__(self, name): def __getitem__(self, name):
try: try:
result = super(DefAttrDict, self).__getitem__(name) result = super().__getitem__(name)
except KeyError: except KeyError:
result = None result = None
if self.default_factory is not None: if self.default_factory is not None:
@ -129,7 +128,7 @@ class DefAttrDict(AttrDict):
def __getattr__(self, name): def __getattr__(self, name):
try: try:
result = super(DefAttrDict, self).__getattr__(name) result = super().__getattr__(name)
except AttributeError: except AttributeError:
# Detect special/reserved names. # Detect special/reserved names.
if self._is_reserved(name): if self._is_reserved(name):

View file

@ -1,6 +1,3 @@
# -*- coding=UTF-8; tab-width: 4 -*-
from .unicolor import Color from .unicolor import Color
import re import re
@ -20,7 +17,7 @@ except NameError:
# function appropriate to the given format - e.g. CTag.convert_pchum. # function appropriate to the given format - e.g. CTag.convert_pchum.
class Lexeme(object): class Lexeme:
def __init__(self, string, origin): def __init__(self, string, origin):
# The 'string' property is just what it came from; the original # The 'string' property is just what it came from; the original
# representation. It doesn't have to be used, and honestly probably # representation. It doesn't have to be used, and honestly probably
@ -104,7 +101,7 @@ class CTag(Specifier):
sets_color = True sets_color = True
def __init__(self, string, origin, color): def __init__(self, string, origin, color):
super(CTag, self).__init__(string, origin) super().__init__(string, origin)
# So we can also have None # So we can also have None
if isinstance(color, tuple): if isinstance(color, tuple):
if len(color) < 2: if len(color) < 2:
@ -256,7 +253,7 @@ class SpecifierEnd(CTagEnd, FTagEnd):
# .sets_color to False # .sets_color to False
class Lexer(object): class Lexer:
# Subclasses need to supply a ref themselves # Subclasses need to supply a ref themselves
ref = None ref = None
compress_tags = False compress_tags = False

View file

@ -1,6 +1,3 @@
# -*- coding=UTF-8; tab-width: 4 -*-
__all__ = ["Color"] __all__ = ["Color"]
# karxi: Copied from my old Textsub script. Please forgive the mess, and keep # 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"]) LabTuple = collections.namedtuple("LabTuple", ["L", "a", "b"])
class Color(object): class Color:
# The threshold at which to consider two colors noticeably different, even # The threshold at which to consider two colors noticeably different, even
# if only barely # if only barely
jnd = 2.3 jnd = 2.3
@ -145,7 +142,7 @@ class Color(object):
def __repr__(self): def __repr__(self):
##return "%s(%r)" % (type(self).__name__, str(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): def __str__(self):
##return self.reduce_hexstr(self.hexstr) ##return self.reduce_hexstr(self.hexstr)
@ -158,8 +155,7 @@ class Color(object):
def __iter__(self): def __iter__(self):
targs = (self.red, self.green, self.blue) targs = (self.red, self.green, self.blue)
for t in targs: yield from targs
yield t
# If we got here, we're out of attributes to provide # If we got here, we're out of attributes to provide
raise StopIteration raise StopIteration

View file

@ -25,7 +25,7 @@ _datadir = ostools.getDataDir()
PchumLog = logging.getLogger("pchumLogger") PchumLog = logging.getLogger("pchumLogger")
class PesterLog(object): class PesterLog:
def __init__(self, handle, parent=None): def __init__(self, handle, parent=None):
global _datadir global _datadir
self.parent = parent self.parent = parent
@ -66,10 +66,12 @@ class PesterLog(object):
self.convos[handle] = {} self.convos[handle] = {}
for (format, t) in modes.items(): for (format, t) in modes.items():
if not os.path.exists( if not os.path.exists(
"%s/%s/%s/%s" % (self.logpath, self.handle, handle, format) "{}/{}/{}/{}".format(self.logpath, self.handle, handle, format)
): ):
os.makedirs( os.makedirs(
"%s/%s/%s/%s" % (self.logpath, self.handle, handle, format) "{}/{}/{}/{}".format(
self.logpath, self.handle, handle, format
)
) )
fp = codecs.open( fp = codecs.open(
"%s/%s/%s/%s/%s.%s.txt" "%s/%s/%s/%s/%s.%s.txt"
@ -94,7 +96,7 @@ class PesterLog(object):
# for (format, t) in modes.items(): # for (format, t) in modes.items():
# self.finish(handle) # 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 </3 # Catching this exception does not stop pchum from dying if we run out of file handles </3
PchumLog.critical(e) PchumLog.critical(e)
errmsg = QtWidgets.QMessageBox() errmsg = QtWidgets.QMessageBox()
@ -125,7 +127,7 @@ class PesterLog(object):
f.close() f.close()
class userConfig(object): class userConfig:
def __init__(self, parent): def __init__(self, parent):
self.parent = parent self.parent = parent
# Use for bit flag log setting # Use for bit flag log setting
@ -184,9 +186,9 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
if not os.path.exists(self.logpath): if not os.path.exists(self.logpath):
os.makedirs(self.logpath) os.makedirs(self.logpath)
try: 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) self.groups = json.load(fp)
except (IOError, ValueError): except (OSError, ValueError):
self.groups = {} self.groups = {}
with open("%s/groups.js" % (self.logpath), "w") as fp: with open("%s/groups.js" % (self.logpath), "w") as fp:
json.dump(self.groups, fp) json.dump(self.groups, fp)
@ -225,15 +227,12 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
pzip.writestr(x, f.read()) pzip.writestr(x, f.read())
PchumLog.info("Updated backups-%s." % current_backup) 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: except shutil.Error as e:
PchumLog.warning("Failed to make backup, shutil error?") PchumLog.warning(f"Failed to make backup, shutil error?\n{e}")
PchumLog.warning(e)
except zipfile.BadZipFile as e: except zipfile.BadZipFile as e:
PchumLog.warning("Failed to make backup, BadZipFile?") PchumLog.warning(f"Failed to make backup, BadZipFile?\n{e}")
PchumLog.warning(e) except OSError as e:
PchumLog.warning(f"Failed to make backup, no permission?\n{e}")
def chums(self): def chums(self):
if "chums" not in self.config: if "chums" not in self.config:
@ -445,7 +444,7 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
if hasattr(self.parent, "serverOverride"): if hasattr(self.parent, "serverOverride"):
return self.parent.serverOverride return self.parent.serverOverride
try: try:
with open(_datadir + "server.json", "r") as server_file: with open(_datadir + "server.json") as server_file:
read_file = server_file.read() read_file = server_file.read()
server_file.close() server_file.close()
server_obj = json.loads(read_file) server_obj = json.loads(read_file)
@ -468,7 +467,7 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
if hasattr(self.parent, "portOverride"): if hasattr(self.parent, "portOverride"):
return self.parent.portOverride return self.parent.portOverride
try: try:
with open(_datadir + "server.json", "r") as server_file: with open(_datadir + "server.json") as server_file:
read_file = server_file.read() read_file = server_file.read()
server_file.close() server_file.close()
server_obj = json.loads(read_file) server_obj = json.loads(read_file)
@ -481,7 +480,7 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
# if hasattr(self.parent, 'tlsOverride'): # if hasattr(self.parent, 'tlsOverride'):
# return self.parent.tlsOverride # return self.parent.tlsOverride
try: try:
with open(_datadir + "server.json", "r") as server_file: with open(_datadir + "server.json") as server_file:
read_file = server_file.read() read_file = server_file.read()
server_file.close() server_file.close()
server_obj = json.loads(read_file) server_obj = json.loads(read_file)
@ -578,7 +577,7 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
+ "</a>" + "</a>"
+ "<br><br>" + "<br><br>"
+ str(e) + str(e)
+ "<\h3><\html>" + r"<\h3><\html>"
) )
# "\" if pesterchum acts oddly you might want to try backing up and then deleting \"" + \ # "\" if pesterchum acts oddly you might want to try backing up and then deleting \"" + \
# _datadir+"pesterchum.js" + \ # _datadir+"pesterchum.js" + \
@ -589,7 +588,7 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
return [userProfile(p) for p in profs] return [userProfile(p) for p in profs]
class userProfile(object): class userProfile:
def __init__(self, user): def __init__(self, user):
self.profiledir = _datadir + "profiles" self.profiledir = _datadir + "profiles"
@ -610,8 +609,8 @@ class userProfile(object):
if len(initials) >= 2: if len(initials) >= 2:
initials = ( initials = (
initials, initials,
"%s%s" % (initials[0].lower(), initials[1]), "{}{}".format(initials[0].lower(), initials[1]),
"%s%s" % (initials[0], initials[1].lower()), "{}{}".format(initials[0], initials[1].lower()),
) )
self.mentions = [r"\b(%s)\b" % ("|".join(initials))] self.mentions = [r"\b(%s)\b" % ("|".join(initials))]
else: else:
@ -624,7 +623,7 @@ class userProfile(object):
# u'XXX\\AppData\\Local\\pesterchum/profiles/XXX.js' # u'XXX\\AppData\\Local\\pesterchum/profiles/XXX.js'
# Part 3 :( # Part 3 :(
try: 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) self.userprofile = json.load(fp)
except (json.JSONDecodeError, FileNotFoundError) as e: except (json.JSONDecodeError, FileNotFoundError) as e:
msgBox = QtWidgets.QMessageBox() msgBox = QtWidgets.QMessageBox()
@ -644,7 +643,7 @@ class userProfile(object):
+ "<br><br>If you got this message at launch you may want to change your default profile." + "<br><br>If you got this message at launch you may want to change your default profile."
+ "<br><br>" + "<br><br>"
+ str(e) + str(e)
+ "<\h3><\html>" + r"<\h3><\html>"
) )
# "\" if pesterchum acts oddly you might want to try backing up and then deleting \"" + \ # "\" if pesterchum acts oddly you might want to try backing up and then deleting \"" + \
# _datadir+"pesterchum.js" + \ # _datadir+"pesterchum.js" + \
@ -674,8 +673,8 @@ class userProfile(object):
if len(initials) >= 2: if len(initials) >= 2:
initials = ( initials = (
initials, initials,
"%s%s" % (initials[0].lower(), initials[1]), "{}{}".format(initials[0].lower(), initials[1]),
"%s%s" % (initials[0], initials[1].lower()), "{}{}".format(initials[0], initials[1].lower()),
) )
self.userprofile["mentions"] = [r"\b(%s)\b" % ("|".join(initials))] self.userprofile["mentions"] = [r"\b(%s)\b" % ("|".join(initials))]
else: else:
@ -736,11 +735,12 @@ class userProfile(object):
return self.mentions return self.mentions
def setMentions(self, mentions): def setMentions(self, mentions):
i = None
try: try:
for (i, m) in enumerate(mentions): for (i, m) in enumerate(mentions):
re.compile(m) re.compile(m)
except re.error as e: 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: else:
self.mentions = mentions self.mentions = mentions
self.userprofile["mentions"] = mentions self.userprofile["mentions"] = mentions
@ -794,7 +794,7 @@ class userProfile(object):
jsonoutput = json.dumps(self.userprofile) jsonoutput = json.dumps(self.userprofile)
except ValueError as e: except ValueError as e:
raise 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) fp.write(jsonoutput)
def saveNickServPass(self): def saveNickServPass(self):
@ -811,7 +811,7 @@ class userProfile(object):
@staticmethod @staticmethod
def newUserProfile(chatprofile): 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) newprofile = userProfile(chatprofile.handle)
else: else:
newprofile = userProfile(chatprofile) newprofile = userProfile(chatprofile)
@ -826,9 +826,9 @@ class PesterProfileDB(dict):
if not os.path.exists(self.logpath): if not os.path.exists(self.logpath):
os.makedirs(self.logpath) os.makedirs(self.logpath)
try: try:
with open("%s/chums.js" % (self.logpath), "r") as fp: with open("%s/chums.js" % (self.logpath)) as fp:
chumdict = json.load(fp) chumdict = json.load(fp)
except (IOError, ValueError): except (OSError, ValueError):
# karxi: This code feels awfully familiar.... # karxi: This code feels awfully familiar....
chumdict = {} chumdict = {}
with open("%s/chums.js" % (self.logpath), "w") as fp: with open("%s/chums.js" % (self.logpath), "w") as fp:
@ -852,7 +852,7 @@ class PesterProfileDB(dict):
handle, handle,
color=QtGui.QColor(c["color"]), color=QtGui.QColor(c["color"]),
mood=Mood(c["mood"]), mood=Mood(c["mood"]),
**options **options,
), ),
) )
) )
@ -928,7 +928,7 @@ class pesterTheme(dict):
try: try:
with open(self.path + "/style.js") as fp: with open(self.path + "/style.js") as fp:
theme = json.load(fp, object_hook=self.pathHook) theme = json.load(fp, object_hook=self.pathHook)
except IOError: except OSError:
theme = json.loads("{}") theme = json.loads("{}")
self.update(theme) self.update(theme)
if "inherits" in self: if "inherits" in self:
@ -939,7 +939,7 @@ class pesterTheme(dict):
def __getitem__(self, key): def __getitem__(self, key):
keys = key.split("/") keys = key.split("/")
try: try:
v = super(pesterTheme, self).__getitem__(keys.pop(0)) v = super().__getitem__(keys.pop(0))
except KeyError as e: except KeyError as e:
if hasattr(self, "inheritedTheme"): if hasattr(self, "inheritedTheme"):
return self.inheritedTheme[key] return self.inheritedTheme[key]
@ -969,7 +969,7 @@ class pesterTheme(dict):
def get(self, key, default): def get(self, key, default):
keys = key.split("/") keys = key.split("/")
try: try:
v = super(pesterTheme, self).__getitem__(keys.pop(0)) v = super().__getitem__(keys.pop(0))
for k in keys: for k in keys:
v = v[k] v = v[k]
return default if v is None else v return default if v is None else v
@ -982,7 +982,7 @@ class pesterTheme(dict):
def has_key(self, key): def has_key(self, key):
keys = key.split("/") keys = key.split("/")
try: try:
v = super(pesterTheme, self).__getitem__(keys.pop(0)) v = super().__getitem__(keys.pop(0))
for k in keys: for k in keys:
v = v[k] v = v[k]
return v is not None return v is not None

View file

@ -7,7 +7,6 @@ except ImportError:
print("PyQt5 fallback (pyquirks.py)") print("PyQt5 fallback (pyquirks.py)")
from PyQt5 import QtWidgets from PyQt5 import QtWidgets
import ostools
from quirks import ScriptQuirks from quirks import ScriptQuirks
PchumLog = logging.getLogger("pchumLogger") PchumLog = logging.getLogger("pchumLogger")

View file

@ -40,16 +40,16 @@ def init(host="127.0.0.1", port=None):
if line.startswith("port=") and line[5:-1].isdigit(): if line.startswith("port=") and line[5:-1].isdigit():
port = int(line[5:-1]) port = int(line[5:-1])
break break
except IOError: except OSError:
raise TwmnError(TwmnError.NO_CONF) raise TwmnError(TwmnError.NO_CONF)
if type(port) == type(str()): if type(port) == type(""):
port = int(port) port = int(port)
global s global s
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((host, port)) s.connect((host, port))
class Notification(object): class Notification:
def __init__(self, title="", msg="", icon=""): def __init__(self, title="", msg="", icon=""):
self.title = str(title) self.title = str(title)
self.msg = str(msg) self.msg = str(msg)

View file

@ -7,7 +7,7 @@ _datadir = ostools.getDataDir()
PchumLog = logging.getLogger("pchumLogger") PchumLog = logging.getLogger("pchumLogger")
class ScriptQuirks(object): class ScriptQuirks:
def __init__(self): def __init__(self):
self._datadir = ostools.getDataDir() self._datadir = ostools.getDataDir()
self.home = os.getcwd() self.home = os.getcwd()
@ -73,7 +73,9 @@ class ScriptQuirks(object):
continue continue
except Exception as e: except Exception as e:
PchumLog.warning( 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: else:
if self.modHas(module, "setup"): if self.modHas(module, "setup"):

View file

@ -6,7 +6,6 @@ except ImportError:
print("PyQt5 fallback (randomer.py)") print("PyQt5 fallback (randomer.py)")
from PyQt5 import QtCore, QtWidgets from PyQt5 import QtCore, QtWidgets
import ostools
PchumLog = logging.getLogger("pchumLogger") PchumLog = logging.getLogger("pchumLogger")

View file

@ -2,7 +2,6 @@
import sys import sys
from cx_Freeze import setup, Executable from cx_Freeze import setup, Executable
import pygame
from version import buildVersion from version import buildVersion

View file

@ -24,7 +24,7 @@ PchumLog = logging.getLogger("pchumLogger")
pynotify = None pynotify = None
class DefaultToast(object): class DefaultToast:
def __init__(self, machine, title, msg, icon): def __init__(self, machine, title, msg, icon):
self.machine = machine self.machine = machine
self.title = title self.title = title
@ -43,8 +43,8 @@ class DefaultToast(object):
PchumLog.info("Done") PchumLog.info("Done")
class ToastMachine(object): class ToastMachine:
class __Toast__(object): class __Toast__:
def __init__(self, machine, title, msg, time=3000, icon="", importance=0): def __init__(self, machine, title, msg, time=3000, icon="", importance=0):
self.machine = machine self.machine = machine
self.title = title self.title = title