@@ -18,7 +18,7 @@ class TdExample:
1818
1919 def __init__ (self , api_id : int = None , api_hash : str = None ):
2020 """Initialize a Telegram client.
21-
21+
2222 Args:
2323 api_id: Telegram API ID (get from https://my.telegram.org)
2424 api_hash: Telegram API hash (get from https://my.telegram.org)
@@ -38,7 +38,7 @@ def _load_library(self) -> None:
3838 tdjson_path = os .path .join (os .path .dirname (__file__ ), 'tdjson.dll' )
3939 else :
4040 sys .exit ("Error: Can't find 'tdjson' library. Make sure it's installed correctly." )
41-
41+
4242 try :
4343 self .tdjson = CDLL (tdjson_path )
4444 except Exception as e :
@@ -74,24 +74,24 @@ def _setup_functions(self) -> None:
7474
7575 def _setup_logging (self , verbosity_level : int = 1 ) -> None :
7676 """Configure TDLib logging.
77-
77+
7878 Args:
7979 verbosity_level: 0-fatal, 1-errors, 2-warnings, 3+-debug
8080 """
8181 @self .log_message_callback_type
8282 def on_log_message_callback (verbosity_level , message ):
8383 if verbosity_level == 0 :
8484 sys .exit (f'TDLib fatal error: { message .decode ("utf-8" )} ' )
85-
85+
8686 self ._td_set_log_message_callback (2 , on_log_message_callback )
8787 self .execute ({'@type' : 'setLogVerbosityLevel' , 'new_verbosity_level' : verbosity_level })
8888
8989 def execute (self , query : Dict [str , Any ]) -> Optional [Dict [str , Any ]]:
9090 """Execute a synchronous TDLib request.
91-
91+
9292 Args:
9393 query: The request to execute
94-
94+
9595 Returns:
9696 Response from TDLib or None
9797 """
@@ -103,7 +103,7 @@ def execute(self, query: Dict[str, Any]) -> Optional[Dict[str, Any]]:
103103
104104 def send (self , query : Dict [str , Any ]) -> None :
105105 """Send an asynchronous request to TDLib.
106-
106+
107107 Args:
108108 query: The request to send
109109 """
@@ -112,10 +112,10 @@ def send(self, query: Dict[str, Any]) -> None:
112112
113113 def receive (self , timeout : float = 1.0 ) -> Optional [Dict [str , Any ]]:
114114 """Receive a response or update from TDLib.
115-
115+
116116 Args:
117117 timeout: Maximum number of seconds to wait
118-
118+
119119 Returns:
120120 An update or response from TDLib, or None if nothing received
121121 """
@@ -127,42 +127,42 @@ def receive(self, timeout: float = 1.0) -> Optional[Dict[str, Any]]:
127127 def login (self ) -> None :
128128 """Start the authentication process."""
129129 self .send ({'@type' : 'getOption' , 'name' : 'version' })
130-
130+
131131 print ("Starting Telegram authentication flow..." )
132132 print ("Press Ctrl+C to cancel at any time." )
133-
133+
134134 try :
135135 self ._handle_authentication ()
136136 except KeyboardInterrupt :
137- print ("\n Authentication cancelled by user." )
137+ print ("\n Authentication canceled by user." )
138138 sys .exit (0 )
139-
139+
140140 def _handle_authentication (self ) -> None :
141141 """Handle the TDLib authentication flow."""
142142 while True :
143143 event = self .receive ()
144144 if not event :
145145 continue
146-
146+
147147 # Print all updates for debugging
148148 if event .get ('@type' ) != 'updateAuthorizationState' :
149- print (f"Received : { json .dumps (event , indent = 2 )} " )
150-
149+ print (f"Receive : { json .dumps (event , indent = 2 )} " )
150+
151151 # Process authorization states
152152 if event .get ('@type' ) == 'updateAuthorizationState' :
153153 auth_state = event ['authorization_state' ]
154154 auth_type = auth_state .get ('@type' )
155-
155+
156156 if auth_type == 'authorizationStateClosed' :
157157 print ("Authorization state closed." )
158158 break
159-
159+
160160 elif auth_type == 'authorizationStateWaitTdlibParameters' :
161161 if not self .api_id or not self .api_hash :
162162 print ("\n You MUST obtain your own api_id and api_hash at https://my.telegram.org" )
163163 self .api_id = int (input ("Please enter your API ID: " ))
164164 self .api_hash = input ("Please enter your API hash: " )
165-
165+
166166 print ("Setting TDLib parameters..." )
167167 self .send ({
168168 '@type' : 'setTdlibParameters' ,
@@ -175,35 +175,35 @@ def _handle_authentication(self) -> None:
175175 'device_model' : 'Python TDLib Client' ,
176176 'application_version' : '1.1' ,
177177 })
178-
178+
179179 elif auth_type == 'authorizationStateWaitPhoneNumber' :
180180 phone_number = input ('Please enter your phone number (international format): ' )
181181 self .send ({'@type' : 'setAuthenticationPhoneNumber' , 'phone_number' : phone_number })
182-
182+
183183 elif auth_type == 'authorizationStateWaitEmailAddress' :
184184 email_address = input ('Please enter your email address: ' )
185185 self .send ({'@type' : 'setAuthenticationEmailAddress' , 'email_address' : email_address })
186-
186+
187187 elif auth_type == 'authorizationStateWaitEmailCode' :
188188 code = input ('Please enter the email authentication code you received: ' )
189189 self .send ({
190190 '@type' : 'checkAuthenticationEmailCode' ,
191191 'code' : {'@type' : 'emailAddressAuthenticationCode' , 'code' : code }
192192 })
193-
193+
194194 elif auth_type == 'authorizationStateWaitCode' :
195195 code = input ('Please enter the authentication code you received: ' )
196196 self .send ({'@type' : 'checkAuthenticationCode' , 'code' : code })
197-
197+
198198 elif auth_type == 'authorizationStateWaitRegistration' :
199199 first_name = input ('Please enter your first name: ' )
200200 last_name = input ('Please enter your last name: ' )
201201 self .send ({'@type' : 'registerUser' , 'first_name' : first_name , 'last_name' : last_name })
202-
202+
203203 elif auth_type == 'authorizationStateWaitPassword' :
204204 password = input ('Please enter your password: ' )
205205 self .send ({'@type' : 'checkAuthenticationPassword' , 'password' : password })
206-
206+
207207 elif auth_type == 'authorizationStateReady' :
208208 print ("Authorization complete! You are now logged in." )
209209 return
@@ -213,32 +213,32 @@ def main():
213213 """Main function to demonstrate client usage."""
214214 # Example API credentials - DO NOT USE THESE
215215 # Get your own from https://my.telegram.org
216- DEFAULT_API_ID = 94575
216+ DEFAULT_API_ID = 94575
217217 DEFAULT_API_HASH = "a3406de8d171bb422bb6ddf3bbd800e2"
218-
218+
219219 print ("TDLib Python Client" )
220220 print ("===================" )
221221 print ("IMPORTANT: You should obtain your own api_id and api_hash at https://my.telegram.org" )
222222 print (" The default values are for demonstration only.\n " )
223-
223+
224224 use_default = input ("Use default API credentials for testing? (y/n): " ).lower () == 'y'
225-
225+
226226 if use_default :
227227 client = TdExample (DEFAULT_API_ID , DEFAULT_API_HASH )
228228 else :
229229 client = TdExample ()
230-
230+
231231 # Test execute method
232232 print ("\n Testing TDLib execute method..." )
233233 result = client .execute ({
234- '@type' : 'getTextEntities' ,
234+ '@type' : 'getTextEntities' ,
235235 'text' : '@telegram /test_command https://telegram.org telegram.me'
236236 })
237237 print (f"Text entities: { json .dumps (result , indent = 2 )} " )
238-
238+
239239 # Start login process
240240 client .login ()
241-
241+
242242 # Main event loop
243243 print ("\n Entering main event loop. Press Ctrl+C to exit." )
244244 try :
0 commit comments