API Reference

Bot

class vk_botting.bot.Bot(command_prefix, description=None, **options)

Represents a VK bot. This class is a subclass of vk_botting.client.Client and as a result anything that you can do with a vk_botting.client.Client you can do with this bot.

This class also subclasses GroupMixin to provide the functionality to manage commands.

command_prefix

The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and Message as its second parameter and returns the prefix. This is to facilitate “dynamic” command prefixes. This callable can be either a regular function or a coroutine.

The command prefix could also be an iterable of strings indicating that multiple checks for the prefix should be used and the first one to match will be the invocation prefix. You can get this prefix via Context.prefix. To avoid confusion empty iterables are not allowed.

Note

When passing multiple prefixes be careful to not pass a prefix that matches a longer prefix occurring later in the sequence. For example, if the command prefix is ('!', '!?') the '!?' prefix will never be matched to any message as the previous one matches messages starting with !?. This is especially important when passing an empty string, it should always be last as no prefix after it will be matched.

case_insensitive

Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well.

Type

bool

self_bot

If True, the bot will only listen to commands invoked by itself rather than ignoring itself. If False (the default) then the bot will ignore itself. This cannot be changed once initialised.

Type

bool

v

VK API version. Defaults to ‘5.131’ (latest currently supported)

Warning

Library is not intended to be used with API Version lower than ‘5.131’ or higher than ‘5.131

Type

str

force

If bot should force optimal longpoll settings automatically

Type

bool

lang

Lang parameter for API requests

Type

str

add_check(func, *, call_once=False)

Adds a global check to the bot. This is the non-decorator interface to check() and check_once().

Parameters
  • func – The function that was used as a global check.

  • call_once (bool) – If the function should only be called once per Command.invoke() call.

add_cog(cog)

Adds a “cog” to the bot. A cog is a class that has its own event listeners and commands.

Parameters

cog (Cog) – The cog to register to the bot.

Raises
add_command(command)

Adds a Command or its subclasses into the internal list of commands.

This is usually not called, instead the command() shortcut decorator are used instead.

Parameters

command (Command) – The command to add.

Raises
add_listener(func, name=None)

The non decorator alternative to listen().

Parameters
  • func (coroutine) – The function to call.

  • name (Optional[str]) – The name of the event to listen for. Defaults to func.__name__.

Example

async def on_ready(): pass
async def my_message(message): pass
bot.add_listener(on_ready)
bot.add_listener(my_message, 'on_message_new')
await add_user_token(token)

This function is a coroutine. Alternative for Client.attach_user_token()

after_invoke(coro)

A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required. This post-invoke hook takes a sole parameter, a Context.

Note

Similar to before_invoke(), this is not called unless checks and argument parsing procedures succeed. This hook is, however, always called regardless of the internal command callback raising an error (i.e. CommandInvokeError). This makes it ideal for clean-up scenarios.

Parameters

coro (coroutine) – The coroutine to register as the post-invoke hook.

Raises

TypeError – The coroutine passed is not actually a coroutine.

await attach_user_token(token)

This function is a coroutine.

Attaches user token to the bot, enabling it to execute API calls available to users only.

Also puts User object corresponding to the token into self.user

Parameters

token (str) – User token to attach

before_invoke(coro)

A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required. This pre-invoke hook takes a sole parameter, a Context.

Note

The before_invoke() and after_invoke() hooks are only called if all checks and argument parsing procedures pass without error. If any check or argument parsing procedures fail then the hooks are not called.

Parameters

coro (coroutine) – The coroutine to register as the pre-invoke hook.

Raises

TypeError – The coroutine passed is not actually a coroutine.

exception botCommandException
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

build_msg(msg)

Build Message instance from message object dict.

Normally should not be used at all.

Parameters

msg (dict) – dict representation of Message object returned by VK API

Returns

Message instance representing original object

Return type

Message

check(func)

A decorator that adds a global check to the bot. A global check is similar to a check() that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.

Note

This function can either be a regular function or a coroutine.

Similar to a command check(), this takes a single parameter of type Context and can only raise exceptions inherited from CommandError. .. rubric:: Example

@bot.check
def check_commands(ctx):
    return ctx.command.qualified_name in allowed_commands
check_once(func)

A decorator that adds a “call once” global check to the bot. Unlike regular global checks, this one is called only once per Command.invoke() call. Regular global checks are called whenever a command is called or Command.can_run() is called. This type of check bypasses that and ensures that it’s called only once, even inside the default help command.

Note

This function can either be a regular function or a coroutine.

Similar to a command check(), this takes a single parameter of type Context and can only raise exceptions inherited from CommandError.

Example

@bot.check_once
def whitelist(ctx):
    return ctx.message.author.id in my_whitelist
cogs

A read-only mapping of cog name to cog.

Type

Mapping[str, Cog]

