idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
30,700
def from_url ( cls , url , filename = None , chunk_size = CHUNK_SIZE ) : pipe = _WebPipe ( url , chunk_size = chunk_size ) if filename is None : filename = pipe . name return cls ( pipe , filename , chunk_size )
Download file from URL
30,701
def save ( self , filename , chunk_size = CHUNK_SIZE ) : with open ( filename , 'wb' ) as fp : while True : data = self . file . read ( chunk_size ) if not data : break fp . write ( data ) fp . flush ( ) if self . file . seekable ( ) : self . file . seek ( 0 )
Write file to disk
30,702
def create ( cls , selective : typing . Optional [ base . Boolean ] = None ) : return cls ( selective = selective )
Create new force reply
30,703
async def cancel_handler ( message : types . Message , state : FSMContext , raw_state : Optional [ str ] = None ) : if raw_state is None : return await state . finish ( ) await message . reply ( 'Canceled.' , reply_markup = types . ReplyKeyboardRemove ( ) )
Allow user to cancel any action
30,704
async def process_name ( message : types . Message , state : FSMContext ) : async with state . proxy ( ) as data : data [ 'name' ] = message . text await Form . next ( ) await message . reply ( "How old are you?" )
Process user name
30,705
def rate_limit ( limit : int , key = None ) : def decorator ( func ) : setattr ( func , 'throttling_rate_limit' , limit ) if key : setattr ( func , 'throttling_key' , key ) return func return decorator
Decorator for configuring rate limit and key in different functions .
30,706
async def on_process_message ( self , message : types . Message , data : dict ) : handler = current_handler . get ( ) dispatcher = Dispatcher . get_current ( ) if handler : limit = getattr ( handler , 'throttling_rate_limit' , self . rate_limit ) key = getattr ( handler , 'throttling_key' , f"{self.prefix}_{handler.__n...
This handler is called when dispatcher receives a message
30,707
async def message_throttled ( self , message : types . Message , throttled : Throttled ) : handler = current_handler . get ( ) dispatcher = Dispatcher . get_current ( ) if handler : key = getattr ( handler , 'throttling_key' , f"{self.prefix}_{handler.__name__}" ) else : key = f"{self.prefix}_message" delta = throttled...
Notify user only on first exceed and notify about unlocking only on last exceed
30,708
def generate_hash ( data : dict , token : str ) -> str : secret = hashlib . sha256 ( ) secret . update ( token . encode ( 'utf-8' ) ) sorted_params = collections . OrderedDict ( sorted ( data . items ( ) ) ) msg = '\n' . join ( "{}={}" . format ( k , v ) for k , v in sorted_params . items ( ) if k != 'hash' ) return hm...
Generate secret hash
30,709
def check_token ( data : dict , token : str ) -> bool : param_hash = data . get ( 'hash' , '' ) or '' return param_hash == generate_hash ( data , token )
Validate auth token
30,710
def resolve ( self , event_handler , * custom_filters , ** full_config ) -> typing . List [ typing . Union [ typing . Callable , AbstractFilter ] ] : filters_set = [ ] filters_set . extend ( self . _resolve_registered ( event_handler , { k : v for k , v in full_config . items ( ) if v is not None } ) ) if custom_filter...
Resolve filters to filters - set
30,711
def _resolve_registered ( self , event_handler , full_config ) -> typing . Generator : for record in self . _registered : filter_ = record . resolve ( self . _dispatcher , event_handler , full_config ) if filter_ : yield filter_ if full_config : raise NameError ( 'Invalid filter name(s): \'' + '\', ' . join ( full_conf...
Resolve registered filters
30,712
def parse ( cls , request : web . Request ) -> AuthWidgetData : try : query = dict ( request . query ) query [ 'id' ] = int ( query [ 'id' ] ) query [ 'auth_date' ] = int ( query [ 'auth_date' ] ) widget = AuthWidgetData ( ** query ) except ( ValueError , KeyError ) : raise web . HTTPBadRequest ( text = 'Invalid auth d...
Parse request as Telegram auth widget data .
30,713
def _check_ip ( ip : str ) -> bool : address = ipaddress . IPv4Address ( ip ) return address in allowed_ips
Check IP in range
30,714
def allow_ip ( * ips : typing . Union [ str , ipaddress . IPv4Network , ipaddress . IPv4Address ] ) : for ip in ips : if isinstance ( ip , ipaddress . IPv4Address ) : allowed_ips . add ( ip ) elif isinstance ( ip , str ) : allowed_ips . add ( ipaddress . IPv4Address ( ip ) ) elif isinstance ( ip , ipaddress . IPv4Netwo...
Allow ip address .
30,715
def configure_app ( dispatcher , app : web . Application , path = DEFAULT_WEB_PATH , route_name = DEFAULT_ROUTE_NAME ) : app . router . add_route ( '*' , path , WebhookRequestHandler , name = route_name ) app [ BOT_DISPATCHER_KEY ] = dispatcher
You can prepare web . Application for working with webhook handler .
30,716
def get_dispatcher ( self ) : dp = self . request . app [ BOT_DISPATCHER_KEY ] try : from aiogram import Bot , Dispatcher Dispatcher . set_current ( dp ) Bot . set_current ( dp . bot ) except RuntimeError : pass return dp
Get Dispatcher instance from environment
30,717
async def parse_update ( self , bot ) : data = await self . request . json ( ) update = types . Update ( ** data ) return update
Read update from stream and deserialize it .
30,718
async def post ( self ) : self . validate_ip ( ) dispatcher = self . get_dispatcher ( ) update = await self . parse_update ( dispatcher . bot ) results = await self . process_update ( update ) response = self . get_response ( results ) if response : web_response = response . get_web_response ( ) else : web_response = w...
Process POST request
30,719
async def process_update ( self , update ) : dispatcher = self . get_dispatcher ( ) loop = dispatcher . loop waiter = loop . create_future ( ) timeout_handle = loop . call_later ( RESPONSE_TIMEOUT , asyncio . tasks . _release_waiter , waiter ) cb = functools . partial ( asyncio . tasks . _release_waiter , waiter ) fut ...
Need respond in less than 60 seconds in to webhook .
30,720
def respond_via_request ( self , task ) : warn ( f"Detected slow response into webhook. " f"(Greater than {RESPONSE_TIMEOUT} seconds)\n" f"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts." , TimeoutWarning ) dispatcher = self . get_dispatcher ( ) loop = dispatcher . loop try : r...
Handle response after 55 second .
30,721
def get_response ( self , results ) : if results is None : return None for result in itertools . chain . from_iterable ( results ) : if isinstance ( result , BaseResponse ) : return result
Get response object from results .
30,722
def check_ip ( self ) : forwarded_for = self . request . headers . get ( 'X-Forwarded-For' , None ) if forwarded_for : return forwarded_for , _check_ip ( forwarded_for ) peer_name = self . request . transport . get_extra_info ( 'peername' ) if peer_name is not None : host , _ = peer_name return host , _check_ip ( host ...
Check client IP . Accept requests only from telegram servers .
30,723
def validate_ip ( self ) : if self . request . app . get ( '_check_ip' , False ) : ip_address , accept = self . check_ip ( ) if not accept : raise web . HTTPUnauthorized ( )
Check ip if that is needed . Raise web . HTTPUnauthorized for not allowed hosts .
30,724
def cleanup ( self ) -> typing . Dict : return { k : v for k , v in self . prepare ( ) . items ( ) if v is not None }
Cleanup response after preparing . Remove empty fields .
30,725
async def execute_response ( self , bot ) : method_name = helper . HelperMode . apply ( self . method , helper . HelperMode . snake_case ) method = getattr ( bot , method_name , None ) if method : return await method ( ** self . cleanup ( ) ) return await bot . request ( self . method , self . cleanup ( ) )
Use this method if you want to execute response as simple HTTP request .
30,726
def reply ( self , message : typing . Union [ int , types . Message ] ) : setattr ( self , 'reply_to_message_id' , message . message_id if isinstance ( message , types . Message ) else message ) return self
Reply to message
30,727
def to ( self , target : typing . Union [ types . Message , types . Chat , types . base . Integer , types . base . String ] ) : if isinstance ( target , types . Message ) : chat_id = target . chat . id elif isinstance ( target , types . Chat ) : chat_id = target . id elif isinstance ( target , ( int , str ) ) : chat_id...
Send to chat
30,728
def write ( self , * text , sep = ' ' ) : self . text += markdown . text ( * text , sep ) return self
Write text to response
30,729
def message ( self , message : types . Message ) : setattr ( self , 'from_chat_id' , message . chat . id ) setattr ( self , 'message_id' , message . message_id ) return self
Select target message
30,730
def check_address ( cls , * , chat : typing . Union [ str , int , None ] = None , user : typing . Union [ str , int , None ] = None ) -> ( typing . Union [ str , int ] , typing . Union [ str , int ] ) : if chat is None and user is None : raise ValueError ( '`user` or `chat` parameter is required but no one is provided!...
In all storage s methods chat or user is always required . If one of them is not provided you have to set missing value based on the provided one .
30,731
async def get_data ( self , * , chat : typing . Union [ str , int , None ] = None , user : typing . Union [ str , int , None ] = None , default : typing . Optional [ typing . Dict ] = None ) -> typing . Dict : raise NotImplementedError
Get state - data for user in chat . Return default if no data is provided in storage .
30,732
async def update_data ( self , * , chat : typing . Union [ str , int , None ] = None , user : typing . Union [ str , int , None ] = None , data : typing . Dict = None , ** kwargs ) : raise NotImplementedError
Update data for user in chat
30,733
async def reset_state ( self , * , chat : typing . Union [ str , int , None ] = None , user : typing . Union [ str , int , None ] = None , with_data : typing . Optional [ bool ] = True ) : chat , user = self . check_address ( chat = chat , user = user ) await self . set_state ( chat = chat , user = user , state = None ...
Reset state for user in chat . You may desire to use this method when finishing conversations .
30,734
async def finish ( self , * , chat : typing . Union [ str , int , None ] = None , user : typing . Union [ str , int , None ] = None ) : await self . reset_state ( chat = chat , user = user , with_data = True )
Finish conversation for user in chat .
30,735
async def get_bucket ( self , * , chat : typing . Union [ str , int , None ] = None , user : typing . Union [ str , int , None ] = None , default : typing . Optional [ dict ] = None ) -> typing . Dict : raise NotImplementedError
Get bucket for user in chat . Return default if no data is provided in storage .
30,736
async def set_bucket ( self , * , chat : typing . Union [ str , int , None ] = None , user : typing . Union [ str , int , None ] = None , bucket : typing . Dict = None ) : raise NotImplementedError
Set bucket for user in chat
30,737
async def update_bucket ( self , * , chat : typing . Union [ str , int , None ] = None , user : typing . Union [ str , int , None ] = None , bucket : typing . Dict = None , ** kwargs ) : raise NotImplementedError
Update bucket for user in chat
30,738
async def reset_bucket ( self , * , chat : typing . Union [ str , int , None ] = None , user : typing . Union [ str , int , None ] = None ) : await self . set_data ( chat = chat , user = user , data = { } )
Reset bucket dor user in chat .
30,739
async def connect ( self ) -> Connection : if self . _conn is None : self . _conn = await r . connect ( host = self . _host , port = self . _port , db = self . _db , auth_key = self . _auth_key , user = self . _user , password = self . _password , timeout = self . _timeout , ssl = self . _ssl , io_loop = self . _loop )...
Get or create a connection .
30,740
def attach_many ( self , * medias : typing . Union [ InputMedia , typing . Dict ] ) : for media in medias : self . attach ( media )
Attach list of media
30,741
def validate ( cls , full_config : Dict [ str , Any ] ) -> Optional [ Dict [ str , Any ] ] : config = { } if 'commands' in full_config : config [ 'commands' ] = full_config . pop ( 'commands' ) if config and 'commands_prefix' in full_config : config [ 'prefixes' ] = full_config . pop ( 'commands_prefix' ) if config and...
Validator for filters factory
30,742
async def check ( self , message : types . Message ) : check = await super ( CommandStart , self ) . check ( message ) if check and self . deep_link is not None : if not isinstance ( self . deep_link , re . Pattern ) : return message . get_args ( ) == self . deep_link match = self . deep_link . match ( message . get_ar...
If deep - linking is passed to the filter result of the matching will be passed as deep_link to the handler
30,743
def paginate ( data : typing . Iterable , page : int = 0 , limit : int = 10 ) -> typing . Iterable : return data [ page * limit : page * limit + limit ]
Slice data over pages
30,744
async def download_file_by_id ( self , file_id : base . String , destination = None , timeout : base . Integer = 30 , chunk_size : base . Integer = 65536 , seek : base . Boolean = True ) : file = await self . get_file ( file_id ) return await self . download_file ( file_path = file . file_path , destination = destinati...
Download file by file_id to destination
30,745
async def get_webhook_info ( self ) -> types . WebhookInfo : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . GET_WEBHOOK_INFO , payload ) return types . WebhookInfo ( ** result )
Use this method to get current webhook status . Requires no parameters .
30,746
async def get_me ( self ) -> types . User : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . GET_ME , payload ) return types . User ( ** result )
A simple method for testing your bot s auth token . Requires no parameters .
30,747
async def send_poll ( self , chat_id : typing . Union [ base . Integer , base . String ] , question : base . String , options : typing . List [ base . String ] , disable_notification : typing . Optional [ base . Boolean ] , reply_to_message_id : typing . Union [ base . Integer , None ] , reply_markup : typing . Union [...
Use this method to send a native poll . A native poll can t be sent to a private chat . On success the sent Message is returned .
30,748
async def get_file ( self , file_id : base . String ) -> types . File : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . GET_FILE , payload ) return types . File ( ** result )
Use this method to get basic info about a file and prepare it for downloading . For the moment bots can download files of up to 20MB in size .
30,749
async def export_chat_invite_link ( self , chat_id : typing . Union [ base . Integer , base . String ] ) -> base . String : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . EXPORT_CHAT_INVITE_LINK , payload ) return result
Use this method to generate a new invite link for a chat ; any previously generated link is revoked . The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
30,750
async def set_chat_photo ( self , chat_id : typing . Union [ base . Integer , base . String ] , photo : base . InputFile ) -> base . Boolean : payload = generate_payload ( ** locals ( ) , exclude = [ 'photo' ] ) files = { } prepare_file ( payload , files , 'photo' , photo ) result = await self . request ( api . Methods...
Use this method to set a new profile photo for the chat . Photos can t be changed for private chats . The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
30,751
async def set_chat_description ( self , chat_id : typing . Union [ base . Integer , base . String ] , description : typing . Union [ base . String , None ] = None ) -> base . Boolean : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . SET_CHAT_DESCRIPTION , payload ) return re...
Use this method to change the description of a supergroup or a channel . The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
30,752
async def unpin_chat_message ( self , chat_id : typing . Union [ base . Integer , base . String ] ) -> base . Boolean : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . UNPIN_CHAT_MESSAGE , payload ) return result
Use this method to unpin a message in a supergroup chat . The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
30,753
async def get_chat_administrators ( self , chat_id : typing . Union [ base . Integer , base . String ] ) -> typing . List [ types . ChatMember ] : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . GET_CHAT_ADMINISTRATORS , payload ) return [ types . ChatMember ( ** chatmember ...
Use this method to get a list of administrators in a chat .
30,754
async def get_chat_member ( self , chat_id : typing . Union [ base . Integer , base . String ] , user_id : base . Integer ) -> types . ChatMember : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . GET_CHAT_MEMBER , payload ) return types . ChatMember ( ** result )
Use this method to get information about a member of a chat .
30,755
async def set_chat_sticker_set ( self , chat_id : typing . Union [ base . Integer , base . String ] , sticker_set_name : base . String ) -> base . Boolean : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . SET_CHAT_STICKER_SET , payload ) return result
Use this method to set a new group sticker set for a supergroup . The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
30,756
async def delete_chat_sticker_set ( self , chat_id : typing . Union [ base . Integer , base . String ] ) -> base . Boolean : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . DELETE_CHAT_STICKER_SET , payload ) return result
Use this method to delete a group sticker set from a supergroup . The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
30,757
async def stop_poll ( self , chat_id : typing . Union [ base . String , base . Integer ] , message_id : base . Integer , reply_markup : typing . Union [ types . InlineKeyboardMarkup , None ] = None ) -> types . Poll : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . STOP_POLL...
Use this method to stop a poll which was sent by the bot . On success the stopped Poll with the final results is returned .
30,758
async def get_sticker_set ( self , name : base . String ) -> types . StickerSet : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . GET_STICKER_SET , payload ) return types . StickerSet ( ** result )
Use this method to get a sticker set .
30,759
async def create_new_sticker_set ( self , user_id : base . Integer , name : base . String , title : base . String , png_sticker : typing . Union [ base . InputFile , base . String ] , emojis : base . String , contains_masks : typing . Union [ base . Boolean , None ] = None , mask_position : typing . Union [ types . Mas...
Use this method to create new sticker set owned by a user . The bot will be able to edit the created sticker set .
30,760
async def set_sticker_position_in_set ( self , sticker : base . String , position : base . Integer ) -> base . Boolean : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . SET_STICKER_POSITION_IN_SET , payload ) return result
Use this method to move a sticker in a set created by the bot to a specific position .
30,761
async def delete_sticker_from_set ( self , sticker : base . String ) -> base . Boolean : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . DELETE_STICKER_FROM_SET , payload ) return result
Use this method to delete a sticker from a set created by the bot .
30,762
async def send_invoice ( self , chat_id : base . Integer , title : base . String , description : base . String , payload : base . String , provider_token : base . String , start_parameter : base . String , currency : base . String , prices : typing . List [ types . LabeledPrice ] , provider_data : typing . Union [ typi...
Use this method to send invoices .
30,763
async def answer_shipping_query ( self , shipping_query_id : base . String , ok : base . Boolean , shipping_options : typing . Union [ typing . List [ types . ShippingOption ] , None ] = None , error_message : typing . Union [ base . String , None ] = None ) -> base . Boolean : if shipping_options : shipping_options = ...
If you sent an invoice requesting a shipping address and the parameter is_flexible was specified the Bot API will send an Update with a shipping_query field to the bot .
30,764
async def answer_pre_checkout_query ( self , pre_checkout_query_id : base . String , ok : base . Boolean , error_message : typing . Union [ base . String , None ] = None ) -> base . Boolean : payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . ANSWER_PRE_CHECKOUT_QUERY , payload...
Once the user has confirmed their payment and shipping details the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query . Use this method to respond to such pre - checkout queries .
30,765
def get_keyboard ( ) -> types . InlineKeyboardMarkup : markup = types . InlineKeyboardMarkup ( ) for post_id , post in POSTS . items ( ) : markup . add ( types . InlineKeyboardButton ( post [ 'title' ] , callback_data = posts_cb . new ( id = post_id , action = 'view' ) ) ) return markup
Generate keyboard with list of posts
30,766
def find_locales ( self ) -> Dict [ str , gettext . GNUTranslations ] : translations = { } for name in os . listdir ( self . path ) : if not os . path . isdir ( os . path . join ( self . path , name ) ) : continue mo_path = os . path . join ( self . path , name , 'LC_MESSAGES' , self . domain + '.mo' ) if os . path . e...
Load all compiled locales from path
30,767
def lazy_gettext ( self , singular , plural = None , n = 1 , locale = None ) -> LazyProxy : return LazyProxy ( self . gettext , singular , plural , n , locale )
Lazy get text
30,768
def on_startup ( self , callback : callable , polling = True , webhook = True ) : self . _check_frozen ( ) if not webhook and not polling : warn ( 'This action has no effect!' , UserWarning ) return if isinstance ( callback , ( list , tuple , set ) ) : for cb in callback : self . on_startup ( cb , polling , webhook ) r...
Register a callback for the startup process
30,769
def on_shutdown ( self , callback : callable , polling = True , webhook = True ) : self . _check_frozen ( ) if not webhook and not polling : warn ( 'This action has no effect!' , UserWarning ) return if isinstance ( callback , ( list , tuple , set ) ) : for cb in callback : self . on_shutdown ( cb , polling , webhook )...
Register a callback for the shutdown process
30,770
def get_requirements ( filename = None ) : if filename is None : filename = 'requirements.txt' file = WORK_DIR / filename install_reqs = parse_requirements ( str ( file ) , session = 'hack' ) return [ str ( ir . req ) for ir in install_reqs ]
Read requirements from requirements txt
30,771
def request_timeout ( self , timeout ) : timeout = self . _prepare_timeout ( timeout ) token = self . _ctx_timeout . set ( timeout ) try : yield finally : self . _ctx_timeout . reset ( token )
Context manager implements opportunity to change request timeout in current context
30,772
async def request ( self , method : base . String , data : Optional [ Dict ] = None , files : Optional [ Dict ] = None , ** kwargs ) -> Union [ List , Dict , base . Boolean ] : return await api . make_request ( self . session , self . __token , method , data , files , proxy = self . proxy , proxy_auth = self . proxy_au...
Make an request to Telegram Bot API
30,773
async def download_file ( self , file_path : base . String , destination : Optional [ base . InputFile ] = None , timeout : Optional [ base . Integer ] = sentinel , chunk_size : Optional [ base . Integer ] = 65536 , seek : Optional [ base . Boolean ] = True ) -> Union [ io . BytesIO , io . FileIO ] : if destination is ...
Download file by file_path to destination
30,774
def get_value ( self , instance ) : return instance . values . get ( self . alias , self . default )
Get value for the current object instance
30,775
def set_value ( self , instance , value , parent = None ) : self . resolve_base ( instance ) value = self . deserialize ( value , parent ) instance . values [ self . alias ] = value self . _trigger_changed ( instance , value )
Set prop value
30,776
def clean ( self ) : for key , value in self . values . copy ( ) . items ( ) : if value is None : del self . values [ key ]
Remove empty values
30,777
def mention ( self ) : if self . username : return '@' + self . username if self . type == ChatType . PRIVATE : return self . full_name return None
Get mention if a Chat has a username or get full name if this is a Private Chat otherwise None is returned
30,778
async def update_chat ( self ) : other = await self . bot . get_chat ( self . id ) for key , value in other : self [ key ] = value
User this method to update Chat data
30,779
async def export_invite_link ( self ) : if not self . invite_link : self . invite_link = await self . bot . export_chat_invite_link ( self . id ) return self . invite_link
Use this method to export an invite link to a supergroup or a channel . The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
30,780
def is_group_or_super_group ( cls , obj ) -> bool : return cls . _check ( obj , [ cls . GROUP , cls . SUPER_GROUP ] )
Check chat is group or super - group
30,781
def get_text ( self , text ) : if sys . maxunicode == 0xffff : return text [ self . offset : self . offset + self . length ] if not isinstance ( text , bytes ) : entity_text = text . encode ( 'utf-16-le' ) else : entity_text = text entity_text = entity_text [ self . offset * 2 : ( self . offset + self . length ) * 2 ] ...
Get value of entity
30,782
def parse ( self , text , as_html = True ) : if not text : return text entity_text = self . get_text ( text ) if self . type == MessageEntityType . BOLD : if as_html : return markdown . hbold ( entity_text ) return markdown . bold ( entity_text ) elif self . type == MessageEntityType . ITALIC : if as_html : return mark...
Get entity value with markup
30,783
def _normalize ( obj ) : if isinstance ( obj , list ) : return [ _normalize ( item ) for item in obj ] elif isinstance ( obj , dict ) : return { k : _normalize ( v ) for k , v in obj . items ( ) if v is not None } elif hasattr ( obj , 'to_python' ) : return obj . to_python ( ) return obj
Normalize dicts and lists
30,784
def _screaming_snake_case ( cls , text ) : if text . isupper ( ) : return text result = '' for pos , symbol in enumerate ( text ) : if symbol . isupper ( ) and pos > 0 : result += '_' + symbol else : result += symbol . upper ( ) return result
Transform text to SCREAMING_SNAKE_CASE
30,785
def _camel_case ( cls , text , first_upper = False ) : result = '' need_upper = False for pos , symbol in enumerate ( text ) : if symbol == '_' and pos > 0 : need_upper = True else : if need_upper : result += symbol . upper ( ) else : result += symbol . lower ( ) need_upper = False if first_upper : result = result [ 0 ...
Transform text to camelCase or CamelCase
30,786
def apply ( cls , text , mode ) : if mode == cls . SCREAMING_SNAKE_CASE : return cls . _screaming_snake_case ( text ) elif mode == cls . snake_case : return cls . _snake_case ( text ) elif mode == cls . lowercase : return cls . _snake_case ( text ) . replace ( '_' , '' ) elif mode == cls . lowerCamelCase : return cls ....
Apply mode for text
30,787
def filter ( self , record : logging . LogRecord ) : update = types . Update . get_current ( True ) if update : for key , value in self . make_prefix ( self . prefix , self . process_update ( update ) ) : setattr ( record , key , value ) return True
Extend LogRecord by data from Telegram Update object .
30,788
def process_update ( self , update : types . Update ) : yield 'update_id' , update . update_id if update . message : yield 'update_type' , 'message' yield from self . process_message ( update . message ) if update . edited_message : yield 'update_type' , 'edited_message' yield from self . process_message ( update . edi...
Parse Update object
30,789
def make_prefix ( self , prefix , iterable ) : if not prefix : yield from iterable for key , value in iterable : yield f"{prefix}_{key}" , value
Add prefix to the label
30,790
def process_user ( self , user : types . User ) : if not user : return yield 'user_id' , user . id if self . include_content : yield 'user_full_name' , user . full_name if user . username : yield 'user_name' , f"@{user.username}"
Generate user data
30,791
def process_chat ( self , chat : types . Chat ) : if not chat : return yield 'chat_id' , chat . id yield 'chat_type' , chat . type if self . include_content : yield 'chat_title' , chat . full_name if chat . username : yield 'chat_name' , f"@{chat.username}"
Generate chat data
30,792
async def process_updates ( self , updates , fast : typing . Optional [ bool ] = True ) : if fast : tasks = [ ] for update in updates : tasks . append ( self . updates_handler . notify ( update ) ) return await asyncio . gather ( * tasks ) results = [ ] for update in updates : results . append ( await self . updates_ha...
Process list of updates
30,793
async def process_update ( self , update : types . Update ) : types . Update . set_current ( update ) try : if update . message : types . User . set_current ( update . message . from_user ) types . Chat . set_current ( update . message . chat ) return await self . message_handlers . notify ( update . message ) if updat...
Process single update object
30,794
async def start_polling ( self , timeout = 20 , relax = 0.1 , limit = None , reset_webhook = None , fast : typing . Optional [ bool ] = True , error_sleep : int = 5 ) : if self . _polling : raise RuntimeError ( 'Polling already started' ) log . info ( 'Start polling.' ) Dispatcher . set_current ( self ) Bot . set_curre...
Start long - polling
30,795
async def _process_polling_updates ( self , updates , fast : typing . Optional [ bool ] = True ) : need_to_call = [ ] for responses in itertools . chain . from_iterable ( await self . process_updates ( updates , fast ) ) : for response in responses : if not isinstance ( response , BaseResponse ) : continue need_to_call...
Process updates received from long - polling .
30,796
def stop_polling ( self ) : if hasattr ( self , '_polling' ) and self . _polling : log . info ( 'Stop polling...' ) self . _polling = False
Break long - polling process .
30,797
def register_message_handler ( self , callback , * custom_filters , commands = None , regexp = None , content_types = None , state = None , run_task = None , ** kwargs ) : filters_set = self . filters_factory . resolve ( self . message_handlers , * custom_filters , commands = commands , regexp = regexp , content_types ...
Register handler for message
30,798
def message_handler ( self , * custom_filters , commands = None , regexp = None , content_types = None , state = None , run_task = None , ** kwargs ) : def decorator ( callback ) : self . register_message_handler ( callback , * custom_filters , commands = commands , regexp = regexp , content_types = content_types , sta...
Decorator for message handler
30,799
def edited_message_handler ( self , * custom_filters , commands = None , regexp = None , content_types = None , state = None , run_task = None , ** kwargs ) : def decorator ( callback ) : self . register_edited_message_handler ( callback , * custom_filters , commands = commands , regexp = regexp , content_types = conte...
Decorator for edited message handler