每当我启动某个脚本时,Python程序就停止响应

2024-04-18 20:47:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创造一个抽搐.tv聊天机器人,每当我点击'文件'菜单下的'开始',运行'startSpenbot',我得到'这个程序已经停止响应'错误。你知道吗

我已经上传了完整的源代码到GitHub,但是我已经删除了文件的条目密码.txt'. 你可以在这里找到-https://github.com/spencermehta/spenbot/tree/v0.0.8

下面是“startSpenbot”函数

def startSpenbot(self):
        fileBotOwner = open('botOwner.txt', 'r')
        fileNick = open('nick.txt', 'r')
        fileChannel = open('channel.txt', 'r')
        filePassword = open('password.txt', 'r')
        fileCommands = open('commands.txt', 'r')

        for line in fileBotOwner:
            botOwner = str(line)
        for line in fileNick:
            nick = str(line)
        for line in fileChannel:
            channel = str(line)
        for line in filePassword:
            password = str(line)

        lines = 0
        for line in fileCommands:
            lines += 1
            line = line.split('~')
            if lines == 1:
                command1 = line[0]
                command1R = line[1]


        fileBotOwner.close()
        fileNick.close()
        fileChannel.close()
        filePassword.close()
        fileCommands.close()

        server = 'irc.twitch.tv'
        keyword = ''
        rafflelist = []
        raffleshowjoin = 'hide'

        irc = socket.socket()
        irc.connect((server, 6667))

        irc.send(bytes("PASS " + password + "\r\n", "utf-8"))
        irc.send(bytes("USER " + nick + " 0 * :" + botOwner + "\r\n", "utf-8"))
        irc.send(bytes("NICK " + nick + "\r\n", "utf-8"))
        irc.send(bytes("JOIN " + channel + "\r\n", "utf-8"))

        def message(msg): #function for sending messages to the IRC chat
            global queue
            queue += 1
            if queue < 20:
                irc.send(bytes("PRIVMSG " + channel + " :" + msg + "\r\n", "utf-8"))
            else:
                print("Spamming. Message not sent")

        def queuetimer():
            global queue
            queue = 0
            threading.Timer(30,queuetimer).start()
        queuetimer()
        exceptions = 0

        while True:
            twitchdata = irc.recv(1204)
            data = twitchdata.decode().split(":")[1]
            twitchuser = data.split("!")[0]
            twitchmsg = twitchdata.decode().split(":")[2]

            if twitchdata.find(bytes("PING", "utf-8")) != -1:
                irc.send(twitchdata.replace("PING", "PONG")) #responds to PINGS from the server

            if twitchmsg.lower() == command1 + "\r\n":
                message(command1R)

            if "!raffle" in twitchmsg.lower() and twitchuser == botOwner:
                rafflelist = []
                twitchmsg = twitchmsg.split(" ")
                try:
                    keyword = twitchmsg[1]
                    message("Raffle started with keyword " + keyword + ". Defaulting to not showing raffle join messages")
                except:
                    message("You didn't specify a keyword for the raffle")

            if "!draw" in twitchmsg and twitchuser == botOwner:
                message("Drawing winner...")
                message(random.choice(rafflelist) + " has won the raffle!")

            if twitchmsg == keyword and twitchuser not in rafflelist:
                rafflelist.append(twitchuser)

但是,当程序在命令行中运行时,这段代码运行良好,并且在我使用PyQT时只会崩溃

更新:程序在崩溃后仍然可以正常运行-只有GUI崩溃。以下是代码的其余部分:

import socket #imports module allowing connection to IRC
import threading #imports module allowing timing functions
from PyQt4 import QtGui, QtCore
import sys
import random

