AWS Lambda (Serverless) that listens for incoming messages in a private telegram channel and stores the same in a DynamoDB Table. When testing this script locally it works after asking for my phone number and OTP to create a .session file, but when deploying to AWS Lambda it fails (see the logs in CloudWatch Monitor) even after I include the .session file in the zip file for AWS Lambda deployment.
import os
import json
import boto3
from decimal import Decimal
from botocore.exceptions import ClientError
from telethon import TelegramClient, events
#%% Read SECRET KEYS from AWS Lambda ENVIRONMENT VARIABLES
API_ID = os.environ['API_ID']
API_HASH = os.environ['API_HASH']
SOURCE_CHANNEL_ID = int(os.environ['SOURCE_CHANNEL_ID'])
#%% Create Dynamo Table Function
def create_dynamodb_table(table_name):
dynamodb = boto3.client('dynamodb')
# Check if the table already exists
existing_tables = dynamodb.list_tables()['TableNames']
if table_name in existing_tables:
print(f"The table {table_name} already exists. Skipping DynamoDB Table Creation process.")
return None
else:
print(f"Table: {table_name} does not exist. Initiating DynamoDB Table Creation Process...")
# Define the table's partition key schema and attr definition schema
key_schema = [ {'AttributeName': 'MessageID', 'KeyType': 'HASH'} ]
attr_defn_schema = [ {'AttributeName': 'MessageID', 'AttributeType': 'N'} ]
# Define the table's provisioned throughput
provisioned_throughput = {'ReadCapacityUnits': 5,'WriteCapacityUnits': 5}
# Create the table
response = dynamodb.create_table(
TableName=table_name,
KeySchema=key_schema,
AttributeDefinitions=attr_defn_schema,
ProvisionedThroughput=provisioned_throughput
)
print(f"Table {table_name} created successfully.")
print(f"Table details: {response}")
# Create the DynamoDB table called Orders if it does not exist
table_name = "TG_Messages"
create_dynamodb_table(table_name)
# Select the required DynamoDB table by Name
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(table_name)
#%% Initialize Telegram Client
# session_file = os.path.join(os.environ['LAMBDA_TASK_ROOT'], 'TG_Listener_Profile.session')
session_file = '/tmp/TG_Listener_Profile.session'
client = TelegramClient(session_file, API_ID, API_HASH)
@client.on(events.NewMessage())
async def newMessageListener(event):
try:
channel_id = event.peer_id.channel_id
if channel_id == SOURCE_CHANNEL_ID:
msg_dict = {"msg_id":event.message.id,"message":event.message.message}
msg_dict_json = json.loads(json.dumps(msg_dict), parse_float=Decimal)
print("\nRECEIVED new Message Dict:\n", msg_dict_json)
print("Sending order received to DynamoDB")
# Store signal message in order_dict in DynamoDB Table
try:
response = table.put_item(Item=msg_dict_json)
print("Message stored in DynamoDB successfully:", response)
except Exception as e:
print("Failed to store msg in DynamoDB:\n", e.response['Error']['Message'])
return msg_dict
else:
print("Non Signal Type Message Received. IGNORED")
except Exception as e:
print(e, "Message received from personal user ID:", event.peer_id.user_id)
with client:
client.run_until_disconnected()
How to deal with this `.session` file when deploying a telethon app (python script) to AWS Lambda ?
try using Different Session Storage
Try hasebin.com for share your codes
Your link goes to this page? https://www.instagram.com/bluepoem/
What😐 https://www.toptal.com/developers/hastebin
Hi , I try this String Session, ``` client = TelegramClient(StringSession(), API_ID, API_HASH) print(client.session.save()) ``` it is again asking for phone number and OTP token everytime when running the script, it is not saving the session as a string variable anywhere nor printing it? Please note that AWS Lambda is a stateless environment so we cannot give user inputs like phone number and OTP when deploying the python function to AWS Lambda Revised full Code here: https://hastebin.com/share/ipuyutijer.python
Can someone help with this simple code issue?
Обсуждают сегодня