-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfirebase.py
69 lines (54 loc) · 1.9 KB
/
firebase.py
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
#!./.venv/bin/python
from typing import List
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from telegram import Message
from google.cloud.firestore_v1.base_document import DocumentSnapshot
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred)
db = firestore.client()
def convert_user(user):
return {
"id": user.id,
"first_name": user.first_name,
"last_name": user.last_name,
"username": user.username,
}
def convert_reply_message(message: Message):
return {"from": convert_user(message.from_user), "text": message.text}
def save_message(message: Message, image_description: str) -> str:
if message == None:
return
message_text = (
message.text
if message.text != None
else message.caption if message.caption != None else image_description
)
s_message = {
"message_id": message.message_id,
"date": message.date,
"from": convert_user(message.from_user),
"reply_to_message": (
convert_reply_message(message.reply_to_message)
if message.reply_to_message is not None
else ""
),
"text": message_text,
}
if image_description != None and len(image_description) > 0:
s_message["attachment_description"] = image_description
update_time, message_ref = db.collection(str(message.chat.id)).add(s_message)
return message_ref.id
def get_last_messages(chat_id, limit) -> List:
snapshots = (
db.collection(chat_id)
.order_by("date", direction=firestore.Query.DESCENDING)
.limit(limit)
.get()
)
result = list(map(lambda snap: snap.to_dict(), snapshots))
result.reverse()
return result
def get_message(chat_id, message_id) -> DocumentSnapshot:
return db.collection(chat_id).document(message_id).get()