🧹🪣 Mostly pyflakes recommendations.

This commit is contained in:
Dpeta 2022-04-11 05:57:13 +02:00
parent c070745e26
commit 082c0c9c2b
26 changed files with 198 additions and 162 deletions

View file

@ -1,10 +1,17 @@
# Changelog # Changelog
(This document uses YYYY-MM-DD) (This document uses YYYY-MM-DD)
## [v2.2.2] - 2022-03-26 ## [v2.2.2] - 2022-04-11
### Changed
- Removed unused imports.
- Removed unused variables.
- Made some 'from X import *' imports explicit.
### Fixed ### Fixed
- Timeline overflow conditions, time is now replaced with platform max/min on OverflowError. - Timeline overflow conditions, time is now replaced with platform max/min on OverflowError.
- Some accidental redefinitions. (modesUpdated function got overwriten by modesUpdated QtCore.pyqtSignal, 'time' module got overwriten by 'time' variable, etc.)
- A few broken conditions that didn't usually occur.
## [v2.2.1] - 2022-03-26 ## [v2.2.1] - 2022-03-26

View file

@ -2,12 +2,15 @@
## ADD ## ADD
- Memoserv support. - Memoserv support.
- (Re-add) update checking. - Use memopermabanmsg function?
## FIX ## FIX
- Mask & target not being passed to ``_max_msg_len``. - Mask & target not being passed to ``_max_msg_len``.
- Look into using a different IRC library?
- No error message when Pesterchum fails to join a channel. (For example, when the channel name length is over CHANNELLEN) - No error message when Pesterchum fails to join a channel. (For example, when the channel name length is over CHANNELLEN)
- Choose memo window doesn't get updated on theme change. - Choose memo window doesn't get updated on theme change.
- Right click menu's color doesn't get updated on theme change in memos. - Right click menu's color doesn't get updated on theme change in memos.
- Closed windows sometimes stay open. - Closed windows sometimes stay open.
- Should confirm if this is still an issue.
- help() causes console to crash...? - help() causes console to crash...?
- Console is hopelessly broken, it'd be easier to make a list of what commands *don't* cause it to crash. Does anyone use this?

View file

@ -1,23 +1,27 @@
# 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
#from os import remove
import sys
import traceback
import time
import datetime
import logging
import logging.config
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
import re, os, traceback, sys
import time, datetime
from os import remove
import dataobjs, generic, memos, parsetools, ostools import dataobjs
from version import _pcVersion #import generic
#import memos
#import parsetools
import ostools
#from version import _pcVersion
from pnc.dep.attrdict import AttrDict from pnc.dep.attrdict import AttrDict
#~from styling import styler
_datadir = ostools.getDataDir() _datadir = ostools.getDataDir()
logging.config.fileConfig(_datadir + "logging.ini")
import logging PchumLog = logging.getLogger('pchumLogger')
logging.basicConfig(level=logging.WARNING)
class ConsoleWindow(QtWidgets.QDialog): class ConsoleWindow(QtWidgets.QDialog):
@ -370,7 +374,7 @@ class ConsoleText(QtWidgets.QTextEdit):
parent = self.window() parent = self.window()
mwindow = parent.mainwindow mwindow = parent.mainwindow
systemColor = QtGui.QColor(mwindow.theme["convo/systemMsgColor"]) #systemColor = QtGui.QColor(mwindow.theme["convo/systemMsgColor"])
if mwindow.config.showTimeStamps(): if mwindow.config.showTimeStamps():
if mwindow.config.time12Format(): if mwindow.config.time12Format():

View file

