I am operating my own bot using slackbot on Slack. Channels are created for each purpose, and each bot plugin is executed on its own channel.
However, I often get human error that I run a plugin that is not what the channel is for, and I wanted to do something about it.
Therefore, we implemented a mechanism in the bot that executes processing only on a specific channel.
Python 3.6.1 slackbot 0.5.3
Create a decorator that takes as an argument the channels that you want to allow.
import functools
def in_channel(allow_channel):
def decorator(func):
@functools.wraps(func)
def wrapper(message, *args, **kargs):
channel_id = message.body['channel']
channel_info = message.channel._client.channels[channel_id]
channel = channel_info['name']
if allow_channel not in (channel, channel_id):
message.reply("Please post in #{}".format(allow_channel))
return
return func(message, *args, **kargs)
return wrapper
return decorator
In the above code, the argument can be either the channel name or the channel ID.
Then apply the decorator to the function you want to execute only on a particular channel. I put the above code in a file called ʻutils.py`.
from slackbot.bot import listen_to
from .utils import in_channel
@listen_to("^strong$")
@in_channel("playground")
def tsuyoi(message):
message.reply("Not strong:white_frowning_face:")
In the above code, the function tsuyoi
is set to execute only on the channel ** playground **.
--When speaking on the playground channel
--When speaking on a channel other than the playground channel
Write @in_channel
** below ** below the slackbot decorator (@listen_to
in the example above).
If the order is reversed, @listen_to
will be applied first. In that case, I have confirmed that the message will be posted.
By specifying the channel with the decorator, we were able to prevent the mistake of running the plug-in on a channel with a different purpose.
The challenge is that you can only specify one channel (which is fine for my operation). If you want to specify multiple channels, you need to tweak the above code a bit.
Limit slackbot responce to certain channel · Issue #152 · lins05/slackbot · GitHub Reintroduction to Python Decorators ~ Let's Learn Decorators by Type ~ --Qiita
Recommended Posts