Похожие чаты

I am trying to deploy this simple telethon script on

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 ?

6 ответов

23 просмотра

try using Different Session Storage

Try hasebin.com for share your codes

Dilip-Rajkumar Автор вопроса
/ Zanyar
Try hasebin.com for share your codes

Your link goes to this page? https://www.instagram.com/bluepoem/

Dilip Rajkumar
Your link goes to this page? https://www.instagram...

What😐 https://www.toptal.com/developers/hastebin

Dilip-Rajkumar Автор вопроса
Ninym
try using Different Session Storage

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

Dilip-Rajkumar Автор вопроса

Похожие вопросы

Обсуждают сегодня

а зачем этот вопрос для удаления из чата?
Mёdkinson Medvezhkin
63
using next image component with s3 image: "url" parameter is valid but upstream response is invalid code: <Image fill src={s...
Fasil
3
Эх кто-то пришел и весь праздник испортил :( You need complex FBX scene importing setup to change things on import? good luck with that. You need navigation and pathfinding? g...
Serg Gini
5
Friends, how can I find my Wazirx wallet address?
Silm Silm
31
Всем привет! Подскажите. Я написал приложение на Delphi 10.2 Tokyo под Windows 10. И передо мной стал вопрос о том чтобы сделать это приложение кроссплатформенным (под Linux и...
Дмитрий Завгородний
24
Какого хера? /Sources/App/Modules/User/Models/UserLinkApple.swift:21:20: warning: stored property '_id' of 'Sendable'-conforming class 'UserLinkApple' is mutable @ID(...
Alexander Sherbakov
13
My 7 year old daughter recognizes the Bitcoin symbol and knows it's currency. What are the top ,3-5 most basic important concepts to convey to a kid about BCH? I started with ...
Big Hair
24
How many Cashfusion server now?
Crypto life
22
But I'm wondering how exactly we can increase our chances of winning. Do you think it's just a matter of luck, or are there specific actions we need to take to qualify?
Luqman Ayman
12
Кто знает локации, где можно машину красиво отфоткать?
Lalalashechki Lalala
23
Карта сайта