@ -5,21 +5,15 @@ _datadir = ostools.getDataDir()
logging.config.fileConfig(_datadir + "logging.ini") logging.config.fileConfig(_datadir + "logging.ini")
PchumLog = logging.getLogger('pchumLogger') PchumLog = logging.getLogger('pchumLogger')
from string import Template from string import Template
import re
import platform
from time import strftime from time import strftime
from copy import copy
from datetime import datetime, timedelta from datetime import datetime, timedelta
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
from mood import Mood from dataobjs import PesterHistory
from dataobjs import PesterProfile, PesterHistory
from generic import PesterIcon
from parsetools import convertTags, lexMessage, mecmd, colorBegin, colorEnd, \ from parsetools import convertTags, lexMessage, mecmd, colorBegin, colorEnd, \
img2smiley, smiledict smiledict#, img2smiley
import parsetools import parsetools
import pnc.lexercon as lexercon
from pnc.dep.attrdict import AttrDict from pnc.dep.attrdict import AttrDict
class PesterTabWindow(QtWidgets.QFrame): class PesterTabWindow(QtWidgets.QFrame):
@ -95,12 +89,16 @@ class PesterTabWindow(QtWidgets.QFrame):
self.convos[handle].raiseChat() self.convos[handle].raiseChat()
else: else:
self.tabs.setCurrentIndex(tabi) self.tabs.setCurrentIndex(tabi)
"""
There are two instances of "convoHasFocus" for some reason?
This one seems to just get redefined.
def convoHasFocus(self, convo): def convoHasFocus(self, convo):
if ((self.hasFocus() or self.tabs.hasFocus()) and if ((self.hasFocus() or self.tabs.hasFocus()) and
self.tabs.tabText(self.tabs.currentIndex()) == convo.title()): self.tabs.tabText(self.tabs.currentIndex()) == convo.title()):
return True return True
"""
def isBot(self, *args, **kwargs): def isBot(self, *args, **kwargs):
return self.mainwindow.isBot(*args, **kwargs) return self.mainwindow.isBot(*args, **kwargs)
@ -492,7 +490,7 @@ class PesterText(QtWidgets.QTextEdit):
QtCore.Qt.Key_Up, QtCore.Qt.Key_Down) QtCore.Qt.Key_Up, QtCore.Qt.Key_Down)
parent = self.parent() parent = self.parent()
key = event.key() key = event.key()
keymods = event.modifiers() #keymods = event.modifiers()
if hasattr(parent, 'textInput') and key not in pass_to_super: if hasattr(parent, 'textInput') and key not in pass_to_super:
# TODO: Shift focus here on bare (no modifiers) alphanumerics. # TODO: Shift focus here on bare (no modifiers) alphanumerics.
parent.textInput.keyPressEvent(event) parent.textInput.keyPressEvent(event)
@ -745,11 +743,11 @@ class PesterConvo(QtWidgets.QFrame):
memoblink &= self.mainwindow.config.MBLINK memoblink &= self.mainwindow.config.MBLINK
pesterblink &= self.mainwindow.config.PBLINK pesterblink &= self.mainwindow.config.PBLINK
mutednots = self.notifications_muted mutednots = self.notifications_muted
mtsrc = self #mtsrc = self
if parent: if parent:
try: try:
mutednots = parent.notifications_muted mutednots = parent.notifications_muted
mtsrc = parent #mtsrc = parent
except: except:
pass pass
if not (self.hasFocus() or self.textArea.hasFocus() or if not (self.hasFocus() or self.textArea.hasFocus() or

View file

@ -4,13 +4,12 @@ import ostools
_datadir = ostools.getDataDir() _datadir = ostools.getDataDir()
logging.config.fileConfig(_datadir + "logging.ini") logging.config.fileConfig(_datadir + "logging.ini")
PchumLog = logging.getLogger('pchumLogger') PchumLog = logging.getLogger('pchumLogger')
from PyQt5 import QtCore, QtGui from PyQt5 import QtGui
from datetime import * from datetime import datetime
import re import re
import random import random
from mood import Mood from mood import Mood
from generic import PesterIcon
from parsetools import timeDifference, convertTags, lexMessage, parseRegexpFunctions from parsetools import timeDifference, convertTags, lexMessage, parseRegexpFunctions
from mispeller import mispeller from mispeller import mispeller
@ -113,7 +112,7 @@ class pesterQuirks(object):
self.quirklist.append(q) self.quirklist.append(q)
def apply(self, lexed, first=False, last=False): def apply(self, lexed, first=False, last=False):
prefix = [q for q in self.quirklist if q.type=='prefix'] prefix = [q for q in self.quirklist if q.type=='prefix']
suffix = [q for q in self.quirklist if q.type=='suffix'] #suffix = [q for q in self.quirklist if q.type=='suffix'] # <-- Seems unused
newlist = [] newlist = []
for (i, o) in enumerate(lexed): for (i, o) in enumerate(lexed):
@ -256,24 +255,43 @@ class PesterProfile(object):
return "<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo: <c=black>[%s]</c>." % \ return "<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo: <c=black>[%s]</c>." % \
(opchum.colorhtml(), opinit, self.colorhtml(), ", ".join(initials), str(reason)) (opchum.colorhtml(), opinit, self.colorhtml(), ", ".join(initials), str(reason))
else: else:
initials = timeGrammar.pcf+self.initials()+timeGrammar.number # Is timeGrammar defined? Not sure if this works as intented, added try except block to be safe.
if opchum.handle == reason: try:
return "<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo." % \ initials = timeGrammar.pcf+self.initials()+timeGrammar.number
(opchum.colorhtml(), opinit, self.colorhtml(), initials) if opchum.handle == reason:
else: return "<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo." % \
return "<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo: <c=black>[%s]</c>." % \ (opchum.colorhtml(), opinit, self.colorhtml(), initials)
(opchum.colorhtml(), opinit, self.colorhtml(), initials, str(reason)) else:
return "<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo: <c=black>[%s]</c>." % \
(opchum.colorhtml(), opinit, self.colorhtml(), initials, str(reason))
except:
PchumLog.exception('')
initials = self.initials()
if opchum.handle == reason:
return "<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo." % \
(opchum.colorhtml(), opinit, self.colorhtml(), initials)
else:
return "<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo: <c=black>[%s]</c>." % \
(opchum.colorhtml(), opinit, self.colorhtml(), initials, str(reason))
"""
# Currently unused, might be neat to use in the future?
def memopermabanmsg(self, opchum, opgrammar, syscolor, timeGrammar): def memopermabanmsg(self, opchum, opgrammar, syscolor, timeGrammar):
initials = timeGrammar.pcf+self.initials()+timeGrammar.number initials = (timeGrammar.pcf
opinit = opgrammar.pcf+opchum.initials()+opgrammar.number + self.initials()
+ timeGrammar.number)
opinit = (opgrammar.pcf
+ opchum.initials()
+ opgrammar.number)
return "<c=%s>%s</c> permabanned <c=%s>%s</c> from the memo." % \ return "<c=%s>%s</c> permabanned <c=%s>%s</c> from the memo." % \
(opchum.colorhtml(), opinit, self.colorhtml(), initials) (opchum.colorhtml(), opinit, self.colorhtml(), initials)
"""
def memojoinmsg(self, syscolor, td, timeGrammar, verb): def memojoinmsg(self, syscolor, td, timeGrammar, verb):
(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 = 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=%s><c=%s>%s %s [%s]</c> %s %s.</c>" % \
(syscolor.name(), self.colorhtml(), temporal, self.handle, (syscolor.name(), self.colorhtml(), timeGrammar.temporal, self.handle,
initials, timetext, verb) initials, timetext, verb)
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

View file

@ -1,4 +1,4 @@
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtGui, QtWidgets
from datetime import timedelta from datetime import timedelta
class mysteryTime(timedelta): class mysteryTime(timedelta):

4
irc.py
View file

@ -207,7 +207,7 @@ class PesterIRC(QtCore.QThread):
@QtCore.pyqtSlot() @QtCore.pyqtSlot()
def updateColor(self): def updateColor(self):
#PchumLog.debug("irc updateColor (outgoing)") #PchumLog.debug("irc updateColor (outgoing)")
me = self.mainwindow.profile() #me = self.mainwindow.profile()
for h in list(self.mainwindow.convos.keys()): for h in list(self.mainwindow.convos.keys()):
try: try:
helpers.msg(self.cli, h, "COLOR >%s" % (self.mainwindow.profile().colorcmd())) helpers.msg(self.cli, h, "COLOR >%s" % (self.mainwindow.profile().colorcmd()))
@ -449,7 +449,7 @@ class PesterHandler(DefaultCommandHandler):
def welcome(self, server, nick, msg): def welcome(self, server, nick, msg):
self.parent.setConnected() self.parent.setConnected()
mychumhandle = self.mainwindow.profile().handle #mychumhandle = self.mainwindow.profile().handle
mymood = self.mainwindow.profile().mood.value() mymood = self.mainwindow.profile().mood.value()
if not self.mainwindow.config.lowBandwidth(): if not self.mainwindow.config.lowBandwidth():
from time import sleep from time import sleep

View file

@ -1,4 +1,4 @@
import os, sys import os
import codecs import codecs
import re import re
import ostools import ostools

View file

@ -2,19 +2,17 @@ import logging
import logging.config import logging.config
import re import re
from string import Template from string import Template
from copy import copy from datetime import timedelta, datetime
from datetime import time, timedelta, datetime
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
import ostools import ostools
import parsetools import parsetools
from mood import Mood
from dataobjs import PesterProfile, PesterHistory from dataobjs import PesterProfile, PesterHistory
from generic import PesterIcon, RightClickList, mysteryTime from generic import PesterIcon, RightClickList, mysteryTime
from convo import PesterConvo, PesterInput, PesterText, PesterTabWindow from convo import PesterConvo, PesterInput, PesterText, PesterTabWindow
from parsetools import convertTags, addTimeInitial, timeProtocol, \ from parsetools import convertTags, timeProtocol, \
lexMessage, colorBegin, colorEnd, mecmd, smiledict lexMessage, colorBegin, mecmd, smiledict
from logviewer import PesterLogViewer from logviewer import PesterLogViewer
_datadir = ostools.getDataDir() _datadir = ostools.getDataDir()
@ -334,7 +332,12 @@ class MemoText(PesterText):
# new chum! time current # new chum! time current
newtime = timedelta(0) newtime = timedelta(0)
time = TimeTracker(newtime) time = TimeTracker(newtime)
parent.times[handle] = time
# 'handle' undefined?
try:
parent.times[handle] = time
except:
parent.times[chum.handle] = time
else: else:
time = parent.time time = parent.time
@ -1028,7 +1031,7 @@ class PesterMemo(PesterConvo):
else: else:
timed = timedelta.max timed = timedelta.max
except (OSError, ValueError) as e: except (OSError, ValueError) as e:
print(e) PchumLog.warning(str(e))
try: try:
if cmd == "i": if cmd == "i":
timed = timedelta(0) timed = timedelta(0)
@ -1070,8 +1073,8 @@ class PesterMemo(PesterConvo):
def namesUpdated(self, channel): def namesUpdated(self, channel):
c = str(channel) c = str(channel)
if c.lower() != self.channel.lower(): return if c.lower() != self.channel.lower(): return
# get namesdb # get namesdb (unused)
namesdb = self.mainwindow.namesdb #namesdb = self.mainwindow.namesdb
# reload names # reload names
self.userlist.clear() self.userlist.clear()
for n in self.mainwindow.namesdb[self.channel]: for n in self.mainwindow.namesdb[self.channel]:
@ -1098,7 +1101,7 @@ class PesterMemo(PesterConvo):
msgbox.setText("%s: Invites only!" % (c)) msgbox.setText("%s: Invites only!" % (c))
msgbox.setInformativeText("This channel is invite-only. You must get an invitation from someone on the inside before entering.") msgbox.setInformativeText("This channel is invite-only. You must get an invitation from someone on the inside before entering.")
msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok) msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
ret = msgbox.exec_() msgbox.exec_()
def quirkDisable(self, op, msg): def quirkDisable(self, op, msg):
chums = self.userlist.findItems(op, QtCore.Qt.MatchFlags(0)) chums = self.userlist.findItems(op, QtCore.Qt.MatchFlags(0))
@ -1124,12 +1127,12 @@ class PesterMemo(PesterConvo):
chum = PesterProfile(h) chum = PesterProfile(h)
if h == self.mainwindow.profile().handle: if h == self.mainwindow.profile().handle:
chum = self.mainwindow.profile() chum = self.mainwindow.profile()
ttracker = self.time #ttracker = self.time
curtime = self.time.getTime() #curtime = self.time.getTime()
elif h in self.times: #elif h in self.times:
ttracker = self.times[h] # ttracker = self.times[h]
else: #else:
ttracker = TimeTracker(timedelta(0)) # ttracker = TimeTracker(timedelta(0))
opchum = PesterProfile(op) opchum = PesterProfile(op)
PchumLog.debug("op = " + op) PchumLog.debug("op = " + op)
PchumLog.debug("opchum = " + opchum.handle) PchumLog.debug("opchum = " + opchum.handle)
@ -1167,7 +1170,7 @@ class PesterMemo(PesterConvo):
h = str(handle) h = str(handle)
c = str(channel) c = str(channel)
update = str(update) update = str(update)
PchumLog.debug("h=%s\nc=%s\nupdate=%s" % (h,c,update)) #PchumLog.debug("h=%s\nc=%s\nupdate=%s" % (h,c,update))
if update[0:4] == "kick": # yeah, i'm lazy. if update[0:4] == "kick": # yeah, i'm lazy.
l = update.split(":") l = update.split(":")
update = l[0] update = l[0]
@ -1514,10 +1517,11 @@ class PesterMemo(PesterConvo):
@QtCore.pyqtSlot() @QtCore.pyqtSlot()
def sendtime(self): def sendtime(self):
me = self.mainwindow.profile() #me = self.mainwindow.profile()
systemColor = QtGui.QColor(self.mainwindow.theme["memos/systemMsgColor"]) #systemColor = QtGui.QColor(self.mainwindow.theme["memos/systemMsgColor"])
time = txt2delta(self.timeinput.text()) time = txt2delta(self.timeinput.text())
present = self.time.addTime(time) #present = self.time.addTime(time)
self.time.addTime(time)
serverText = "PESTERCHUM:TIME>"+delta2txt(time, "server") serverText = "PESTERCHUM:TIME>"+delta2txt(time, "server")
self.messageSent.emit(serverText, self.title()) self.messageSent.emit(serverText, self.title())

