Skip to content

Lambda Error message

0

How could I resolve the error below? { "errorMessage": "Unable to import module 'lambda_function': No module named 'slack'", "errorType": "Runtime.ImportModuleError", "requestId": "f3a0397c-365e-4fa0-b902-083c5c308130", "stackTrace": [] } Best regards,

asked 2 years ago484 views
2 Answers
1

Hello.

What code are you using in Lambda?
It looks like you're trying to import a module called "slack", but I don't think it's included in the standard Python modules, so I think you'll need to create a layer or zip it with the Lambda code and upload it.
https://docs.aws.amazon.com/lambda/latest/dg/configuration-function-zip.html

EXPERT
answered 2 years ago
EXPERT
reviewed 2 years ago
  • Hello, this is the code which I have entered.

    import os import json import openai import requests

    環境変数からトークンとAPIキーを取得

    SLACK_BOT_TOKEN = os.getenv('SLACK_BOT_TOKEN') OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')

    if not SLACK_BOT_TOKEN or not OPENAI_API_KEY: raise ValueError("Slack Bot Token and OpenAI API Key must be set as environment variables.")

    openai.api_key = OPENAI_API_KEY

    def lambda_handler(event, context): # Slackのイベントを取得 body = json.loads(event['body'])

    # SlackのURL検証
    if "challenge" in body:
        return {
            'statusCode': 200,
            'body': body['challenge']
        }
    
    event_type = body['event']['type']
    
    if event_type == 'message':
        text = body['event'].get('text', [])
        channel_id = body['event']['channel']
        bot_id = body['event'].get('bot_id')
    
        if text and not bot_id:  # 応答が他のBotからでないことを確認
            try:
                # ChatGPT-4に問い合わせ
                response = openai.Completion.create(
                    engine="gpt-4",
                    prompt=text,
                    max_tokens=150
                )
                bot_response = response['choices'][0]['text'].strip()
    
                # Slackに応答を送信
                send_message_to_slack(channel_id, bot_response)
    
            except Exception as e:
                print(f"Unexpected error: {e}")
    
    return {
        'statusCode': 200,
        'body': json.dumps('Message processed successfully!')
    }
    
  • this is the other half.

    def send_message_to_slack(channel, text): url = "https://slack.com/api/chat.postMessage" headers = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {SLACK_BOT_TOKEN}' } payload = { 'channel': channel, 'text': text } response = requests.post(url, headers=headers, json=payload) print(response.json())

  • Looking at the code, it looks like the module "slack" is not imported. Are there any other errors output? By the way, did you click the Lambda deploy button after editing the code?

0

Manually create a folder where you will install all the libraries you need, as well as your Python code file. In Lambda, update the folder. After that, move all the data to a single folder that already exists in Lambda. Check the name of the Python file. If you change the Python file name, update the Handler in the Runtime settings in Lambda.

answered 2 years ago
  • Thank you.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.