Bot

class bale.Bot(token, **kwargs)

Bases: object

This object represents a Bale Bot.

Parameters:

token (str) – Bot Token

Attention

When you create a bot and run for first-step, use bale.Bot.delete_webhook() method in on_before_ready event.

Examples

My First Bot

async ban_chat_member(chat_id, user_id)

Use this method to ban a user from a group, supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first.

await bot.ban_chat_member(1234, 1234)
Parameters:
  • chat_id (Union[int, str]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • user_id (Union[int, str]) – Unique identifier of the target user.

Returns:

On success, True is returned.

Return type:

bool

Raises:
  • NotFound – Invalid Chat or User ID.

  • Forbidden – You do not have permission to ban Chat Member.

  • APIError – ban chat member Failed.

property chats

Represents the chats that the bot has ever encountered.

Type:

weakref.WeakValueDictionary`[:class:`str, bale.Chat]

async close()

Close http Events and bot

async delete_message(chat_id, message_id, *, delay=None)

You can use this service to delete a message that you have already sent through the arm.

await bot.delete_message(1234, 1234)

Warning

In channels or groups, only when the admin can delete other people’s messages. Otherwise, It’s no limit to delete his own message.

Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • message_id (bale.Message) – Unique identifier for the message to delete.

  • delay (Optional[Union[int, float]]) – If used, the message will be deleted after that number of seconds delay.

Raises:
  • NotFound – Invalid Message or Chat ID.

  • Forbidden – You do not have permission to Delete Message.

  • APIError – Delete Message Failed.

async delete_webhook()

This service is used to remove the webhook set for the bot.

await bot.delete_webhook()
Returns:

On success, True is returned.

Return type:

bool

Raises:
  • Forbidden – You do not have permission to delete Webhook.

  • APIError – Delete webhook Failed.

async edit_message(chat_id, message_id, text, *, components=None)

You can use this service to edit text messages that you have already sent through the arm.

await bot.edit_message(1234, 1234, "this is tested", components=None)
Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • message_id (Union[str, int]) – Unique identifier for the message to edit.

  • text (str) – New text of the message, 1- 4096 characters after entities parsing.

  • components (Optional[Union[bale.InlineKeyboardMarkup, bale.MenuKeyboardMarkup]]) – An object for an inline keyboard.

Raises:
  • NotFound – Invalid Message or Chat ID.

  • Forbidden – You do not have permission to Edit Message.

  • APIError – Edit Message Failed.

event(coro)

Set wrapper or listener for selected event (the name of function).

@bot.event
async def on_message(message: bale.Message):
    ...

Hint

The name of the function for which you write the decorator is considered the name of the event.

async forward_message(chat_id, from_chat_id, message_id)

This service is used to send text messages.

await bot.forward_message(1234, 1234, 1234)
Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • from_chat_id (Union[str, int]) – the chat where the original message was sent (or channel username in the format @channelusername).

  • message_id (Union[int, str]) – Message in the chat specified in from_chat_id.

Returns:

The Message

Return type:

bale.Message

Raises:
  • NotFound – Invalid Chat ID.

  • Forbidden – You do not have permission to send Message to this chat.

  • APIError – Forward Message Failed.

async get_chat(chat_id, *, use_cache=True)

Use this method to get up-to-date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.).