View file

@ -4,10 +4,13 @@ from os import remove
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
import ostools import ostools
from generic import RightClickList, RightClickTree, MultiTextDialog, NoneSound import parsetools
from dataobjs import pesterQuirk, PesterProfile from generic import RightClickList, RightClickTree, MultiTextDialog
from dataobjs import pesterQuirk, PesterProfile, PesterHistory
from memos import TimeSlider, TimeInput from memos import TimeSlider, TimeInput
from version import _pcVersion from version import _pcVersion
from convo import PesterInput, PesterText
from parsetools import lexMessage
QString = str QString = str
@ -183,7 +186,7 @@ class PesterQuirkList(QtWidgets.QTreeWidget):
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.Ok) msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
ret = msgbox.exec_() msgbox.exec_()
self.addgroupdialog = None self.addgroupdialog = None
return return
found = self.findItems(gname, QtCore.Qt.MatchExactly) found = self.findItems(gname, QtCore.Qt.MatchExactly)
@ -191,7 +194,7 @@ class PesterQuirkList(QtWidgets.QTreeWidget):
msgbox = QtWidgets.QMessageBox() msgbox = QtWidgets.QMessageBox()
msgbox.setInformativeText("THIS QUIRK GROUP ALREADY EXISTS") msgbox.setInformativeText("THIS QUIRK GROUP ALREADY EXISTS")
msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok) msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
ret = msgbox.exec_() msgbox.exec_()
return return
child_1 = QtWidgets.QTreeWidgetItem([gname]) child_1 = QtWidgets.QTreeWidgetItem([gname])
self.addTopLevelItem(child_1) self.addTopLevelItem(child_1)
@ -222,11 +225,6 @@ class PesterQuirkList(QtWidgets.QTreeWidget):
for j in range(self.topLevelItem(index).childCount()): for j in range(self.topLevelItem(index).childCount()):
self.topLevelItem(index).child(j).setCheckState(0, state) self.topLevelItem(index).child(j).setCheckState(0, state)
from copy import copy
from convo import PesterInput, PesterText
from parsetools import convertTags, lexMessage, mecmd, colorBegin, colorEnd, img2smiley, smiledict
import parsetools
from dataobjs import pesterQuirks, PesterHistory
class QuirkTesterWindow(QtWidgets.QDialog): class QuirkTesterWindow(QtWidgets.QDialog):
def __init__(self, parent): def __init__(self, parent):
QtWidgets.QDialog.__init__(self, parent) QtWidgets.QDialog.__init__(self, parent)
@ -650,7 +648,7 @@ class PesterChooseQuirks(QtWidgets.QDialog):
def editSelected(self): def editSelected(self):
q = self.quirkList.currentQuirk() q = self.quirkList.currentQuirk()
if not q: return if not q: return
quirk = q.quirk #quirk = q.quirk
self.addQuirkDialog(q) self.addQuirkDialog(q)
@QtCore.pyqtSlot() @QtCore.pyqtSlot()

