-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_main.py
More file actions
74 lines (61 loc) · 2.27 KB
/
Copy pathlambda_main.py
File metadata and controls
74 lines (61 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import asyncio
from bot import handle_spotify_auth, load_html_file
import logging
from bot import build_application
import os
import json
import traceback
from telegram import Update
if logging.getLogger().hasHandlers():
logging.getLogger().setLevel(logging.INFO)
else:
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
def lambda_handler(event, context):
logger.info(f"Event body type: {type(event)}")
logger.info(f"Event body content: {event}")
if event.get("body"):
# I'm a telegram bot post webhook served via the API GAteway.
return asyncio.run(main(event, context))
elif event.get("rawPath") == "/spotifyauth":
# This is served by the Lambda Function URL.
# Spotify API refers to this as the redirect URI and it is also the path
# you've specified in your Spotify Developer Dashboard.
return handle_spotify_event(event)
else:
return {"statusCode": 404, "body": "no handler for this request"}
def handle_spotify_event(event):
state_encoded = event["queryStringParameters"].get("state")
code = event["queryStringParameters"].get("code")
if not state_encoded or not code:
return {"statusCode": 400, "body": "Missing required parameters"}
handle_spotify_auth(state_encoded, code)
html_content = load_html_file("index.html")
return {
"statusCode": 200,
"headers": {"Content-Type": "text/html"},
"body": html_content,
}
async def main(event, context):
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
application = build_application(TOKEN)
# Convert the incoming event to a Telegram Update object
if isinstance(event["body"], str):
body = json.loads(event["body"])
else:
body = event["body"]
try:
await application.initialize()
await application.process_update(Update.de_json(body, application.bot))
return {"statusCode": 200, "body": json.dumps("Success")}
except Exception:
logger.exception("Error processing update")
return {
"statusCode": 500,
"body": f"Error processing update: {traceback.format_exc()}",
}
finally:
await application.shutdown()
logger.info("application.shutdown")
if __name__ == "__main__":
main()