await bot.get_chat(1234)
...
await bot.get_chat("1234")
Parameters:
  • chat_id (Union[int, str]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • use_cache (Optional[bool]) – Use of caches stored in relation to chats.

Returns:

The chat or None if not found.

Return type:

Optional[bale.Chat]

Raises:
  • Forbidden – You do not have permission to get Chat.

  • APIError – Get chat Failed.

async get_chat_administrators(chat_id)

Use this method to get a list of administrators in a chat.

await bot.get_chat_administrators(1234)
Parameters:

chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

Returns:

list of chat member.

Return type:

List[bale.ChatMember]

Raises:
  • NotFound – Invalid Chat ID.

  • Forbidden – You do not have permission to get Administrators of the Chat.

  • APIError – get Administrators of the Chat from chat Failed.

async get_chat_member(chat_id, user_id)

Use this method to get information about a member of a chat. The method is only guaranteed to work for other users if the bot is an administrator in the chat.

await bot.get_chat_member(1234, 1234)

Warning

Just only when the admin can ban member(s).

Parameters:
  • chat_id (Union[int, str]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • user_id (Union[int, str]) – Unique identifier of the target user.

Returns:

The chat member of None if not found.

Return type:

Optional[bale.ChatMember]

Raises:
  • NotFound – Invalid Chat or User ID.

  • Forbidden – You do not have permission to get Chat Member.

  • APIError – Get chat member Failed.

async get_chat_members_count(chat_id)

Use this method to get the number of members in a chat.

await bot.get_chat_members_count(1234)
Parameters:

chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

Raises:
  • NotFound – Invalid Chat ID.

  • Forbidden – You do not have permission to get Members count of the Chat.

  • APIError – get Members count of the Chat Failed.

Returns:

The members count of the chat

Return type:

int

async get_file(file_id)

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 20 MB in size.

await bot.get_file("FILE_ID")
Parameters:

file_id (str) – Either the file identifier to get file information about.

Returns:

The content of the file

Return type:

bytes

Raises:
  • NotFound – Invalid file ID.

  • Forbidden – You do not have permission to download File.

  • APIError – download File Failed.

async get_me()

Get bot information

Returns:

Bot User information.

Return type:

bale.User

Raises:

APIError – Get bot Failed.

async get_user(user_id, *, use_cache=True)

This Method almost like bale.Bot.get_chat() , but this a filter that only get user.

await bot.get_user(1234)
...
await bot.get_user("1234")
Parameters:
  • user_id (Union[int, str]) – Unique identifier for the target chat.

  • use_cache (Optional[bool]) – Use of caches stored in relation to chats.

Returns:

The user or None if not found.

Return type:

Optional[bale.User]

Raises:
  • Forbidden – You do not have permission to get User.

  • APIError – Get user Failed.

http_is_closed()

bool: HTTPClient Status

async invite_user(chat_id, user_id)

Invite user to the chat

await bot.get_chat(1234, 1234)
Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • user_id (Union[str, int]) – Unique identifier for the target user.

Raises:
  • NotFound – Invalid Chat or User ID.

  • Forbidden – You do not have permission to Add user to Chat.

  • APIError – Invite user Failed.

is_closed()

bool: Bot Status

async leave_chat(chat_id)

Use this method for your bot to leave a group, channel.

await bot.leave_chat(1234)
Parameters:

chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

Raises:
  • Forbidden – You do not have permission to Leave from chat.

  • APIError – Leave from chat Failed.

listen(event_name)

Set wrapper or listener for selected event (custom function name).

@bot.listen("on_message")
async def _message(message: bale.Message):
    ...
Parameters:

event_name (str) – Name of the event to set.

async on_error(event_name, error)

an Event for get errors when exceptions

async promote_chat_member(chat_id, user_id, can_be_edited=None, can_change_info=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_invite_users=None, can_restrict_members=None, can_pin_messages=None, can_promote_members=None, can_send_messages=None, can_send_media_messages=None, can_reply_to_story=None, can_send_link_message=None, can_send_forwarded_message=None, can_see_members=None, can_add_story=None)

an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user.

await bot.promote_chat_member(1234, 1234, can_change_info = True)
Parameters:
  • chat_id (Union[int, str]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • user_id (Union[int, str]) – Unique identifier of the target user.

  • can_be_edited (bool) – Pass True, if the bot is allowed to edit administrator privileges of that user.

  • can_change_info (bool) – Pass True, if the user can change the chat title, photo and other settings.

  • can_post_messages (bool) – Pass True, if the administrator can post messages in the channel, or access channel statistics; channels only.

  • can_edit_messages (bool) – Pass True, if the administrator can edit messages of other users and can pin messages; channels only.

  • can_delete_messages (bool) – Pass True, if the administrator can delete messages of other users.

  • can_invite_users (bool) – Pass True, if the user can invite new users to the chat.

  • can_restrict_members (bool) – Pass True, if the administrator can restrict, ban or unban chat members.

  • can_pin_messages (bool) – Pass True, if the user is allowed to pin messages, groups, channels only.

  • can_promote_members (bool) – Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by the user).

  • can_send_messages (bool) – Pass True, if the user is allowed to send messages.

  • can_send_media_messages (bool) – Pass True, if the user is allowed to send a media message.

  • can_reply_to_story (bool) – Pass True, if the user is allowed to reply to a story.

  • can_send_link_message (bool) – Pass True, if the user is allowed to send a link message.

  • can_send_forwarded_message (bool) – Pass True, if the user is allowed to forward a message to chat.

  • can_see_members (bool) – Pass True, if the user is allowed to see the list of chat members.

  • can_add_story (bool) – Pass True, if the user is allowed to post a story from chat.

Returns:

On success, True is returned.

Return type:

bool

Raises:
  • NotFound – Invalid Chat or User ID.

  • Forbidden – You do not have permission to promote Chat Member.

  • APIError – Promote chat member Failed.

run()

Starting the bot, updater and HTTPClient.

async send_animation(chat_id, animation, *, duration=None, width=None, height=None, caption=None, components=None, reply_to_message_id=None, delete_after=None)

This service is used to send Animation.

await bot.send_animation(1234, bale.InputFile("FILE_ID"), caption = "this is a caption", ...)
Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • animation (bale.InputFile) – File to send. visit bale.InputFile to see more info.

  • duration (int) – Duration of sent animation in seconds.

  • width (int) – Animation width.

  • height (int) – Animation height.

  • caption (Optional[str]) – Animation caption.

  • components (Optional[Union[bale.InlineKeyboardMarkup, bale.MenuKeyboardMarkup]]) – Message Components

  • reply_to_message_id (Optional[Union[str, int]]) – If the message is a reply, ID of the original message.

  • delete_after (Optional[Union[float, int]]) – If used, the sent message will be deleted after the specified number of seconds.

Returns:

The Message.

Return type:

bale.Message

Raises:
  • NotFound – Invalid Chat ID.

  • Forbidden – You do not have permission to Send Animation to chat.

  • APIError – Send Animation Failed.

async send_audio(chat_id, audio, *, caption=None, components=None, reply_to_message_id=None, delete_after=None)

This service is used to send Audio.

await bot.send_audio(1234, bale.InputFile("FILE_ID"), caption = "this is a caption", ...)
Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • audio (bale.InputFile) – File to send. visit bale.InputFile to see more info.

  • caption (Optional[str]) – Audio caption.

  • components (Optional[Union[bale.InlineKeyboardMarkup, bale.MenuKeyboardMarkup]]) – Message Components

  • reply_to_message_id (Optional[Union[str, int]]) – If the message is a reply, ID of the original message.

  • delete_after (Optional[Union[float, int]]) – If used, the sent message will be deleted after the specified number of seconds.

Returns:

The Message.

Return type:

bale.Message

Raises:
  • NotFound – Invalid Chat ID.

  • Forbidden – You do not have permission to Send Audio to chat.

  • APIError – Send Audio Failed.

async send_contact(chat_id, contact, components=None, reply_to_message_id=None, delete_after=None)

This service is used to send contact.

await bot.send_cantact(1234, bale.Contact('09****', 'first name', 'last name'))
Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • contact (bale.Contact) – The Contact.

  • components (Optional[Union[bale.InlineKeyboardMarkup, bale.MenuKeyboardMarkup]]) – Message Components

  • reply_to_message_id (Optional[Union[str, int]]) – If the message is a reply, ID of the original message.

  • delete_after (Optional[Union[float, int]]) – If used, the sent message will be deleted after the specified number of seconds.

Returns:

The Message.

Return type:

bale.Message

Raises:
  • NotFound – Invalid Chat ID.

  • Forbidden – You do not have permission to send Contact Message to this chat.

  • APIError – Send Contact Message Failed.

async send_document(chat_id, document, *, caption=None, components=None, reply_to_message_id=None, delete_after=None)

This service is used to send document.

await bot.send_document(1234, bale.InputFile("FILE_ID"), caption = "this is a caption", ...)
Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • document (bale.InputFile) – File to send. visit bale.InputFile to see more info.

  • caption (Optional[str]) – Document caption.

  • components (Optional[Union[bale.InlineKeyboardMarkup, bale.MenuKeyboardMarkup]]) – Message Components

  • reply_to_message_id (Optional[Union[str, int]]) – If the message is a reply, ID of the original message.

  • delete_after (Optional[Union[float, int]]) – If used, the sent message will be deleted after the specified number of seconds.

Returns:

The Message.

Return type:

bale.Message

Raises:
  • NotFound – Invalid Chat ID.

  • Forbidden – You do not have permission to send Document to this chat.

  • APIError – Send Document Failed.

async send_invoice(chat_id, title, description, provider_token, prices, *, payload=None, photo_url=None, need_name=False, need_phone_number=False, need_email=False, need_shipping_address=False, is_flexible=True, delete_after=None)

You can use this service to send money request messages.

Important

When paying the amount, a fee will be charged from the sender.

Hint

The on_successful_payment event is called when the sent transaction is done.

await bot.send_invoice(
    1234, "invoice title", "invoice description", "6037************", [bale.LabeledPrice("label", 2000)],
    payload = "unique invoice payload", ...
)

Examples

Payment Bot

Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • title (str) – Product name. 1- 32 characters.

  • description (str) – Product description. 1- 255 characters.

  • provider_token (str) – You can use 3 methods to receive money: 1.Card number 2. Port number and acceptor number 3. Wallet number “Bale”

  • prices (List[bale.LabeledPrice]) – A list of prices.

  • payload (Optional[str]) – Bot-defined invoice payload. This will not be displayed to the user, use for your internal processes.

  • photo_url (Optional[str]) – URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for.

  • need_name (Optional[bool]) – Pass True, if you require the user’s full name to complete the order.

  • need_phone_number (Optional[bool]) – Pass True, if you require the user’s phone number to complete the order.

  • need_email (Optional[bool]) – Pass True, if you require the user’s email to complete the order.

  • need_shipping_address (Optional[bool]) – Pass True, if you require the user’s shipping address to complete the order.

  • is_flexible (Optional[bool]) – Pass True, if the final price depends on the shipping method.

  • delete_after (Optional[Union[float, int]]) – If used, the sent message will be deleted after the specified number of seconds.

Return type:

bale.Message

Raises:
  • NotFound – Invalid Chat ID.

  • Forbidden – You do not have permission to send Invoice to this chat.

  • APIError – Send Invoice Failed.

async send_location(chat_id, location, components=None, reply_to_message_id=None, delete_after=None)

Use this method to send point on the map.

await bot.send_location(1234, bale.Location(35.71470468031143, 51.8568519168293))
Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • location (bale.Location) – The Location.

  • components (Optional[Union[bale.InlineKeyboardMarkup, bale.MenuKeyboardMarkup]]) – Message Components

  • reply_to_message_id (Optional[Union[str, int]]) – If the message is a reply, ID of the original message.

  • delete_after (Optional[Union[float, int]]) – If used, the sent message will be deleted after the specified number of seconds.

Returns:

The Message.

Return type:

bale.Message

Raises:
  • NotFound – Invalid Chat ID.

  • Forbidden – You do not have permission to send Location to this chat.

  • APIError – Send Location Failed.

async send_message(chat_id, text, *, components=None, reply_to_message_id=None, delete_after=None)

This service is used to send text messages.

await bot.send_message(1234, "hi, python-bale-bot!", ...)
Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • text (str) – Text of the message to be sent. Max 4096 characters after entities parsing.

  • components (Optional[Union[bale.InlineKeyboardMarkup, bale.MenuKeyboardMarkup]]) – Message Components

  • reply_to_message_id (Optional[Union[str, int]]) – If the message is a reply, ID of the original message.

  • delete_after (Optional[Union[float, int]]) – If used, the sent message will be deleted after the specified number of seconds.

Returns:

The Message

Return type:

bale.Message

Raises:
  • NotFound – Invalid Chat ID.

  • Forbidden – You do not have permission to send Message to this chat.

  • APIError – Send Message Failed.

async send_photo(chat_id, photo, *, caption=None, components=None, reply_to_message_id=None, delete_after=None)

This service is used to send photo.

await bot.send_photo(1234, bale.InputFile("FILE_ID"), caption = "this is a caption", ...)
Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • photo (bale.InputFile) – File to send. visit bale.InputFile to see more info.

  • caption (Optional[str]) – Photo caption.

  • components (Optional[Union[bale.InlineKeyboardMarkup, bale.MenuKeyboardMarkup]]) – Message Components

  • reply_to_message_id (Optional[Union[str, int]]) – If the message is a reply, ID of the original message.

  • delete_after (Optional[Union[float, int]]) – If used, the sent message will be deleted after the specified number of seconds.

Returns:

The Message.

Return type:

bale.Message

Raises:
  • NotFound – Invalid Chat ID.

  • Forbidden – You do not have permission to Send Photo to chat.

  • APIError – Send photo Failed.

async send_video(chat_id, video, *, caption=None, components=None, reply_to_message_id=None, delete_after=None)

This service is used to send Video.

await bot.send_video(1234, bale.InputFile("FILE_ID"), caption = "this is a caption", ...)
Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • video (bale.InputFile) – File to send. visit bale.InputFile to see more info.

  • caption (Optional[str]) – Video caption.

  • components (Optional[Union[bale.InlineKeyboardMarkup, bale.MenuKeyboardMarkup]]) – Message Components

  • reply_to_message_id (Optional[Union[str, int]]) – If the message is a reply, ID of the original message.

  • delete_after (Optional[Union[float, int]]) – If used, the sent message will be deleted after the specified number of seconds.

Returns:

The Message.

Return type:

bale.Message

Raises:
  • NotFound – Invalid Chat ID.

  • Forbidden – You do not have permission to Send Video to chat.

  • APIError – Send Video Failed.

async set_chat_photo(chat_id, photo)

Use this method to set a new profile photo for the chat.

await bot.set_chat_photo(1234, bale.InputFile("FILE_ID"))
Parameters:
  • chat_id (Union[str, int]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • photo (bale.InputFile) – New chat photo. visit bale.InputFile to see more info.

Returns:

On success, True is returned.

Return type:

bool

Raises:
  • NotFound – Invalid Chat ID.

  • Forbidden – You do not have permission to Set Chat Photo to chat.

  • APIError – Set chat photo Failed.

async set_webhook(url)

Use this method to specify an url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, Bale will send an HTTPS POST request to the specified url, containing An Update. In case of an unsuccessful request, Bale will give up after a reasonable amount of attempts.

await bot.set_webhook("https://example.com")
Parameters:

url (str) – HTTPS url to send updates to. Use an empty string to remove webhook integration.

Returns:

On success, True is returned.

Return type:

bool

property state

Represents the state class for cache data. None if bot not logged in

Type:

Optional[bale.State]

async unban_chat_member(chat_id, user_id, *, only_if_banned=None)

Use this method to unban a previously kicked user in a group or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don’t want this, use the parameter only_if_banned.

await bot.unban_chat_member(1234, 1234)
Parameters:
  • chat_id (Union[int, str]) – Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • user_id (Union[int, str]) – Unique identifier of the target user.

  • only_if_banned (Optional[bool]) – Do nothing if the user is not banned.

Returns:

On success, True is returned.

Return type:

bool

Raises:
  • NotFound – Invalid Chat or User ID.

  • Forbidden – You do not have permission to unban Chat Member.

  • APIError – unban chat member Failed.

property user

Represents the connected client. None if not logged in

Type:

Optional[bale.User]

property users

Represents the users that the bot has ever encountered.

Type:

weakref.WeakValueDictionary`[:class:`str, bale.User]

wait_for(event_name, *, check=None, timeout=None)

Waits for an event to be dispatched.

This could be used to wait for a user to reply to a message, or send a photo, or to edit a message in a self-contained way. The timeout parameter is passed onto asyncio.wait_for(). By default, it does not timeout. Note that this does propagate the asyncio.TimeoutError for you in case of timeout and is provided for ease of use. In case the event returns multiple arguments, a tuple containing those arguments is returned instead. This function returns the first event that meets the requirements.

message = await bot.wait_for("message", check = lambda m: m.author.user_id == '1234')
...
try:
    message = await bot.wait_for("message", ..., timeout = 20.0)
except asyncio.TimeoutError: # 20s A message with the conditions specified in the `check` parameter was not found.
    pass

Examples

conversation Bot

Parameters:
  • event_name (str) – Name of the event

  • check (Optional[Callable[…, bool]]) – A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.

  • timeout (Optional[float]) – The number of seconds to wait before timing out and raising asyncio.TimeoutError.

Raises:

asyncio.TimeoutError – If a timeout is provided, and it was reached.