View file

@ -1,4 +1,4 @@
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtWidgets
from generic import PesterIcon from generic import PesterIcon

View file

@ -2,7 +2,6 @@ import os
import sys import sys
import platform import platform
from PyQt5.QtGui import QDesktopServices
from PyQt5.QtCore import QStandardPaths from PyQt5.QtCore import QStandardPaths
def isOSX(): def isOSX():

View file

@ -24,15 +24,13 @@ PchumLog = logging.getLogger('pchumLogger')
import logging import logging
import socket import socket
import sys
import time import time
import os
import traceback import traceback
import ssl import ssl
import json import json
import select import select
from oyoyo.parse import * from oyoyo.parse import parse_raw_irc_command
from oyoyo import helpers from oyoyo import helpers
from oyoyo.cmdhandler import CommandError from oyoyo.cmdhandler import CommandError

View file

@ -23,8 +23,6 @@ PchumLog = logging.getLogger('pchumLogger')
import inspect import inspect
import logging import logging
import sys
import traceback
from oyoyo import helpers from oyoyo import helpers
from oyoyo.parse import parse_nick from oyoyo.parse import parse_nick

View file

@ -17,15 +17,14 @@
import logging import logging
import logging.config import logging.config
import ostools import ostools
from oyoyo.ircevents import numeric_events
_datadir = ostools.getDataDir() _datadir = ostools.getDataDir()
logging.config.fileConfig(_datadir + "logging.ini") logging.config.fileConfig(_datadir + "logging.ini")
PchumLog = logging.getLogger('pchumLogger') PchumLog = logging.getLogger('pchumLogger')
import sys
from oyoyo.ircevents import *
def parse_raw_irc_command(element): def parse_raw_irc_command(element):
""" """
This function parses a raw irc command and returns a tuple This function parses a raw irc command and returns a tuple

View file

