如何在线程中使用Telethon [英] How to use telethon in a thread

查看:226
本文介绍了如何在线程中使用Telethon的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在后台运行一个函数.所以我在代码中使用了线程.

I want to run a function in background. so I use Threading in my code.

但返回错误ValueError: signal only works in main thread,并且不知道两件事:

but return error ValueError: signal only works in main thread and don't know about two things:

  1. 什么是主线程
  2. 如何解决这个问题:)

views.py

def callback(update):
    print('I received', update)

def message_poll_start():
    try:
        client = TelegramClient('phone', api_id, api_hash,
            update_workers=1, spawn_read_thread=False)
        client.connect()
        client.add_update_handler(callback)
        client.idle()
    except TypeNotFoundError:
        pass

def message_poll_start_thread(request):
    t = threading.Thread(target=message_poll_start, args=(), kwargs={})
    t.setDaemon(True)
    t.start()
    return HttpResponse("message polling started")

urls.py

urlpatterns = [
    path('message_poll_start', messagemanager_views.message_poll_start_thread, name="message_poll_start"),
]

trace

[12/Jan/2018 11:24:38] "GET /messages/message_poll_start HTTP/1.1" 200 23
Exception in thread Thread-3:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/home/teletogram/telethogram/messagemanager/views.py", line 123, in message_poll_start
    client0.idle()
  File "/home/teletogram/.env/lib/python3.5/site-packages/telethon/telegram_bare_client.py", line 825, in idle
    signal(sig, self._signal_handler)
  File "/usr/lib/python3.5/signal.py", line 47, in signal
    handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread

推荐答案

1)默认情况下,python脚本在主线程中运行.如果使用threading.Thread生成新线程,则将创建一个新线程,该线程与主线程分开运行.当我开始学习线程时,我花了很多时间阅读它,然后才开始单击.官方线程文档对于基本功能很合适,我喜欢本教程进行更深入的研究.

1) A python script runs in the main thread by default. If you spawn a new thread using threading.Thread, that will create a new thread which runs separately from the main one. When I began learning about threading I spent a lot of time reading before it started to click. The official threading docs are decent for basic functionality, and I like this tutorial for a deeper dive.

2)Telethon的内部依赖于asyncio.在异步中,每个线程都需要有自己的异步事件循环,因此产生的线程需要显式创建的事件循环.像线程处理一样,asyncio是一个很大的主题, Telethon文档中涉及了一些主题.

2) The internals of Telethon rely on asyncio. In asyncio each thread needs its own asynchronous event loop, and thus spawned threads need an explicitly created event loop. Like threading, asyncio is a large topic, some of which is covered in the Telethon docs.

类似的事情应该起作用:

Something like this should work:

import asyncio
def message_poll_start():
    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        client = TelegramClient('phone', api_id, api_hash, loop=loop)
        client.connect()
        client.add_update_handler(callback)
        client.idle()
    except TypeNotFoundError:
        pass

这篇关于如何在线程中使用Telethon的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