如何在python中使用slackbot?

如何在python中使用slackbot?,python,python-3.x,slack,slack-api,chatbot,Python,Python 3.x,Slack,Slack Api,Chatbot,我正在尝试为我的团队构建一个slackbot,我尝试了示例代码和其他一些东西,但它没有向团队发送消息 首先我试着通过终端 export SLACK_API_TOKEN="my_token_id" 然后 其重新调谐: {'error': 'invalid_auth', 'ok': False} 我没有弄错,Access token是正确的,我想通过bot发布一些消息,所以我如何在slack上创建一个bot,并使用该bot通过python发送消息?当我用php和symfony实现slack bo

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

首先我试着通过终端

export SLACK_API_TOKEN="my_token_id"
然后

其重新调谐:

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

我没有弄错,Access token是正确的,我想通过bot发布一些消息,所以我如何在slack上创建一个bot,并使用该bot通过python发送消息?

当我用php和symfony实现slack bot时,我遇到了类似的问题。 正确地创建和配置slack应用程序、bot和OAuth权限并不是那么简单

如果您需要,我在这篇博文中解释了所有这些配置:

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

总结,TL;博士:

  • 转到并单击“创建新应用”

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

  • 仍然在此应用程序配置中,转到菜单“OAuth&Permissions”,并允许作用域“chat:write:bot”并复制“OAuth访问令牌”的值

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


根据web上的一些示例构建: 及

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

随机导入
导入时间
进口稀土
从slackclient导入slackclient
bot_id=None
slack_token='xoxb-no.more.mister.nice.gui'
sc=SlackClient(slack_令牌)
#常数
RTM_READ_DELAY=从RTM读取之间的1#1秒延迟
默认的\u RESPONSE=“问候语:‘你好’、‘你好’、‘问候语’、‘支持’、‘有什么事’/命令:‘做’”
默认命令=“do”
提及_REGEX=“^(.*)”
def parse_bot_命令(slack_事件):
"""
解析来自slack rtm api的事件列表以查找bot命令
:param slack_事件:
:返回:
"""
对于slack_事件中的事件:
如果事件[“类型”]=“消息”而不是事件中的“子类型”:
用户id,message=parse\u direct\u notice(事件[“text”])
如果用户\u id==bot\u id:
返回消息,事件[“通道”]
返回None,None
def解析直接提及(消息文本):
"""
查找直接消息并返回用户id
:参数消息\u文本:
:返回:
"""
匹配=重新搜索(提及正则表达式、消息和文本)
#第一组包含用户名,第二组包含
#剩下的消息
如果匹配其他项(无,无),则返回(matches.group(1),matches.group(2).strip())
def handle_命令(命令,通道):
"""
如果命令已知,则执行bot命令
:param命令:
:参数通道:
:返回:
"""
问候语\关键词=(“你好”、“你好”、“问候语”、“支持”、“最近好”)
问候语回答=[“你好”,“头晕”,“干得好吗?”]
#默认响应是用户的帮助文本
default\u response=“不确定您的意思。请尝试*{}*”。格式(默认\u响应)
#查找并执行给定命令,填充响应
响应=无
#在此行下面实现更多命令
if命令中的关键字:
响应=随机选择(问候语\响应)
其他:
if command.startswith(默认_命令):
response=“当然……再写一些代码,我会这么做的”
#将响应发送回通道
sc.api_调用(
“聊天。邮件”,
频道=“#危险室”,
as_user=“true:”,
text=响应或默认响应)
如果名称=“\uuuuu main\uuuuuuuu”:
如果sc.rtm\u connect(团队状态为False):
打印(“已连接并正在运行!”)
#调用web api方法auth.test以获取机器人usre id
bot_id=sc.api_调用(“auth.test”)[“user_id”]
尽管如此:
命令,通道=parse_bot_命令(sc.rtm_read())
如果命令:
handle_命令(命令,通道)
睡眠时间(RTM_读取_延迟)
其他:
打印(“连接失败。上面打印的异常回溯”)

如果错误为
无效\u auth
,则您的访问令牌可能是错误的,即使您认为它是正确的。@Tvde1我重新生成了访问令牌并尝试了相同的错误。您的环境变量正确吗?试着打印它。是的,它的返回键类似于“7S4z5lMQ”。你能在这里总结一下链接文章的内容吗,以防将来无法使用?仅链接的答案位于堆栈溢出上。
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}
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.")