@ -1,6 +1,3 @@
import sys
from .helpers import msg
# NickServ basic functions # NickServ basic functions
_nickservfuncs = ( _nickservfuncs = (
'register', 'register',

View file

@ -1,12 +1,11 @@
import logging import logging
import logging.config import logging.config
import re import re
import random
import collections import collections
from copy import copy from copy import copy
from datetime import timedelta from datetime import timedelta
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtGui, QtWidgets
import dataobjs import dataobjs
import ostools import ostools
@ -293,7 +292,7 @@ def convertTags(lexed, format="html"):
if type(lexed) in [str, str]: if type(lexed) in [str, str]:
lexed = lexMessage(lexed) lexed = lexMessage(lexed)
escaped = "" escaped = ""
firststr = True #firststr = True
for (i, o) in enumerate(lexed): for (i, o) in enumerate(lexed):
if type(o) in [str, str]: if type(o) in [str, str]:
if format == "html": if format == "html":
@ -380,7 +379,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
curlen = 0 curlen = 0
# Maximum number of characters *to* use. # Maximum number of characters *to* use.
if not maxlen: if not maxlen:
maxlen = __max_msg_len(None, None, ctx.mainwindow.profile().handle, ctx.mainwindow.irc.cli.real_name) maxlen = _max_msg_len(None, None, ctx.mainwindow.profile().handle, ctx.mainwindow.irc.cli.real_name)
elif maxlen < 0: elif maxlen < 0:
# Subtract the (negative) length, giving us less leeway in this # Subtract the (negative) length, giving us less leeway in this
# function. # function.
@ -394,7 +393,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
tags that will be needed.""" tags that will be needed."""
return maxlen - curlen - (len(open_ctags) * 4) return maxlen - curlen - (len(open_ctags) * 4)
safekeeping = lexed[:] #safekeeping = lexed[:]
lexed = collections.deque(lexed) lexed = collections.deque(lexed)
rounds = 0 rounds = 0
# NOTE: This entire mess is due for a rewrite. I'll start splitting it into # NOTE: This entire mess is due for a rewrite. I'll start splitting it into

View file

@ -27,11 +27,10 @@ if ('--help' in sys.argv[1:]) or ('-h' in sys.argv[1:]):
sys.exit() sys.exit()
import logging import logging
from datetime import * from datetime import timedelta
import random import random
import re import re
from time import time from time import time
import queue#, threading
try: try:
import json import json
except: except:
@ -80,8 +79,8 @@ if not ((major > 5) or (major == 5 and minor >= 0)):
logging.critical("You currently have version " + vnum + ". Please upgrade Qt.") logging.critical("You currently have version " + vnum + ". Please upgrade Qt.")
exit() exit()
from version import _pcVersion from profile import userConfig, userProfile, pesterTheme, PesterLog, \
PesterProfileDB
import ostools import ostools
# Placed here before importing the rest of pesterchum, since bits of it need # Placed here before importing the rest of pesterchum, since bits of it need
# OSX's data directory and it doesn't hurt to have everything set up before # OSX's data directory and it doesn't hurt to have everything set up before
@ -208,10 +207,10 @@ from menus import PesterChooseQuirks, PesterChooseTheme, \
LoadingScreen, AboutPesterchum, UpdatePesterchum, AddChumDialog LoadingScreen, AboutPesterchum, UpdatePesterchum, AddChumDialog
from mood import Mood, PesterMoodAction, PesterMoodHandler, PesterMoodButton from mood import Mood, PesterMoodAction, PesterMoodHandler, PesterMoodButton
from dataobjs import PesterProfile, pesterQuirk, pesterQuirks from dataobjs import PesterProfile, pesterQuirk, pesterQuirks
from generic import PesterIcon, RightClickList, RightClickTree, \ from generic import PesterIcon, RightClickTree, \
MultiTextDialog, PesterList, CaseInsensitiveDict, MovingWindow, \ PesterList, CaseInsensitiveDict, MovingWindow, \
NoneSound, WMButton NoneSound, WMButton
from convo import PesterTabWindow, PesterText, PesterInput, PesterConvo from convo import PesterTabWindow, PesterConvo
from parsetools import convertTags, addTimeInitial, themeChecker, ThemeException from parsetools import convertTags, addTimeInitial, themeChecker, ThemeException
from memos import PesterMemo, MemoTabWindow, TimeTracker from memos import PesterMemo, MemoTabWindow, TimeTracker
from irc import PesterIRC from irc import PesterIRC
@ -225,7 +224,6 @@ import nickservmsgs
from toast import PesterToastMachine, PesterToast from toast import PesterToastMachine, PesterToast
import pytwmn import pytwmn
from profile import *
#canon_handles = ["apocalypseArisen", "arsenicCatnip", "arachnidsGrip", "adiosToreador", \ #canon_handles = ["apocalypseArisen", "arsenicCatnip", "arachnidsGrip", "adiosToreador", \
# "caligulasAquarium", "cuttlefishCuller", "carcinoGeneticist", "centaursTesticle", \ # "caligulasAquarium", "cuttlefishCuller", "carcinoGeneticist", "centaursTesticle", \
@ -439,7 +437,8 @@ class chumArea(RightClickTree):
elif text in self.groups: elif text in self.groups:
return self.groupMenu return self.groupMenu
else: else:
currenthandle = self.currentItem().chum.handle #currenthandle = self.currentItem().chum.handle
#if currenthandle in canon_handles: #if currenthandle in canon_handles:
# return self.canonMenu # return self.canonMenu
#else: #else:
@ -944,7 +943,7 @@ class chumArea(RightClickTree):
msgbox.setStyleSheet("QMessageBox{" + self.mainwindow.theme["main/defaultwindow/style"] + "}") msgbox.setStyleSheet("QMessageBox{" + self.mainwindow.theme["main/defaultwindow/style"] + "}")
msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME") msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME")
msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok) msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
ret = msgbox.exec_() msgbox.exec_()
self.addgroupdialog = None self.addgroupdialog = None
return return
currentGroup = self.currentItem() currentGroup = self.currentItem()
@ -1488,6 +1487,9 @@ class PesterWindow(MovingWindow):
self.updatemenu.raise_() self.updatemenu.raise_()
self.updatemenu.activateWindow() self.updatemenu.activateWindow()
"""
Depreciated
@QtCore.pyqtSlot() @QtCore.pyqtSlot()
def updatePC(self): def updatePC(self):
version.updateDownload(str(self.updatemenu.url)) version.updateDownload(str(self.updatemenu.url))
@ -1495,6 +1497,7 @@ class PesterWindow(MovingWindow):
@QtCore.pyqtSlot() @QtCore.pyqtSlot()
def noUpdatePC(self): def noUpdatePC(self):
self.updatemenu = None self.updatemenu = None
"""
@QtCore.pyqtSlot() @QtCore.pyqtSlot()
def checkPing(self): def checkPing(self):
@ -2216,7 +2219,7 @@ class PesterWindow(MovingWindow):
msgbox.setText("This chumhandle has been registered; you may not use it.") msgbox.setText("This chumhandle has been registered; you may not use it.")
msgbox.setInformativeText("Your handle is now being changed to %s." % (changedto)) msgbox.setInformativeText("Your handle is now being changed to %s." % (changedto))
msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok) msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
ret = msgbox.exec_() msgbox.exec_()
elif h == self.randhandler.randNick: elif h == self.randhandler.randNick:
self.randhandler.incoming(msg) self.randhandler.incoming(msg)
elif h in self.convos: elif h in self.convos:
@ -2252,9 +2255,10 @@ class PesterWindow(MovingWindow):
@QtCore.pyqtSlot(QString, QString) @QtCore.pyqtSlot(QString, QString)
def cannotSendToChan(self, channel, msg): def cannotSendToChan(self, channel, msg):
self.deliverMemo(channel, "ChanServ", msg) self.deliverMemo(channel, "ChanServ", msg)
@QtCore.pyqtSlot(QString, QString) # Unused and redefined.
def modesUpdated(self, channel, modes): #@QtCore.pyqtSlot(QString, QString)
self.modesUpdated.emit(channel, modes) #def modesUpdated(self, channel, modes):
# self.modesUpdated.emit(channel, modes)
@QtCore.pyqtSlot(QString, QString, QString) @QtCore.pyqtSlot(QString, QString, QString)
def timeCommand(self, chan, handle, command): def timeCommand(self, chan, handle, command):
(c, h, cmd) = (str(chan), str(handle), str(command)) (c, h, cmd) = (str(chan), str(handle), str(command))
@ -2280,7 +2284,7 @@ class PesterWindow(MovingWindow):
def userPresentUpdate(self, handle, channel, update): def userPresentUpdate(self, handle, channel, update):
c = str(channel) c = str(channel)
n = str(handle) n = str(handle)
PchumLog.debug("c=%s\nn=%s\nupdate=%s\n" % (c, n, update)) #PchumLog.debug("c=%s\nn=%s\nupdate=%s\n" % (c, n, update))
if update == "nick": if update == "nick":
l = n.split(":") l = n.split(":")
oldnick = l[0] oldnick = l[0]
@ -2320,7 +2324,7 @@ class PesterWindow(MovingWindow):
except KeyError: except KeyError:
self.namesdb[c] = [n] self.namesdb[c] = [n]
PchumLog.debug("handle=%s\nchannel=%s\nupdate=%s\n" % (handle, channel, update)) #PchumLog.debug("handle=%s\nchannel=%s\nupdate=%s\n" % (handle, channel, update))
self.userPresentSignal.emit(handle, channel, update) self.userPresentSignal.emit(handle, channel, update)
@QtCore.pyqtSlot() @QtCore.pyqtSlot()
@ -2500,7 +2504,7 @@ class PesterWindow(MovingWindow):
replace = replace_mo.group(1) replace = replace_mo.group(1)
try: try:
re.compile(regexp_state) re.compile(regexp_state)
except re.error as e: except re.error:
continue continue
newquirk = pesterQuirk({"type": "regexp", newquirk = pesterQuirk({"type": "regexp",
"from": regexp_state, "from": regexp_state,
@ -2665,7 +2669,7 @@ class PesterWindow(MovingWindow):
msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME") msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME")
msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok) msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
msgbox.setStyleSheet("QMessageBox{" + self.theme["main/defaultwindow/style"] + "}")#Style :) (memos/style or convo/style works :3 ) msgbox.setStyleSheet("QMessageBox{" + self.theme["main/defaultwindow/style"] + "}")#Style :) (memos/style or convo/style works :3 )
ret = msgbox.exec_() msgbox.exec_()
self.addgroupdialog = None self.addgroupdialog = None
return return
self.addGroup(gname) self.addGroup(gname)
@ -2998,13 +3002,21 @@ class PesterWindow(MovingWindow):
msgBox.setWindowTitle(":(") msgBox.setWindowTitle(":(")
msgBox.setTextFormat(QtCore.Qt.RichText) # Clickable html links msgBox.setTextFormat(QtCore.Qt.RichText) # Clickable html links
self.filename = _datadir+"pesterchum.js" self.filename = _datadir+"pesterchum.js"
msgBox.setText("<html><h3>Failed to load: " + ("<a href='%s'>%s/%s.js</a>" % (self.profiledir, self.profiledir, user)) + \ try:
"<br><br> Try to check for syntax errors if the file exists." + \ msgBox.setText("<html><h3>Failed to load: " + ("<a href='%s'>%s/%s.js</a>" % (self.profiledir, self.profiledir, user)) + \
"<br><br>If you got this message at launch you may want to change your default profile." + \ "<br><br> Try to check for syntax errors if the file exists." + \
"<br><br>" + str(e) + "<\h3><\html>") "<br><br>If you got this message at launch you may want to change your default profile." + \
#"\" if pesterchum acts oddly you might want to try backing up and then deleting \"" + \ "<br><br>" + str(e) + "<\h3><\html>")
#_datadir+"pesterchum.js" + \ #"\" if pesterchum acts oddly you might want to try backing up and then deleting \"" + \
#"\"") #_datadir+"pesterchum.js" + \
#"\"")
except:
# More generic error for if not all variables are available.
msgBox.setText("Unspecified profile error." + \
"<br><br> Try to check for syntax errors if the file exists." + \
"<br><br>If you got this message at launch you may want to change your default profile." + \
"<br><br>" + str(e) + "<\h3><\html>")
PchumLog.critical(e) PchumLog.critical(e)
msgBox.exec_() msgBox.exec_()
return return
@ -3180,7 +3192,7 @@ class PesterWindow(MovingWindow):
msgbox.setWindowIcon(PesterIcon(self.theme["main/icon"])) msgbox.setWindowIcon(PesterIcon(self.theme["main/icon"]))
msgbox.setInformativeText("Incorrect format :(") msgbox.setInformativeText("Incorrect format :(")
msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok) msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
ret = msgbox.exec_() msgbox.exec_()
self.chooseServer() self.chooseServer()
return 1 return 1
@ -3215,7 +3227,7 @@ class PesterWindow(MovingWindow):
+ "Please tell me if this error occurs :'3") + "Please tell me if this error occurs :'3")
msgbox.addButton(QtWidgets.QPushButton("Yes"), QtWidgets.QMessageBox.YesRole) msgbox.addButton(QtWidgets.QPushButton("Yes"), QtWidgets.QMessageBox.YesRole)
msgbox.addButton(QtWidgets.QPushButton("No"), QtWidgets.QMessageBox.NoRole) msgbox.addButton(QtWidgets.QPushButton("No"), QtWidgets.QMessageBox.NoRole)
ret = msgbox.exec_() msgbox.exec_()
reply = msgbox.buttonRole(msgbox.clickedButton()) reply = msgbox.buttonRole(msgbox.clickedButton())
if (reply==QtWidgets.QMessageBox.YesRole): if (reply==QtWidgets.QMessageBox.YesRole):

