liorblob
liorblob

Reputation: 537

slackclient python - async RTM client

I'm quite new to all things async in python. I have a certain code I would like to run while an async slack RTM client is listening on messages with a dedicated callback, like this:

RTM_CLIENT.start()
    while True:
        ...
except Exception as e:
    ...
finally:
    RTM_CLIENT.stop()

the callback function:

@slack.RTMClient.run_on(event='message')
def listen(**payload):
...

The RTM_CLIENT.start() function returns a future object. I'm not getting any message events though. Am I doing something wrong?

Upvotes: 2

Views: 1318

Answers (1)

liorblob
liorblob

Reputation: 537

This solves it(thread sync):

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())

Upvotes: 2

Related Questions