【发布时间】:2022-11-22 13:11:57
【问题描述】:
我是初学者程序员。有必要通过按下按钮将消息发送到电报。我使用 Telethon 和 PyQt 库。此代码失败并出现以下错误:
sys:1: RuntimeWarning: 从未等待协程“SendMessage.run” RuntimeWarning:启用 tracemalloc 以获取对象分配回溯 进程已完成,退出代码为 -1073740791 (0xC0000409)。
from PyQt6.QtWidgets import *
from telethon import *
from PyQt6.QtCore import QThread
api_id = 'api_id'
api_hash = 'api_hash'
client = TelegramClient('anon', api_id, api_hash, proxy=("http", '192...', 8...))
class SendMassage(QThread):
def __init__(self, mainwindow, parent = None):
super().__init__()
self.mainwindow = mainwindow
async def run(self):
client.start()
await client.send_message('me', 'hello')
client.disconnect()
class SendMessageTest(QDialog):
def __init__(self, parent=None):
super().__init__()
self.PushButton = QPushButton("Send")
self.setGeometry(300,300,300,150)
vbox = QVBoxLayout()
vbox.addWidget(self.PushButton)
self.setLayout(vbox)
self.PushButton.clicked.connect(self.launch_send)
self.sendMessage_instance = SendMessage(mainwindow=self)
def launch_send(self):
self.sendMessage_instance.start()
import sys
app = QApplication(sys.argv)
main = SendMessageTest()
main.show()
sys.exit(app.exec())
请帮忙解决这个问题。
【问题讨论】:
-
你为什么使用异步/等待?
-
因为 telethon 库是异步的。
-
My answer to "How to combine python asyncio with threads?" 可能会对您有所帮助。您应该有一个线程专用于运行
asyncio事件循环,并通过队列与它安全通信。这不是一件小事。 -
@Simon70 请注意,如果您真的不需要 asyncio 并且您可以在另一个线程中运行该库,只需实现
run()而无需任何这些并从那里处理该库的事件循环。如果你确实需要asyncio,那么你就不需要 QThread:看看 this answer 并做一些进一步的研究(这两个库似乎没有得到积极维护 - 这并不意味着它们不起作用,顺便说一句)
标签: pyqt python-asyncio qthread telethon sendmessage