I am getting started with the Slack API, so i just wanted to write a bot that listens into a channel and whenever someone says a keyword, it responds with an answer. In this case, if someone says 'hello' it responds with 'world'.
Here is what I have done so far. I registered for a Slack account. I registered a a new bot at https://slack.com/apps/build >> Make a Custom Integration >> Something just for my team, gave it a name etc.
Then i created a virtualenv and then wrote this script:
import time
from slackclient import SlackClient
BOT_TOKEN = "I PUT MY TOKEN HERE THAT I GOT FROM REGISTRATION"
CHANNEL_NAME = "general"
def main():
# Create the slackclient instance
sc = SlackClient(BOT_TOKEN)
# Connect to slack
if sc.rtm_connect():
# Send first message
sc.rtm_send_message(CHANNEL_NAME, "I'm the Hello World Bot")
while True:
# Read latest messages
for slack_message in sc.rtm_read():
message = slack_message.get("text")
user = slack_message.get("user")
if not message or not user:
continue
if "hello" in message:
sc.rtm_send_message(CHANNEL_NAME, "world")
else:
print("Couldn't connect to slack")
if __name__ == '__main__':
main()
When i run it, my command prompt is just blinking, nothing happens, not even the intro message in the channel. So I have a few questions:
1) What is wrong, if anything, with my script?
2) In my Slack, I can see the bot's name in the Direct Messages list, but when i go to the #general channel, I only have one user, me, and the bot is not there. How do i add it there? When i click invite, it wants me to add people by email.
3) If I wanted it to listen to multiple channels, what would I have to change in the script?
As @smarx said, you definitely need to invite your bot to the channel. And then I use the chat.postMessage
method to do a call and response:
if re.search("hello", message):
self.client.api_call("chat.postMessage", as_user="true",
channel=CHANNEL_NAME, text="world")
I also have a pause in my script, so try something closer to:
while True:
for slack_message in sc.rtm_read():
message = slack_message.get("text")
user = slack_message.get("user")
room = slack_message.get("channel")
if re.search("hello", message):
self.client.api_call("chat.postMessage", as_user="true",
channel=CHANNEL_NAME, text="world")
time.sleep(0.25)