在 Azure 函数中运行的 Bolt python 机器人

问题描述 投票:0回答:1

当前有一个 Azure 函数(python),它响应来自 slack 的挑战并触发另一个函数将消息发送到我的 slack 通道。 我想监听事件(来自任何用户的简单问候)并将消息发送到带有机器人的通道,理想情况下在线程中,但也可以在通道中。 但对于螺栓框架,它不起作用((

我尝试了什么

import azure.functions as func
from slack_bolt import App
import json
import os

# Initializes your app with your bot token and signing secret
app = App(
    token=os.environ.get("SLACK_BOT_TOKEN"),
    signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
)


# Listens to incoming messages that contain "hello"
@app.message("hello")
def message_hello(message,say):
# say() sends a message to the channel where the event was triggered
    say(f"Hey there <@{message['user']}>")


def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        # checking if in req http request has a json and putting this value into req_body
        req_body = req.get_json() 

    except ValueError: 
        return func.HttpResponse("Invalid JSON in request body", status_code=400)

    request_type = req_body.get('type')# here we are getting the request type value 

    if request_type == 'url_verification': #checking if the request type is url_verification 

        challenge = req_body.get('challenge') #from request type we are getting challenge value 

        if challenge: # if challenge is has something in it

            #Responding with the challenge in JSON format 
            response_data ={"challenge":challenge} #creating a dict for storing challenge key is challenge 

            #returning the response with json format 
            return func.HttpResponse(json.dumps(response_data),status_code=200, mimetype="application/json")
            
        else:
            # Missing challenge parameter in the request
            return func.HttpResponse("Missing challenge parameter in the request", status_code=400)
        
    else:
        # Respond to other types of requests as needed
        
        return func.HttpResponse("Unhandled request type", status_code=400)
        


#start our app 
if __name__=="__main__":

     app.start(port=int(os.environ.get("PORT", 3000)))   
python-3.x azure function slack-bolt
1个回答
0
投票

您可能需要在 Slack 应用程序配置页面 (https://api.slack.com/apps//event-subscriptions) 上启用事件,如果您已经这样做了,请订阅适当的事件(例如,消息.频道)。

在您的代码中,您可以使用像本示例这样的装饰器,或者在当前代码中使用

app.message
(更多信息:https://slack.dev/bolt-python/api-docs/slack_bolt/kwargs_injection/args)。 html):

@app.event("message")
def handle_message_events(client, logger, message):
    logger.info(message)
    print(f"message event - Message:\n{message}\n")

请记住,如果您想监听私人频道上的消息事件,您需要将您的应用机器人添加为私人频道的成员。

问你一个问题,通过上面的代码,你可以使用命令

func start
启动Azure功能在本地进行测试吗?我试图在部署之前执行此操作,但收到一条错误消息:
Worker failed to index functions ... Could not find top level function app instances in function_app.py

© www.soinside.com 2019 - 2024. All rights reserved.