Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Slack Bot to Answer Request

I would like to create a Slack bot to answer some simple question or perform some task on the server. Here is what I have tried

token = "i-put-my-bot-token-here"      # found at https://api.slack.com/#auth)
sc = SlackClient(token)

sc.api_call("chat.postMessage", channel="magic", text="Hello World!")

It was posted as the Slackbot and not the bot account that I created?

Also if I were to listen the message, according to the python library it says

if sc.rtm_connect():
    while True:
        print sc.rtm_read()
        time.sleep(1)
else:
    print "Connection Failed, invalid token?"

Or should I use incoming webhook instead?

like image 901
drhanlau Avatar asked Feb 11 '23 18:02

drhanlau


2 Answers

As you can see here this call accepts an argument 'as_user' which can be true. If you set it as true, messages will be posted as the bot you created.

like image 93
juangesino Avatar answered Feb 13 '23 09:02

juangesino


I'm in the middle of creating a bot right now as well. I found that if you specified as_user='true', it would post as you, the authed user. If you want it to be your bot, pass in the name of our bot and other options like emoji's like so:

sc.api_call(
    'chat.postMessage',
    username='new_slack_bot',
    icon_emoji=':ghost:',
    as_user='false',
    channel='magic',
    text='Hello World!'
)

Check emoji cheat sheet for more.

Then, if you want to listen to events, like questions or commands, try intercepting the messages that are sent in. Example found on this post:

while True:
    new_evts = sc.rtm_read()
    for evt in new_evts:
      print(evt)
      if "type" in evt:
        if evt["type"] == "message" and "text" in evt:    
          message=evt["text"]
          # write operations below to receive commands and respond as you like
like image 33
jkwok Avatar answered Feb 13 '23 10:02

jkwok