Похожие чаты

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

54 просмотра

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

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

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

30500 за редактор? )
Владимир
47
any reference of this implementation?
BitBuddha
29
Ⓐrtto, [4/23/24 7:02 PM] Please explain more fully how it is not working exactly, and what are the steps you are taking, and what error messages come or what happens. Ⓐrtto, ...
Ezza Kezza
2
sounds like people have lost their kaspa on tradeogre... does this mean tradeogre not trustworthy?
Ezza Kezza
15
Страшнейшая правда про списки ЦБ. С первых дней жизни P2P сферы, молодые человеки, начитавшись законодательной базы и "внутренних" документов, решили, что им противостоит сер...
Foxcool
3
Недавно Google Project Zero нашёл багу в SQLite с помощью LLM, о чём достаточно было шумно в определённых интернетах, которые сопровождались рассказами, что скоро всех "ибешни...
Alex Sherbakov
5
So much speculation in the last week. So much volatility in price. This is because Hedera has a GC that isn't using the network it's governing. Why aren't people asking why a...
Summit Seeker R
8
Anyone else having this error when trying to make transactions?
Datzel
11
Question: How viable is it to use Anvil as the backend infrastructure for managing a TradFi portfolio, while integrating Flexa for instant liquidity and payment solutions? Cou...
Kevin
2
вы делали что-то подобное и как? может есть либы готовые? увидел картинку нокода, где всё линиями соединено и стало интересно попробовать то же в ddl на lua сделать. решил с ч...
Victor
8
Карта сайта