I am attempting to wrap V2 of the Slack API into a class so that I can keep information about my bot encapsulated. Here is one of their example snippets:
import slack
slack_token = os.environ["SLACK_API_TOKEN"]
rtmclient = slack.RTMClient(token=slack_token)
@slack.RTMClient.run_on(event='message')
def say_hello(**payload):
data = payload['data']
if 'Hello' in data['text']:
channel_id = data['channel']
thread_ts = data['ts']
user = data['user']
webclient = payload['web_client']
webclient.chat_postMessage(
channel=channel_id,
text="Hi <@{}>!".format(user),
thread_ts=thread_ts
)
rtmclient.start()
My understanding here is that this say_hello
function is being passed into the slack object because of the decorator, so if I were to wrap this into a class, that function isn't really sitting inside my class. How do I wrap the say_hello
function for it to be able to call methods and reference properties that belonged to an instance of my class?
Have a look at how decorators work!
def decorator_factory(f):
def decoration(*args, **kwargs):
print('before')
r = f(*args, **kwargs)
print('after')
return r
return decoration
@decorator_factory
def inc(i):
'''
>>> inc(23)
before
after
42
'''
return i + 1
There may be a better, canonical way to achieve what you want, but this would do the job:
class Client():
def __init__(self):
slack.RTMClient.run_on(event='message')(self.decorated)
def decorated(self, x, y, z):
pass
They key is not to use the decorator at all.
From Markus' solution, just call the "run_on" function directly, before you call "start" function, similar to the below:
rtmclient = slack.RTMClient(token=self.Token)
rtmclient.run_on(event='message')(self.handle_command)
rtmclient.start()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.