class Spenbot(QtGui.QMainWindow):

    def __init__(self):
        super(Spenbot, self).__init__()

        self.spenbotUI()


    def spenbotUI(self):

        exitAction = QtGui.QAction('Exit', self)
        exitAction.setStatusTip('Exit Application')
        exitAction.triggered.connect(self.close)

        configureAction = QtGui.QAction('Configure', self)
        configureAction.setStatusTip('Configure login data and commands')
        configureAction.triggered.connect(self.spenbotConfigure)

        startAction = QtGui.QAction('Start', self)
        startAction.setStatusTip('Start Spenbot')
        startAction.triggered.connect(self.startSpenbot)

        self.statusBar()

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)
        fileMenu.addAction(startAction)
        settingsMenu = menubar.addMenu('&Settings')
        settingsMenu.addAction(configureAction)

        self.setGeometry(300, 300, 400, 300)
        self.setWindowTitle('Spenbot')
        self.setWindowIcon(QtGui.QIcon('logo.png'))
        self.show()


    def spenbotConfigure(self):
        self.configWidget = configWidget()
        self.configWidget.show()

    def closeEvent(self, event):

        reply = QtGui.QMessageBox.question(self, 'Spenbot', 'Are you sure want to quit?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def startSpenbot(self):
        fileBotOwner = open('botOwner.txt', 'r')
        fileNick = open('nick.txt', 'r')
        fileChannel = open('channel.txt', 'r')
        filePassword = open('password.txt', 'r')
        fileCommands = open('commands.txt', 'r')

        for line in fileBotOwner:
            botOwner = str(line)
        for line in fileNick:
            nick = str(line)
        for line in fileChannel:
            channel = str(line)
        for line in filePassword:
            password = str(line)

        lines = 0
        for line in fileCommands:
            lines += 1
            line = line.split('~')
            if lines == 1:
                command1 = line[0]
                command1R = line[1]


        fileBotOwner.close()
        fileNick.close()
        fileChannel.close()
        filePassword.close()
        fileCommands.close()

        print('Files opened and variables saved')
        server = 'irc.twitch.tv'
        keyword = ''
        rafflelist = []
        raffleshowjoin = 'hide'

        irc = socket.socket()
        irc.connect((server, 6667))

        irc.send(bytes("PASS " + password + "\r\n", "utf-8"))
        irc.send(bytes("USER " + nick + " 0 * :" + botOwner + "\r\n", "utf-8"))
        irc.send(bytes("NICK " + nick + "\r\n", "utf-8"))
        irc.send(bytes("JOIN " + channel + "\r\n", "utf-8"))

        print('Connected to irc')

        def message(msg): #function for sending messages to the IRC chat
            global queue
            queue += 1
            if queue < 20:
                irc.send(bytes("PRIVMSG " + channel + " :" + msg + "\r\n", "utf-8"))
            else:
                print("Spamming. Message not sent")

        def queuetimer():
            global queue
            queue = 0
            threading.Timer(30,queuetimer).start()
        queuetimer()
        exceptions = 0

        print('Queuetimer set')

        while True:
            twitchdata = irc.recv(1204)
            data = twitchdata.decode().split(":")[1]
            twitchuser = data.split("!")[0]
            twitchmsg = twitchdata.decode().split(":")[2]

            if twitchdata.find(bytes("PING", "utf-8")) != -1:
                irc.send(twitchdata.replace("PING", "PONG")) #responds to PINGS from the server

            print('ping pong')
            if twitchmsg.lower() == command1 + "\r\n":
                message(command1R)

            print('command1')

            if "!raffle" in twitchmsg.lower() and twitchuser == botOwner:
                rafflelist = []
                twitchmsg = twitchmsg.split(" ")
                try:
                    keyword = twitchmsg[1]
                    message("Raffle started with keyword " + keyword + ". Defaulting to not showing raffle join messages")
                except:
                    message("You didn't specify a keyword for the raffle")

            if "!draw" in twitchmsg and twitchuser == botOwner:
                message("Drawing winner...")
                message(random.choice(rafflelist) + " has won the raffle!")

            if twitchmsg == keyword and twitchuser not in rafflelist:
                rafflelist.append(twitchuser)

            print('end')

class configWidget(QtGui.QWidget):

    def __init__(self):
        super(configWidget, self).__init__()

        self.configUI()


    def configUI(self):

        fileBotOwner = open('botOwner.txt', 'r')
        fileNick = open('nick.txt', 'r')
        fileChannel = open('channel.txt', 'r')
        filePassword = open('password.txt', 'r')
        fileCommands = open('commands.txt', 'r')

        for line in fileBotOwner:
            botOwner = str(line)
        for line in fileNick:
            nick = str(line)
        for line in fileChannel:
            channel = line[1:]
        for line in filePassword:
            password = str(line)

        lines = 0
        for line in fileCommands:
            lines += 1
            line = line.split('~')
            if lines == 1:
                command1 = line[0]
                command1R = line[1]

        fileBotOwner.close()
        fileNick.close()
        fileChannel.close()
        filePassword.close()
        fileCommands.close()

        inputBotOwner = QtGui.QLabel('Your Twitch Username')
        inputNick = QtGui.QLabel('Your bot\'s Twitch Username')
        inputChannel = QtGui.QLabel('Channel you want bot to join')
        inputPassword = QtGui.QLabel('Enter the bot account\'s OAuth Code (Find it at twitchapps.com/tmi)')
        inputCommand1 = QtGui.QLabel('Command 1 keyword')
        inputCommand1R = QtGui.QLabel('Command 1 response')

        try:
            self.botOwnerEdit = QtGui.QLineEdit(botOwner)
        except:
            self.botOwnerEdit = QtGui.QLineEdit()
        try:
            self.nickEdit = QtGui.QLineEdit(nick)
        except:
            self.nickEdit = QtGui.QLineEdit()
        try:
            self.channelEdit = QtGui.QLineEdit(channel)
        except:
            self.channelEdit = QtGui.QLineEdit()
        try:
            self.passwordEdit = QtGui.QLineEdit(password)
        except:
            self.passwordEdit = QtGui.QLineEdit()
        try:
            self.command1Edit = QtGui.QLineEdit(command1)
        except:
            self.command1Edit = QtGui.QLineEdit()
        try:
            self.command1REdit = QtGui.QLineEdit(command1R)
        except:
            self.command1REdit = QtGui.QLineEdit()

        btn = QtGui.QPushButton('OK', self)
        btn.clicked.connect(self.getResponses)

        grid = QtGui.QGridLayout()
        grid.setSpacing(1)

        grid.addWidget(inputBotOwner, 1, 0)
        grid.addWidget(self.botOwnerEdit, 1, 1)

        grid.addWidget(inputNick, 2, 0)
        grid.addWidget(self.nickEdit, 2, 1)

        grid.addWidget(inputChannel, 3, 0)
        grid.addWidget(self.channelEdit, 3, 1)

        grid.addWidget(inputPassword, 4, 0)
        grid.addWidget(self.passwordEdit, 4, 1)

        grid.addWidget(inputCommand1, 5, 0)
        grid.addWidget(self.command1Edit, 5, 1)
        grid.addWidget(inputCommand1R, 6, 0)
        grid.addWidget(self.command1REdit, 6, 1)

        grid.addWidget(btn)

        self.setLayout(grid)
        self.setGeometry(300, 300, 600, 200)
        self.setWindowTitle('Spenbot - Configuration')
        self.setWindowIcon(QtGui.QIcon('logo.png'))
        self.show()

    def getResponses(self):
            botOwner = self.botOwnerEdit.text()
            nick = self.nickEdit.text()
            channel = self.channelEdit.text()
            channel = '#' + channel
            password = self.passwordEdit.text()
            command1 = self.command1Edit.text()
            command1R = self.command1REdit.text()

            fileBotOwner = open('botOwner.txt', 'w')
            fileNick = open('nick.txt', 'w')
            fileChannel = open('channel.txt', 'w')
            filePassword = open('password.txt', 'w')
            fileCommands = open('commands.txt', 'w')

            fileBotOwner.write(botOwner)
            fileNick.write(nick)
            fileChannel.write(channel)
            filePassword.write(password)
            fileCommands.write(command1 + '~' + command1R)
            self.close()


def main():
    app = QtGui.QApplication(sys.argv)
    ex = Spenbot()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

Tags: inselftxtforcloseifdefirc
1条回答
网友
1楼 · 发布于 2024-04-18 20:47:01

我对线程和Qt没有经验。然而,在我看来,问题在于startSpenbot函数包含一个无限while循环,因此没有在主事件循环中返回控制。这让你的桂挂。你知道吗

如果我是您,我会使用QThreads而不是标准库的threading包,因为在某个时候您可能希望您的线程与用户界面交互(请参见#1#2)。一个好的起点(当然是Qt文档旁边)是mandelbrot example。你知道吗

相关问题 更多 >