Похожие чаты

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 ответов

82 просмотра

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 Автор вопроса

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

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

Господа, а что сейчас вообще с рынком труда на делфи происходит? Какова ситуация?
Rꙮman Yankꙮvsky
29
А вообще, что может смущать в самой Julia - бы сказал, что нет единого стандартного подхода по многим моментам, поэтому многое выглядит как "хаки" и произвол. Короче говоря, с...
Viktor G.
2
@Benzenoid can you tell me the easiest, and safest way to bu.y HEX now?
Živa Žena
20
This is a question from my wife who make a fortune with memes 😂😂 About the Migration and Tokens: 1. How will the old tokens be migrated to the new $LGCYX network? What is th...
🍿 °anton°
2
30500 за редактор? )
Владимир
47
а через ESC-код ?
Alexey Kulakov
29
What is the Dex situation? Agora team started with the Pnetwork for their dex which helped them both with integration. It’s completed but as you can see from the Pnetwork ann...
Ben
1
Гайс, вопрос для разносторонее развитых: читаю стрим с юарта, нада выделять с него фреймы с определенной структурой, если ли чо готовое, или долбаться с ринг буффером? нада у...
Vitaly
9
Anyone knows where there are some instructions or discort about failed bridge transactions ?
Jochem
21
@lozuk how do I get my phex copies of my ehex from a atomic wallet, to move to my rabby?
Justfrontin 👀
11
Карта сайта