65 lines
1.4 KiB
Python
65 lines
1.4 KiB
Python
import json
|
|
|
|
from pyrogram.client.types.messages_and_media import Message
|
|
|
|
|
|
class JsonSerializerFixes:
|
|
@staticmethod
|
|
def user(obj):
|
|
obj.type = "private"
|
|
return obj
|
|
|
|
@staticmethod
|
|
def user_type(obj):
|
|
obj.type = "channel" if obj.id < 0 else "private"
|
|
return obj
|
|
|
|
|
|
class JsonSerializer:
|
|
fixes = {
|
|
"from_user": {
|
|
"new_name": "from",
|
|
"patch": JsonSerializerFixes.user
|
|
},
|
|
|
|
"user": {
|
|
"new_name": "user",
|
|
"patch": JsonSerializerFixes.user_type
|
|
}
|
|
}
|
|
|
|
@staticmethod
|
|
def default(obj):
|
|
if isinstance(obj, bytes):
|
|
return repr(obj)
|
|
|
|
cls = JsonSerializer
|
|
result = {}
|
|
|
|
for name in filter(lambda x: not x.startswith("_"), obj.__dict__):
|
|
value = getattr(obj, name)
|
|
|
|
if value is None:
|
|
continue
|
|
|
|
if name in cls.fixes:
|
|
value = cls.fixes[name]["patch"](value)
|
|
name = cls.fixes[name]["new_name"]
|
|
|
|
result[name] = value
|
|
|
|
return result
|
|
|
|
|
|
async def message_to_bot_api(client, users, chats, message) -> str:
|
|
message = await Message._parse(client, message, users, chats)
|
|
|
|
return json.dumps(
|
|
{"update_id": 1, "message": message},
|
|
default=JsonSerializer.default,
|
|
ensure_ascii=True,
|
|
allow_nan=False,
|
|
check_circular=True,
|
|
sort_keys=False
|
|
)
|