创建Slack Bot以应答请求

2024-05-16 03:23:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个Slack bot来回答一些简单的问题或在服务器上执行一些任务。这是我试过的

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!")

它是作为Slackbot发布的,而不是我创建的bot帐户?

如果我要听消息,根据python库,它会说

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

还是应该使用传入的webhook?


Tags: https服务器tokenapihereputmybot
2条回答

我现在也在创建一个机器人。我发现如果您指定了as_user='true',它将以您身份发布,即已验证的用户。如果您想让它成为您的机器人,请输入我们机器人的名称和其他选项,如emoji,如下所示:

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

查看emoji cheat sheet了解更多信息。

然后,如果您想监听事件,如问题或命令,请尝试拦截传入的消息。在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

如您所见,here此调用接受一个参数'As_user',该参数可以为true。如果将其设置为true,则消息将作为创建的bot发布。

相关问题 更多 >