我正在尝试将发送错误消息集成到 PyQt5 内的电报中。我输入了 ctrl+x 组合来创建错误。此后,应创建一个具有 win 属性的文件并将其与 Traceback 文本一起发送。我试过:
import io
import sys
import asyncio
import traceback
import keyboard as k
from telegram import Bot
from qasync import QEventLoop
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox
TELEGRAM_TOKEN = 'TOKEN'
CHAT_ID = 'ID'
class Main_widget(QWidget):
def __init__(self):
super().__init__()
self.x = 1
k.hook_key('ctrl', lambda e: self.switch(e))
k.hook_key('x', lambda e: self.check(e))
self.show()
def switch(self, e):
if 'down' in str(e):
self.temp = True
else:
self.temp = False
def check(self, e):
if self.temp and 'down' in str(e):
try:
if e.name == 'x':
aa = 5 / 0
except:
ex_type, ex_val, ex_tb = sys.exc_info()
excepthook(ex_type, ex_val, ex_tb)
async def send_report(tb, lines):
bot = Bot(token=TELEGRAM_TOKEN)
file_content = "\n".join(lines) or "Нет данных"
file_stream = io.StringIO(file_content)
file_stream.name = "attributes.txt"
try:
await bot.send_document(
chat_id=CHAT_ID,
document=file_stream,
caption=f"Сообщение об ошибке:\n{tb}"
)
except Exception as e:
print(f"Ошибка отправки в Telegram: {e}")
finally:
file_stream.close()
def excepthook(exc_type, exc_value, exc_tb):
tb = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
lines = []
if win:
for name, value in win.__dict__.items():
if not callable(value) and not name.startswith("__"):
lines.append(f"{name}: {value}")
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setWindowTitle("Ошибка")
msg.setText("Во время работы программы возникла ошибка.")
report = msg.addButton('Сообщить об ошибке и выйти', msg.ActionRole)
report.clicked.connect(lambda: send_report(tb, lines))
win.close()
msg.show()
sys.excepthook = excepthook
if __name__ == "__main__":
app = QApplication(sys.argv)
loop = QEventLoop(app)
asyncio.set_event_loop(loop)
win = Main_widget()
with loop:
loop.run_forever()
当代码显示错误消息时,主窗口将关闭,并且不会发生任何其他事情,尽管程序仍在运行。请帮我弄清楚
我的最终选择: