0

I am a beginner programmer. It is necessary to send a message to telegram by pressing a button. I use Telethon and PyQt libraries. This code fails with the following error:

sys:1: RuntimeWarning: coroutine 'SendMessage.run' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback Process finished with exit code -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())

Help, please, deal with this problem.

Simon70
  • 1
  • 1
  • Why are you using async/await? – musicamante Nov 21 '22 at 17:25
  • Because the telethon library is asynchronous. – Simon70 Nov 21 '22 at 17:46
  • 2
    [My answer to "How to combine python asyncio with threads?"](https://stackoverflow.com/a/62112712/) might help you. You should have one thread dedicated to running the `asyncio` event loop, and the communicate safely with it via queues. It is not something trivial to do. – Lonami Nov 21 '22 at 19:36
  • @Simon70 Note that if you don't really need asyncio and you can just run the library in another thread, just implement `run()` without any of that and process the library's event loop from there. If you *do need* asyncio, then you don't need QThread: take a look at [this answer](https://stackoverflow.com/a/65145951) and do some further research (it seems that those two libraries are not actively maintained - which doesn't mean that they don't work, btw) – musicamante Nov 22 '22 at 01:05

0 Answers0