我对python中异步的所有事物都比较陌生。我有一个特定的代码,我想在异步松弛RTM客户端通过专用回调监听消息时运行,例如:
RTM_CLIENT.start()
while True:
...
except Exception as e:
...
finally:
RTM_CLIENT.stop()
回调函数:
@slack.RTMClient.run_on(event='message')
def listen(**payload):
...
RTM_CLIENT.start()
函数返回一个future
对象。
我没有收到任何消息事件。我在做错什么吗?
答案 0 :(得分:0)
这解决了它(线程同步):
import re
import slack
import time
import asyncio
import concurrent
from datetime import datetime
@slack.RTMClient.run_on(event='message')
async def say_hello(**payload):
data = payload['data']
print(data.get('text'))
def sync_loop():
while True:
print("Hi there: ", datetime.now())
time.sleep(5)
async def slack_main():
loop = asyncio.get_event_loop()
rtm_client = slack.RTMClient(token='x', run_async=True, loop=loop)
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
await asyncio.gather(
loop.run_in_executor(executor, sync_loop),
rtm_client.start()
)
if __name__ == "__main__":
asyncio.run(slack_main())