【问题标题】:PyQt, Telethon. How to send a message on button click?PyQt,电视节目。如何在单击按钮时发送消息?
【发布时间】: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


【解决方案1】:

也许我在这里遗漏了一些东西,但在我看来,您需要做的就是删除 async defawait 关键字,而是使用 asyncio.run()

例如:

from PyQt6.QtWidgets import *
from telethon import *
from PyQt6.QtCore import QThread
import asyncio

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

    def run(self):
        client.start()
        asyncio.run(client.send_message('me', 'hello'))
        client.disconnect()

更新...基于电视节目文档send_message 不是协程。所以不需要使用任何特殊的语法来运行它。

def run(self):
    client.start()
    client.send_message('me','hello')
    client.disconnect()

【讨论】:

  • 在这种情况下,不会发生错误,但 asyncio.run(client.send_message('me', 'hello')) 不起作用。消息仍未发送。
  • @Simon70 查看更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-01
  • 2022-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
相关资源
最近更新 更多