Can't import external Python library (tweepy) in AWS Lambda function

Viewed 52

I'm a complete amateur with this kind of thing. I'm trying to move my little Twitter bot from Heroku to AWS Lambda, but Tweepy seems to be causing trouble. I think the problem is just with importing the module at all, but here is everything in my lambda_function.py file, in case there's something else.

import tweepy
import random
import os
import json

ckey = os.getenv('ckey')
csec = os.getenv('csec')
atok = os.getenv('atok')
atos = os.getenv('atos')

def lambda_handler(event, context):
    # TODO implement
    tweet()
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }
    
def tweet():
    client = tweepy.Client(consumer_key=ckey, consumer_secret=csec, access_token=atok, access_token_secret=atos)
    quote = random.choice(list(open('quotes.txt')))
    client.create_tweet(text = quote)

I'm aware I need to upload any external packages as a Lambda layer, which I did do (and tried multiple different ways). The zip file I currently have uploaded as the layer for the function looks like this, in addition to a dist-info folder for each library's folder that I didn't include here.

tweepylayer.zip
└───python
    └───python310 
        └───lib
             └───site-packages
                  └───bin
                    │ certifi
                    │ charset_normalizer
                    │ idna
                    │ oauthlib
                    │ requests
                    │ requests_oauthlib
                    │ tweepy
                    │ urllib3

Every time I attempt to test the function, it gives me this error.

{
  "errorMessage": "Unable to import module 'lambda_function': No module named 'tweepy'",
  "errorType": "Runtime.ImportModuleError",
  "requestId": "1a06e902-f8b9-4c3b-b671-8934d4183dc3",
  "stackTrace": []
}

Thank you so, so much to anyone who is able to help at all, I'm still struggling to wrap my head around any of this stuff. And my apologies for this post being so long, I wasn't sure what did or did not need to be included.

1 Answers

This folder hierarchy is not supported by the Lambda Python runtime. The modules need to be installed under python directory or python/lib/python3.10/site-packages directory and zipped.

More in AWS documentation.

tweepylayer.zip
└───python
    └───certifi
    └───charset_normalizer
    └───idna
    └───oauthlib
    └───requests
    └───requests_oauthlib
    └───tweepy
    └───urllib3
Related