View file

@ -534,7 +534,13 @@ class RelayChat(Lexer):
# Go down the stack until we have a line color TO end # Go down the stack until we have a line color TO end
while cstack: while cstack:
# Add a </c> since we'll need one anyway # Add a </c> since we'll need one anyway
closecolor()
# Is closecolor accessible here?
try:
closecolor()
except Exception as e:
print(e)
##if isinstance(color, LineColor): ##if isinstance(color, LineColor):
if isinstance(cstack.pop(), LineColor): if isinstance(cstack.pop(), LineColor):
# We found what we wanted, and the color # We found what we wanted, and the color
@ -552,7 +558,11 @@ class RelayChat(Lexer):
# It's not a line color, so remove it # It's not a line color, so remove it
del cstack[-1] del cstack[-1]
# Add a </c> # Add a </c>
closecolor() # Is closecolor accessible here?
try:
closecolor()
except Exception as e:
print(e)
else: else:
# It's a line color, so stop searching. # It's a line color, so stop searching.
# Using break here prevents the 'else' # Using break here prevents the 'else'

View file

@ -1,24 +1,22 @@
import logging
import logging.config
import os import os
import sys import sys
import json import json
import re import re
import codecs import codecs
import platform
import datetime
import shutil import shutil
import zipfile import zipfile
import logging
import logging.config
from string import Template from string import Template
from datetime import * from datetime import datetime
from time import strftime, time from time import strftime
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
import ostools import ostools
from mood import Mood from mood import Mood
from dataobjs import PesterProfile, pesterQuirk, pesterQuirks from dataobjs import PesterProfile, pesterQuirks
from parsetools import convertTags, addTimeInitial, themeChecker, ThemeException from parsetools import convertTags
_datadir = ostools.getDataDir() _datadir = ostools.getDataDir()
logging.config.fileConfig(_datadir + "logging.ini") logging.config.fileConfig(_datadir + "logging.ini")
@ -35,36 +33,36 @@ class PesterLog(object):
def log(self, handle, msg): def log(self, handle, msg):
if self.parent.config.time12Format(): if self.parent.config.time12Format():
time = strftime("[%I:%M") log_time = strftime("[%I:%M")
else: else:
time = strftime("[%H:%M") log_time = strftime("[%H:%M")
if self.parent.config.showSeconds(): if self.parent.config.showSeconds():
time += strftime(":%S] ") log_time += strftime(":%S] ")
else: else:
time += "] " log_time += "] "
if handle[0] == '#': if handle[0] == '#':
if not self.parent.config.logMemos() & self.parent.config.LOG: return if not self.parent.config.logMemos() & self.parent.config.LOG: return
if not self.parent.config.logMemos() & self.parent.config.STAMP: if not self.parent.config.logMemos() & self.parent.config.STAMP:
time = "" log_time = ""
else: else:
if not self.parent.config.logPesters() & self.parent.config.LOG: return if not self.parent.config.logPesters() & self.parent.config.LOG: return
if not self.parent.config.logPesters() & self.parent.config.STAMP: if not self.parent.config.logPesters() & self.parent.config.STAMP:
time = "" log_time = ""
if self.parent.isBot(handle): return if self.parent.isBot(handle): return
#watch out for illegal characters #watch out for illegal characters
handle = re.sub(r'[<>:"/\\|?*]', "_", handle) handle = re.sub(r'[<>:"/\\|?*]', "_", handle)
bbcodemsg = time + convertTags(msg, "bbcode") bbcodemsg = log_time + convertTags(msg, "bbcode")
html = time + convertTags(msg, "html")+"<br />" html = log_time + convertTags(msg, "html")+"<br />"
msg = time +convertTags(msg, "text") msg = log_time +convertTags(msg, "text")
modes = {"bbcode": bbcodemsg, "html": html, "text": msg} modes = {"bbcode": bbcodemsg, "html": html, "text": msg}
if handle not in self.convos: if handle not in self.convos:
time = datetime.now().strftime("%Y-%m-%d.%H.%M") log_time = datetime.now().strftime("%Y-%m-%d.%H.%M")
self.convos[handle] = {} self.convos[handle] = {}
for (format, t) in modes.items(): for (format, t) in modes.items():
if not os.path.exists("%s/%s/%s/%s" % (self.logpath, self.handle, handle, format)): if not os.path.exists("%s/%s/%s/%s" % (self.logpath, self.handle, handle, format)):
os.makedirs("%s/%s/%s/%s" % (self.logpath, self.handle, handle, format)) os.makedirs("%s/%s/%s/%s" % (self.logpath, self.handle, handle, format))
try: try:
fp = codecs.open("%s/%s/%s/%s/%s.%s.txt" % (self.logpath, self.handle, handle, format, handle, time), encoding='utf-8', mode='a') fp = codecs.open("%s/%s/%s/%s/%s.%s.txt" % (self.logpath, self.handle, handle, format, handle, log_time), encoding='utf-8', mode='a')
except (IOError, OSError) as e: except (IOError, OSError) 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)
@ -135,7 +133,7 @@ class userConfig(object):
msgbox.setInformativeText("<html><h3>Failed to load pesterchum.js, this might require manual intervention.<br><br>\ msgbox.setInformativeText("<html><h3>Failed to load pesterchum.js, this might require manual intervention.<br><br>\
Consider overriding: <a href='%s'>%s</a> <br>\ Consider overriding: <a href='%s'>%s</a> <br>\
with a backup from: <a href='%s'>%s</a></h3></html>" % (_datadir, self.filename, os.path.join(_datadir, "backup"), os.path.join(_datadir, "backup"))) with a backup from: <a href='%s'>%s</a></h3></html>" % (_datadir, self.filename, os.path.join(_datadir, "backup"), os.path.join(_datadir, "backup")))
ret = msgbox.exec_() msgbox.exec_()
sys.exit() sys.exit()
# Trying to fix: # Trying to fix:
@ -469,7 +467,7 @@ with a backup from: <a href='%s'>%s</a></h3></html>" % (_datadir, self.filename,
for x in profs: for x in profs:
c_profile = os.path.join(profileloc, x+".js") c_profile = os.path.join(profileloc, x+".js")
try: try:
js_profile = json.load(open(c_profile)) json.load(open(c_profile))
PchumLog.info(x + ": Pass.") PchumLog.info(x + ": Pass.")
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
PchumLog.warning(x + ": Fail.") PchumLog.warning(x + ": Fail.")

