-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpnba.py
147 lines (117 loc) · 4.44 KB
/
pnba.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""
Phone number-based Authentication Client Module.
"""
import logging
import re
import datetime
import asyncio
import sentry_sdk
import telegram_client
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
class PNBAClient:
"""
PNBA client implementation.
"""
def __init__(self, platform_name, phone_number) -> None:
"""
Initialize the PNBAClient.
Args:
platform_name (str): The name of the platform (e.g., 'telegram').
"""
self.platform = platform_name.lower()
self.phone_number = re.sub(r"\s+", "", phone_number)
if not self.phone_number.startswith("+"):
self.phone_number = "+" + self.phone_number
self.session = telegram_client if self.platform == "telegram" else None
def authorization(self):
"""
Send an authorization request to the platform.
Returns:
dict: A dictionary containing the response message or error.
"""
try:
client = self.session.Methods(self.phone_number)
asyncio.run(client.authorize())
return {
"response": f"Successfully sent authorization to your {self.platform} app."
}
except (
self.session.Errors.SessionExistError,
self.session.Errors.FloodWaitError,
self.session.Errors.RPCError,
) as e:
return {"error": str(e)}
def validation(self, code: str):
"""
Validate the authorization code sent to the platform.
Args:
code (str): The authorization code received from the platform.
Returns:
dict: A dictionary containing the validation result or error.
"""
try:
client = self.session.Methods(self.phone_number)
result = asyncio.run(client.validate(code=code))
return {"response": result}
except (
self.session.Errors.PhoneCodeInvalidError,
self.session.Errors.PhoneCodeExpiredError,
self.session.Errors.FloodWaitError,
) as e:
return {"error": str(e)}
except self.session.Errors.SessionPasswordNeededError:
return {"two_step_verification_enabled": True}
def password_validation(self, password) -> dict:
"""
Validate the password for two-step verification.
Args:
password (str): The password for two-step verification.
Returns:
dict: A dictionary containing the validation result or error.
"""
try:
client = self.session.Methods(self.phone_number)
result = asyncio.run(client.validate_with_password(password=password))
return {"response": result}
except (
self.session.Errors.PasswordHashInvalidError,
self.session.Errors.FloodWaitError,
) as e:
return {"error": str(e)}
def invalidation(self) -> None:
"""
Invalidate the session token.
Returns:
dict: A dictionary containing the invalidation result or error.
"""
try:
client = self.session.Methods(self.phone_number)
asyncio.run(client.invalidate(token=self.phone_number))
return {"response": f"Successfully revoked access for {self.platform}."}
except Exception as error:
logger.exception(error)
return {"error": str(error)}
def send_message(self, recipient, message):
"""Send a message.
Args:
message (dict): The message payload to be sent. The payload should be a
properly formatted dictionary according to the platform's specifications.
"""
client = self.session.Methods(self.phone_number)
recipient = re.sub(r"\s+", "", recipient)
if not recipient.startswith("+"):
recipient = "+" + recipient
asyncio.run(client.message(recipient=recipient, text=message))
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
publish_alert = (
f"Successfully sent message for '{self.platform}' at {timestamp}"
)
sentry_sdk.capture_message(
publish_alert,
level="info",
)
logger.info(publish_alert)
return f"Successfully sent message to '{self.platform}' on your behalf at {timestamp}."