command(*args, **kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_command().

commands

A unique set of commands without aliases that are registered.

Type

Set[Command]

extensions

A read-only mapping of extension name to extension.

Type

Mapping[str, types.ModuleType]

get_cog(name)

Gets the cog instance requested. If the cog is not found, None is returned instead.

Parameters

name (str) – The name of the cog you are requesting. This is equivalent to the name passed via keyword argument in class creation or the class name if unspecified.

get_command(name)

Get a Command or subclasses from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters

name (str) – The name of the command to get.

Returns

The command that was requested. If not found, returns None.

Return type

Command or subclass

await get_context(message, *, cls=<class 'vk_botting.context.Context'>)

This function is a coroutine.

Returns the invocation context from the message. This is a more low-level counter-part for process_commands() to allow users more fine grained control over the processing. The returned context is not guaranteed to be a valid invocation context, Context.valid must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under invoke().

Parameters
  • message (Message) – The message to get the invocation context from.

  • cls – The factory class that will be used to create the context. By default, this is Context. Should a custom class be provided, it must be similar enough to Context’s interface.

Returns

The invocation context. The type of this can change via the cls parameter.

Return type

Context

await get_group(gid)

This function is a coroutine.

Alias for VK Api ‘groups.get’ method call that returns only one group.

Parameters

gid (int) – Id of group to request

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Group instance for requested group

Return type

Group

await get_groups(*gids)

This function is a coroutine.

Alias for VK Api ‘groups.get’ method call

Parameters

gids (List[int]) – List of group ids to request

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

List of Group instances for requested groups

Return type

List[Group]

await get_own_page()

This function is a coroutine.

Gets page for current token, whether it is Group or User

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Group or User instance for current token

Return type

Union[Group, User]

await get_page(pid, fields=None, name_case=None)

This function is a coroutine.

Gets page for given id, whether it is Group or User

Parameters
  • pid (int) – Id of page to request

  • fields (List[str]) – Optional. Fields that should be requested from VK Api for users. None by default

  • name_case (str) – Optional. Name case for user’s name to be returned in. ‘nom’ by default. Can be ‘nom’, ‘gen’, ‘dat’, ‘acc’, ‘ins’ or ‘abl’

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Group or User instance for requested id

Return type

Union[Group, User]

await get_pages(*ids, fields=None, name_case=None)

This function is a coroutine.

Gets pages for given ids, whether it is Group or User

Parameters
  • ids (List[int]) – List of ids to request

  • fields (List[str]) – Optional. Fields that should be requested from VK Api for users. None by default

  • name_case (str) – Optional. Name case for users’ names to be returned in. ‘nom’ by default. Can be ‘nom’, ‘gen’, ‘dat’, ‘acc’, ‘ins’ or ‘abl’

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

List of Group or User instances for requested ids

Return type

List[Union[Group, User]]

await get_prefix(message)

This function is a coroutine.

Retrieves the prefix the bot is listening to with the message as a context.

Parameters

message (Message) – The message context to get the prefix of.

Returns

A list of prefixes or a single prefix that the bot is listening for.

Return type

Union[List[str], str]

await get_user(uid, fields=None, name_case=None)

This function is a coroutine.

Alias for VK Api ‘users.get’ method call that returns only one user.

Parameters
  • uid (int) – Id of user to request

  • fields (List[str]) – Optional. Fields that should be requested from VK Api. None by default

  • name_case (str) – Optional. Name case for user’s name to be returned in. ‘nom’ by default. Can be ‘nom’, ‘gen’, ‘dat’, ‘acc’, ‘ins’ or ‘abl’

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

User instance for requested user

Return type

User

await get_users(*uids, fields=None, name_case=None)

This function is a coroutine.

Alias for VK Api ‘users.get’ method call

Parameters
  • uids (List[int]) – List of user ids to request

  • fields (List[str]) – Optional. Fields that should be requested from VK Api. None by default

  • name_case (str) – Optional. Name case for users’ names to be returned in. ‘nom’ by default. Can be ‘nom’, ‘gen’, ‘dat’, ‘acc’, ‘ins’ or ‘abl’

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

List of User instances for requested users

Return type

List[User]

await invoke(ctx)

This function is a coroutine.

Invokes the command given under the invocation context and handles all the internal event dispatch mechanisms.

Parameters

ctx (Context) – The invocation context to invoke.

listen(name=None)

A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as on_ready() The functions being listened to must be a coroutine.

Example

@bot.listen()
async def on_message_new(message):
    print('one')
# in some other file...
@bot.listen('on_message_new')
async def my_message(message):
    print('two')

Would print one and two in an unspecified order.

Raises

TypeError – The function being listened to is not a coroutine.

load_extension(name)

Loads an extension. An extension is a python module that contains commands, cogs, or listeners. An extension must have a global function, setup defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the bot.

Parameters

name (str) – The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

Raises
await on_command_error(context, exception)

This function is a coroutine. The default command error handler provided by the bot. By default this prints to sys.stderr however it could be overridden to have a different implementation. This only fires if you do not specify any listeners for command error.

await on_error(event_method, *args, **kwargs)

This function is a coroutine.

The default error handler provided by the client.

By default this prints to sys.stderr however it could be overridden to have a different implementation.

Check vk_botting.on_error() for more details.

await process_commands(message)

This function is a coroutine.

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the on_message_new() event. If you choose to override the on_message_new() event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to get_context() followed by a call to invoke().

This also checks if the message’s author is a bot and doesn’t call get_context() or invoke() if so.

Parameters

message (Message) – The message to process commands for.

reload_extension(name)

Atomically reloads an extension. This replaces the extension with the same extension, only refreshed. This is equivalent to a unload_extension() followed by a load_extension() except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.

Parameters

name (str) – The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

Raises
remove_check(func, *, call_once=False)

Removes a global check from the bot. This function is idempotent and will not raise an exception if the function is not in the global checks.

Parameters
  • func – The function to remove from the global checks.

  • call_once (bool) – If the function was added with call_once=True in the Bot.add_check() call or using check_once().

remove_cog(name)

Removes a cog from the bot. All registered commands and event listeners that the cog has registered will be removed as well. If no cog is found then this method has no effect.

Parameters

name (str) – The name of the cog to remove.

remove_command(name)

Remove a Command or subclasses from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters

name (str) – The name of the command to remove.

Returns

The command that was removed. If the name is not valid then None is returned instead.

Return type

Command or subclass

remove_listener(func, name=None)

Removes a listener from the pool of listeners.

Parameters
  • func – The function that was used as a listener to remove.

  • name (str) – The name of the event we want to remove. Defaults to func.__name__.

run(token, owner_id=None)

A blocking call that abstracts away the event loop initialisation from you.

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.

Parameters
  • token (str) – Bot token. Should be group token or user token with access to group

  • owner_id (int) – Should only be passed alongside user token. Owner id of group to connect to

await send_message(peer_id=None, message=None, attachment=None, sticker_id=None, keyboard=None, reply_to=None, forward_messages=None, forward=None, **kwargs)

This function is a coroutine.

Sends a message to the given destination with the text given.

The content must be a type that can convert to a string through str(message).

If the content is set to None (the default), then the attachment or sticker_id parameter must be provided.

If the attachment parameter is provided, it must be str, List[str], Attachment or List[Attachment]

If the keyboard parameter is provided, it must be str or Keyboard (recommended)

Parameters
  • peer_id (int) – Id of conversation to send message to

  • message (str) – The text of the message to send.

  • attachment (Union[List[str], str, List[Attachment], Attachment]) – The attachment to the message sent.

  • sticker_id (Union[str, int]) – Sticker_id to be sent.

  • keyboard (Keyboard) – The keyboard to send along message.

  • reply_to (Union[str, int]) – A message id to reply to.

  • forward_messages (Union[List[int], List[str]]) – Message ids to be forwarded along with message.

  • forward (dict) – Check docs for more details on this one.

  • as_user (bool) – If message should be sent as user (using attached user token).

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

The message that was sent.

Return type

Message

unload_extension(name)

Unloads an extension. When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported. The extension can provide an optional global function, teardown, to do miscellaneous clean-up if necessary. This function takes a single parameter, the bot, similar to setup from load_extension().

Parameters

name (str) – The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

Raises

ExtensionNotLoaded – The extension was not loaded.

await upload_document(peer_id, file, type=<DocType.DOCUMENT: 'doc'>, title=None)

This function is a coroutine.

Upload a document to conversation with given peer_id.

Returns ready-to-use in send_message attachment.

Parameters
  • peer_id (int) – Peer_id of the destination. The uploaded document cannot be used outside of given conversation.

  • file (str) – Path to document to upload. Can be relative.

  • type (str) – Uploaded document type. Can be value from DocType enum.

  • title (str) – Title for uploaded document. Filename by default.

Returns

Attachment instance representing uploaded document.

Return type

Attachment

await upload_image_to_server(server, filename=None, url=None, raw=None, format=None)

This function is a coroutine.

Upload an image to some VK upload server.

Returns dict representation of server response.

Parameters
  • server (str) – Upload server url. Can be requested from API methods like photos.getUploadServer.

  • filename (str) – Path to image to upload. Can be relative.

  • url (str) – Url of image to upload. Should be a direct url to supported image format, otherwise wont work.

  • raw (bytes) – Raw bytes of image to upload. If used, format has to be provided.

  • format (str) – Extension of image to upload. Should be used only alongside raw data.

Returns

dict representation of server response.

Return type

dict

await upload_photo(peer_id, filename=None, url=None, raw=None, format=None)

This function is a coroutine.

Upload a photo to conversation with given peer_id.

Returns ready-to-use in send_message attachment.

Parameters
  • peer_id (int) – Peer_id of the destination. The uploaded photo cannot be used outside of given conversation.

  • filename (str) – Path to image to upload. Can be relative.

  • url (str) – Url of image to upload. Should be a direct url to supported image format, otherwise wont work.

  • raw (bytes) – Raw bytes of image to upload. If used, format has to be provided.

  • format (str) – Extension of image to upload. Should be used only alongside raw data.

Returns

Attachment instance representing uploaded photo.

Return type

Attachment

await user_vk_request(method, post=True, **kwargs)

This function is a coroutine.

Implements abstract VK Api method request with attached User token.

Parameters
  • method (str) – String representation of method name (e.g. ‘users.get’)

  • post (bool) – If request should be POST. Defaults to true. Changing this is not recommended

  • kwargs (Any) –

    Payload arguments to send along with request

    Note

    access_token and v parameters should not be passed as they are automatically added from current bot attributes

Returns

Dict representation of json response received from the server

Return type

dict

await vk_request(method, post=True, **kwargs)

This function is a coroutine.

Implements abstract VK Api method request.

Parameters
  • method (str) – String representation of method name (e.g. ‘users.get’)

  • post (bool) – If request should be POST. Defaults to true. Changing this is not recommended

  • kwargs (Any) –

    Payload arguments to send along with request

    Note

    access_token and v parameters should not be passed as they are automatically added from current bot attributes

Returns

Dict representation of json response received from the server

Return type

dict

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

This function is a coroutine.

Waits for an event to be dispatched.

This could be used to wait for a user to reply to a message or to edit a message in a self-containedway.

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. Please check the documentation for a list of events and their parameters.

This function returns the first event that meets the requirements.

Examples

Waiting for a user reply:

@bot.command()
async def greet(ctx):
    await ctx.send('Say hello!')
    def check(m):
        return m.text == 'hello' and m.from_id == ctx.from_id
    msg = await bot.wait_for('message_new', check=check)
    await ctx.send('Hello {.from_id}!'.format(msg))
Parameters
  • event (str) – The event name, similar to the event reference, but without the on_ prefix, to wait for.

  • 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.

Returns

Returns no arguments, a single argument, or a tuple of multiple arguments that mirrors the parameters passed in the event reference.

Return type

Any

for ... in walk_commands()

An iterator that recursively walks through all commands and subcommands.

vk_botting.bot.when_mentioned(bot, msg)

A callable that implements a command prefix equivalent to being mentioned. These are meant to be passed into the Bot.command_prefix attribute.

vk_botting.bot.when_mentioned_or(*prefixes)

A callable that implements when mentioned or other prefixes provided. These are meant to be passed into the Bot.command_prefix attribute.

Example

bot = Bot(command_prefix=commands.when_mentioned_or('!'))

Note

This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example:

async def get_prefix(bot, message):
    extras = await prefixes_for(message.peer_id) # returns a list
    return commands.when_mentioned_or(*extras)(bot, message)
vk_botting.bot.when_mentioned_or_pm()

A callable that implements when mentioned or bot gets pm. These are meant to be passed into the Bot.command_prefix attribute.

Example

bot = commands.Bot(command_prefix=commands.when_mentioned_or_pm())
vk_botting.bot.when_mentioned_or_pm_or(*prefixes)

A callable that implements when mentioned, pm or other prefixes provided. These are meant to be passed into the Bot.command_prefix attribute.

Example

bot = commands.Bot(command_prefix=commands.when_mentioned_or_pm_or('!'))

Note

This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example:

async def get_prefix(bot, message):
    extras = await prefixes_for(message.peer_id) # returns a list
    return commands.when_mentioned_or(*extras)(bot, message)

Context

class vk_botting.context.Context(**attrs)

Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the Messageable ABC.

message

The message that triggered the command being executed.

Type

Message

bot

The bot that contains the command being executed.

Type

Bot

args

The list of transformed arguments that were passed into the command. If this is accessed during the on_command_error() event then this list could be incomplete.

Type

list

kwargs

A dictionary of transformed arguments that were passed into the command. Similar to args, if this is accessed in the on_command_error() event then this dict could be incomplete.

Type

dict

prefix

The prefix that was used to invoke the command.

Type

str

command

The command (i.e. Command or its subclasses) that is being invoked currently.

invoked_with

The command name that triggered this invocation. Useful for finding out which alias called the command.

Type

str

invoked_subcommand

The subcommand (i.e. Command or its subclasses) that was invoked. If no valid subcommand was invoked then this is equal to None.

subcommand_passed

The string that was attempted to call a subcommand. This does not have to point to a valid registered subcommand and could just point to a nonsense string. If nothing was passed to attempt a call to a subcommand then this is set to None.

Type

Optional[str]

command_failed

A boolean that indicates if the command failed to be parsed, checked, or invoked.

Type

bool

await invoke(*args, **kwargs)

This function is a coroutine.

Calls a command with the arguments given.

This is useful if you want to just call the callback that a Command holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function.

Warning

The first parameter passed must be the command being invoked.

Parameters
  • command (Command) – A command or subclass of a command that is going to be called.

  • *args – The arguments to to use.

  • **kwargs – The keyword arguments to use.

await reinvoke(*, call_hooks=False, restart=True)

This function is a coroutine.

Calls the command again.

This is similar to invoke() except that it bypasses checks, cooldowns, and error handlers.

Note

If you want to bypass ArgumentError derived exceptions, it is recommended to use the regular invoke() as it will work more naturally. After all, this will end up using the old arguments the user has used and will thus just fail again.

Parameters
  • call_hooks (bool) – Whether to call the before and after invoke hooks.

  • restart (bool) – Whether to start the call chain from the very beginning or where we left off (i.e. the command that caused the error). The default is to start where we left off.

await reply(message=None, *, attachment=None, sticker_id=None, keyboard=None)

This function is a coroutine. Shorthand for Message.reply()

await get_user(fields=None, name_case=None)

This function is a coroutine. Returns the author of original message as instance of User class

await get_author(*args, **kwargs)

This function is a coroutine. Alternative for Context.get_user()

await fetch_user(*args, **kwargs)

This function is a coroutine. Alternative for Context.get_user()

await fetch_author(*args, **kwargs)

This function is a coroutine. Alternative for Context.get_user()

cog

Returns the cog associated with this context’s command. None if it does not exist.

valid

Checks if the invocation context is valid to be invoked with.

author

Shorthand for Message.from_id

from_id

Shorthand for Message.from_id

peer_id

Shorthand for Message.peer_id

text

Shorthand for Message.text

me

Returns bot Group or User, depending on whether it is Bot or UserBot

await send(message=None, *, attachment=None, sticker_id=None, keyboard=None, reply_to=None, forward_messages=None)

This function is a coroutine.

Sends a message to the destination with the text given.

The content must be a type that can convert to a string through str(message).

If the content is set to None (the default), then the attachment or sticker_id parameter must be provided.

If the attachment parameter is provided, it must be str, List[str], Attachment or List[Attachment]

If the keyboard parameter is provided, it must be str or Keyboard (recommended)

Parameters
  • message (str) – The text of the message to send.

  • attachment (Union[List[str], str, List[Attachment], Attachment]) – The attachment to the message sent.

  • sticker_id (Union[str, int]) – Sticker_id to be sent.

  • keyboard (Keyboard) – The keyboard to send along message.

  • reply_to (Union[str, int]) – A message id to reply to.

  • forward_messages (Union[List[int], List[str]]) – Message ids to be forwarded along with message.

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

The message that was sent.

Return type

Message

await trigger_typing()

This function is a coroutine.

Triggers typing state of bot.

Can be used instead of typing() in some cases.

Typing state ends in 10 seconds or when message is sent.

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Json payload result of VK API request.

Return type

dict

typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

Note

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with ctx.typing():
    # do expensive stuff here
    await ctx.send('done!')

Event Reference

This page outlines the different types of events listened by Bot.

There are two ways to register an event, the first way is through the use of Bot.listen(). The second way is through subclassing Bot and overriding the specific events. For example:

import vk_botting

class MyBot(vk_botting.Bot):
    async def on_message_new(self, message):
        if message.from_id == self.group.id:
            return

        if message.text.startswith('$hello'):
            await message.send('Hello World!')

If an event handler raises an exception, on_error() will be called to handle it, which defaults to print a traceback and ignoring the exception.

Warning

All the events must be a coroutine. If they aren’t, then you might get unexpected errors. In order to turn a function into a coroutine they must be async def functions.

on_ready()

Called when the bot is done preparing the data received from VK. Usually after login is successful and the Bot.group and co. are filled up.

on_error(event, \*args, \*\*kwargs)

Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.

The information of the exception raised and the exception itself can be retrieved with a standard call to sys.exc_info().

If you want exception to propagate out of the Bot class you can define an on_error handler consisting of a single empty The raise statement. Exceptions raised by on_error will not be handled in any way by Bot.

Parameters
  • event (str) – The name of the event that raised the exception.

  • args – The positional arguments for the event that raised the exception.

  • kwargs – The keyword arguments for the event that raised the exception.

on_command_error(ctx, error)

An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided (Bot.on_command_error()).

Parameters
  • ctx (Context) – The invocation context.

  • error (CommandError derived) – The error that was raised.

on_command(ctx)

An event that is called when a command is found and is about to be invoked.

This event is called regardless of whether the command itself succeeds via error or completes.

Parameters

ctx (Context) – The invocation context.

on_command_completion(ctx)

An event that is called when a command has completed its invocation.

This event is called only if the command succeeded, i.e. all checks have passed and the user input it correctly.

Parameters

ctx (Context) – The invocation context.

on_message_new(message)

Called when bot receives a message.

Parameters

message (message.Message) – Received message.

on_message_event(event)

Called when a callback button is pressed.

Parameters

event – Received event.

on_message_reply(message)

Called when bot replies with a message.

Parameters

message (message.Message) – Sent message.

on_message_edit(message)

Called when message is edited.

Parameters

message (message.Message) – Edited message.

on_message_typing_state(state)

Called when typing state is changed (e.g. someone starts typing).

Parameters

state (states.State) – New state.

on_conversation_start(message)

Called when user starts conversation using special button.

Parameters

message (message.Message) – Message sent when conversation is started.

on_chat_kick_user(message)

Called when user is kicked from the chat.

Parameters

message (message.Message) – Message sent when user is kicked.

on_chat_invite_user(message)

Called when user is invited to the chat.

Parameters

message (message.Message) – Message sent when user is invited.

Called when user is invited to the chat by link.

Parameters

message (message.Message) – Message sent when user is invited.

on_chat_photo_update(message)

Called when chat photo is updated.

Parameters

message (message.Message) – Message sent when photo is updated.

on_chat_photo_remove(message)

Called when chat photo is removed.

Parameters

message (message.Message) – Message sent when photo is removed.

on_chat_create(message)

Called when chat is created.

Parameters

message (message.Message) – Message sent when chat is created.

on_chat_title_update(message)

Called when chat title is updated.

Parameters

message (message.Message) – Message sent when chat title is updated.

on_chat_pin_message(message)

Called when message is pinned in chat.

Parameters

message (message.Message) – Message sent when message is pinned in chat.

on_chat_unpin_message(message)

Called when message is unpinned in chat.

Parameters

message (message.Message) – Message sent when message is unpinned in chat.

on_message_allow(user)

Called when user allows getting messages from bot.

Parameters

user (user.User) – User who allowed messages.

on_message_deny(user)

Called when user denies getting messages from bot.

Parameters

user (user.User) – User who denied messages.

on_photo_new(photo)

Called when new photo is uploaded to bot group.

Parameters

photo (attachments.Photo) – Photo that got uploaded.

on_audio_new(audio)

Called when new audio is uploaded to bot group.

Parameters

audio (attachments.Audio) – Audio that got uploaded.

on_video_new(video)

Called when new video is uploaded to bot group.

Parameters

video (attachments.Video) – Video that got uploaded.

on_photo_comment_new(comment)

Called when new comment is added to photo.

Parameters

comment (group.PhotoComment) – Comment that got send.

on_photo_comment_edit(comment)

Called when comment on photo gets edited.

Parameters

comment (group.PhotoComment) – Comment that got edited.

on_photo_comment_restore(comment)

Called when comment on photo is restored.

Parameters

comment (group.PhotoComment) – Comment that got restored.

on_photo_comment_delete(comment)

Called when comment on photo is deleted.

Parameters

comment (group.DeletedPhotoComment) – Comment that got deleted.

on_video_comment_new(comment)

Called when new comment is added to video.

Parameters

comment (group.VideoComment) – Comment that got send.

on_video_comment_edit(comment)

Called when comment on video gets edited.

Parameters

comment (group.VideoComment) – Comment that got edited.

on_video_comment_restore(comment)

Called when comment on video is restored.

Parameters

comment (group.VideoComment) – Comment that got restored.

on_video_comment_delete(comment)

Called when comment on video is deleted.

Parameters

comment (group.DeletedVideoComment) – Comment that got deleted.

on_market_comment_new(comment)

Called when new comment is added to market.

Parameters

comment (group.MarketComment) – Comment that got send.

on_market_comment_edit(comment)

Called when comment on market gets edited.

Parameters

comment (group.MarketComment) – Comment that got edited.

on_market_comment_restore(comment)

Called when comment on market is restored.

Parameters

comment (group.MarketComment) – Comment that got restored.

on_market_comment_delete(comment)

Called when comment on market is deleted.

Parameters

comment (group.DeletedMarketComment) – Comment that got deleted.

on_board_post_new(comment)

Called when new post is added to board.

Parameters

comment (group.BoardComment) – New post on the board.

on_board_post_edit(comment)

Called when post on board gets edited.

Parameters

comment (group.BoardComment) – Post that got edited.

on_board_post_restore(comment)

Called when post on board is restored.

Parameters

comment (group.BoardComment) – Post that got restored.

on_board_post_delete(comment)

Called when post on board is deleted.

Parameters

comment (group.DeletedBoardComment) – Post that got deleted.

on_wall_post_new(post)

Called when new post in added to wall.

Parameters

post (group.Post) – Post that got added.

on_wall_repost(post)

Called when wall post is reposted.

Parameters

post (group.Post) – Post that got reposted.

on_wall_reply_new(comment)

Called when new comment is added to wall.

Parameters

comment (group.WallComment) – Comment that got send.

on_wall_reply_edit(comment)

Called when comment on wall gets edited.

Parameters

comment (group.WallComment) – Comment that got edited.

on_wall_reply_restore(comment)

Called when comment on wall is restored.

Parameters

comment (group.WallComment) – Comment that got restored.

on_wall_reply_delete(comment)

Called when comment on wall is deleted.

Parameters

comment (group.DeletedWallComment) – Comment that got deleted.

on_group_join(user, join_type)

Called when user joins bot group.

Parameters
  • user (user.User) – User that joined the group.

  • join_type (str) – User join type. Can be ‘join’ if user just joined, ‘unsure’ for events, ‘accepted’ if user was invited, ‘approved’ if user join request was approved or ‘request’ if user requested to join

on_group_leave(user, self)

Called when user leaves bot group.

Parameters
  • user (user.User) – User that left the group.

  • self (bool) – If user left on their own (True) or was kicked (False).

on_user_block(user)

Called when user is blocked in bot group.

Parameters

user (user.BlockedUser) – User that was blocked.

on_user_unblock(user)

Called when user is unblocked in bot group.

Parameters

user (user.UnblockedUser) – User that was unblocked.

on_poll_vote_new(vote)

Called when new poll vote is received.

Parameters

vote (group.PollVote) – New vote.

on_group_officers_edit(edit)

Called when group officers are edited.

Parameters

edit (group.OfficersEdit) – New edit.

on_unknown(payload)

Called when unknown event is received.

Parameters

payload (dict) – Json payload of the event.

Cogs

Cog

class vk_botting.cog.Cog

The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the Cogs page.

When inheriting from this class, the options shown in CogMeta are equally valid here.

qualified_name

Returns the cog’s specified name, not the class name.

Type

str

description

Returns the cog’s description, typically the cleaned docstring.

Type

str

for ... in walk_commands()

An iterator that recursively walks through this cog’s commands and subcommands.

get_listeners()

Returns a list of (name, function) listener pairs that are defined in this cog.

classmethod listener(name=None)

A decorator that marks a function as a listener.

This is the cog equivalent of Bot.listen().

Parameters

name (str) – The name of the event being listened to. If not provided, it defaults to the function’s name.

Raises

TypeError – The function is not a coroutine function or a string was not passed as the name.

cog_unload()

A special method that is called when the cog gets removed.

This function cannot be a coroutine. It must be a regular function.

Subclasses must replace this if they want special unloading behaviour.

bot_check_once(ctx)

A special method that registers as a Bot.check_once() check.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

bot_check(ctx)

A special method that registers as a Bot.check_once() check.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

cog_check(ctx)

A special method that registers as a commands.check() for every command and subcommand in this cog.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

cog_command_error(ctx, error)

A special method that is called whenever an error is dispatched inside this cog.

This is similar to on_command_error() except only applying to the commands inside this cog.

This function can be a coroutine.

Parameters
  • ctx (Context) – The invocation context where the error happened.

  • error (CommandError) – The error that happened.

await cog_before_invoke(ctx)

A special method that acts as a cog local pre-invoke hook. This is similar to Command.before_invoke().

This must be a coroutine.

Parameters

ctx (Context) – The invocation context.

await cog_after_invoke(ctx)

A special method that acts as a cog local post-invoke hook. This is similar to Command.after_invoke().

This must be a coroutine.

Parameters

ctx (Context) – The invocation context.

CogMeta

class vk_botting.cog.CogMeta(*args, **kwargs)

A metaclass for defining a cog.

Note that you should probably not use this directly. It is exposed purely for documentation purposes along with making custom metaclasses to intermix with other metaclasses such as the abc.ABCMeta metaclass.

For example, to create an abstract cog mixin class, the following would be done.

import abc
class CogABCMeta(CogMeta, abc.ABCMeta):
    pass
class SomeMixin(metaclass=abc.ABCMeta):
    pass
class SomeCogMixin(SomeMixin, Cog, metaclass=CogABCMeta):
    pass

Note

When passing an attribute of a metaclass that is documented below, note that you must pass it as a keyword-only argument to the class creation like the following example:

class MyCog(Cog, name='My Cog'):
    pass
name

The cog name. By default, it is the name of the class with no modification.

Type

str

command_attrs

A list of attributes to apply to every command inside this cog. The dictionary is passed into the Command (or its subclass) options at __init__. If you specify attributes inside the command attribute in the class, it will override the one specified inside this attribute. For example:

class MyCog(Cog, command_attrs=dict(hidden=True)):
    @command()
    async def foo(self, ctx):
        pass # hidden -> True

    @command(hidden=False)
    async def bar(self, ctx):
        pass # hidden -> False
Type

dict

Abstract Base Classes

An abstract base class (also known as an abc) is a class that models can inherit to get their behaviour. The Python implementation of an abc is slightly different in that you can register them at run-time. Abstract base classes cannot be instantiated. They are mainly there for usage with isinstance() and issubclass().

This library has a module related to abstract base classes, some of which are actually from the abc standard module, others which are not.

class vk_botting.abstract.Messageable

An ABC that details the common operations on a model that can send messages.

The following implement this ABC:

async with typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

Note

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with ctx.typing():
    # do expensive stuff here
    await ctx.send('done!')
await send(message=None, *, attachment=None, sticker_id=None, keyboard=None, reply_to=None, forward_messages=None)

This function is a coroutine.

Sends a message to the destination with the text given.

The content must be a type that can convert to a string through str(message).

If the content is set to None (the default), then the attachment or sticker_id parameter must be provided.

If the attachment parameter is provided, it must be str, List[str], Attachment or List[Attachment]

If the keyboard parameter is provided, it must be str or Keyboard (recommended)

Parameters
  • message (str) – The text of the message to send.

  • attachment (Union[List[str], str, List[Attachment], Attachment]) – The attachment to the message sent.

  • sticker_id (Union[str, int]) – Sticker_id to be sent.

  • keyboard (Keyboard) – The keyboard to send along message.

  • reply_to (Union[str, int]) – A message id to reply to.

  • forward_messages (Union[List[int], List[str]]) – Message ids to be forwarded along with message.

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

The message that was sent.

Return type

Message

await trigger_typing()

This function is a coroutine.

Triggers typing state of bot.

Can be used instead of typing() in some cases.

Typing state ends in 10 seconds or when message is sent.

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Json payload result of VK API request.

Return type

dict

Utility Classes

Attachment

class vk_botting.attachments.AttachmentType

Specifies the type of Attachment

PHOTO = 'photo'

Attached photo

VIDEO = 'video'

Attached video

AUDIO = 'audio'

Attached audio

DOCUMENT = 'doc'

Attached document

WALL = 'wall'

Attached wall post

MARKET = 'market'

Attached market good

POLL = 'poll'

Attached poll

class vk_botting.attachments.Attachment(owner_id, _id, type)

Represents VK Attachment.

You can get str(Attachment) to get string representation used by VK API or pass it to Bot.send_message()

owner_id

Id of attachment owner. Positive integer for users, negative for groups.

Type

int

id

Id of attachment itself. Positive integer.

Type

int

type

Type of an attachment. Can be value from AttachmentType enum.

Type

str

Keyboard

class vk_botting.keyboard.KeyboardColor

Represents Keyboard colors

PRIMARY = 'primary'

Primary color (blue)

SECONDARY = 'secondary'

Secondary color (gray)

NEGATIVE = 'negative'

Negative color (red)

POSITIVE = 'positive'

Positive color (green)

class vk_botting.keyboard.Keyboard(one_time=False, inline=False)

Class for easier creation and changing of Bot Keyboards.

Can be used in Bot.send_message() as it is

one_time

If keyboard is one-time (should disappear after one usage)

Type

bool

inline

If keyboard should be inline. Restricts keyboard to be only 6x5

Type

bool

classmethod get_empty_keyboard()

Classmethod for getting empty keyboard. Useful when keyboard should be cleared

add_button(label, color=<KeyboardColor.PRIMARY: 'primary'>, payload=None)

Adds button to current line

Parameters
  • label (str) – Button label to be displayed

  • color (:class:Union[str, KeyboardColor]) – Button color. Can be value from KeyboardColor enum

  • payload (dict) – Optional. Should be used for some buttons

Raises

vk_botting.VKApiError – When there are already too many buttons on one line

add_callback_button(label, color=<KeyboardColor.PRIMARY: 'primary'>, payload=None)

Adds a callback button (https://vk.com/dev/bots_docs_5) to current line

Parameters
  • label (str) – Button label to be displayed

  • color (:class:Union[str, KeyboardColor]) – Button color. Can be value from KeyboardColor enum

  • payload (dict) – Optional. Should be used for some buttons

Raises

vk_botting.VKApiError – When there are already too many buttons on one line

add_location_button(payload=None)

Adds location button to current line

Parameters

payload (dict) – Payload for a location button

Raises

vk_botting.VKApiError – When there are already too many buttons on one line

add_vkpay_button(_hash, payload=None)

Adds button to current line

Parameters
  • _hash (str) – Hash for a VKPay button

  • payload (dict) – Payload for a VKPay button

Raises

vk_botting.VKApiError – When there are already too many buttons on one line

add_vkapps_button(app_id, owner_id, label, _hash, payload=None)

Adds button to current line

Parameters
  • app_id (int) – Id of VK App

  • owner_id (int) – Id of VK App owner

  • label (str) – Button label to be displayed

  • _hash (str) – Hash for a VK App button

  • payload (dict) – Optional. Should be used for some button types

Raises

vk_botting.VKApiError – When there are already too many buttons on one line

add_line()

Adds new line to the keyboard

Raises

vk_botting.VKApiError – When there are already too many lines in a keyboard

Cooldown

vk_botting.commands.cooldown(rate, per, type=<BucketType.default: 0>)

A decorator that adds a cooldown to a Command or its subclasses.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-user, per-conversation, per-member or global basis.

Denoted by the third argument of type which must be of enum type BucketType which could be either:

  • BucketType.default for a global basis.

  • BucketType.user for a per-user basis.

  • BucketType.conversation for a per-conversation basis.

  • BucketType.member for a per-member.

If a cooldown is triggered, then CommandOnCooldown is triggered in on_command_error() and the local error handler.

A command can only have a single cooldown.

Parameters
  • rate (int) – The number of times a command can be used before triggering a cooldown.

  • per (float) – The amount of seconds to wait for a cooldown when it’s been triggered.

  • type (BucketType) – The type of cooldown to have.

class vk_botting.cooldowns.BucketType

Represents type of cooldown bucket

default = 0

Default cooldown. On global basis. Basically, counts command used anywhere towards cooldown bucket.

user = 1

Per-user basis. Counts command usage for every user, no matter where said user used the command.

conversation = 2

Per-conversation basis. Counts command usage for every conversation, no matter who used the command and if that conversation is personal or group chat.

member = 3

Per-member basis. Member here is user in conversation. Same user will be able to use the command in another conversation and that will count towards different bucket.

VK Models

Models are classes that are received from VK and are not meant to be created by the user of the library.

Danger

The classes listed below are not intended to be created by users and are also read-only.

For example, this means that you should not make your own User instances nor should you modify the User instance yourself.

User

class vk_botting.user.User(bot, data)

Represents a VK User.

This class has a lot of unused attributes that won’t be listed here, they are mainly based on VK API fields, so you should use VK API docs for them.

All of the attributes can be None if not enough data is provided.

id

Id of the user, positive integer

Type

int

first_name

User’s first name

Type

str

last_name

User’s last name

Type

str

is_closed

True if user’s page is closed

Type

bool

can_access_closed

True if bot can access user’s page even if closed

Type

bool

sex

1 for female, 2 for male, 0 for not specified

Type

int

async with typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

Note

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with ctx.typing():
    # do expensive stuff here
    await ctx.send('done!')
await send(message=None, *, attachment=None, sticker_id=None, keyboard=None, reply_to=None, forward_messages=None)

This function is a coroutine.

Sends a message to the destination with the text given.

The content must be a type that can convert to a string through str(message).

If the content is set to None (the default), then the attachment or sticker_id parameter must be provided.

If the attachment parameter is provided, it must be str, List[str], Attachment or List[Attachment]

If the keyboard parameter is provided, it must be str or Keyboard (recommended)

Parameters
  • message (str) – The text of the message to send.

  • attachment (Union[List[str], str, List[Attachment], Attachment]) – The attachment to the message sent.

  • sticker_id (Union[str, int]) – Sticker_id to be sent.

  • keyboard (Keyboard) – The keyboard to send along message.

  • reply_to (Union[str, int]) – A message id to reply to.

  • forward_messages (Union[List[int], List[str]]) – Message ids to be forwarded along with message.

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

The message that was sent.

Return type

Message

await trigger_typing()

This function is a coroutine.

Triggers typing state of bot.

Can be used instead of typing() in some cases.

Typing state ends in 10 seconds or when message is sent.

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Json payload result of VK API request.

Return type

dict

Group

class vk_botting.group.Group(data)

Represents a VK Group

id

Id of group, positive int

Type

int

name

Display name of the group

Type

str

screen_name

Screen name of the group (link part after vk.com/)

Type

str

is_closed

True if group is closed

Type

bool

type

Can be either event, group or page depending on group type

Type

str

photo

Has group photo urls with different sizes

Type

dict

Message

class vk_botting.message.Message(data)

Represents any message sent or received by bot.

Should only be created using Bot.build_msg()

id

Id of the message in conversation

Warning

Do not try to use this parameter in group chats with Bot, as it will always be 0 and cause errors.

Type

int

date

Datetime when message was sent

Type

datetime.datetime

update_time

Datetime when message was updated

Type

datetime.datetime

peer_id

Id of conversation where message was sent

Type

int

from_id

Id of message author

Type

int

text

Text of the message. Can be empty

Type

str

attachments

List of attachments delivered with message

Type

List[Attachment]

fwd_messages

List of forwarded messages

Type

List[Message]

reply_message

Message that this message replied to

Type

Message

action

Action payload

Type

Union[MessageAction, NoneType]

async with typing()

Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

Note

This is both a regular context manager and an async context manager. This means that both with and async with work with this.

Example Usage:

async with ctx.typing():
    # do expensive stuff here
    await ctx.send('done!')
await edit(message=None, *, attachment=None, keep_forward_messages=1, keep_snippets=1)

This function is a coroutine.

Coroutine to edit the message.

Parameters
  • message (str) – New text of the message.

  • attachment (Union[List[str], str, List[Attachment], Attachment]) – New attachment to the message.

  • keep_forward_messages (bool) – True if fwd_messages should be kept. Defaults to True

  • keep_snippets (bool) – True if snippets should be kept. Defaults to True

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

The message that was sent.

Return type

Message

await delete(delete_for_all=1)

This function is a coroutine.

Coroutine to delete the message.

Parameters

delete_for_all (bool) – True if message should be deleted for all users. Defaults to True

Raises

vk_botting.VKApiError – When error is returned by VK API.

await reply(message=None, **kwargs)

This function is a coroutine.

Sends a message to the destination as a reply to original message.

The content must be a type that can convert to a string through str(message).

If the content is set to None (the default), then the attachment or sticker_id parameter must be provided.

If the attachment parameter is provided, it must be str, List[str], Attachment or List[Attachment]

If the keyboard parameter is provided, it must be str or Keyboard (recommended)

Parameters
  • message (str) – The text of the message to send.

  • attachment (Union[List[str], str, List[Attachment], Attachment]) – The attachment to the message sent.

  • sticker_id (Union[str, int]) – Sticker_id to be sent.

  • keyboard (Keyboard) – The keyboard to send along message.

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

The message that was sent.

Return type

Message

await get_user()

This function is a coroutine. Returns the author of original message as instance of User class

await get_author()

This function is a coroutine. Alternative for Message.get_user()

await fetch_user()

This function is a coroutine. Alternative for Message.get_user()

await fetch_author()

This function is a coroutine. Alternative for Message.get_user()

await send(message=None, *, attachment=None, sticker_id=None, keyboard=None, reply_to=None, forward_messages=None)

This function is a coroutine.

Sends a message to the destination with the text given.

The content must be a type that can convert to a string through str(message).

If the content is set to None (the default), then the attachment or sticker_id parameter must be provided.

If the attachment parameter is provided, it must be str, List[str], Attachment or List[Attachment]

If the keyboard parameter is provided, it must be str or Keyboard (recommended)

Parameters
  • message (str) – The text of the message to send.

  • attachment (Union[List[str], str, List[Attachment], Attachment]) – The attachment to the message sent.

  • sticker_id (Union[str, int]) – Sticker_id to be sent.

  • keyboard (Keyboard) – The keyboard to send along message.

  • reply_to (Union[str, int]) – A message id to reply to.

  • forward_messages (Union[List[int], List[str]]) – Message ids to be forwarded along with message.

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

The message that was sent.

Return type

Message

await trigger_typing()

This function is a coroutine.

Triggers typing state of bot.

Can be used instead of typing() in some cases.

Typing state ends in 10 seconds or when message is sent.

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Json payload result of VK API request.

Return type

dict

MessageEvent

class vk_botting.message.MessageEvent(data)

Represents a message event (https://vk.com/dev/bots_docs_5).

conversation_message_id

Id of the message in conversation

Type

int

user_id

Id of the user that triggered the event

Type

int

peer_id

Id of conversation where message was sent

Type

int

event_id

Unique id of the event (can only be used once within 60 seconds)

Type

str

payload

Payload sent along with the button. Can be None

Type

dict

await blank_answer()

This function is a coroutine.

Coroutine to send a blank answer to the event (stops loading animation on the button).

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Server answer

Return type

dict

await show_snackbar(text)

This function is a coroutine.

Coroutine to send a show_snackbar answer to the event (shows a snackbar to a user).

Parameters

text (str) – Text to be displayed on a snackbar

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Server answer

Return type

dict

This function is a coroutine.

Coroutine to send an open_link answer to the event (opens certain link).

Parameters

link (str) – Link to be opened

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Server answer

Return type

dict

await open_app(app_id, owner_id, _hash)

This function is a coroutine.

Coroutine to send an open_app answer to the event (opens certain VK App).

Parameters
  • app_id (int) – Id of an app to be opened

  • owner_id (Optional[int]) – owner_id of said app

  • _hash (str) – I don’t actually know what this one is for (read vk docs)

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Server answer

Return type

dict

Exceptions

class vk_botting.exceptions.VKException

Base exception class for vk_botting

Ideally speaking, this could be caught to handle any exceptions thrown from this library.

class vk_botting.exceptions.VKApiError

Exception for most of errors sent by VK API in responses

class vk_botting.exceptions.CommandError(message=None, *args)

The base exception type for all command related errors.

This inherits from VKException.

This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from Bot, on_command_error().

class vk_botting.exceptions.CommandNotFound

Exception raised when a command is attempted to be invoked but no command under that name is found.

This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.

This inherits from CommandError.

class vk_botting.exceptions.DisabledCommand(message=None, *args)

Exception raised when the command being invoked is disabled.

This inherits from CommandError

class vk_botting.exceptions.CommandOnCooldown(cooldown, retry_after)

Exception raised when the command being invoked is on cooldown. This inherits from CommandError

cooldown

A class with attributes rate, per, and type similar to the cooldown() decorator.

Type

Cooldown

retry_after

The amount of seconds to wait before you can retry again.

Type

float

class vk_botting.exceptions.CheckFailure(message=None, *args)

Exception raised when the predicates in Command.checks have failed.

This inherits from CommandError

class vk_botting.exceptions.ClientException

Exception that’s thrown when an operation in the Client fails.

These are usually for exceptions that happened due to user input.

class vk_botting.exceptions.CommandInvokeError(e)

Exception raised when the command being invoked raised an exception. This inherits from CommandError

original

The original exception that was raised. You can also get this via the __cause__ attribute.

class vk_botting.exceptions.ArgumentError(message=None, *args)

The base exception type for errors that involve errors regarding arguments.

This inherits from CommandError.

class vk_botting.exceptions.BadArgument(message=None, *args)

Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command.

This inherits from ArgumentError

class vk_botting.exceptions.BadUnionArgument(param, converters, errors)

Exception raised when a typing.Union converter fails for all its associated types. This inherits from ArgumentError

param

The parameter that failed being converted.

Type

inspect.Parameter

converters

A tuple of converters attempted in conversion, in order of failure.

Type

Tuple[Type, ..]

errors

A list of errors that were caught from failing the conversion.

Type

List[CommandError]

class vk_botting.exceptions.MissingRequiredArgument(param)

Exception raised when parsing a command and a parameter that is required is not encountered.

This inherits from ArgumentError

param

The argument that is missing.

Type

inspect.Parameter

class vk_botting.exceptions.TooManyArguments(message=None, *args)

Exception raised when the command was passed too many arguments and its Command.ignore_extra attribute was not set to True.

This inherits from ArgumentError

class vk_botting.exceptions.ConversionError(converter, original)

Exception raised when a Converter class raises non-CommandError. This inherits from CommandError.

converter

The converter that failed.

Type

conversions.Converter

original

The original exception that was raised. You can also get this via the __cause__ attribute.

class vk_botting.exceptions.ExtensionError(message=None, *args, name)

Base exception for extension related errors.

This inherits from VKException.

name

The extension that had an error.

Type

str

class vk_botting.exceptions.ExtensionAlreadyLoaded(name)

An exception raised when an extension has already been loaded.

This inherits from ExtensionError

class vk_botting.exceptions.ExtensionNotLoaded(name)

An exception raised when an extension was not loaded.

This inherits from ExtensionError

class vk_botting.exceptions.NoEntryPointError(name)

An exception raised when an extension does not have a setup entry point function.

This inherits from ExtensionError

class vk_botting.exceptions.ExtensionFailed(name, original)

An exception raised when an extension failed to load during execution of the module or setup entry point.

This inherits from ExtensionError

name

The extension that had the error.

Type

str

original

The original exception that was raised. You can also get this via the __cause__ attribute.

Type

Exception

class vk_botting.exceptions.ExtensionNotFound(name, original)

An exception raised when an extension is not found.

This inherits from ExtensionError

name

The extension that had the error.

Type

str

original

Always None for backwards compatibility.

Type

NoneType

class vk_botting.exceptions.UnexpectedQuoteError(quote)

An exception raised when the parser encounters a quote mark inside a non-quoted string.

This inherits from ArgumentError.

quote

The quote mark that was found inside the non-quoted string.

Type

str

class vk_botting.exceptions.InvalidEndOfQuotedStringError(char)

An exception raised when a space is expected after the closing quote in a string but a different character is found.

This inherits from ArgumentError.

char

The character found instead of the expected string.

Type

str

class vk_botting.exceptions.ExpectedClosingQuoteError(close_quote)

An exception raised when a quote character is expected but not found.

This inherits from ArgumentError.

close_quote

The quote character expected.

Type

str

class vk_botting.exceptions.LoginError

Exception that’s thrown when bot fails to login with provided token for some reason

Additional Classes

class vk_botting.commands.GroupMixin(*args, **kwargs)

A mixin that implements common functionality for classes that are allowed to register commands.

all_commands

A mapping of command name to Command or subclass objects.

Type

dict

case_insensitive

Whether the commands should be case insensitive. Defaults to False.

Type

bool

commands

A unique set of commands without aliases that are registered.

Type

Set[Command]

add_command(command)

Adds a Command or its subclasses into the internal list of commands.

This is usually not called, instead the command() shortcut decorator are used instead.

Parameters

command (Command) – The command to add.

Raises
remove_command(name)

Remove a Command or subclasses from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters

name (str) – The name of the command to remove.

Returns

The command that was removed. If the name is not valid then None is returned instead.

Return type

Command or subclass

for ... in walk_commands()

An iterator that recursively walks through all commands and subcommands.

get_command(name)

Get a Command or subclasses from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters

name (str) – The name of the command to get.

Returns

The command that was requested. If not found, returns None.

Return type

Command or subclass

command(*args, **kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_command().

class vk_botting.commands.Command(func, **kwargs)

A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the command.

Type

str

callback

The coroutine that is executed when the command is called.

Type

coroutine

aliases

The list of aliases the command can be invoked under.

Type

list

enabled

A boolean that indicates if the command is currently enabled. If the command is invoked while it is disabled, then DisabledCommand is raised to the on_command_error() event. Defaults to True.

Type

bool

parent

The parent command that this command belongs to. None if there isn’t one.

Type

Optional[Command]

cog

The cog that this command belongs to. None if there isn’t one.

Type

Optional[Cog]

checks

A list of predicates that verifies if the command could be executed with the given Context as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_command_error() event.

Type

List[Callable[…, bool]]

rest_is_raw

If False and a keyword-only argument is provided then the keyword only argument is stripped and handled as if it was a regular argument that handles MissingRequiredArgument and default values in a regular matter rather than passing the rest completely raw. If True then the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults to False.

Type

bool

invoked_subcommand

The subcommand that was invoked, if any.

Type

Optional[Command]

ignore_extra

If True, ignores extraneous strings passed to a command if all its requirements are met (e.g. ?foo a b c when only expecting a and b). Otherwise on_command_error() and local error handlers are called with TooManyArguments. Defaults to True.

Type

bool

cooldown_after_parsing

If True, cooldown processing is done after argument parsing, which calls converters. If False then cooldown processing is done first and then the converters are called second. Defaults to False.

Type

bool

add_check(func)

Adds a check to the command. This is the non-decorator interface to check().

Parameters

func – The function that will be used as a check.

remove_check(func)

Removes a check from the command. This function is idempotent and will not raise an exception if the function is not in the command’s checks.

Parameters

func – The function to remove from the checks.

update(**kwargs)

Updates Command instance with updated attribute.

This works similarly to the command() decorator in terms of parameters in that they are passed to the Command or subclass constructors, sans the name and callback.

copy()

Creates a copy of this command.

clean_params

Retrieves the parameter OrderedDict without the context or self parameters.

Useful for inspecting signature.

full_parent_name

Retrieves the fully qualified parent command name.

This the base command name required to execute it. For example, in ?one two three the parent name would be one two.

Type

str

parents

Retrieves the parents of this command.

If the command has no parents then it returns an empty list.

For example in commands ?a b c test, the parents are [c, b, a].

Type

Command

root_parent

Retrieves the root parent of this command.

If the command has no parents then it returns None.

For example in commands ?a b c test, the root parent is a.

qualified_name

Retrieves the fully qualified command name.

This is the full parent name with the command name as well. For example, in ?one two three the qualified name would be one two three.

Type

str

is_on_cooldown(ctx)

Checks whether the command is currently on cooldown.

Parameters

ctx (Context) – The invocation context to use when checking the commands cooldown status.

Returns

A boolean indicating if the command is on cooldown.

Return type

bool

reset_cooldown(ctx)

Resets the cooldown on this command.

Parameters

ctx (Context) – The invocation context to reset the cooldown under.

error(coro)

A decorator that registers a coroutine as a local error handler.

A local error handler is an on_command_error() event limited to a single command. However, the on_command_error() is still invoked afterwards as the catch-all.

Parameters

coro (coroutine) – The coroutine to register as the local error handler.

Raises

TypeError – The coroutine passed is not actually a coroutine.

before_invoke(coro)

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.

This pre-invoke hook takes a sole parameter, a Context.

See Bot.before_invoke() for more info.

Parameters

coro (coroutine) – The coroutine to register as the pre-invoke hook.

Raises

TypeError – The coroutine passed is not actually a coroutine.

after_invoke(coro)

A decorator that registers a coroutine as a post-invoke hook.

A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required.

This post-invoke hook takes a sole parameter, a Context.

See Bot.after_invoke() for more info.

Parameters

coro (coroutine) – The coroutine to register as the post-invoke hook.

Raises

TypeError – The coroutine passed is not actually a coroutine.

cog_name

The name of the cog this command belongs to. None otherwise.

Type

str

await can_run(ctx)

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute. This also checks whether the command is disabled.

Parameters

ctx (Context) – The ctx of the command currently being invoked.

Raises

CommandError – Any command error that was raised during a check call will be propagated by this function.

Returns

A boolean indicating if the command can be invoked.

Return type

bool

class vk_botting.client.Client(**kwargs)

Class that represent Client for interation with VK Api

Warning

Should not be used outside of Bot, as it is not intended and will probably not work

exception botCommandException
wait_for(event, *, check=None, timeout=None)

This function is a coroutine.

Waits for an event to be dispatched.

This could be used to wait for a user to reply to a message or to edit a message in a self-containedway.

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. Please check the documentation for a list of events and their parameters.

This function returns the first event that meets the requirements.

Examples

Waiting for a user reply:

@bot.command()
async def greet(ctx):
    await ctx.send('Say hello!')
    def check(m):
        return m.text == 'hello' and m.from_id == ctx.from_id
    msg = await bot.wait_for('message_new', check=check)
    await ctx.send('Hello {.from_id}!'.format(msg))
Parameters
  • event (str) – The event name, similar to the event reference, but without the on_ prefix, to wait for.

  • 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.

Returns

Returns no arguments, a single argument, or a tuple of multiple arguments that mirrors the parameters passed in the event reference.

Return type

Any

await vk_request(method, post=True, **kwargs)

This function is a coroutine.

Implements abstract VK Api method request.

Parameters
  • method (str) – String representation of method name (e.g. ‘users.get’)

  • post (bool) – If request should be POST. Defaults to true. Changing this is not recommended

  • kwargs (Any) –

    Payload arguments to send along with request

    Note

    access_token and v parameters should not be passed as they are automatically added from current bot attributes

Returns

Dict representation of json response received from the server

Return type

dict

await user_vk_request(method, post=True, **kwargs)

This function is a coroutine.

Implements abstract VK Api method request with attached User token.

Parameters
  • method (str) – String representation of method name (e.g. ‘users.get’)

  • post (bool) – If request should be POST. Defaults to true. Changing this is not recommended

  • kwargs (Any) –

    Payload arguments to send along with request

    Note

    access_token and v parameters should not be passed as they are automatically added from current bot attributes

Returns

Dict representation of json response received from the server

Return type

dict

await get_users(*uids, fields=None, name_case=None)

This function is a coroutine.

Alias for VK Api ‘users.get’ method call

Parameters
  • uids (List[int]) – List of user ids to request

  • fields (List[str]) – Optional. Fields that should be requested from VK Api. None by default

  • name_case (str) – Optional. Name case for users’ names to be returned in. ‘nom’ by default. Can be ‘nom’, ‘gen’, ‘dat’, ‘acc’, ‘ins’ or ‘abl’

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

List of User instances for requested users

Return type

List[User]

await get_groups(*gids)

This function is a coroutine.

Alias for VK Api ‘groups.get’ method call

Parameters

gids (List[int]) – List of group ids to request

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

List of Group instances for requested groups

Return type

List[Group]

await get_pages(*ids, fields=None, name_case=None)

This function is a coroutine.

Gets pages for given ids, whether it is Group or User

Parameters
  • ids (List[int]) – List of ids to request

  • fields (List[str]) – Optional. Fields that should be requested from VK Api for users. None by default

  • name_case (str) – Optional. Name case for users’ names to be returned in. ‘nom’ by default. Can be ‘nom’, ‘gen’, ‘dat’, ‘acc’, ‘ins’ or ‘abl’

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

List of Group or User instances for requested ids

Return type

List[Union[Group, User]]

await get_user(uid, fields=None, name_case=None)

This function is a coroutine.

Alias for VK Api ‘users.get’ method call that returns only one user.

Parameters
  • uid (int) – Id of user to request

  • fields (List[str]) – Optional. Fields that should be requested from VK Api. None by default

  • name_case (str) – Optional. Name case for user’s name to be returned in. ‘nom’ by default. Can be ‘nom’, ‘gen’, ‘dat’, ‘acc’, ‘ins’ or ‘abl’

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

User instance for requested user

Return type

User

await get_group(gid)

This function is a coroutine.

Alias for VK Api ‘groups.get’ method call that returns only one group.

Parameters

gid (int) – Id of group to request

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Group instance for requested group

Return type

Group

await get_page(pid, fields=None, name_case=None)

This function is a coroutine.

Gets page for given id, whether it is Group or User

Parameters
  • pid (int) – Id of page to request

  • fields (List[str]) – Optional. Fields that should be requested from VK Api for users. None by default

  • name_case (str) – Optional. Name case for user’s name to be returned in. ‘nom’ by default. Can be ‘nom’, ‘gen’, ‘dat’, ‘acc’, ‘ins’ or ‘abl’

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Group or User instance for requested id

Return type

Union[Group, User]

await get_own_page()

This function is a coroutine.

Gets page for current token, whether it is Group or User

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

Group or User instance for current token

Return type

Union[Group, User]

await upload_image_to_server(server, filename=None, url=None, raw=None, format=None)

This function is a coroutine.

Upload an image to some VK upload server.

Returns dict representation of server response.

Parameters
  • server (str) – Upload server url. Can be requested from API methods like photos.getUploadServer.

  • filename (str) – Path to image to upload. Can be relative.

  • url (str) – Url of image to upload. Should be a direct url to supported image format, otherwise wont work.

  • raw (bytes) – Raw bytes of image to upload. If used, format has to be provided.

  • format (str) – Extension of image to upload. Should be used only alongside raw data.

Returns

dict representation of server response.

Return type

dict

await upload_document(peer_id, file, type=<DocType.DOCUMENT: 'doc'>, title=None)

This function is a coroutine.

Upload a document to conversation with given peer_id.

Returns ready-to-use in send_message attachment.

Parameters
  • peer_id (int) – Peer_id of the destination. The uploaded document cannot be used outside of given conversation.

  • file (str) – Path to document to upload. Can be relative.

  • type (str) – Uploaded document type. Can be value from DocType enum.

  • title (str) – Title for uploaded document. Filename by default.

Returns

Attachment instance representing uploaded document.

Return type

Attachment

await upload_photo(peer_id, filename=None, url=None, raw=None, format=None)

This function is a coroutine.

Upload a photo to conversation with given peer_id.

Returns ready-to-use in send_message attachment.

Parameters
  • peer_id (int) – Peer_id of the destination. The uploaded photo cannot be used outside of given conversation.

  • filename (str) – Path to image to upload. Can be relative.

  • url (str) – Url of image to upload. Should be a direct url to supported image format, otherwise wont work.

  • raw (bytes) – Raw bytes of image to upload. If used, format has to be provided.

  • format (str) – Extension of image to upload. Should be used only alongside raw data.

Returns

Attachment instance representing uploaded photo.

Return type

Attachment

build_msg(msg)

Build Message instance from message object dict.

Normally should not be used at all.

Parameters

msg (dict) – dict representation of Message object returned by VK API

Returns

Message instance representing original object

Return type

Message

await on_error(event_method, *args, **kwargs)

This function is a coroutine.

The default error handler provided by the client.

By default this prints to sys.stderr however it could be overridden to have a different implementation.

Check vk_botting.on_error() for more details.

await send_message(peer_id=None, message=None, attachment=None, sticker_id=None, keyboard=None, reply_to=None, forward_messages=None, forward=None, **kwargs)

This function is a coroutine.

Sends a message to the given destination with the text given.

The content must be a type that can convert to a string through str(message).

If the content is set to None (the default), then the attachment or sticker_id parameter must be provided.

If the attachment parameter is provided, it must be str, List[str], Attachment or List[Attachment]

If the keyboard parameter is provided, it must be str or Keyboard (recommended)

Parameters
  • peer_id (int) – Id of conversation to send message to

  • message (str) – The text of the message to send.

  • attachment (Union[List[str], str, List[Attachment], Attachment]) – The attachment to the message sent.

  • sticker_id (Union[str, int]) – Sticker_id to be sent.

  • keyboard (Keyboard) – The keyboard to send along message.

  • reply_to (Union[str, int]) – A message id to reply to.

  • forward_messages (Union[List[int], List[str]]) – Message ids to be forwarded along with message.

  • forward (dict) – Check docs for more details on this one.

  • as_user (bool) – If message should be sent as user (using attached user token).

Raises

vk_botting.VKApiError – When error is returned by VK API.

Returns

The message that was sent.

Return type

Message

await add_user_token(token)

This function is a coroutine. Alternative for Client.attach_user_token()

await attach_user_token(token)

This function is a coroutine.

Attaches user token to the bot, enabling it to execute API calls available to users only.

Also puts User object corresponding to the token into self.user

Parameters

token (str) – User token to attach

run(token, owner_id=None)

A blocking call that abstracts away the event loop initialisation from you.

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.

Parameters
  • token (str) – Bot token. Should be group token or user token with access to group

  • owner_id (int) – Should only be passed alongside user token. Owner id of group to connect to

vk_botting.commands.command(name=None, cls=None, **attrs)

A decorator that transforms a function into a Command.

All checks added using the check() & co. decorators are added into the function. There is no way to supply your own checks through this decorator.

Parameters
  • name (str) – The name to create the command with. By default this uses the function name unchanged.

  • cls – The class to construct with. By default this is Command. You usually do not change this.

  • attrs – Keyword arguments to pass into the construction of the class denoted by cls.

Raises

TypeError – If the function is not a coroutine or is already a command.