问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/56761860/how-to-wrap-these-decorated-functions-into-a-class