【问题标题】:How to work with slackbot in python?如何在 python 中使用 slackbot?
【发布时间】:2018-06-15 08:27:35
【问题描述】:

我正在尝试为我的小组构建一个 slackbot,我尝试了示例代码和其他一些东西,但它没有向小组发送消息。

首先我通过终端尝试

export SLACK_API_TOKEN="my_token_id"

然后

from slackclient import SlackClient
import os

slack_token = os.environ["SLACK_API_TOKEN"]
sc = SlackClient(slack_token)

sc.api_call(
  "chat.postMessage",
  channel="#random",
  text="Hello from Python! :tada:",
  thread_ts="283.5127(dummy_id)",
  reply_broadcast=False
)

print(sc)

#<slackclient.client.SlackClient object at 0x109b77ba8>

但是 slack 组中没有消息。

我尝试使用此代码:

from slackclient import SlackClient
import os
slack_token = os.environ['SLACK_API_TOKEN']
sc = SlackClient(slack_token)
print(sc.api_call("channels.list"))

它的重新调整:

{'error': 'invalid_auth', 'ok': False}

我没有明白我做错了什么,访问令牌是正确的,我想通过机器人发布一些消息,那么我如何在 slack 上创建一个机器人并使用该机器人我可以通过 python 发送消息?

【问题讨论】:

  • 如果错误是invalid_auth,即使您认为它是正确的,您的访问令牌也可能是错误的。
  • @Tvde1 我重新生成访问令牌并尝试但同样的错误。
  • 您的环境变量是否正确?试试printing。
  • 是的,它的返回键类似于'7S4z5lMQ'

标签: python python-3.x slack slack-api chatbot


【解决方案1】:

当我使用 php 和 symfony 实现一个 slack 机器人时,我遇到了类似的问题。 正确创建和配置 Slack 应用、bot 和 OAuth 权限并不是那么简单。

如果您需要,我在这篇博文中解释了所有这些配置:https://blog.eleven-labs.com/en/en/replace-erp-by-slack-bot-with-dialogflow-and-symfony/

另外,我在 PHP 中的代码与解析 Slack 请求并发布到其 API 所需的代码非常相似。

总结,TL;DR:

  • 转到https://api.slack.com/apps 并点击“创建新应用”。

  • 在此应用配置中,转到左侧菜单“机器人用户”或从“基本信息”>“添加特性和功能”>“机器人”。

  • 仍在此应用配置中,转到菜单“OAuth & Permissions”并允许范围“chat:write:bot”并复制“OAuth Access Token”的值

  • 从您的代码中,使用以前的令牌值调用带有“Authorization”标头的“chat.postMessage”API 方法。

【讨论】:

  • 请您在此处总结链接帖子的内容,以防将来无法使用?仅链接的答案是 Stack Overflow 上的 discouraged
【解决方案2】:

根据网上找到的一些示例构建了这个:liza daly - brobot : github.comHow to Build Your First Slack Bot with Python : fullstackpython.com

当然不是最好的实现,但它可以作为(我认为)的适当答案

import random
import time
import re
from slackclient import SlackClient
bot_id = None
slack_token = 'xoxb-no.more.mister.nice.gui'
sc = SlackClient(slack_token)

# constants

RTM_READ_DELAY = 1 # 1 second delay between reading from RTM
DEFAULT_RESPONSE = "greetings: 'hello', 'hi', 'greetings', 'sup', 'what's     up' / commands: 'do'"
DEFAULT_COMMAND = "do"
MENTION_REGEX = "^<@(|[WU].+?)>(.*)"

def parse_bot_commands(slack_events):
    """
    parses a list of events coming from the slack rtm api to find bot commands
    :param slack_events:
    :return:
"""
for event in slack_events:
    if event["type"] == "message" and not "subtype" in event:
        user_id, message = parse_direct_mention(event["text"])
        if user_id == bot_id:
            return message, event["channel"]
return None, None
def parse_direct_mention(message_text):
"""
finds direct message and returns user id
:param message_text:
:return:
"""
matches = re.search(MENTION_REGEX, message_text)
# the first group contains the user name, the second group contains
# the remaining message

return (matches.group(1), matches.group(2).strip()) if matches else (None, None)
def handle_command(command, channel):
"""
    executes bot command if the command is known
:param command:
:param channel:
:return:
"""
GREETING_KEYWORDS = ("hello", "hi", "greetings", "sup", "what's up",)
GREETING_RESPONSES = ["'sup brah", "hey", "*headnod*", "didjageddathingahsencha?"]

# default response is help text for the user
default_response = "Not sure what you mean. Try *{}*.".format(DEFAULT_RESPONSE)

# finds and executes the given command, filling the response
response = None

#implement more commands below this line
if command in GREETING_KEYWORDS:
    response = random.choice(GREETING_RESPONSES)
else:
    if command.startswith(DEFAULT_COMMAND):
        response = "Sure...write some more code and I'll do that"

# Sends the response back to the channel
sc.api_call(
    "chat.postMessage",
    channel="#the_danger_room",
    as_user="true:",
    text=response or default_response)

if __name__ == "__main__":
if sc.rtm_connect(with_team_state=False):
    print("Connected and running!")

    #call web api method auth.test to get bot usre id
    bot_id = sc.api_call("auth.test")["user_id"]
    while True:
        command, channel = parse_bot_commands(sc.rtm_read())
        if command:
            handle_command(command, channel)
        time.sleep(RTM_READ_DELAY)
    else:
        print("Connection failed. Exception traceback printed above.")

【讨论】:

    猜你喜欢
    • 2019-11-09
    • 2018-12-10
    • 2023-01-12
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多