View file

@ -1,7 +1,8 @@
import PyInstaller.__main__ import os
import sys import sys
import shutil import shutil
import os
import PyInstaller.__main__
if sys.version_info < (3, 0, 0): if sys.version_info < (3, 0, 0):
sys.exit("Python versions lower than 3 are not supported.") sys.exit("Python versions lower than 3 are not supported.")
@ -58,7 +59,7 @@ Some of the include files are specific to my instalation, so you might have to e
if crt_path == '': if crt_path == '':
crt_path = "C:\\Program Files (x86)\\Windows Kits\\10\\Redist\\10.0.19041.0\\ucrt\\DLLs\\x86" # Default directory. crt_path = "C:\\Program Files (x86)\\Windows Kits\\10\\Redist\\10.0.19041.0\\ucrt\\DLLs\\x86" # Default directory.
print("crt_path = " + crt_path) print("crt_path = " + crt_path)
except KeyboardInterrupt as e: except KeyboardInterrupt:
sys.exit("KeyboardInterrupt") sys.exit("KeyboardInterrupt")
exclude_modules = ['collections.sys', exclude_modules = ['collections.sys',

View file

@ -1,11 +1,8 @@
import os
import sys
import re
import logging import logging
import logging.config import logging.config
import importlib.util import importlib.util
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtWidgets
import ostools import ostools
from quirks import ScriptQuirks from quirks import ScriptQuirks

View file

@ -1,11 +1,7 @@
import os import os
import sys
import re
import logging import logging
import logging.config import logging.config
from PyQt5 import QtCore, QtGui, QtWidgets
import ostools import ostools
_datadir = ostools.getDataDir() _datadir = ostools.getDataDir()

View file

@ -1,7 +1,7 @@
import logging import logging
import logging.config import logging.config
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtWidgets
import ostools import ostools
@ -67,7 +67,6 @@ class RandomHandler(QtCore.QObject):
pass pass
elif code == "!": elif code == "!":
if l[1] == "x": if l[1] == "x":
from PyQt5 import QtGui, QtWidgets
msgbox = QtWidgets.QMessageBox() msgbox = QtWidgets.QMessageBox()
msgbox.setText("Unable to fetch you a random encounter!") msgbox.setText("Unable to fetch you a random encounter!")
msgbox.setInformativeText("Try again later :(") msgbox.setInformativeText("Try again later :(")

View file

@ -1,7 +1,8 @@
# Windows-only cx_freeze setup file # Windows-only cx_freeze setup file, macOS may work but I've not tested it.
from cx_Freeze import *
import sys import sys
from cx_Freeze import setup, Executable
from version import buildVersion from version import buildVersion
if sys.version_info < (3, 0, 0): if sys.version_info < (3, 0, 0):

View file

@ -1,5 +1,5 @@
import os import os
import time #import time
import inspect import inspect
import logging import logging
import logging.config import logging.config